"""
//*************************************************************************
// Example program 
//					
// @file	svm.py					
// @author Luis M. Jimenez
// @date 2025
//
// @brief Course: Computer Vision (1782)
// Dpo. of Systems Engineering and Automation
// Automation, Robotics and Computer Vision Lab (ARVC)
// http://arvc.umh.es
// University Miguel Hernandez
//
// @note Description: 
//	- SVM Classifier:  Support Vector Machine with Linear and Gaussian Kernels
//
//  Dependencies:
//     sklearn, matplotlib, numpy
//*************************************************************************
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split  # Import for data splitting


# Plot Data / Classification rules
def plotData(data, labels=None, val_data=None, val_labels=None, 
              model=None, fig=None, title="Data", show_ids=False):

    # Plot Data 
    plt.figure(fig, figsize=(9, 7))
    plt.clf()
    plt.title(title)
    plt.xlabel("x1")
    plt.ylabel("x2")
    plt.gcf().canvas.manager.set_window_title('SVM Support Vector Machine')

    # plot decision rule
    if (model is not None):
        all_data = data if val_data is None else np.concatenate((data, val_data), axis=0)
        x_min, x_max = all_data[:, 0].min() - 1, all_data[:, 0].max() + 1
        y_min, y_max = all_data[:, 1].min() - 1, all_data[:, 1].max() + 1
        xx, yy = np.meshgrid(np.linspace(x_min, x_max, 200),
                            np.linspace(y_min, y_max, 200))

        # predict the grid points
        Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        # plot decision rule regions
        plt.contourf(xx, yy, Z, alpha=0.2, cmap='coolwarm')

        # Evaluate decision function for grid points
        Z = model.decision_function(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        
        # Plot decision rule limit and decsion margins [-1, 0, 1]
        contours = plt.contour(xx, yy, Z, levels=[-1, 0, 1], 
                              colors=['blue', 'black', 'red'], 
                              linestyles=['dashed', 'solid', 'dashed'])
        plt.clabel(contours, inline=True, fontsize=10)

    # plot data points
    if labels is not None:
        plt.scatter(data[:,0], data[:,1], s=25, marker='o', c=labels, cmap='coolwarm', alpha=0.6, edgecolors='k')
    else:
        plt.scatter(data[:,0], data[:,1], s=25, marker='o', alpha=0.6, edgecolors='k')
 
    # Bold  support vectors
    if model is not None:
      plt.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], 
                    s=150, facecolors='none', edgecolors='k', linewidths=1.5, label="Support Vectors")
      plt.legend(loc='best')

    # Plot Validation Data (predict)
    if val_data is not None and val_labels is not None:
        plt.scatter(val_data[:,0],val_data[:,1], marker='x', s=40, c=val_labels, cmap='coolwarm', label="Validation Data")
        
        # Plot items ids
        if show_ids:
          for i, (x, y) in enumerate(zip(val_data[:, 0], val_data[:, 1])):
              plt.annotate(str(i), xy=(x, y), xytext=(-3, 3), textcoords='offset points', ha='right', va='bottom')
        plt.legend(loc='best')

    plt.draw()
    plt.pause(0.1)  # gives control to GUI event manager to show the plot
# end plotData


# Non correlated data generator (same variance)
np.random.seed(42)
mean_class0 = [-1, 0]  # mean class 0
mean_class1 = [2, 2]  # mean class 1
cov_matrix = [[1, 0], [0, 1]]  # both variables are independent with same variance 

# Generate random samples for each class
m = 100  # number of samples
X0 = np.random.multivariate_normal(mean_class0, cov_matrix, m)
X1 = np.random.multivariate_normal(mean_class1, cov_matrix, m)

# Build dataset
X = np.vstack((X0, X1))
y = np.hstack((np.zeros(m), np.ones(m)))  # Labels {0  1}

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) 

###############################################################
print("\nSVM Classifier Linear Kernel")
plotData(X, y, fig=1, title="Data")  # plot data
input("...Press return to continue...")

# SVM classifier with linear kernel
# kernel: 'linear', 'poly', 'rbf', 'sigmoid'
# C: regularization factor, increase C to reduce the regularization 
# kernel = 'linear'  : k(x,l) = (xT * l)
model_svm = SVC(kernel='linear', C=1.0)     # Linear kernel

# Train the model (estimate thetas using Gradient Descent over loss function)
model_svm.fit(X_train, y_train)
train_loss = model_svm.decision_function(X_train)  # Train SVM loss value 
train_loss = np.abs(train_loss).mean()      # mean of absolute loss values
n_sv= len(model_svm.support_vectors_)       # number of support vectors

# Make predictions on the test data
y_pred = model_svm.predict(X_test)
accuracy = np.sum(y_pred == y_test)/len(y_pred)    # Calculate the accuracy (1 - error rate)

print("\nSVM Classifier Linear Kernel")
print(f"Train Loss: {train_loss:.4f}")
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Number of Suppor Vectors: {n_sv}")

plotData(X_train, y_train, val_data=X_test, val_labels=y_test, model=model_svm,
          fig=1, title=f"SVM Linear Classifier ({n_sv} Support Vectors)")

input("...Press return to continue...")

###############################################################
# SVM classifier with gaussian kernel
# kernel: 'linear', 'poly', 'rbf', 'sigmoid'
# C: regularization factor, increase C to reduce the regularization 
# gamma: {‘scale’, ‘auto’} or float  Kernel coefficient for 'rbf', 'poly' and 'sigmoid'
# kernel = 'rbf'  : k(x,l) = exp(-gamma*||x-l||^2)
# gamma = 'scale' : 1 / (n_features * X.var())
model_svm = SVC(kernel='rbf', C=1.0, gamma='scale')    # gamma: gaussian kernel factor: 'scale' -> auto


# Train the model (estimate thetas using Gradient Descent over loss function)
model_svm.fit(X_train, y_train)
train_loss = model_svm.decision_function(X_train)  # Train SVM loss value 
train_loss = np.abs(train_loss).mean()      # mean of absolute loss values
n_sv= len(model_svm.support_vectors_)   # number of support vectors

# Make predictions on the test data
y_pred = model_svm.predict(X_test)
accuracy = np.sum(y_pred == y_test)/len(y_pred)    # Calculate the accuracy (1 - error rate)

print("\nSVM Classifier RBF (Gaussian) Kernel")
print(f"Train Loss: {train_loss:.4f}")
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Number of Suppor Vectors: {n_sv}")

plotData(X_train, y_train, val_data=X_test, val_labels=y_test, model=model_svm,
          fig=1, title=f"SVM (RBF Gaussian kernel) Classifier  ({n_sv} Support Vectors)")

input("...Press return to continue...")
