python - 使用张量数组时 SymPy 中的类型错误

标签 python arrays slice sympy

我对 SymPy、SciPy、NumPy 等相当陌生,所以也许有更简单的方法来实现我的目标,即为 4- 定义一系列索引 4x4 变换矩阵杆联动。我对第三个rd 维度没有任何迫切的需求,除了可以轻松迭代序列 {A0 ... A3} 在我的代码中。

下面的代码生成以下错误。

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 表达式):

In [18]: A_numpy = numpy.array(A.tolist()).astype(object)

运行 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⎦⎦

关于python - 使用张量数组时 SymPy 中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46796005/

相关文章:

python - Python 中的 Unicode 问题

python - 在多个文件/目录中搜索字符串,然后打印文本文件的内容

javascript - 根据项目的一个属性获取项目的数组索引

java - 在数组中打印 "x"以下的所有数字

Python 服务器 "Aborted (Core dumped)"

python - 解析列表项并使用理解返回字典

c++ - 调用cudaMemcpy2DToArray时访问违规读取位置

python - 我如何引用列表中不同范围的值?

types - golang 中的通用 slice 类型?

c++ - 切片 std::array