"""
Validation and uncertainty of a discovered law
==============================================

A discovered equation is a nonlinear regression model and can be checked like
one. This example fits the Arrhenius law to noisy rate constants, inspects the
residuals (normality, autocorrelation, heteroscedasticity), and computes Wald,
profile-likelihood and bootstrap intervals of the parameters (Bates and Watts,
1988) and the prediction band of the model.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.analysis import confidence_intervals, prediction_intervals, residual_diagnostics

rng = np.random.default_rng(4)
T = np.sort(rng.uniform(300, 420, 40))
k = 3.0e6 * np.exp(-6000 / T) * (1 + 0.06 * rng.normal(size=40))
X = T.reshape(-1, 1)

# %%
# Fitting the structure and checking the residuals
# ------------------------------------------------
arr = eq.Equation.from_string("1e6*exp(-5000/T)", feature_names=["T"]).refit(X, k, restarts=5, random_state=0)
print(arr)
diag = residual_diagnostics(k, arr.predict(X), order=T)
print({key: round(v, 3) for key, v in diag.items()})
# %%
# Parameter intervals and the prediction band
# -------------------------------------------
for method in ("wald", "profile", "bootstrap"):
    print(method)
    print(confidence_intervals(arr, X, k, method=method, n_boot=200).round(3))
yhat, lo, hi = prediction_intervals(arr, X, k, X, kind="prediction")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
eq.viz.plot_prediction_band(T, k, yhat, lo, hi, ax=axs[0], label="95 % prediction band")
axs[0].set_xlabel("T (K)")
axs[0].set_ylabel("rate constant k")
cis = {m: confidence_intervals(arr, X, k, method=m, n_boot=200) for m in ("wald", "profile", "bootstrap")}
names = ["$k_0$", "$E/R$"]
for j in range(len(names)):
    for i, (m, ci) in enumerate(cis.items()):
        v, lo_, hi_ = ci.loc[j, "value"], ci.loc[j, "lower"], ci.loc[j, "upper"]
        axs[1].errorbar([i + 4 * j], [v / abs(v)], yerr=[[(v - lo_) / abs(v)], [(hi_ - v) / abs(v)]], fmt="o", color=eq.viz.OKABE_ITO[i], capsize=4, label=m if j == 0 else None)
axs[1].set_xticks([1, 5])
axs[1].set_xticklabels(names)
axs[1].set_ylabel("interval / estimate")
axs[1].legend(frameon=False, fontsize=8)
fig.tight_layout()
eq.viz.plot_residuals(k, arr.predict(X))

# %%
# Parameter study: sample size and interval width
# -----------------------------------------------
ns = [10, 20, 40, 80, 160]
width = []
for n in ns:
    Tn = np.sort(rng.uniform(300, 420, n))
    kn = 3.0e6 * np.exp(-6000 / Tn) * (1 + 0.06 * rng.normal(size=n))
    an = arr.refit(Tn.reshape(-1, 1), kn)
    ci = confidence_intervals(an, Tn.reshape(-1, 1), kn, method="profile")
    width.append(float((ci.upper - ci.lower).iloc[1]))
print("samples", ns, "profile interval width of E/R", np.round(width, 1).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.loglog(ns, width, "o-", color="#285780", label="profile interval of E/R")
ax.loglog(ns, width[0] * np.sqrt(ns[0] / np.array(ns)), color="#6B7785", ls="--", label="$1/\\sqrt{N}$")
ax.set_xlabel("number of measurements")
ax.set_ylabel("interval width")
ax.legend(frameon=False, fontsize=8)
plt.show()
