.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/08_knowledge/plot_29_units.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_08_knowledge_plot_29_units.py: Physical units: dimensional consistency and Buckingham groups ============================================================= A formula that adds metres to seconds is wrong however well it fits. With ``units=`` the search penalizes dimensional inconsistencies (Keijzer and Babovic, 1999): sums of quantities with different units, transcendental functions of dimensional arguments, and an output unit different from the target's. Fitted constants may carry any unit, as :math:`g` or :math:`k_B` do. The second part uses the Buckingham :math:`\Pi` theorem to reduce the period of a pendulum to one dimensionless group before any search, the first step of AI Feynman (Udrescu and Tegmark, 2020). .. GENERATED FROM PYTHON SOURCE LINES 14-24 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq from eqdisco.knowledge import buckingham_pi, check_units, dimensionless_features prob = eq.datasets.get_problem("feynman-I.27.6", noise=0.05, n_train=60) # thin lens: 1 / (1/d1 + n/d2) print(prob.truth, prob.units) .. rst-class:: sphx-glr-script-out .. code-block:: none 1/(1/d1 + n/d2) {'d1': 'm', 'd2': 'm', 'n': '1', '__target__': 'm'} .. GENERATED FROM PYTHON SOURCE LINES 25-27 Search with and without units ----------------------------- .. GENERATED FROM PYTHON SOURCE LINES 27-50 .. code-block:: Python res = {} for use in (False, True): res[use] = [ eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "square"), units=prob.units if use else None, feature_names=prob.feature_names, random_state=s).fit(prob.X_train, prob.y_train) for s in range(5) ] for use, rr in res.items(): ok = [check_units(r.equation_, prob.units)["consistent"] for r in rr] print("units" if use else "no units", "consistent:", sum(ok), "of", len(ok), "| e.g.", rr[0].equation_) fig, axs = plt.subplots(1, 2, figsize=(10, 3.4)) for k, (use, rr) in enumerate(res.items()): r2 = [r.equation_.score(prob.X_test, prob.y_test) for r in rr] cons = [check_units(r.equation_, prob.units)["consistent"] for r in rr] axs[0].scatter([e.equation_.complexity for e in rr], 1 - np.array(r2), color=eq.viz.OKABE_ITO[k], s=40, marker="o", label="with units" if use else "without units") for r, c in zip(rr, cons): if c: axs[0].scatter([r.equation_.complexity], [1 - r.equation_.score(prob.X_test, prob.y_test)], s=110, facecolor="none", edgecolor="#009E73", lw=1.5) axs[0].set_yscale("log") axs[0].set_xlabel("model size") axs[0].set_ylabel("$1-R^2$ (test); green ring: consistent") axs[0].legend(frameon=False, fontsize=8) .. image-sg:: /auto_examples/08_knowledge/images/sphx_glr_plot_29_units_001.png :alt: plot 29 units :srcset: /auto_examples/08_knowledge/images/sphx_glr_plot_29_units_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none no units consistent: 0 of 5 | e.g. 0.1549 + 1.328 * ((-3.184)^2 + d2 + d1 / n) * (d2 / (-2.433))^2 / (d2 + n + d2 / d1)^2 units consistent: 3 of 5 | e.g. 0.00624 + 0.9965 * d2 / (n + d2 / d1) .. GENERATED FROM PYTHON SOURCE LINES 51-53 Buckingham groups: the pendulum ------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 53-66 .. code-block:: Python units = {"T": "s", "l": "m", "g": "m/s^2", "m": "kg"} groups = buckingham_pi(units, target="T") print(groups) # [{'T': 1, 'l': -0.5, 'g': 0.5}]: T * sqrt(g/l) is dimensionless, the mass drops out rng = np.random.default_rng(0) l, g, m = rng.uniform(0.2, 2, 100), rng.uniform(1, 25, 100), rng.uniform(0.1, 5, 100) T = 2 * np.pi * np.sqrt(l / g) P, _ = dimensionless_features(np.column_stack([T, l, g]), ["T", "l", "g"], groups) axs[1].scatter(l / g, T, s=10, color="#6B7785", label="T against l/g") axs[1].set_xlabel("l / g (s$^2$)") axs[1].set_ylabel("period T (s)") axs[1].set_title(f"$\\Pi = T\\sqrt{{g/l}}$ = {P.mean():.4f} for every pendulum ($2\\pi$ = {2 * np.pi:.4f})", fontsize=9) fig.tight_layout() .. rst-class:: sphx-glr-script-out .. code-block:: none [{'T': 1.0, 'l': -0.5, 'g': 0.5}] .. GENERATED FROM PYTHON SOURCE LINES 67-69 Parameter study: the weight of the unit penalty ----------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 69-81 .. code-block:: Python weights = [0.0, 0.1, 1.0, 10.0] share = [] for w in weights: rr = [eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "square"), units=prob.units, constraint_weight=w, feature_names=prob.feature_names, random_state=s).fit(prob.X_train, prob.y_train) for s in range(4)] share.append(np.mean([check_units(r.equation_, prob.units)["consistent"] for r in rr])) print("unit weight", weights, "share of unit-consistent models", share) fig, ax = plt.subplots(figsize=(4.5, 3)) ax.plot(weights, share, "o-", color="#285780") ax.set_xscale("symlog", linthresh=0.1) ax.set_xlabel("weight of the unit penalty") ax.set_ylabel("share of consistent models") plt.show() .. image-sg:: /auto_examples/08_knowledge/images/sphx_glr_plot_29_units_002.png :alt: plot 29 units :srcset: /auto_examples/08_knowledge/images/sphx_glr_plot_29_units_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none unit weight [0.0, 0.1, 1.0, 10.0] share of unit-consistent models [np.float64(0.0), np.float64(0.75), np.float64(0.5), np.float64(0.75)] .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 18.648 seconds) .. _sphx_glr_download_auto_examples_08_knowledge_plot_29_units.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/08_knowledge/plot_29_units.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_29_units.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_29_units.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_29_units.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_