"""
A small benchmark of methods
============================

:func:`~eqdisco.benchmarks.run_benchmark` runs several estimators on several
problems with repeated seeds and records test accuracy, model size, time and the
recovery of the ground truth by the criterion of SRBench (La Cava et al., 2021).
The budgets here are small so that the example runs in a minute; the same call
with larger budgets and more problems reproduces a proper comparison.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.benchmarks import run_benchmark, summarize

# %%
# Five methods, six problems
# --------------------------
methods = {
    "GP": eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "sin", "cos", "exp", "log")),
    "GP + LM": eq.SymbolicRegressor(population_size=200, generations=20, optimize="lm", functions=("add", "sub", "mul", "div", "sin", "cos", "exp", "log")),
    "MGGP": eq.MultiGeneRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "sin", "cos")),
    "FFX": eq.FFXRegressor(),
    "STLSQ": eq.SparseRegressor(degree=4, functions=("sin", "cos", "exp", "log")),
}
problems = ["nguyen-1", "nguyen-5", "nguyen-7", "keijzer-11", "keijzer-14", "feynman-I.12.2"]
results = run_benchmark(methods, problems, n_runs=2)
print(summarize(results).round(3))
fig, axs = plt.subplots(1, 2, figsize=(10, 3.6))
r = results.copy()
r["1-r2"] = (1 - r["r2_test"]).clip(lower=1e-12)
eq.viz.plot_benchmark(r, metric="1-r2", ax=axs[0])
axs[0].set_yscale("log")
axs[0].set_ylabel("$1-R^2$ on test data")
s = summarize(results)
order = list(dict.fromkeys(results["method"]))  # same colours as the box plots
colour = {m: eq.viz.OKABE_ITO[k % len(eq.viz.OKABE_ITO)] for k, m in enumerate(order)}
axs[1].scatter(s["median_size"], s["solution_rate"], s=60, color=[colour[m] for m in s.index])
for k, (name, row) in enumerate(s.sort_values("median_size").iterrows()):
    axs[1].annotate(name, (row["median_size"], row["solution_rate"]), xytext=(6, 6 if k % 2 else -12), textcoords="offset points", fontsize=8)
axs[1].set_xlabel("median model size")
axs[1].set_ylabel("share of exact recoveries")
fig.tight_layout()

# %%
# Parameter study: noise
# ----------------------
fig, ax = plt.subplots(figsize=(4.8, 3.2))
for k, name in enumerate(("GP", "FFX")):
    med = []
    for nz in (0.0, 0.01, 0.1):
        rr = run_benchmark({name: methods[name]}, ["nguyen-7", "keijzer-11"], n_runs=1, noise=nz)
        med.append(rr["r2_test"].median())
    print(name, "median test R2 by noise (0, 0.01, 0.1):", np.round(med, 4).tolist())
    ax.plot([0, 0.01, 0.1], med, "o-", color=eq.viz.OKABE_ITO[k], label=name)
ax.set_xscale("symlog", linthresh=0.01)
ax.set_xlabel("noise level (training data)")
ax.set_ylabel("median test $R^2$")
ax.legend(frameon=False, fontsize=8)
plt.show()
