###############################################################################
# Demo: Power Fuzzy Clustering & Cluster-wise Regression
#
# This script demonstrates:
#   1. PFCR (regression) on the 'students' dataset from flexCWM
#   2. PFC  (clustering) on the 'iris' dataset
# using Mahalanobis and Minkowski distances with various (m, q) settings.
#
# Prerequisites:
#   library(pfclust)
#   install.packages("flexCWM")
###############################################################################

library(pfclust)
library(flexCWM)

# =============================================================================
# 1. Cluster-wise Regression  -  Students data
#    Columns: 1 = true class, 2-3 = Y (HEIGHT, WEIGHT), 4 = X (HEIGHT.F)
# =============================================================================
data("students")
Y <- students[, 2:3]
X <- students[, 4]
l <- students[, 1]

# --- 1a. Mahalanobis distance (default m=2, q=2) ---
resMah <- PFCR(X, Y, K = 2, distance = "Mahalanobis")
table(resMah$l, l)

# --- 1b. Minkowski distance (default m=2, q=2, p=2) ---
resMin <- PFCR(X, Y, K = 2)
table(resMin$l, l)

# --- 1c. Mahalanobis with m=3, q=3 ---
resMah33 <- PFCR(X, Y, K = 2, m = 3, q = 3, distance = "Mahalanobis")
table(resMah33$l, l)

# --- Plots for the (m=3, q=3) Mahalanobis result ---
pp    <- apply(resMah33$p, 1, max)
color <- ifelse(resMah33$l == unique(resMah33$l)[1], "blue", "red")

plot(Y, col = color, pch = 16, cex = pp,
     main = "PFCR Mahalanobis (3,3)")

plot(X, Y[, 1], ylab = "HEIGHT", xlab = "HEIGHT.F",
     pch = 16, cex = pp, col = color,
     main = "PFCR Mahalanobis (3,3)")
abline(resMah33$B[1, 1, 1], resMah33$B[2, 1, 1], col = "blue", lwd = 2)
abline(resMah33$B[1, 1, 2], resMah33$B[2, 1, 2], col = "red",  lwd = 2)

plot(X, Y[, 2], ylab = "WEIGHT", xlab = "HEIGHT.F",
     pch = 16, cex = pp, col = color,
     main = "PFCR Mahalanobis (3,3)")
abline(resMah33$B[1, 2, 1], resMah33$B[2, 2, 1], col = "blue", lwd = 2)
abline(resMah33$B[1, 2, 2], resMah33$B[2, 2, 2], col = "red",  lwd = 2)

# =============================================================================
# 2. Clustering (no covariates)  -  Iris data
# =============================================================================
Y <- iris[, 1:4]
l <- iris[, 5]

# --- 2a. Mahalanobis distance ---
resMahC <- PFC(Y, K = 3, distance = "Mahalanobis")
table(resMahC$l, l)
pairs(Y, col = resMahC$l)

# --- 2b. Minkowski distance (default p=2) ---
resMinC <- PFC(Y, K = 3)
table(resMinC$l, l)
pairs(Y, col = resMinC$l)

# --- 2c. Minkowski distance (p=1, Manhattan) ---
resMin1C <- PFC(Y, K = 3, p = 1)
table(resMin1C$l, l)
pairs(Y, col = resMin1C$l)
