How do you define the real/imaginary parts of long symbolic expression without evaluation?
<p>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,</p>

<pre><code>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)
</code></pre>

<p>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,</p>

<pre><code>In [93]: alpha=sympy.im(g)/sympy.re(g)
</code></pre>

<p>,but I get the error,</p>

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

  File "&lt;ipython-input-94-e3054aea27cc&gt;", line 1, in &lt;module&gt;
    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'
</code></pre>

<p>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?</p>

<p>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,</p>

<pre><code>p1=sympy.plot_implicit(f(alpha(a,b),beta(a,b)),(a,0,2.5),(b,0,4))
</code></pre>

<p>Is this the most efficient way or would a different approach be better?</p>

<p>I was thinking of using lambdify to define g_num,</p>

<pre><code>g_num=sympy.lambdify((a,b), g, 'numpy')
</code></pre>

<p>After that define a lambda function</p>

<pre><code>lambda a,b,delta : f(alpha(a,b), beta(a,b))
</code></pre>

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

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

<p><code>re</code> and <code>im</code> are <a href="https://github.com/sympy/sympy/issues/11600" rel="nofollow">presently</a> only defined to operate on scalars, not matrices. That's why you are getting the error you are getting. Using <code>re(g, evaluate=False)</code> should work, since the lambdified <code>re</code> from NumPy will just broadcast over the array. </p>

python numpy math plot sympy