"""
Bayesian sampling of model structures
=====================================

How certain is a discovered law? :class:`~eqdisco.BayesianSymbolicRegressor`
samples expressions by Metropolis moves with parallel tempering. The energy is
half the Bayesian information criterion plus a prior that charges every
operation, so that :math:`e^{-E}` approximates the posterior probability of a
structure -- the idea of the Bayesian machine scientist (Guimerà et al., 2020).
The posterior is estimated over the visited structures from their energies. The data: twenty noisy rates of an enzyme reaction obeying
Michaelis--Menten kinetics, :math:`v=V_{\\max}S/(K_m+S)`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(6)
S = np.sort(rng.uniform(0.05, 5, 20))
v = 2.0 * S / (0.6 + S) * (1 + 0.03 * rng.normal(size=20))
X = S.reshape(-1, 1)

# %%
# Sampling
# --------
bms = eq.BayesianSymbolicRegressor(functions=("add", "sub", "mul", "div", "exp", "log"), n_steps=2500, temperatures=(1.0, 1.6, 2.6, 4.2), feature_names=["S"], random_state=0)
bms.fit(X, v)
print(bms.posterior_.head(6)[["equation", "posterior", "share", "energy", "size"]])
print("MAP model:", bms.equation_, "| acceptance:", np.round(bms.acceptance_, 2))
fig, axs = plt.subplots(1, 3, figsize=(13, 3.4), gridspec_kw={"width_ratios": [1, 1.4, 1]})
axs[0].plot(bms.trace_["energy"], color="#285780", lw=0.7)
axs[0].set_xlabel("step")
axs[0].set_ylabel("energy of the T = 1 chain")
eq.viz.plot_posterior(bms.posterior_, top=8, ax=axs[1])
s = np.linspace(0, 5, 200).reshape(-1, 1)
axs[2].scatter(S, v, color="#6B7785", s=15, label="data")
for k in range(3):
    e = bms.posterior_.iloc[k]
    f = bms._eq(e["expression"])
    axs[2].plot(s, f.predict(s), color=eq.viz.OKABE_ITO[k], lw=1.4, label=f"{e['posterior']:.2f}: {e['equation'][:22]}")
axs[2].set_xlabel("substrate S")
axs[2].set_ylabel("rate v")
axs[2].legend(frameon=False, fontsize=6.5)
fig.tight_layout()

# %%
# Parameter study: the prior penalty per operation
# ------------------------------------------------
pens = [0.0, 1.0, 3.0]
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, p in enumerate(pens):
    b = eq.BayesianSymbolicRegressor(functions=("add", "sub", "mul", "div", "exp", "log"), n_steps=1200, prior_penalty=p, random_state=0).fit(X, v)
    by_size = b.posterior_.groupby("size")["posterior"].sum()
    print(f"penalty {p}: posterior mass by size", {int(k): round(float(v), 3) for k, v in by_size.items() if v > 0.01})
    ax.plot(by_size.index, by_size.to_numpy(), "o-", color=eq.viz.OKABE_ITO[k], ms=3, label=f"penalty {p}")
ax.set_xlabel("size of the structures")
ax.set_ylabel("posterior probability")
ax.legend(frameon=False, fontsize=8)
plt.show()
