Friday, September 4, 2020

representing the Laplace operator (nabla in Latex) in SymPy using Del

https://en.wikipedia.org/wiki/Laplace_operator
https://docs.sympy.org/latest/modules/vector/fields.html

>>> import sympy
>>> from sympy import *
>>> from sympy.parsing.latex import parse_latex
>>> from sympy.vector import Del


Original expression as Latex converted to SymPy to Latex:
>>> latex(eval(sympy.srepr(parse_latex("\\frac{-\\hbar^2}{2m} \\nabla = {\\calH}"))))
'- \\frac{\\hbar^{2} nabla}{2 m} = calH'

The first two conversions yield SymPy:
>>> sympy.srepr(parse_latex("\\frac{-\\hbar^2}{2m} \\nabla = {\\calH}"))
"Equality(Mul(Symbol('nabla'), Mul(Mul(Integer(-1), Pow(Symbol('hbar'), Integer(2))), Pow(Mul(Integer(2), Symbol('m')), Integer(-1)))), Symbol('calH'))"

This can be successfully evaluated as SymPy because the 'nabla' is a Symbol
>>> eval("Equality(Mul(Symbol('nabla'), Mul(Mul(Integer(-1), Pow(Symbol('hbar'), Integer(2))), Pow(Mul(Integer(2), Symbol('m')), Integer(-1)))), Symbol('calH'))")
Eq(-hbar**2*nabla/(2*m), calH)

However, replacing 'nabla' with 'Del' causes the eval to fail:
>>> eval("Equality(Mul(Del, Mul(Mul(Integer(-1), Pow(Symbol('hbar'), Integer(2))), Pow(Mul(Integer(2), Symbol('m')), Integer(-1)))), Symbol('calH'))")
Traceback (most recent call last):
...
  File "/usr/local/lib/python3.6/dist-packages/sympy/core/mul.py", line 307, in flatten
    b, e = o.as_base_exp()
AttributeError: type object 'Del' has no attribute 'as_base_exp'



Original expression to convert to SymPy:
>>> sympy.srepr(parse_latex("\\nabla^2 \\psi \\left( \\vec{r},t) \\right) = \\frac{i}{\\hbar} \\vec{p} \\cdot \\left( \\vec{ \\nabla} \\psi( \\vec{r},t) \\right)"))
"Mul(Pow(Symbol('nabla'), Integer(2)), Mul(Symbol('psi'), Mul(Symbol('right'), Function('left')(Mul(Symbol('r'), Symbol('vec')), Symbol('t')))))"


The Latex "\nabla" is SymPy's "Del". However, squaring Del isn't available
>>> sympy.latex(sympy.Pow(Del, sympy.Integer(2)), sympy.Symbol('x'))
...
AttributeError: type object 'Del' has no attribute '_eval_power'


The Laplacian operator is the dot product of two Del operators, so
>>> delop = Del()
>>> sympy.latex(delop.dot(delop(sympy.Function('\psi')(sympy.Symbol('r'), sympy.Symbol('t')))))
'0'


No comments:

Post a Comment