Search code examples
sympy

Sympy replace angular momentum operator


I'm working right on quite complex and long equations for my PhD and I was hoping that I could use sympy in order to check my equations and obtain them faster. These equations have Spherical Harmonics and I was hoping I could factorize the L^2 operator to replace it just with L^2. But I tried many different things without sucess, so I did several test to find where is the problem :

zeta,theta,phi=sy.symbols(r"\zeta \theta \phi")

Lsqr=sy.Function(r"L^2")(theta,phi)


a=sy.Function("a")(zeta)
b=sy.Function("b")(zeta)
c=sy.Function("c")(zeta)
d=sy.Function("d")(zeta)
e=sy.Function("e")(zeta)

#first case without dividing function
test_L=e*a+b*e
Lsquare=a+b

test_L=sy.factor(test_L,Lsquare)
test_L=test_L.replace(Lsquare,Lsqr)
print("test")
print(test_L)
# result : L^2(\theta, \phi)*e(\zeta) => GOOD

#second case with dividing function

test_L=e*a/c+b*e
Lsquare=a/c+b

test_L=sy.factor(test_L,Lsquare)
test_L=test_L.replace(Lsquare,Lsqr)
print("test")
print(test_L)

# result : (a(\zeta) + b(\zeta)*c(\zeta))*e(\zeta)/c(\zeta) => BAD I would like same form has before 

I would like to have the same form as done in the first test : L^2*c

The reason of that I have equations under the form :

\frac{\left(\sin{\left(\theta \right)} \frac{\partial^{2}}{\partial \theta^{2}} \operatorname{Y^{m}_{l}}{\left(\theta,\phi \right)} + \cos{\left(\theta \right)} \frac{\partial}{\partial \theta} \operatorname{Y^{m}_{l}}{\left(\theta,\phi \right)}\right) \rho_{0}{\left(\zeta,\theta \right)}}{\sin{\left(\theta \right)}} + \frac{\rho_{0}{\left(\zeta,\theta \right)} \frac{\partial^{2}}{\partial \phi^{2}} \operatorname{Y^{m}_{l}}{\left(\theta,\phi \right)}}{\sin^{2}{\left(\theta \right)}}

And I would like to obtain :

\rho_0(\zeta,\theta) L^2 Y_l^m(\theta,\phi)

Sorry, I don t know how to edit latex formulas.


Solution

  • Since L^2 = a/c+b and the pattern a/c+b does not appear as a single argument in the expression, the substitution fails. But if you replace b with L^2 - a/c you will have some success:

    >>> test_L.subs(b,Lsqr-a/c).factor()
    L^2(\\theta, \\phi)*e(\\zeta)