"""
//*************************************************************************
// Example program
//					
// @file	logreg.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: 
//	- Logistic Regression Classifier
//
//  Dependencies:
//     sklearn, matplotlib, numpy
//*************************************************************************
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split  # Import for data splitting
from sklearn.metrics import log_loss        # cross entropy / Log Loss

# 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 difference 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(f'\nLogistic Regression Classifier:\n') 
plotData(X, y, fig=1, title="Data")  # plot data
input("...Press return to continue...")

# Logistic Regression Classifier
# solver: 'libfgs', 'liblinear', 'sag', 'saga', 'newton-cg', 'newton-ckolesky'
# random_state:  random seed to suffle the data ('sag', 'saga', 'liblinear')
# 'sag' solver: Stochastic Average Gradient
model_lr = LogisticRegression(solver='sag', random_state=42)  # Initialize the model

# Train the model (estimate thetas using Gradient Descent over Cross Entropy loss function)
model_lr.fit(X_train, y_train) 
train_loss = log_loss(y_train, model_lr.predict_proba(X_train))  # Train loss value: cross entropy / Log Loss

# Make predictions on the test data
y_pred = model_lr.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_lr.predict_proba(X_test)

# Print model coefficients 
print("\nLogistic Regression Classifier")
print(f"Train Loss: {train_loss:.4f}")
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Model Coefficients (w1, w2): {model_lr.coef_[0]}")
print(f"Intercept/Bias (w0): {model_lr.intercept_[0]}")

plotData(X_train, y_train, val_data=X_test, val_labels=y_test, model=model_lr, 
          fig=1, title="Logistic Regression Classifier")

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