.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01_basics/plot_01_expressions.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_01_basics_plot_01_expressions.py: 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. .. GENERATED FROM PYTHON SOURCE LINES 13-20 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq from eqdisco.viz import plot_tree .. GENERATED FROM PYTHON SOURCE LINES 21-23 Parsing and the tree -------------------- .. GENERATED FROM PYTHON SOURCE LINES 23-31 .. code-block:: Python 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) .. image-sg:: /auto_examples/01_basics/images/sphx_glr_plot_01_expressions_001.png :alt: prefix tree of the rate expression :srcset: /auto_examples/01_basics/images/sphx_glr_plot_01_expressions_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none 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') .. GENERATED FROM PYTHON SOURCE LINES 32-34 Evaluation, Jacobian and interval bounds ---------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 34-48 .. code-block:: Python 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() .. rst-class:: sphx-glr-script-out .. code-block:: none Jacobian shape (200, 2) | bounds on the box: 26.951787996341867 142.69597338900957 .. GENERATED FROM PYTHON SOURCE LINES 49-51 Symbolic forms -------------- .. GENERATED FROM PYTHON SOURCE LINES 51-55 .. code-block:: Python eqn = eq.Equation(rate) print(eqn.sympy()) print(eqn.latex(lhs="r")) print(eq.export.to_python(eqn, protected=False)) .. rst-class:: sphx-glr-script-out .. code-block:: none 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) .. GENERATED FROM PYTHON SOURCE LINES 56-65 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. .. GENERATED FROM PYTHON SOURCE LINES 65-86 .. code-block:: Python 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() .. image-sg:: /auto_examples/01_basics/images/sphx_glr_plot_01_expressions_002.png :alt: plot 01 expressions :srcset: /auto_examples/01_basics/images/sphx_glr_plot_01_expressions_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none bound widths: [520.6, 435.7, 393.3, 372.1, 361.5, 356.2] | true range: 350.9 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.391 seconds) .. _sphx_glr_download_auto_examples_01_basics_plot_01_expressions.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/eqdisco/main?urlpath=lab/tree/notebooks/auto_examples/01_basics/plot_01_expressions.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_01_expressions.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_01_expressions.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_01_expressions.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_