"""
//*************************************************************************
// Example program using OpenCV library
//					
// @file	dtree.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: 
//	- Decision Tree  Classifier
//
//  Dependencies:
//     scipy, sklearn, matplotlib, numpy, argparse
//*************************************************************************
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, plot_tree
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(f'\nDecision Tree Classifier:\n') 
plotData(X, y, fig=1, title="Data")  # plot data
#input("...Press return to continue...")

# Decision Tree Classifier
# max_depth: max depth of the tree 'None':  no limit
# max_leaf_nodes: max number of leaf nodes
# min_samples_split: (default 2) minimum of samples to split a node
# criterion: 'gini', 'entropy'
# splitter: 'best', 'random' strategy to choose feature at each node
# random_state:  random seed to suffle the data 
model_tree = DecisionTreeClassifier(max_depth=3, criterion='gini', splitter='best',
                                    random_state=42) # Initialize the model
# Train Decision Tree Classifier
model_tree.fit(X_train, y_train)  # Train the model
train_loss = model_tree.tree_.impurity.mean()  # impurity of each leaf

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

# Print model coefficients (similar to means and variances in Naive Bayes)
print("\nDecision Tree 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_tree, 
          title="Decision Tree Classifier")

# Visualize tree structure
plt.figure(figsize=(12, 8))
plot_tree(model_tree, filled=True,  precision=2, rounded=True, fontsize=10,
          feature_names=["x1", "x2"], class_names=["Class 0", "Class 1"] )
plt.title("Decision Tree structure (Rules)")
plt.pause(0.1)

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