"""
Separability and symmetries detected from data
==============================================

Before searching, it pays to ask what form the law has. Fitting a smooth neural
surrogate to the data and probing it (:func:`~eqdisco.knowledge.fit_surrogate`)
reveals additive and multiplicative separability, translational symmetry
(:math:`f` depends on :math:`x_i-x_j`) and scaling symmetry (:math:`x_i/x_j`) --
the tests of AI Feynman (Udrescu and Tegmark, 2020). The data follow the Feynman
equation I.18.4, the centre of mass :math:`r=(m_1r_1+m_2r_2)/(m_1+m_2)`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.knowledge import fit_surrogate, interaction_matrix, suggest_structure, symmetry_tests

prob = eq.datasets.get_problem("feynman-I.18.4", n_train=800)
names = prob.feature_names

# %%
# Tests on a surrogate
# --------------------
f = fit_surrogate(prob.X_train, prob.y_train, random_state=0)
M = interaction_matrix(f, prob.X_train)
st = symmetry_tests(f, prob.X_train, names)
print(st.round(4))
for line in suggest_structure(f, prob.X_train, names, tol=0.03):
    print(line)
fig, axs = plt.subplots(1, 2, figsize=(10, 3.6))
eq.viz.plot_interaction_matrix(M, names, ax=axs[0])
axs[0].set_title("additive interaction of variable pairs", fontsize=9)
x = np.arange(len(st))
axs[1].bar(x - 0.2, st["scaling"], 0.4, color="#285780", label="scaling $x_i/x_j$")
axs[1].bar(x + 0.2, st["translation"], 0.4, color="#D55E00", label="translation $x_i-x_j$")
axs[1].plot(x, st["reference"], "k_", ms=18, label="change of one variable")
axs[1].set_xticks(x)
axs[1].set_xticklabels(st["pair"], rotation=30, fontsize=8)
axs[1].set_yscale("log")
axs[1].set_ylabel("relative change of f")
axs[1].legend(frameon=False, fontsize=7)
fig.tight_layout()

# %%
# Parameter study: surrogate quality and the scaling test
# -------------------------------------------------------
sizes = [100, 200, 400, 800]
err = []
for n in sizes:
    fs = fit_surrogate(prob.X_train[:n], prob.y_train[:n], random_state=0)
    s = symmetry_tests(fs, prob.X_train[:n], names)
    err.append(float(s.loc[s.pair == "m1, m2", "scaling"].iloc[0]))
print("surrogate samples", sizes, "scaling-test error (m1, m2)", np.round(err, 4).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(sizes, err, "o-", color="#285780")
ax.set_xlabel("samples for the surrogate")
ax.set_ylabel("scaling-test error for (m1, m2)")
plt.show()
