Python 使用张量数组时在SymPy中键入错误
我对SymPy、SciPy、NumPy等比较陌生,所以也许有更简单的方法来实现我的目标,即为四杆机构定义一系列索引的4x4变换矩阵。我对第三维没有任何迫切的需求,只是为了使代码中的序列{A0…A3}易于迭代 下面的代码生成以下错误Python 使用张量数组时在SymPy中键入错误,python,arrays,slice,sympy,Python,Arrays,Slice,Sympy,我对SymPy、SciPy、NumPy等比较陌生,所以也许有更简单的方法来实现我的目标,即为四杆机构定义一系列索引的4x4变换矩阵。我对第三维没有任何迫切的需求,只是为了使代码中的序列{A0…A3}易于迭代 下面的代码生成以下错误 TypeError: unorderable types: slice() >= int() 另一方面,将A[:,:,i]替换为下面的A0确实会生成预期的4x4符号数组,因此可能我没有正确定义切片——但是,其他切片排列似乎也不起作用。(我在最后一行代码的隐含行
TypeError: unorderable types: slice() >= int()
另一方面,将A[:,:,i]
替换为下面的A0
确实会生成预期的4x4符号数组,因此可能我没有正确定义切片——但是,其他切片排列似乎也不起作用。(我在最后一行代码的隐含行延续上也有问题,所以我将所有内容都内联。)
如果您能就如何解决这个问题提出建议,我将不胜感激
from sympy import *
def plg_jac():
a_3, a_4, d_2, theta_1, theta_4 = symbols('a_3, a_4, d_2, theta_1, theta_4')
# The D-H table is defined by the following 4 vectors
a = Matrix([0, 0, a_3, -a_4])
alpha = Matrix([pi/2, pi/2, 0, 0])
d = Matrix([0, d_2, 0, 0])
theta = Matrix([theta_1, pi, 0, theta_4])
# Initialise a mutable 4x4x4 array
A = tensor.array.MutableDenseNDimArray(range(64), (4,4,4))
# Now define A0 ... A3, the transformation matrices between links i & i+1
for i in range(a.shape[0]):
A[:,:,i] = Array([[cos(theta[i]), -sin(theta[i])*cos(alpha[i]), sin(theta[i])*sin(alpha[i]), a[i]*cos(theta[i])], [sin(theta[i]), cos(theta[i])*cos(alpha[i]), -cos(theta[i])*sin(alpha[i]), a[i]*sin(theta[i])], [0, sin(alpha[i]), cos(alpha[i]), d[i]], [0, 0, 0, 1]])
缺少对SymPy数组切片的赋值,可以使用numpy来弥补这一不足 将NumPy导入为:
import numpy
将SymPy数组转换为NumPy数组(对象类型,以便包含SymPy表达式):
运行for循环的修改版本:
In [19]: for i in range(a.shape[0]):
...: A_numpy[:, :, i] = [[cos(theta[i]), -sin(theta[i])*cos(alpha[i]), s
...: in(theta[i])*sin(alpha[i]), a[i]*cos(theta[i])], [sin(theta[i]), cos(th
...: eta[i])*cos(alpha[i]), -cos(theta[i])*sin(alpha[i]), a[i]*sin(theta[i])
...: ], [0, sin(alpha[i]), cos(alpha[i]), d[i]], [0, 0, 0, 1]]
...:
将生成的NumPy数组转换回SymPy数组:
In [20]: A = Array(A_numpy)
打印其内容:
In [21]: A
Out[21]:
⎡⎡cos(θ₁) -1 1 cos(θ₄) ⎤ ⎡sin(θ₁) 0 0 sin(θ₄) ⎤ ⎡0 0 0 0⎤
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢⎢ 0 0 0 -sin(θ₄) ⎥ ⎢ 0 0 1 cos(θ₄) ⎥ ⎢1 1 0 0⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢⎢sin(θ₁) 0 0 0 ⎥ ⎢-cos(θ₁) 1 0 0 ⎥ ⎢0 0 1 1⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎣⎣ 0 0 a₃ -a₄⋅cos(θ₄)⎦ ⎣ 0 0 0 -a₄⋅sin(θ₄)⎦ ⎣0 d₂ 0 0⎦
⎡0 0 0 0⎤⎤
⎢ ⎥⎥
⎢0 0 0 0⎥⎥
⎢ ⎥⎥
⎢0 0 0 0⎥⎥
⎢ ⎥⎥
⎣1 1 1 1⎦⎦
这是完美的;这正是我需要的。非常感谢你!
In [21]: A
Out[21]:
⎡⎡cos(θ₁) -1 1 cos(θ₄) ⎤ ⎡sin(θ₁) 0 0 sin(θ₄) ⎤ ⎡0 0 0 0⎤
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢⎢ 0 0 0 -sin(θ₄) ⎥ ⎢ 0 0 1 cos(θ₄) ⎥ ⎢1 1 0 0⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢⎢sin(θ₁) 0 0 0 ⎥ ⎢-cos(θ₁) 1 0 0 ⎥ ⎢0 0 1 1⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎣⎣ 0 0 a₃ -a₄⋅cos(θ₄)⎦ ⎣ 0 0 0 -a₄⋅sin(θ₄)⎦ ⎣0 d₂ 0 0⎦
⎡0 0 0 0⎤⎤
⎢ ⎥⎥
⎢0 0 0 0⎥⎥
⎢ ⎥⎥
⎢0 0 0 0⎥⎥
⎢ ⎥⎥
⎣1 1 1 1⎦⎦