"""
//*************************************************************************
// Example program using OpenCV library
//					
// @file	mlp.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: 
//	- MLP Multi Layer Perceptron
//
//  Dependencies:
//     scipy, sklearn, matplotlib, numpy, argparse
//*************************************************************************
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
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('Bayesian Classifier')

     # 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')

        # predict probabilities for the grid points
        Z_proba = model.predict_proba(np.c_[xx.ravel(), yy.ravel()])  # probabilities
        Z_diff = Z_proba[:, 1] - Z_proba[:, 0]  # Probability differenc between classes
        Z_diff = Z_diff.reshape(xx.shape)
        # Plot decision rule limit (equal probability)
        plt.contour(xx, yy, Z_diff, levels=[0], colors='k', linewidths=1)

    # 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')
 
    # 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='lower right')



    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.2, random_state=42) 

###############################################################
print("\nMLP Multi Layer Perceptron Classifier")
plotData(X, y, fig=1, title="Data")  # plot data
input("...Press return to continue...")

# MLP network model
# hidden_layer_size: tuple wiwth the neuron of each hidden layer
# activation: 'identity', 'logistic', 'tanh', 'relu'
# solver: 'lbfgs', 'sgd', 'adam'
# alpha: regularization L2 penalty factor
# batch_size: 'auto' or int  
# learning_rate: 'constant', 'invscaling' 'adaptative'
# momentum: used in 'sgd' to  promediate the gradients
# random_state:  random seed to suffle the data 
# max_iter: number of epochs
model_mlp = MLPClassifier(hidden_layer_sizes=(10, 10), activation='tanh', 
                          solver='sgd', max_iter=1000, random_state=42) # Initialize the model

# train MLP Network
model_mlp.fit(X_train, y_train)  
train_loss = model_mlp.loss_

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

# obtain class probabilites
y_prob = model_mlp.predict_proba(X_test)

# Print model coefficients (similar to means and variances in Naive Bayes)
print("\nMLP Multi Layer Perceptron Classifier")
print(f"Train Loss: {train_loss:.4f}")
print(f"Test Accuracy: {accuracy:.4f}")

plotData(X_train, y_train, val_data=X_test, val_labels=y_test, model=model_mlp, 
          title="MLP Multi Layer Perceptron")

input('\n...Press return to finish program...')