2

I'm new to python and am having trouble with sympy. I define complex equations which are functions of the parameters a, b and use hold=true to save computation time. For example I have defined g in terms of other quantities A,B,C,D,E,F, as,

In [92]: g=sympy.MatAdd(sympy.MatMul(A, B), \
    ...:     sympy.MatMul(C, D, hold=sympy.true), \
    ...:     sympy.MatMul(E, F, hold=sympy.true), hold=sympy.true)

I want to define new quantities which are the ratio of the imaginary and real parts. For instance, alpha=Im(g)/Re(g). I have tried this by doing the following,

In [93]: alpha=sympy.im(g)/sympy.re(g)

,but I get the error,

In [94]: alpha=sympy.im(g)/sympy.re(g)
Traceback (most recent call last):

  File "<ipython-input-94-e3054aea27cc>", line 1, in <module>
    alpha=sympy.im(g)/sympy.re(g)

  File "C:\Anaconda3\lib\site-packages\sympy\core\function.py", line 385, in __new__
    result = super(Function, cls).__new__(cls, *args, **options)

  File "C:\Anaconda3\lib\site-packages\sympy\core\function.py", line 209, in __new__
    evaluated = cls.eval(*args)

  File "C:\Anaconda3\lib\site-packages\sympy\functions\elementary\complexes.py", line 158, in eval
    coeff = term.as_coefficient(S.ImaginaryUnit)

AttributeError: 'MatAdd' object has no attribute 'as_coefficient'

Even if this was successful though, I doubt I'd want to wait around for it to finish. My first question is - how can one fix the definition on line 93, while suppressing the evaluation?

Providing this can somehow be done, I want to define f(alpha(a,b), beta(a,b)), where beta is defined similarly to alpha. I want to then plot a and b such that f=0. I was thinking something like this would work,

p1=sympy.plot_implicit(f(alpha(a,b),beta(a,b)),(a,0,2.5),(b,0,4))

Is this the most efficient way or would a different approach be better?

I was thinking of using lambdify to define g_num,

g_num=sympy.lambdify((a,b), g, 'numpy')

After that define a lambda function

lambda a,b,delta : f(alpha(a,b), beta(a,b))

but then I don't know how to obtain the implicit plot f(a,b)=0 with this method.

ben_afobe
  • 95
  • 4
  • By the way: all your backslashes for continuation are **useless**. Parenthesis already imply continuation so you should just remove them. – Bakuriu Sep 09 '16 at 11:33
  • I found a solution to the first question: re(g,evaluate=false) seems to work – ben_afobe Sep 09 '16 at 13:18

1 Answers1

1

hold=True isn't a real SymPy option. You want evaluate=False. Note that MatMul already doesn't evaluate by default.

re and im are presently only defined to operate on scalars, not matrices. That's why you are getting the error you are getting. Using re(g, evaluate=False) should work, since the lambdified re from NumPy will just broadcast over the array.

asmeurer
  • 86,894
  • 26
  • 169
  • 240