Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Expressions: trees, evaluation, derivatives and bounds#
An equation in eqdisco is an Expression, a tree stored in
prefix (Polish) order. Functions are inner nodes, variables and constants are
leaves; the constants are the parameters \(\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
\(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)

2000 * c * exp(-1500 / T) | size 8 | depth 4 | parameters [ 2000. -1500.]
[Node(kind=0, value=Primitive('mul', arity=2), fixed=False), Node(kind=2, value=2000.0, fixed=False), Node(kind=0, value=Primitive('mul', arity=2), fixed=False), Node(kind=1, value=0, fixed=False)]
Text(0.5, 1.0, 'prefix tree of the rate expression')
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()
Jacobian shape (200, 2) | bounds on the box: 26.951787996341867 142.69597338900957
Symbolic forms#
eqn = eq.Equation(rate)
print(eqn.sympy())
print(eqn.latex(lhs="r"))
print(eq.export.to_python(eqn, protected=False))
2000*c*exp(-1500/T)
r = 2000 c e^{- \frac{1500}{T}}
import math
def f(c, T):
return 2000 * c * math.exp(-1500 / T)
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()

bound widths: [520.6, 435.7, 393.3, 372.1, 361.5, 356.2] | true range: 350.9
Total running time of the script: (0 minutes 0.391 seconds)