From 183c0921a04530b15ca07ddb8f7ac7a4a6c8915d Mon Sep 17 00:00:00 2001 From: Remco de Boer <29308176+redeboer@users.noreply.github.com> Date: Mon, 12 Feb 2024 10:53:41 +0100 Subject: [PATCH] DOC: explain usage of `argument()` function --- docs/usage/sympy.ipynb | 66 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/docs/usage/sympy.ipynb b/docs/usage/sympy.ipynb index bc35b5cbf..902676bdf 100644 --- a/docs/usage/sympy.ipynb +++ b/docs/usage/sympy.ipynb @@ -213,6 +213,72 @@ "Math(aslatex({e: e.doit() for e in exprs}))" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By default, instance attributes are converted ['sympified'](https://docs.sympy.org/latest/modules/core.html#module-sympy.core.sympify). To avoid this behavior, use the {func}`.argument` function." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from typing import Callable\n", + "\n", + "from ampform.sympy import argument\n", + "\n", + "\n", + "class Transformation:\n", + " def __init__(self, power: int) -> None:\n", + " self.power = power\n", + "\n", + " def __call__(self, x: sp.Basic, y: sp.Basic) -> sp.Expr:\n", + " return x + y**self.power\n", + "\n", + "\n", + "@unevaluated\n", + "class MyExpr(sp.Expr):\n", + " x: Any\n", + " y: Any\n", + " functor: Callable = argument(sympify=False)\n", + "\n", + " def evaluate(self) -> sp.Expr:\n", + " return self.functor(self.x, self.y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how the `functor` attribute has not been sympified (there is no SymPy equivalent for a callable object), but the `functor` can be called in the `evaluate()`/`doit()` method." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "a, b, k = sp.symbols(\"a b k\")\n", + "expr = MyExpr(a, y=b, functor=Transformation(power=k))\n", + "assert expr.x is a\n", + "assert expr.y is b\n", + "assert not isinstance(expr.functor, sp.Basic)\n", + "Math(aslatex({expr: expr.doit()}))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + ":::{tip}\n", + "An example where this is used, is in the {class}`.EnergyDependentWidth` class, where we do not want to sympify the {attr}`~.EnergyDependentWidth.phsp_factor` protocol.\n", + ":::" + ] + }, { "cell_type": "markdown", "metadata": {},