"""
Expressions: trees, evaluation, derivatives and bounds
======================================================

An equation in eqdisco is an :class:`~eqdisco.Expression`, a tree stored in
prefix (Polish) order. Functions are inner nodes, variables and constants are
leaves; the constants are the parameters :math:`\\boldsymbol\\theta` of the model.
The same object is evaluated on data, differentiated with respect to its
parameters, bounded over boxes by interval arithmetic, and converted to SymPy,
LaTeX and source code. This example builds the Arrhenius-type rate
:math:`r = k_0\\,c\\,e^{-E/T}` and looks at it from all these angles.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.viz import plot_tree

# %%
# Parsing and the tree
# --------------------
pset = eq.PrimitiveSet(n_features=2, feature_names=["c", "T"])
rate = eq.Expression.from_string("2.0e3 * c * exp(-1500 / T)", pset)
print(rate, "| size", rate.size, "| depth", rate.depth, "| parameters", rate.theta)
print(rate.nodes[:4])  # prefix order: mul, mul, constant, variable ...
fig, axs = plt.subplots(1, 2, figsize=(9, 3.4), gridspec_kw={"width_ratios": [1, 1.3]})
plot_tree(rate, ax=axs[0])
axs[0].set_title("prefix tree of the rate expression", fontsize=9)

# %%
# Evaluation, Jacobian and interval bounds
# ----------------------------------------
T = np.linspace(300, 450, 200)
X = np.column_stack([np.full_like(T, 2.0), T])
r = rate.evaluate(X)  # vectorized over the rows of X
value, J = rate.jacobian(X)  # d r / d theta, forward mode
lo, hi = rate.interval([2.0, 300.0], [2.0, 450.0])  # guaranteed bounds on the box
print("Jacobian shape", J.shape, "| bounds on the box:", lo[0], hi[0])
ax = axs[1]
ax.plot(T, r, color="#285780", lw=2, label="r(c = 2, T)")
ax.axhspan(lo[0], hi[0], color="#0072B2", alpha=0.08, label="interval bound on [300, 450] K")
ax.set_xlabel("T (K)")
ax.set_ylabel("rate")
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Symbolic forms
# --------------
eqn = eq.Equation(rate)
print(eqn.sympy())
print(eqn.latex(lhs="r"))
print(eq.export.to_python(eqn, protected=False))
# %%
# Parameter study: interval bounds tighten when the box is split
# --------------------------------------------------------------
# When every variable occurs once, as in the rate above, interval arithmetic
# returns the exact range of a monotone expression. When a variable occurs more
# than once, the bound ignores that the occurrences are equal (the dependency
# problem) and overestimates the range. The net rate of a reversible reaction,
# with the reverse term 40 c^2, shows the effect; splitting the box into k x k
# sub-boxes makes the union of the bounds approach the true range, which is
# computed here on a fine grid.
net = eq.Expression.from_string("2.0e3 * c * exp(-1500 / T) - 40 * c^2", pset)
cg, Tg = np.meshgrid(np.linspace(1, 3, 400), np.linspace(300, 450, 400))
vals = net.evaluate(np.column_stack([cg.ravel(), Tg.ravel()]))
true_range = vals.max() - vals.min()
widths = []
splits = [1, 2, 4, 8, 16, 32]
for k in splits:
    ce, te = np.linspace(1, 3, k + 1), np.linspace(300, 450, k + 1)
    L = np.array([[ce[i], te[j]] for i in range(k) for j in range(k)])
    U = np.array([[ce[i + 1], te[j + 1]] for i in range(k) for j in range(k)])
    lo_k, hi_k = net.interval(L, U)
    widths.append(hi_k.max() - lo_k.min())
print("bound widths:", np.round(widths, 1).tolist(), "| true range:", round(true_range, 1))
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(splits, widths, "o-", color="#285780")
ax.axhline(true_range, color="#D55E00", ls="--", lw=1, label="true range on the box")
ax.set_xscale("log", base=2)
ax.set_xlabel("boxes per variable")
ax.set_ylabel("width of the bound")
ax.legend(frameon=False, fontsize=8)
plt.show()
