# 出典: mo-notebooks/05/svm.ipynb

# %%
# install AMPL and solvers
#%pip install -q amplpy pandas numpy matplotlib scikit-learn

SOLVER_LO = "cbc"
SOLVER_NLO = "ipopt"

from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["coin"],  # modules to install
    license_uuid="default",  # license to use
)  # instantiate AMPL object and register magics

# %%
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split

# read data set
df = pd.read_csv(
    "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/datasets/data_banknote_authentication.txt",
    header=None,
)
df.columns = ["variance", "skewness", "curtosis", "entropy", "class"]
df.name = "Banknotes"

# show a few rows
df.head()

# %%
# get a statistical description of the data set
df.describe()

# %%
# create training and validation test sets
df_train, df_test = train_test_split(df, test_size=0.2)

# select training features
features = ["variance", "skewness"]

# separate into features and outputs
X_train = df_train[features]
y_train = 1 - 2 * df_train["class"]

# separate into features and outputs
X_test = df_test[features]
y_test = 1 - 2 * df_test["class"]

# %%
def scatter_labeled_data(X, y, labels=["+1", "-1"], colors=["g", "r"], **kwargs):
    """
    Creates a scatter plot for labeled data with default labels and colors.

    Parameters:
    X : DataFrame
        Feature matrix as a DataFrame.
    y : Series
        Target vector as a Series.
    labels : list, optional
        Labels for the positive and negative classes. Default is ["+1", "-1"].
    colors : list, optional
        Colors for the positive and negative classes. Default is ["g", "r"].
    **kwargs : dict
        Additional keyword arguments for the scatter plot.

    Returns:
    None
    """

    # Prepend keyword arguments for all scatter plots
    kw = {"x": 0, "y": 1, "kind": "scatter", "alpha": 0.4}
    kw.update(kwargs)

    # Ignore warnings from matplotlib scatter plot
    import warnings

    with warnings.catch_warnings():
        warnings.filterwarnings("ignore")
        kw["ax"] = X[y > 0].plot(**kw, c=colors[0], label=labels[0])
        X[y < 0].plot(**kw, c=colors[1], label=labels[1])

# %%
# plot training and test sets in two axes
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
scatter_labeled_data(
    X_train,
    y_train,
    labels=["genuine", "counterfeit"],
    ax=ax[0],
    title="Training Set",
)
scatter_labeled_data(
    X_test,
    y_test,
    labels=["genuine", "counterfeit"],
    ax=ax[1],
    title="Test Set",
)

# %%
# import required libraries
import pandas as pd
import numpy as np


# Linear Support Vector Machine (SVM) class
class LinearSVM:
    # Initialize the Linear SVM with weights and bias
    def __init__(self, w, b):
        """
        Args:
            w (Pandas Series or dictionary): Weights of the SVM
            b (float): Bias of the SVM
        """
        self.w = pd.Series(w)
        self.b = float(b)

    # Call method to compute the decision function
    def __call__(self, X):
        """
        Args:
            X (pandas.DataFrame): Input data

        Returns:
            numpy.array: Array of decision function values
        """
        return np.sign(X.dot(self.w) + self.b)

    # Representation method for the Linear SVM class
    def __repr__(self):
        """
        Returns:
            str: String representation of the Linear SVM
        """
        return f"LinearSvm(w = {self.w.to_dict()}, b = {self.b})"

# %%
# Visual estimaate of w and b for a linear classifier
w = pd.Series({"variance": 1, "skewness": 0})
b = 0

# create an instance of LinearSVM
svm = LinearSVM(w, b)
print(svm)

# predictions for the training set
y_pred = svm(X_test)

# fraction of correct predictions
accuracy = sum(y_pred == y_test) / len(y_test)
print(f"Accuracy = {100 * accuracy: 0.1f}%")

# %%
def scatter_comparison(X, y, y_pred):
    """
    Creates scatter plots comparing actual and predicted outcomes for both training and test sets.

    Parameters:
    X : DataFrame
        Feature matrix as a DataFrame.
    y : Series
        Actual target vector as a Series.
    y_pred : Series
        Predicted target vector as a Series.

    Returns:
    None
    """

    xmin, ymin = X.min()
    xmax, ymax = X.max()
    xlim = [xmin - 0.05 * (xmax - xmin), xmax + 0.05 * (xmax - xmin)]
    ylim = [ymin - 0.05 * (ymax - ymin), ymax + 0.05 * (ymax - ymin)]

    # Plot training and test sets
    labels = ["genuine", "counterfeit"]
    fig, ax = plt.subplots(1, 2, figsize=(10, 4))
    scatter_labeled_data(
        X, y, labels, ["g", "r"], ax=ax[0], xlim=xlim, ylim=ylim, title="Actual"
    )
    scatter_labeled_data(
        X,
        y_pred,
        labels,
        ["c", "m"],
        ax=ax[1],
        xlim=xlim,
        ylim=ylim,
        title="Prediction",
    )

    # Plot actual positives and actual negatives
    fig, ax = plt.subplots(1, 2, figsize=(10, 4))
    scatter_labeled_data(
        X[y > 0],
        y_pred[y > 0],
        ["true positive", "false negative"],
        ["c", "m"],
        xlim=xlim,
        ylim=ylim,
        ax=ax[0],
        title="Actual Positives",
    )
    scatter_labeled_data(
        X[y < 0],
        y_pred[y < 0],
        ["false positive", "true negative"],
        ["c", "m"],
        xlim=xlim,
        ylim=ylim,
        ax=ax[1],
        title="Actual Negatives",
    )

# %%
scatter_comparison(X_test, y_test, y_pred)

# %%
def validate(y_true, y_pred, verbose=True):
    """
    This function calculates and displays the sensitivity, precision, and Matthews correlation coefficient
    (MCC) for a binary classifier based on its true labels (y_true) and predicted labels (y_pred).

    Args:
    y_true (array-like): A list or array containing the true labels of the samples.
    y_pred (array-like): A list or array containing the predicted labels of the samples.
    verbose (bool, optional): If True, the function prints and displays the calculated metrics and
                              confusion matrix. Defaults to True.

    Returns:
    float: The calculated Matthews correlation coefficient (MCC).
    """

    # Calculate the elements of the confusion matrix
    true_positives = sum((y_true > 0) & (y_pred > 0))
    false_negatives = sum((y_true > 0) & (y_pred < 0))
    false_positives = sum((y_true < 0) & (y_pred > 0))
    true_negatives = sum((y_true < 0) & (y_pred < 0))
    total = true_positives + true_negatives + false_positives + false_negatives

    # Calculate the Matthews correlation coefficient (MCC)
    mcc_numerator = (true_positives * true_negatives) - (
        false_positives * false_negatives
    )
    mcc_denominator = np.sqrt(
        (true_positives + false_positives)
        * (true_positives + false_negatives)
        * (true_negatives + false_positives)
        * (true_negatives + false_negatives)
    )
    mcc = mcc_numerator / mcc_denominator

    if verbose:
        print(f"Matthews correlation coefficient (MCC) = {mcc:0.3f}")

        # report sensitivity and precision, and accuracy
        sensitivity = true_positives / (true_positives + false_negatives)
        precision = true_positives / (true_positives + false_positives)
        accuracy = (true_positives + true_negatives) / total

        print(f"Sensitivity = {100 * sensitivity: 0.1f}%")
        print(f"Precision = {100 * precision: 0.1f}%")
        print(f"Accuracy = {100 * accuracy: 0.1f}%")

        # Display the binary confusion matrix
        confusion_matrix = pd.DataFrame(
            [
                [true_positives, false_negatives],
                [false_positives, true_negatives],
            ],
            index=["Actual Positive", "Actual Negative"],
            columns=["Predicted Positive", "Predicted Negative"],
        )
        display(confusion_matrix)

    return mcc

# %%
def test(svm, X_test, y_test):
    y_pred = svm(X_test)
    print(svm, "\n")
    validate(y_test, y_pred)
    scatter_comparison(X_test, y_test, y_pred)


# train and test
svm = LinearSVM({"variance": 1, "skewness": 0}, 0.0)
test(svm, X_test, y_test)

# %%
def svm_factory_lp(X, y, lambd=1):
    """
    Creates a linear support vector machine (SVM) model using linear programming.

    Parameters:
    X : DataFrame
        Feature matrix as a DataFrame.
    y : Series
        Target vector as a Series.
    lambd : float, optional
        Regularization parameter. Default is 1.

    Returns:
    LinearSvm :
        A trained linear SVM model.
    """

    m = AMPL()

    m.eval(
        """
        set P;
        set N;

        param lambd;
        param X{N,P};
        param y{N};

        # Decision variables
        var wp{P} >= 0;
        var wn{P} >= 0;
        var b;
        var z{N} >= 0;
        var w{p in P} = wp[p] - wn[p];

        minimize lasso: sum{i in N} z[i] / card(N)
                            + lambd * sum{p in P} (wp[p]+wn[p]);

        subject to hingeloss{i in N}:
            z[i] >= 1-y[i]*(sum{p in P} w[p]*X[i,p] + b);

    """
    )

    # Use dataframe columns and index to index variables and constraints
    m.set["P"] = list(X.columns)
    m.set["N"] = np.array(X.index)

    m.param["lambd"] = lambd
    m.param["y"] = y

    m.param["X"] = X

    # Solve QP with the interior point method
    m.solve(solver=SOLVER_NLO, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    w = pd.Series([m.var["w"][p].value() for p in X.columns], index=X.columns)
    b = m.var["b"].value()

    return LinearSVM(w, b)


# Train and test
svm_lp = svm_factory_lp(X_train, y_train)
test(svm_lp, X_test, y_test)

# %%
def svm_factory_qp(X, y, c=1):
    """
    Creates a linear support vector machine (SVM) model using quadratic programming.

    Parameters:
    X : DataFrame
        Feature matrix as a DataFrame.
    y : Series
        Target vector as a Series.
    c : float, optional
        Regularization parameter. Default is 1.

    Returns:
    LinearSvm :
        A trained linear SVM model.
    """

    m = AMPL()

    m.eval(
        """
        set P;
        set N;

        param c;
        param X{N,P};
        param y{N};

        # Decision variables
        var b;
        var z{N} >= 0;
        var w{P};

        minimize qp: c / card(N) * sum{i in N} z[i]
                            + sum{p in P} w[p]^2;

        subject to hingeloss{i in N}:
            z[i] >= 1-y[i]*(sum{p in P} w[p]*X[i,p] + b);

    """
    )

    # Use dataframe columns and index to index variables and constraints
    m.set["P"] = list(X.columns)
    m.set["N"] = np.array(X.index)

    m.param["c"] = c
    m.param["y"] = y

    m.param["X"] = X

    # Solve QP with the interior point method
    m.solve(solver=SOLVER_NLO, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    P = m.set["P"].members()

    # Extract solution
    w = pd.Series([m.var["w"][p].value() for p in X.columns], index=X.columns)
    b = m.var["b"].value()

    return LinearSVM(w, b)


# Train and test
svm_lp = svm_factory_qp(X_train, y_train)
test(svm_lp, X_test, y_test)

# %%
def svm_factory_dual(X, y, c=1):
    """
    Creates a linear support vector machine (SVM) model using the dual formulation
    and quadratic programming.

    Parameters:
    X : DataFrame
        Feature matrix as a DataFrame.
    y : Series
        Target vector as a Series.
    c : float, optional
        Regularization parameter. Default is 1.

    Returns:
    LinearSvm :
        A trained linear SVM model.
    """

    m = AMPL()

    m.eval(
        """
        set P;
        set N;

        param y{N};
        param F{P,N};
        param C;

        # Decision variables
        var w{P};
        var a{N} >= 0 <= C;

        minimize qp: 1/2 * sum{p in P} w[p]^2 - sum{i in N} a[i];

        subject to bias:
            sum{i in N} y[i] * a[i] = 0;

        subject to projection{p in P}:
            w[p] = sum{i in N} F[p,i] * a[i];
    """
    )

    # Use dataframe columns and index to index variables and constraints
    m.set["P"] = list(X.columns)
    m.set["N"] = np.array(X.index)

    # Model parameters
    C = c / len(X.index)
    m.param["C"] = C
    m.param["y"] = y
    m.param["F"] = X.mul(y, axis=0).T

    # Solve QP with the interior point method
    m.solve(solver=SOLVER_NLO, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    P = m.set["P"].members()
    N = m.set["N"].members()

    # Extract solution
    w = pd.Series([m.var["w"][p].value() for p in X.columns], index=X.columns)
    a = pd.Series([m.var["a"][i].value() for i in X.index], index=X.index)

    # Find alpha closest to the center of [0, c/n]
    i = a.index[(a - C / 2).abs().argmin()]
    b = y.loc[i] - X.loc[i, :].dot(w)

    return LinearSVM(w, b)


# Train and test
svm_lp = svm_factory_dual(X_train, y_train)
test(svm_lp, X_test, y_test)

# %%
import pandas as pd
import numpy as np


class KernelSVM:
    """
    Kernel Support Vector Machine (SVM) class.
    """

    def __init__(self, X, y, a, b, kernel):
        """
        Initialize the Kernel SVM with weights and bias.

        :param X: numpy array or list, training data.
        :param y: numpy array or list, target labels.
        :param a: numpy array or list, alpha values for the support vectors.
        :param b: float, bias value.
        :param kernel: function, kernel function to be used in the SVM.
        """
        self.X = np.array(X)
        self.u = np.multiply(np.array(a), np.array(y))
        self.b = b
        self.kernel = kernel

    def __call__(self, Z):
        """
        Compute the decision function.

        :param Z: pandas DataFrame, test data.
        :return: pandas Series, predicted labels.
        """
        K = [
            [self.kernel(self.X[i, :], Z.loc[j, :]) for j in Z.index]
            for i in range(len(self.X))
        ]
        y_pred = np.sign((self.u @ K) + self.b)
        return pd.Series(y_pred, index=Z.index)

    def __repr__(self):
        """
        Returns:
            str: String representation of the Linear SVM
        """
        return f"KernelSvm(b = {self.b})"

# %%
def svm_factory_kernel(X, y, c=1, tol=1e-8, kernel=lambda x, z: x @ z):
    """
    Creates a linear support vector machine (SVM) model using the dual formulation
    and quadratic programming.

    Parameters:
    X : DataFrame
        Feature matrix as a DataFrame.
    y : Series
        Target vector as a Series.
    c : float, optional
        Regularization parameter. Default is 1.

    Returns:
    LinearSvm :
        A trained linear SVM model.
    """

    # Convert to numpy arrays for speed improvement
    n, p = X.shape
    X_ = X.to_numpy()
    y_ = y.to_numpy()

    # Gram matrix
    G = np.zeros((n, n))
    for i in range(n):
        for j in range(i, n):
            G[j, i] = G[i, j] = y_[i] * y_[j] * kernel(X_[i, :], X_[j, :])

    # Factor the Gram matrix
    eigvals, eigvecs = np.linalg.eigh(G)
    idx = eigvals >= tol * max(eigvals)
    F = pd.DataFrame(eigvecs[:, idx] @ np.diag(np.sqrt(eigvals[idx])), index=X.index)

    # Build model
    m = AMPL()

    m.eval(
        """
        set Q;
        set N;

        param y{N};
        param F{N,Q};
        param C;

        # Decision variables
        var u{Q};
        var a{N} >= 0 <= C;

        minimize qp: 1/2 * sum{q in Q} u[q]^2 - sum{i in N} a[i];

        subject to bias:
            sum{i in N} y[i] * a[i] = 0;

        subject to projection{q in Q}:
            u[q] = sum{i in N} F[i,q] * a[i];
    """
    )

    # Use dataframe columns and index to index variables and constraints
    m.set["Q"] = list(F.columns)
    m.set["N"] = np.array(F.index)

    # Model parameters
    C = c / len(F.index)
    m.param["C"] = C
    m.param["y"] = y
    m.param["F"] = F

    # Solve QP with the interior point method
    m.solve(solver=SOLVER_NLO, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    # Extract solution
    a = pd.Series([m.var["a"][i].value() for i in X.index], index=X.index)

    # Find b by locating a closest to the center of [0, c/n]
    j = a.index[(a - C / 2).abs().argmin()]
    b = y.loc[j] - sum(
        [a[i] * y.loc[i] * kernel(X.loc[i, :], X.loc[j, :]) for i in X.index]
    )

    # Display the support vectors
    y_support = pd.Series(
        [1 if a[i] > 1e-4 * C else -1 for i in X.index], index=X.index
    )
    scatter_labeled_data(
        X,
        y_support,
        colors=["b", "y"],
        labels=["Support Vector", ""],
        title="Support Vectors",
    )

    # Find support vectors
    SV = [i for i in X.index if a[i] > 1e-3 * C]

    return KernelSVM(X.loc[SV, :], y.loc[SV], a.loc[SV], b, kernel)

# %%
svm_kernel = svm_factory_kernel(X_train, y_train)
test(svm_kernel, X_test, y_test)

# %%
quadratic = lambda x, z: (1 + x @ z) ** 2

svm_kernel = svm_factory_kernel(X_train, y_train, kernel=quadratic)
test(svm_kernel, X_test, y_test)

# %%
cubic = lambda x, z: (1 + x @ z) ** 3

svm_kernel = svm_factory_kernel(X_train, y_train, kernel=cubic)
test(svm_kernel, X_test, y_test)
