"""
Fast Function Extraction (FFX)
==============================

FFX (McConaghy, 2011) avoids evolution altogether: it generates thousands of
basis functions -- powers, absolute values, logarithms, hinge functions and their
pairwise products -- and runs the elastic-net regularization path. Every point of
the path is a model with a different number of bases; the non-dominated ones form
a front of accuracy versus size, computed in a fraction of a second. The test
problem is Vladislavleva-1, a ratio of a Gaussian bump and a quadratic.
"""

import matplotlib.pyplot as plt

import eqdisco as eq

prob = eq.datasets.get_problem("vladislavleva-1")

# %%
# The FFX front
# -------------
ffx = eq.FFXRegressor(n_knots=3, max_bases=15).fit(prob.X_train, prob.y_train)
print(len(ffx.bases_), "candidate bases;", len(ffx.pareto_front_), "models on the front")
print(ffx.equation_)
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
nb = [e.meta["n_bases"] for e in ffx.pareto_front_]
tr = [1 - e.score(prob.X_train, prob.y_train) for e in ffx.pareto_front_]
te = [1 - e.score(prob.X_test, prob.y_test) for e in ffx.pareto_front_]
print("test 1-R2 of the model with the most bases:", f"{te[-1]:.4f}", "| best test 1-R2 on the front:", f"{min(te):.4f}", "with", nb[te.index(min(te))], "bases")
axs[0].step(nb, tr, where="post", color="#285780", label="train")
axs[0].step(nb, te, where="post", color="#009E73", label="test")
axs[0].set_yscale("log")
axs[0].set_xlabel("number of bases")
axs[0].set_ylabel("$1-R^2$")
axs[0].legend(frameon=False, fontsize=8)
eq.viz.plot_parity(prob.y_test, ffx.predict(prob.X_test), ax=axs[1], label="test")
fig.tight_layout()

# %%
# Parameter study: interactions and hinge knots
# ---------------------------------------------
settings = {"univariate": dict(interactions=False, n_knots=0), "+ hinges": dict(interactions=False, n_knots=3), "+ interactions": dict(interactions=True, n_knots=0), "all": dict(interactions=True, n_knots=3)}
fig, ax = plt.subplots(figsize=(4.8, 3.2))
for k, (name, kw) in enumerate(settings.items()):
    f = eq.FFXRegressor(max_bases=15, **kw).fit(prob.X_train, prob.y_train)
    print(f"{name:15s} best test 1-R2 per setting: {min(1 - e.score(prob.X_test, prob.y_test) for e in f.pareto_front_):.4f}")
    ax.step([e.meta["n_bases"] for e in f.pareto_front_], [1 - e.score(prob.X_test, prob.y_test) for e in f.pareto_front_], where="post", color=eq.viz.OKABE_ITO[k], label=name)
ax.set_yscale("log")
ax.set_xlabel("number of bases")
ax.set_ylabel("$1-R^2$ (test)")
ax.legend(frameon=False, fontsize=8)
plt.show()
