# 出典: mo-notebooks/02/lad-regression.ipynb

# %%
# install dependencies and select solver
#%pip install -q amplpy numpy matplotlib scikit-learn ipywidgets

SOLVER = "highs"

from amplpy import AMPL, ampl_notebook

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

# %%
from sklearn.datasets import make_regression
import numpy as np

n_features = 1
n_samples = 1000
noise = 30

# generate regression dataset
np.random.seed(2020)
X, y = make_regression(n_samples=n_samples, n_features=n_features, noise=noise)

# %%
import matplotlib.pyplot as plt

if n_features == 1:
    plt.scatter(X, y, alpha=0.3)
    plt.xlabel("X")
    plt.ylabel("y")
    plt.grid(True)

plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))))
plt.title("histogram y - mean(y)")
plt.ylabel("counts")

# %%
def lad_regression(X, y):
    ampl = AMPL()
    ampl.read("lad_regression.mod")

    n, k = X.shape
    
    # note use of Python style zero based indexing
    ampl.set["I"] = range(n)
    ampl.set["J"] = range(k)

    ampl.param["y"] = y
    ampl.param["X"] = X

    ampl.solve(solver=SOLVER)
    assert ampl.solve_result == "solved", ampl.solve_result

    return ampl


m = lad_regression(X, y)
m.display("m")
m.display("b")

# %%
m_m = list(m.var["m"].to_dict().values())
m_b = m.var["b"].value()

y_fit = np.array([sum(x[j] * v for j, v in enumerate(m_m)) + m_b for x in X])

if n_features == 1:
    plt.scatter(X, y, alpha=0.3, label="data")
    plt.plot(X, y_fit, "r", label="y_fit")
    plt.xlabel("X")
    plt.ylabel("y")
    plt.grid(True)
    plt.legend()

plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))), alpha=0.5, label="y - mean(y)")
plt.hist(y - y_fit, bins=int(np.sqrt(len(y))), color="r", alpha=0.8, label="y - y_fit")
plt.title("histogram of residuals")
plt.ylabel("counts")
plt.legend()
