Note
Go to the end to download the full example code or to run this example in your browser via Binder.
A first search: Kepler’s third law from the planets#
The eight planets of the solar system give eight pairs of semi-major axis
\(a\) (astronomical units) and orbital period \(T\) (years). Johannes
Kepler found in 1619 that \(T^2\propto a^3\). Can genetic programming
rediscover the law from the eight data points? SymbolicRegressor
searches over expressions built from \(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}")
0.003055 + 0.9994 * sqrt(a) * a
5 R2 = 0.976376 -8.794 + 5.385 * a
7 R2 = 0.987532 4.803 + 0.1832 * a * a
8 R2 = 1.000000 0.003055 + 0.9994 * sqrt(a) * a
27 R2 = 1.000000 0.003568 + 1.069 * sqrt(a + sqrt(-3.616e+09 * (a - (a * a + a - a * a)))) * 3.39 * a / 3.626
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()

runs (out of 10) that found T = a^1.5: {50: 10, 300: 9}
Total running time of the script: (0 minutes 12.302 seconds)