"""
Exhaustive search with a description length
===========================================

For small formulas the whole space can be searched. :class:`~eqdisco.ExhaustiveRegressor`
enumerates every canonical expression up to a given size, fits its parameters,
removes functions that compute the same values, and ranks the rest by a
description length -- the cost of the data given the model plus the cost of the
model -- following the minimum description length approach of exhaustive
symbolic regression (Bartlett, Desmond and Ferreira, 2024). The data are the
energy of a spring, :math:`E=\\tfrac12 kx^2`, with 1 % noise.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

prob = eq.datasets.get_problem("feynman-I.14.4", noise=0.01, n_train=100)

# %%
# Enumeration and ranking
# -----------------------
ex = eq.ExhaustiveRegressor(functions=("add", "sub", "mul", "div", "square"), max_size=6, max_params=2, feature_names=prob.feature_names)
ex.fit(prob.X_train, prob.y_train)
print(ex.n_candidates_, "expressions,", len(ex.results_), "distinct functions")
print(ex.results_.head(6)[["equation", "size", "n_params", "mse", "bic", "mdl"]])
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
r = ex.results_
axs[0].scatter(r["size"] + np.random.default_rng(0).uniform(-0.2, 0.2, len(r)), r["mdl"], s=8, color="#6B7785", alpha=0.5)
best = r.iloc[0]
axs[0].scatter([best["size"]], [best["mdl"]], s=80, facecolor="none", edgecolor="#D55E00", lw=2, label=f"best: {best['equation']}")
axs[0].set_xlabel("size (nodes)")
axs[0].set_ylabel("description length (nats)")
axs[0].legend(frameon=False, fontsize=8)
top = r.head(10).iloc[::-1]
axs[1].barh(top["equation"], top["mdl"] - r["mdl"].min() + 1, color="#285780")
axs[1].set_xscale("log")
axs[1].set_xlabel("description length above the best (+1)")
axs[1].tick_params(axis="y", labelsize=7)
fig.tight_layout()

# %%
# Parameter study: size limit and cost
# ------------------------------------
import time  # noqa: E402

sizes, counts, times = [3, 4, 5, 6], [], []
for s in sizes:
    t0 = time.perf_counter()
    m = eq.ExhaustiveRegressor(functions=("add", "sub", "mul", "div", "square"), max_size=s, max_params=2).fit(prob.X_train, prob.y_train)
    counts.append(m.n_candidates_)
    times.append(time.perf_counter() - t0)
print("max size", sizes, "candidates", counts, "seconds", np.round(times, 2).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.semilogy(sizes, counts, "o-", color="#285780", label="candidates")
ax.semilogy(sizes, times, "s--", color="#D55E00", label="seconds")
ax.set_xlabel("maximum size")
ax.legend(frameon=False, fontsize=8)
plt.show()
