Lambdify或评估CoordSys3D

时间:2018-07-23 17:47:39

标签: python sympy

如何评估Sympy CoordSys3D表达式上的点?

使用Sympy物理学模块,此过程可以按预期工作

from sympy import *
from sympy.physics.vector import ReferenceFrame, CoordinateSym, divergence
R = ReferenceFrame('R')
field = R[0]*R[1]*R[2]*(R.x+R.y+R.z) 

div = divergence(vect=field, frame=R)
div_func = lambdify([R[0], R[1], R[2]], div, modules='numpy')
print('Function evaluated at a point = {}'.format(div_func(1,2,8)))

但是,如果我改用CoordSys3D进行lambdify的过程尚不清楚:

from sympy.vector import CoordSys3D, divergence, curl

A = CoordSys3D('A')  
field = A.x*A.y*A.z*(A.i + A.j + A.k)
div = divergence(field)

# How do I lambdify / evaluate this? 

# This fails:   
#    File "<lambdifygenerated-5>", line 1
#    def _lambdifygenerated(A.x, A.y, A.z):
#    SyntaxError: invalid syntax
# div_func = lambdify([A.x, A.y, A.z], div, modules='numpy')

# This fails:
#    "name 'x' is not defined"
# div_func = lambdify([x, y, z], div, modules='numpy')

print('Function evaluated at a point = {}'.format(div_func(1,2,8)))

一些观察结果:

  • R[0]sympy.physics.vector.frame.CoordinateSym
  • A.xsympy.vector.scalar.BaseScalar

CoordSys3D似乎是我想要的格式,特别是因为对球坐标系的支持非常简单。

例如:

A = CoordSys3D('A', transformation='spherical')  # transformation requires Sympy 1.2 
vec_field = a*A.r**2*A.i + c*cos(A.theta)/A.r*A.j + b * A.k 
div = divergence(vec_field)

1 个答案:

答案 0 :(得分:3)

看起来lambdify不能正确解释A.x,而应该生成符号,因此您必须用符号替换它。

vars = symbols('A.x A.y A.z')
div_func = lambdify(vars, div.subs(dict(zip([A.x, A.y, A.z], vars))), modules='numpy')
print(div_func(1, 2, 8))  # 26

什么叫符号vars并不重要,我将它们命名为“ A.x”,以确保一致性。它们也可能像vars = symbols('v0:3')