"""
Learning a grammar of good expressions (new in eqdisco)
=======================================================

:class:`~eqdisco.GrammarCERegressor` keeps a probability table over the symbols
of an expression, conditioned on the parent symbol and the argument position.
Each iteration samples a batch of expressions, keeps only the best few percent --
the *risk-seeking* elite of deep symbolic regression (Petersen et al., 2021) --
and moves the table toward their symbol frequencies, as the cross-entropy method
does. The search distribution concentrates on the useful structure. The target is
Nguyen-10, :math:`2\\sin x\\cos y`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

prob = eq.datasets.get_problem("nguyen-10")

# %%
# Learning curve
# --------------
gce = eq.GrammarCERegressor(functions=("add", "sub", "mul", "sin", "cos"), n_iterations=40, batch_size=300, elite_fraction=0.05, random_state=0, feature_names=["x", "y"])
gce.fit(prob.X_train, prob.y_train)
print(gce.equation_)
root = gce.probabilities_[(-1, 0)]
print("root symbol probabilities:", {k: round(p, 2) for k, p in sorted(root.items(), key=lambda kv: -kv[1])[:4]})
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
h = gce.history_
axs[0].plot(h["iteration"], h["best_reward"], color="#285780", lw=2, label="best reward")
axs[0].plot(h["iteration"], h["elite_reward"], color="#285780", lw=1, ls="--", label="mean elite reward")
ax2 = axs[0].twinx()
ax2.plot(h["iteration"], h["entropy"], color="#D55E00", lw=1.2)
ax2.set_ylabel("mean entropy of the table", color="#D55E00")
axs[0].set_xlabel("iteration")
axs[0].set_ylabel("reward 1/(1+NRMSE)")
axs[0].legend(frameon=False, fontsize=8, loc="lower right")
syms = sorted(root, key=lambda k: -root[k])
axs[1].bar(syms, [root[s] for s in syms], color="#285780")
axs[1].set_ylabel("probability at the root")
fig.tight_layout()

# %%
# Parameter study: how risk-seeking?
# ----------------------------------
fracs = [0.01, 0.05, 0.2, 0.5]
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, f in enumerate(fracs):
    H = np.mean([eq.GrammarCERegressor(functions=("add", "sub", "mul", "sin", "cos"), n_iterations=25, batch_size=200, elite_fraction=f, random_state=s).fit(prob.X_train, prob.y_train).history_["best_reward"] for s in range(3)], axis=0)
    print(f"elite {int(100 * f)} %: mean best reward at iteration 25: {H[-1]:.3f}")
    ax.plot(H, color=eq.viz.OKABE_ITO[k], label=f"elite {int(100 * f)} %")
ax.set_xlabel("iteration")
ax.set_ylabel("mean best reward (3 runs)")
ax.legend(frameon=False, fontsize=8)
plt.show()
