"""
Sensitivity analysis of a discovered model
==========================================

An explicit formula can be probed exactly. On the Friedman-1 benchmark,
:math:`10\\sin(\\pi x_0x_1)+20(x_2-0.5)^2+10x_3+5x_4` plus five irrelevant
inputs, a multi-gene model is identified and analysed: partial dependence curves,
derivative-based sensitivities, and variance-based Sobol indices (Saltelli et
al., 2010; Jansen, 1999), whose gap between total and first-order index reveals
the interaction of :math:`x_0` and :math:`x_1`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.analysis import local_sensitivity, partial_derivatives, sobol_indices

prob = eq.datasets.get_problem("friedman-1", n_train=400)

# %%
# The model and its sensitivities
# -------------------------------
model = eq.MultiGeneRegressor(population_size=300, generations=40, max_genes=5, functions=("add", "sub", "mul", "sin", "square"), random_state=0)
model.fit(prob.X_train, prob.y_train)
eqn = model.equation_
print(eqn, "| test R2", round(eqn.score(prob.X_test, prob.y_test), 4))
print(partial_derivatives(eqn).get("x3"))
S = sobol_indices(eqn, bounds=[(0, 1)] * 10, n=8192)
print(S.round(3))
fig, axs = plt.subplots(1, 2, figsize=(10, 3.6))
eq.viz.plot_sobol(S, ax=axs[0])
eq.viz.plot_sensitivity(local_sensitivity(eqn, prob.X_test), ax=axs[1])
fig.tight_layout()
eq.viz.plot_partial_dependence(eqn, prob.X_test, features=["x0", "x1", "x2", "x3", "x4", "x5"], ncols=3)

# %%
# Parameter study: sample size of the Sobol estimate
# --------------------------------------------------
ns = [256, 1024, 4096, 16384]
est = np.array([sobol_indices(eqn, bounds=[(0, 1)] * 10, n=n, random_state=s).set_index("variable").loc["x0", "ST"] for n in ns for s in range(5)]).reshape(len(ns), 5)
print("n", ns, "ST of x0: mean", np.round(est.mean(1), 3).tolist(), "sd", np.round(est.std(1), 3).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.errorbar(ns, est.mean(1), yerr=est.std(1), fmt="o-", color="#285780", capsize=4)
ax.set_xscale("log")
ax.set_xlabel("base sample size n")
ax.set_ylabel("total index of $x_0$ (mean ± sd, 5 seeds)")
plt.show()
