Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy - Lambdify - miningful names to dummy variables

Tags:

python

sympy

Let say I want to create an expression with a single symbol, written in Latex (because it is really helpful to visualize it in a Jupyter Notebook). Then I use lambdify to get a function I can evaluate for multiple values. Problem is this function will show a variable named _Dummy_, as shown below.

AoB = sp.symbols(r'\frac{\alpha}{\beta}')
expr = 2 * AoB
lam = sp.lambdify([AoB], expr, 'numpy')
display(lam)

Output: <function _lambdifygenerated(_Dummy_1198)>

Now, imagine a wrapper function: inside it I have defined several sympy expressions, each using different Latex symbols. I give an index argument to this function, which is used to return the lambdify version of the corresponding expression.

When the lambdify function is returned, I would really love to know what _Dummy_ is referring to, especially when the lambdify function requires two or more arguments to be evaluated. For instance, in the above example I would have no problem if the function argument was called AoB (which I can interpret as alpha over beta).

Ideally, I would love to create a Symbol that accepts both Latex (for visualization purposes) and also a fallback symbol to be used whenever a Dummy variable is going to be created (for example, with lambdify). Is it possible?

like image 654
Davide_sd Avatar asked Oct 29 '19 23:10

Davide_sd


1 Answers

Probably the simplest solution to this would be to keep a mapping of latex Symbol to normal Symbols, and substitute it before lambdifying, like

AoB = sp.symbols(r'\frac{\alpha}{\beta}')
mapping = {AoB: Symbol('AoB')}
expr = 2 * AoB
lam = sp.lambdify([mapping[AoB]], expr.xreplace(mapping), 'numpy')
like image 117
asmeurer Avatar answered Oct 18 '22 16:10

asmeurer