"""
A first search: Kepler's third law from the planets
===================================================

The eight planets of the solar system give eight pairs of semi-major axis
:math:`a` (astronomical units) and orbital period :math:`T` (years). Johannes
Kepler found in 1619 that :math:`T^2\\propto a^3`. Can genetic programming
rediscover the law from the eight data points? :class:`~eqdisco.SymbolicRegressor`
searches over expressions built from :math:`a`, a few functions and constants,
and returns a Pareto front of models of increasing complexity.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.viz import plot_pareto, plot_tree

# %%
# Data and search
# ---------------
planets = eq.datasets.load_kepler()
X, T = planets[["a"]], planets["T"].to_numpy()
sr = eq.SymbolicRegressor(population_size=300, generations=25, functions=("add", "sub", "mul", "div", "sqrt"), random_state=0)
sr.fit(X, T)
print(sr.equation_)  # about 1.0 * a * sqrt(a), i.e. T = a^1.5
for e in sr.pareto_front_:
    print(f"{e.complexity:3d}  R2 = {e.metrics['r2']:.6f}  {e}")
# %%
# The law, the front and the tree
# -------------------------------
fig, axs = plt.subplots(1, 3, figsize=(12, 3.4))
a = np.linspace(0.3, 32, 300).reshape(-1, 1)
axs[0].loglog(planets["a"], T, "o", color="#6B7785", label="planets")
for name, (ai, ti) in planets.iterrows():
    axs[0].annotate(name, (ai, ti), xytext=(4, -9), textcoords="offset points", fontsize=7)
axs[0].loglog(a, sr.predict(a), color="#285780", lw=1.5, label=f"T = {sr.equation_}")
axs[0].set_xlabel("semi-major axis a (AU)")
axs[0].set_ylabel("period T (years)")
axs[0].legend(frameon=False, fontsize=7, loc="upper left")
plot_pareto(sr, ax=axs[1], annotate=True, max_labels=4)
plot_tree(sr.equation_, ax=axs[2])
fig.tight_layout()

# %%
# Parameter study: how often is the law found?
# --------------------------------------------
# Genetic programming is stochastic. Ten runs with different seeds and two
# population sizes show how the chance of finding the exact law depends on the
# search effort.
found = {}
for mu in (50, 300):
    hits = 0
    for seed in range(10):
        m = eq.SymbolicRegressor(population_size=mu, generations=25, functions=("add", "sub", "mul", "div", "sqrt"), random_state=seed).fit(X, T)
        # equivalent to a^1.5 up to the linear scaling a + b*f fitted to the data
        hits += eq.benchmarks.is_symbolic_solution(m.equation_, "a^(3/2)", affine=True)
    found[mu] = hits
print("runs (out of 10) that found T = a^1.5:", found)
fig, ax = plt.subplots(figsize=(3.5, 2.8))
ax.bar([str(k) for k in found], list(found.values()), color="#285780")
ax.set_xlabel("population size")
ax.set_ylabel("runs finding the law (of 10)")
plt.show()
