"""
Physical units: dimensional consistency and Buckingham groups
=============================================================

A formula that adds metres to seconds is wrong however well it fits. With
``units=`` the search penalizes dimensional inconsistencies (Keijzer and Babovic,
1999): sums of quantities with different units, transcendental functions of
dimensional arguments, and an output unit different from the target's. Fitted
constants may carry any unit, as :math:`g` or :math:`k_B` do. The second part
uses the Buckingham :math:`\\Pi` theorem to reduce the period of a pendulum to one
dimensionless group before any search, the first step of AI Feynman (Udrescu and
Tegmark, 2020).
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.knowledge import buckingham_pi, check_units, dimensionless_features

prob = eq.datasets.get_problem("feynman-I.27.6", noise=0.05, n_train=60)  # thin lens: 1 / (1/d1 + n/d2)
print(prob.truth, prob.units)

# %%
# Search with and without units
# -----------------------------
res = {}
for use in (False, True):
    res[use] = [
        eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "square"), units=prob.units if use else None,
                             feature_names=prob.feature_names, random_state=s).fit(prob.X_train, prob.y_train)
        for s in range(5)
    ]
for use, rr in res.items():
    ok = [check_units(r.equation_, prob.units)["consistent"] for r in rr]
    print("units" if use else "no units", "consistent:", sum(ok), "of", len(ok), "| e.g.", rr[0].equation_)
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for k, (use, rr) in enumerate(res.items()):
    r2 = [r.equation_.score(prob.X_test, prob.y_test) for r in rr]
    cons = [check_units(r.equation_, prob.units)["consistent"] for r in rr]
    axs[0].scatter([e.equation_.complexity for e in rr], 1 - np.array(r2), color=eq.viz.OKABE_ITO[k], s=40, marker="o", label="with units" if use else "without units")
    for r, c in zip(rr, cons):
        if c:
            axs[0].scatter([r.equation_.complexity], [1 - r.equation_.score(prob.X_test, prob.y_test)], s=110, facecolor="none", edgecolor="#009E73", lw=1.5)
axs[0].set_yscale("log")
axs[0].set_xlabel("model size")
axs[0].set_ylabel("$1-R^2$ (test); green ring: consistent")
axs[0].legend(frameon=False, fontsize=8)

# %%
# Buckingham groups: the pendulum
# -------------------------------
units = {"T": "s", "l": "m", "g": "m/s^2", "m": "kg"}
groups = buckingham_pi(units, target="T")
print(groups)  # [{'T': 1, 'l': -0.5, 'g': 0.5}]: T * sqrt(g/l) is dimensionless, the mass drops out
rng = np.random.default_rng(0)
l, g, m = rng.uniform(0.2, 2, 100), rng.uniform(1, 25, 100), rng.uniform(0.1, 5, 100)
T = 2 * np.pi * np.sqrt(l / g)
P, _ = dimensionless_features(np.column_stack([T, l, g]), ["T", "l", "g"], groups)
axs[1].scatter(l / g, T, s=10, color="#6B7785", label="T against l/g")
axs[1].set_xlabel("l / g (s$^2$)")
axs[1].set_ylabel("period T (s)")
axs[1].set_title(f"$\\Pi = T\\sqrt{{g/l}}$ = {P.mean():.4f} for every pendulum ($2\\pi$ = {2 * np.pi:.4f})", fontsize=9)
fig.tight_layout()

# %%
# Parameter study: the weight of the unit penalty
# -----------------------------------------------
weights = [0.0, 0.1, 1.0, 10.0]
share = []
for w in weights:
    rr = [eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "square"), units=prob.units, constraint_weight=w, feature_names=prob.feature_names, random_state=s).fit(prob.X_train, prob.y_train) for s in range(4)]
    share.append(np.mean([check_units(r.equation_, prob.units)["consistent"] for r in rr]))
print("unit weight", weights, "share of unit-consistent models", share)
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(weights, share, "o-", color="#285780")
ax.set_xscale("symlog", linthresh=0.1)
ax.set_xlabel("weight of the unit penalty")
ax.set_ylabel("share of consistent models")
plt.show()
