3

My main goal is to identify coefficients in front of exponentials of the form

exp(1j*k*r)

in expressions such as:

(z1*exp(1j*k1*r1) + z2*exp(1j*k2*r2) + c.c.)**2

by first expanding and then using the coeff tool in sympy.

The problem is that I don't know how to expand in such a manner that we can gather the exponents additively. I would like to see this term:

exp(1j*(k1*r1+k2*r2))

but only this kind of term appears:

exp(1j*k1*r1)*exp(1j*k2*r2)

Here is my code:

from sympy import *
u = Symbol('u')
r1,r2 = symbols('r1 r2', real = True)
k1,k2 = symbols('k1 k2', real = True)
z1,z2 = symbols('z1 z2')
uu = z1*exp(1j*k1*r1)+ z2*exp(1j*k1*r2)
u = uu + uu.conjugate()

v = expand(u**2)
print(v)

I can not figure out how to do it. I tried using simplify, or considering the thing as a polynom whith symbolic coefficients, but this didn't work.

More generally, is expanding and then using coeff method the best way to extract coefficients in front of the exponentials ? Is there any automated tool that already makes it ?

Thank you for your help !

EDIT :

I also tried using powsimp with this portion of code:

w = powsimp(expand(u**2))
print(w.coeff(exp(1j*(k1*r1 + k2*r2))))

it returns 0 because we only obtain

exp(1j*k1*r1 + 1j*k2*r2)

but it is not sufficient when applying coeff method to extract the exponent 1j*(k1*r1 + k2*r2).

A. S.
  • 31
  • 3

1 Answers1

0

The function factor_terms will dig into the exponents and mine out the common factor. Is this what you are looking for?

>>> factor_terms(powsimp(posify(u**2)[0].expand()))
z1∗∗2∗exp(2∗k1∗r1∗I)+2∗z1∗∗2+z1∗∗2∗exp(−2∗k1∗r1∗I)+
2∗z1∗z2∗exp(k1∗I∗(−r1+r2))+2∗z1∗z2∗exp(k1∗I∗(r1−r2))+
2∗z1∗z2∗exp(k1∗I∗(r1+r2))+2∗z1∗z2∗exp(−k1∗I∗(r1+r2))+
z2∗∗2∗exp(2∗k1∗r2∗I)+2∗z2∗∗2+z2∗∗2∗exp(−2∗k1∗r2∗I)

The posify assigns assumptions so the exponential factors come together. If they don't when you use powsimp that is probably because there is an assumption that does not permit that rewriting for all possible values of the variables. Note: you will not be able to do matching directly on this, you will have to substitute your original variables back into the result using the second argument that comes back from posify -- see the docstring of posify.

smichr
  • 16,948
  • 2
  • 27
  • 34