"""
Exporting equations to code, spreadsheets and PMML
==================================================

A discovered equation is small enough to run anywhere: in a PLC, a spreadsheet,
a simulator or a scoring engine. :mod:`eqdisco.export` writes it as Python, C,
MATLAB/Octave or Julia source, as an Excel formula, as LaTeX, and as a PMML 4.4
document. With ``protected=True`` the code reproduces the protected operators of
eqdisco exactly; this example verifies that the generated Python and NumPy code
predict the same values as the equation itself.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco import export

rng = np.random.default_rng(0)
X = rng.uniform(0.5, 3, (200, 2))
y = 2.5 * X[:, 0] * np.exp(-0.3 * X[:, 1]) - np.log(X[:, 1]) + 0.01 * rng.normal(size=200)
model = eq.SymbolicRegressor(population_size=300, generations=25, functions=("add", "sub", "mul", "div", "exp", "log"), optimize="lm", feature_names=["flow", "time"], random_state=0).fit(X, y)
eqn = eq.simplify.simplify(model.equation_, X, y, refit=True)

# %%
# Source code and formulas
# ------------------------
print(export.to_python(eqn, name="yield_model"))
print(export.to_c(eqn, name="yield_model"))
print(export.to_excel(eqn, {"flow": "B2", "time": "C2"}))
print(export.to_latex(eqn, lhs="Y"))
pmml = export.to_pmml(eqn, target="yield")
print(pmml.count("<Apply"), "Apply elements in the PMML document")
# %%
# Verifying the generated code
# ----------------------------
namespace = {}
exec(export.to_python(eqn, name="f_py"), namespace)  # code written by eqdisco itself
exec(export.to_python(eqn, name="f_np", numpy=True), namespace)
ref = eqn.predict(X)
py = np.array([namespace["f_py"](*row) for row in X])
vec = namespace["f_np"](X[:, 0], X[:, 1])
print(f"largest difference from eqdisco: Python {np.max(np.abs(py - ref)):.1e}, NumPy {np.max(np.abs(vec - ref)):.1e}")
fig, ax = plt.subplots(figsize=(4.5, 3.2))
ax.semilogy(np.sort(np.abs(py - ref) + 1e-17), color="#285780", label="Python (math)")
ax.semilogy(np.sort(np.abs(vec - ref) + 1e-17), color="#D55E00", label="NumPy")
ax.set_xlabel("sample (sorted by error)")
ax.set_ylabel("|generated code - eqdisco|")
ax.legend(frameon=False, fontsize=8)

# %%
# Parameter study: protected or plain operators
# ---------------------------------------------
# Plain operators give the textbook formula; they differ from eqdisco only where
# a protected operator acts (division by ~0, logarithm of a negative number).
Xbad = np.column_stack([np.linspace(-1, 3, 50), np.linspace(-1, 3, 50)])
ns_plain = {}
exec(export.to_python(eqn, name="g", protected=False, numpy=True), ns_plain)
with np.errstate(all="ignore"):
    plain = ns_plain["g"](Xbad[:, 0], Xbad[:, 1])
print("rows where plain and protected operators differ:", int(np.sum(~np.isclose(plain, eqn.predict(Xbad), equal_nan=False))), "of", len(Xbad))
fig, ax = plt.subplots(figsize=(4.5, 3.2))
ax.plot(Xbad[:, 1], eqn.predict(Xbad), color="#285780", lw=2, label="protected (eqdisco)")
ax.plot(Xbad[:, 1], plain, color="#D55E00", ls="--", label="plain operators")
ax.set_xlabel("time (also outside the data range)")
ax.legend(frameon=False, fontsize=8)
plt.show()
