0

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.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Stef1611
  • 1,978
  • 2
  • 11
  • 30
  • `help(funclamb)` will show you the python code – hpaulj Nov 22 '21 at 15:52
  • @hpaulj. Thanks for answer. But, if possible, I would prefer to use a dictionary. I think it is less prone to error when there are many parameters. Moreover, it is easier to change only one parameter. – Stef1611 Nov 22 '21 at 16:34
  • The point I was trying to make is that code shows you how to call the function. Use what ever python syntax that allows. – hpaulj Nov 22 '21 at 16:39

1 Answers1

1
# 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.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
hpaulj
  • 221,503
  • 14
  • 230
  • 353