"""
Simplification of evolved models
================================

Evolved expressions carry introns and redundant parameters. The simplification
pipeline (:func:`eqdisco.simplify.simplify`) folds constant subtrees, rewrites
identities, merges parameters of addition and multiplication chains (a rule-based
form of the parameter reduction of de França and Kronberger, 2023), optionally
calls SymPy, refits and rounds the coefficients. The function is unchanged except
for the final rounding, which is checked against a tolerance on the error.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.optimize import jacobian_rank
from eqdisco.simplify import apply_rules, simplify

prob = eq.datasets.get_problem("keijzer-12", noise=0.01)
sr = eq.SymbolicRegressor(population_size=300, generations=25, functions=("add", "sub", "mul", "div"), max_size=80, random_state=0).fit(prob.X_train, prob.y_train)

# %%
# One model before and after
# --------------------------
raw = max(sr.pareto_front_, key=lambda e: e.complexity)
clean = simplify(raw, prob.X_train, prob.y_train, sympy=True, refit=True, round_digits=True)
print("before:", raw.complexity, "nodes,", raw.n_params, "parameters (rank", jacobian_rank(raw.expr, prob.X_train), ")")
print("   ", raw)
print("after: ", clean.complexity, "nodes,", clean.n_params, "parameters")
print("   ", clean)
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
pop = sr.population_[:120]
before = np.array([e.complexity for e in pop])
after = np.array([apply_rules(e).complexity for e in pop])
axs[0].scatter(before, after, s=12, color="#285780", alpha=0.6)
axs[0].plot([0, before.max()], [0, before.max()], color="#6B7785", ls="--", lw=1)
axs[0].set_xlabel("size before (nodes)")
axs[0].set_ylabel("size after rules (nodes)")
axs[0].set_title(f"population: mean reduction {100 * (1 - after.sum() / before.sum()):.0f} %", fontsize=9)
p_before = np.array([e.n_params for e in pop])
p_rank = np.array([jacobian_rank(e.expr, prob.X_train) for e in pop])
axs[1].scatter(p_before + np.random.default_rng(0).uniform(-0.2, 0.2, len(pop)), p_rank, s=12, color="#D55E00", alpha=0.6)
axs[1].plot([0, p_before.max()], [0, p_before.max()], color="#6B7785", ls="--", lw=1)
axs[1].set_xlabel("parameters in the expression")
print(f"population: mean size before {before.mean():.1f}, after {after.mean():.1f}; parameters {p_before.sum()}, identifiable {p_rank.sum()}")
axs[1].set_ylabel("rank of the Jacobian (identifiable)")
fig.tight_layout()

# %%
# Parameter study: rounding tolerance
# -----------------------------------
from eqdisco.simplify import round_coefficients  # noqa: E402

unrounded = simplify(raw, prob.X_train, prob.y_train, sympy=True, refit=True)
tols = [0.0, 0.001, 0.01, 0.1]
digits = []
for t in tols:
    r = round_coefficients(unrounded, prob.X_train, prob.y_train, tolerance=t)
    digits.append(np.mean([len(f"{abs(v):g}".replace(".", "").lstrip("0")) for v in r.theta]))
print("tolerance", tols, "mean significant digits", np.round(digits, 2).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(tols, digits, "o-", color="#285780")
ax.set_xscale("symlog", linthresh=1e-3)
ax.set_xlabel("allowed relative increase of the MSE")
ax.set_ylabel("mean significant digits")
plt.show()
