Home > front end >  How to use dictionary with lambdify
How to use dictionary with lambdify

Time:11-23

I wrote sympy functions with parameters. For example,

ampl, freq, phase, cte, t =sp.symbols('ampl freq phase cte t')
func=sp.Function("Func")(t)
func=ampl*sp.cos(freq*t phase) cte

To plot, this function, I use lambdify in this way :

funclamb=sp.lambdify([(ampl, freq, phase, cte) ,t],func)
xline=np.linspace(0,10,11)
yValues=funclamb((5, 4, 1.5, 12) ,xline)
plt.plot(xline,yValues)

But, I must be careful about the element order in the tuple : (ampl, freq, phase, cte). I wonder if there is a mean to use these parameters in a dictionary :

myParamDict={ampl: 5, freq: 4, phase: 1.5, cte: 12}

I tried different things but it does not work.

CodePudding user response:

# Help on function _lambdifygenerated:
    
_lambdifygenerated(_Dummy_23, t)

# Created with lambdify. Signature:
        
func(arg_0, t)
        
# Expression:

ampl*cos(freq*t   phase)   cte

# Source code:

def _lambdifygenerated(_Dummy_23, t):
    [ampl, freq, phase, cte] = _Dummy_23
    return ampl*cos(freq*t   phase)   cte
    

You have to provide 2 arguments, one of which will 'unpack' to the 4 variables.

With function like:

In [5]: def foo(a,b,c):
   ...:     print(a,b,c)
   ...:     return None
   ...: 

inputs can be by position, but they can also be by name or unpacked dict.

In [6]: foo(1,2,3)
1 2 3

In [7]: foo(b=3,c=1,a=1)
1 3 1
In [8]: d={'b':1,'c':2,'a':3}

In [9]: foo(**d)
3 1 2

That means your function can be called with:

In [10]: funclamb(t=np.array([1,2,3]),_Dummy_23=[1,2,3,4])
Out[10]: array([4.28366219, 4.75390225, 3.08886974])

As defined by the lambdify expression, the (ampl, freq, phase, cte) variables have to be provided as a list/tuple.

  • Related