"""
Model families: how many different models do the data support? (new in eqdisco)
================================================================================

The models of a Pareto front, of an ensemble or of repeated runs often compute
nearly the same function in different forms. Grouping them by their predictions
(:func:`~eqdisco.analysis.model_families`) shows how many genuinely different
explanations remain. With noisy data from Nguyen-5, :math:`\\sin(x^2)\\cos x-1`,
on a narrow range, several families fit equally well inside the data but differ
outside -- a warning against over-interpreting one of them.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.analysis import model_families

rng = np.random.default_rng(0)
x = rng.uniform(-1, 1, 60)
y = np.sin(x**2) * np.cos(x) - 1 + 0.02 * rng.normal(size=60)
X = x.reshape(-1, 1)

# %%
# Models of ten runs
# ------------------
models = []
for s in range(10):
    sr = eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "sin", "cos", "exp"), random_state=s).fit(X, y)
    models += [e for e in sr.pareto_front_ if e.metrics["r2"] > 0.9]
labels, table, Z = model_families(models, X, y, threshold=0.05)
print(len(models), "models,", len(table), "families")
print(table.head(6).to_string())
eq.viz.plot_families(models, X, y, threshold=0.05)
fig, ax = plt.subplots(figsize=(6, 3.4))
xs = np.linspace(-2, 2, 300).reshape(-1, 1)
ax.axvspan(-1, 1, color="#E3E7EB", label="range of the data")
ax.scatter(x, y, s=8, color="#6B7785")
for k, r in table.head(4).iterrows():
    e = models[int(r["rep_index"])]
    ax.plot(xs, e.predict(xs), color=eq.viz.OKABE_ITO[k], lw=1.5, label=f"family {k}: {str(e)[:30]}")
ax.set_ylim(-3, 1)
ax.set_xlabel("x")
ax.legend(frameon=False, fontsize=7)

# %%
# Parameter study: the distance threshold
# ---------------------------------------
ths = [0.01, 0.02, 0.05, 0.1, 0.2]
print("threshold", ths, "families", [len(model_families(models, X, y, threshold=t)[1]) for t in ths])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(ths, [len(model_families(models, X, y, threshold=t)[1]) for t in ths], "o-", color="#285780")
ax.set_xscale("log")
ax.set_xlabel("distance threshold")
ax.set_ylabel("number of families")
plt.show()
