"""
Linear scaling: let regression handle offset and scale
======================================================

A target such as :math:`y = 120 + 35\\,x_0 x_1` has the shape of
:math:`x_0 x_1`, but genetic programming has to build the constants 120 and 35
from random leaves before an otherwise perfect shape scores well. Keijzer (2003)
proposed to evaluate every candidate :math:`f` as :math:`a + b f` with the
least-squares :math:`a` and :math:`b`, which cost one pass over the data. The
search then rewards shapes, not constants. This example compares ten runs with
and without linear scaling.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, (200, 2))
y = 120 + 35 * X[:, 0] * X[:, 1] + 3 * np.sin(3 * X[:, 0])

# %%
# Ten runs with and without scaling
# ---------------------------------
hist = {True: [], False: []}
for scaling in (True, False):
    for seed in range(10):
        sr = eq.SymbolicRegressor(population_size=200, generations=20, linear_scaling=scaling, functions=("add", "sub", "mul", "sin"), random_state=seed)
        sr.fit(X, y)
        hist[scaling].append(sr.history_["best_loss"].to_numpy() / np.var(y))
print({("with" if s else "without") + " scaling": f"median final NMSE {np.median(np.array(hist[s])[:, -1]):.2e}" for s in (True, False)})
fig, ax = plt.subplots(figsize=(5.5, 3.4))
for scaling, color in ((True, "#285780"), (False, "#D55E00")):
    H = np.array(hist[scaling])
    for h in H:
        ax.semilogy(h, color=color, lw=0.6, alpha=0.35)
    ax.semilogy(np.median(H, 0), color=color, lw=2.2, label=("with" if scaling else "without") + " linear scaling (median)")
ax.set_xlabel("generation")
ax.set_ylabel("normalized MSE of the best model")
ax.legend(frameon=False, fontsize=8)

# %%
# Parameter study: the size of the offset
# ---------------------------------------
# Without scaling, the larger the offset the harder the problem; with scaling it
# does not matter at all.
offsets = [0, 10, 100, 1000]
res = {True: [], False: []}
for c in offsets:
    yc = c + 35 * X[:, 0] * X[:, 1] + 3 * np.sin(3 * X[:, 0])
    for scaling in (True, False):
        r2s = [eq.SymbolicRegressor(population_size=150, generations=15, linear_scaling=scaling, functions=("add", "sub", "mul", "sin"), random_state=s).fit(X, yc).score(X, yc) for s in range(4)]
        res[scaling].append(np.median(r2s))
print("median R2 by offset", offsets, {("with" if s else "without"): np.round(res[s], 3).tolist() for s in (True, False)})
fig, ax = plt.subplots(figsize=(4.5, 3))
for scaling, color in ((True, "#285780"), (False, "#D55E00")):
    ax.plot(offsets[1:], res[scaling][1:], "o-", color=color, label="with scaling" if scaling else "without scaling")
ax.set_xscale("log")
ax.set_xlabel("offset of the target")
ax.set_ylabel("median $R^2$ (4 runs)")
ax.legend(frameon=False, fontsize=8)
plt.show()
