此解决方案应用其他答案和此处的提示。D
运算符可以定义如下:
- 仅在从左侧相乘时才考虑,因此
D(t)*2*t**3 = 6*t**2
但2*t**3*D(t)
什么也不做
- 使用的所有表达式和符号
D
必须有is_commutative = False
- 在给定表达式的上下文中使用
evaluateExpr()
- 它从右到左沿着表达式找到
D
运算符并将mydiff()
* 应用于相应的右侧部分
*:mydiff
用于代替diff
允许D
创建更高的顺序,例如mydiff(D(t), t) = D(t,t)
diff
里面的内容仅供参考,因为在当前的解决方案中,__mul__()
实际上是在做区分工作。创建了一个 python mudule 并保存为.D
evaluateExpr()
d.py
import sympy
from sympy.core.decorators import call_highest_priority
from sympy import Expr, Matrix, Mul, Add, diff
from sympy.core.numbers import Zero
class D(Expr):
_op_priority = 11.
is_commutative = False
def __init__(self, *variables, **assumptions):
super(D, self).__init__()
self.evaluate = False
self.variables = variables
def __repr__(self):
return 'D%s' % str(self.variables)
def __str__(self):
return self.__repr__()
@call_highest_priority('__mul__')
def __rmul__(self, other):
return Mul(other, self)
@call_highest_priority('__rmul__')
def __mul__(self, other):
if isinstance(other, D):
variables = self.variables + other.variables
return D(*variables)
if isinstance(other, Matrix):
other_copy = other.copy()
for i, elem in enumerate(other):
other_copy[i] = self * elem
return other_copy
if self.evaluate:
return diff(other, *self.variables)
else:
return Mul(self, other)
def __pow__(self, other):
variables = self.variables
for i in range(other-1):
variables += self.variables
return D(*variables)
def mydiff(expr, *variables):
if isinstance(expr, D):
expr.variables += variables
return D(*expr.variables)
if isinstance(expr, Matrix):
expr_copy = expr.copy()
for i, elem in enumerate(expr):
expr_copy[i] = diff(elem, *variables)
return expr_copy
return diff(expr, *variables)
def evaluateMul(expr):
end = 0
if expr.args:
if isinstance(expr.args[-1], D):
if len(expr.args[:-1])==1:
cte = expr.args[0]
return Zero()
end = -1
for i in range(len(expr.args)-1+end, -1, -1):
arg = expr.args[i]
if isinstance(arg, Add):
arg = evaluateAdd(arg)
if isinstance(arg, Mul):
arg = evaluateMul(arg)
if isinstance(arg, D):
left = Mul(*expr.args[:i])
right = Mul(*expr.args[i+1:])
right = mydiff(right, *arg.variables)
ans = left * right
return evaluateMul(ans)
return expr
def evaluateAdd(expr):
newargs = []
for arg in expr.args:
if isinstance(arg, Mul):
arg = evaluateMul(arg)
if isinstance(arg, Add):
arg = evaluateAdd(arg)
if isinstance(arg, D):
arg = Zero()
newargs.append(arg)
return Add(*newargs)
#courtesy: https://stackoverflow.com/a/48291478/1429450
def disableNonCommutivity(expr):
replacements = {s: sympy.Dummy(s.name) for s in expr.free_symbols}
return expr.xreplace(replacements)
def evaluateExpr(expr):
if isinstance(expr, Matrix):
for i, elem in enumerate(expr):
elem = elem.expand()
expr[i] = evaluateExpr(elem)
return disableNonCommutivity(expr)
expr = expr.expand()
if isinstance(expr, Mul):
expr = evaluateMul(expr)
elif isinstance(expr, Add):
expr = evaluateAdd(expr)
elif isinstance(expr, D):
expr = Zero()
return disableNonCommutivity(expr)
示例 1:矢量场的卷曲。请注意,定义变量很重要,commutative=False
因为它们的顺序Mul().args
会影响结果,请参阅this other question。
from d import D, evaluateExpr
from sympy import Matrix
sympy.var('x', commutative=False)
sympy.var('y', commutative=False)
sympy.var('z', commutative=False)
curl = Matrix( [[ D(x), D(y), D(z) ]] )
field = Matrix( [[ x**2*y, x*y*z, -x**2*y**2 ]] )
evaluateExpr( curl.cross( field ) )
# [-x*y - 2*x**2*y, 2*x*y**2, -x**2 + y*z]
示例 2:结构分析中使用的典型 Ritz 近似。
from d import D, evaluateExpr
from sympy import sin, cos, Matrix
sin.is_commutative = False
cos.is_commutative = False
g1 = []
g2 = []
g3 = []
sympy.var('x', commutative=False)
sympy.var('t', commutative=False)
sympy.var('r', commutative=False)
sympy.var('A', commutative=False)
m=5
n=5
for j in xrange(1,n+1):
for i in xrange(1,m+1):
g1 += [sin(i*x)*sin(j*t), 0, 0]
g2 += [ 0, cos(i*x)*sin(j*t), 0]
g3 += [ 0, 0, sin(i*x)*cos(j*t)]
g = Matrix( [g1, g2, g3] )
B = Matrix(\
[[ D(x), 0, 0],
[ 1/r*A, 0, 0],
[ 1/r*D(t), 0, 0],
[ 0, D(x), 0],
[ 0, 1/r*A, 1/r*D(t)],
[ 0, 1/r*D(t), D(x)-1/x],
[ 0, 0, 1],
[ 0, 1, 0]])
ans = evaluateExpr(B*g)
print_to_file()
已经创建了一个函数来快速检查大表达式。
import sympy
import subprocess
def print_to_file( guy, append=False ):
flag = 'w'
if append: flag = 'a'
outfile = open(r'print.txt', flag)
outfile.write('\n')
outfile.write( sympy.pretty(guy, wrap_line=False) )
outfile.write('\n')
outfile.close()
subprocess.Popen( [r'notepad.exe', r'print.txt'] )
print_to_file( B*g )
print_to_file( ans, append=True )