【问题标题】:TypeError: 'dia_matrix' object has no attribute '__getitem__' - PythonTypeError:“dia_matrix”对象没有属性“__getitem__”-Python
【发布时间】:2015-11-29 16:44:14
【问题描述】:

我目前正在尝试从下面“泊松刚度”中的 scipy.sparse.diags 函数形成的对角矩阵中点积一行,但我在选择行时遇到了问题,并且出现以下错误:

TypeError: 'dia_matrix' object has no attribute '__getitem__'

以下是我的代码

def Poisson_Stiffness(x0):
    """Finds the Poisson equation stiffness matrix with any non uniform mesh x0"""

    x0 = np.array(x0)
    N = len(x0) - 1 # The amount of elements; x0, x1, ..., xN

    h = x0[1:] - x0[:-1]

    a = np.zeros(N+1)
    a[0] = 1 #BOUNDARY CONDITIONS
    a[1:-1] = 1/h[1:] + 1/h[:-1]
    a[-1] = 1/h[-1]
    a[N] = 1 #BOUNDARY CONDITIONS

    b = -1/h
    b[0] = 0 #BOUNDARY CONDITIONS

    c = -1/h
    c[N-1] = 0 #BOUNDARY CONDITIONS: DIRICHLET

    data = [a.tolist(), b.tolist(), c.tolist()]
    Positions = [0, 1, -1]
    Stiffness_Matrix = diags(data, Positions, (N+1,N+1))

    return Stiffness_Matrix


def Error_Indicators(Uh,U_mesh,Z,Z_mesh,f):
    """Take in U, Interpolate to same mesh as Z then solve for eta"""

    u_inter = interp1d(U_mesh,Uh) #Interpolation of old mesh
    U2 = u_inter(Z_mesh) #New function u for the new mesh to use in 

    Bz = Poisson_Stiffness(Z_mesh)

    eta = np.empty(len(Z_mesh))
    for i in range(len(Z_mesh)):
        eta[i] = (f[i] - np.dot(Bz[i,:],U2[:]))*z[i]

    return eta

错误具体来自以下代码行:

eta[i] = (f[i] - np.dot(Bz[i,:],U2[:]))*z[i]

导致错误的是 Bz 矩阵,它是使用 scipy.sparse.diags 创建的,并且不允许我调用该行。

Bz = Poisson_Stiffness(np.linspace(0,1,40))
print Bz[0,0]

这段代码也会产生同样的错误。

非常感谢任何帮助 谢谢

【问题讨论】:

  • 出现错误是因为一个(或多个)变量(fBzU2zeta)不可索引(它不是序列) .现在,我不知道这些是什么,(也许 调用 Error_Indicators 的代码和上面的一些行会有所帮助)。在这一点上,我只能建议采用这些变量中的每一个并尝试获取其第一个元素:f 的示例:f[0] 在您的Error_Indicators 中并查看哪个(或多个)触发了错误。
  • 嗨,它是 Bz 矩阵,因为它是由 scipy.sparse.diags 产生的,因此是 dia_matrix 的东西。所以我不确定如何从 scipy.sparse.diags 矩阵中调用一行(甚至是单个组件)。我将添加更多内容以举例说明我如何称呼它们

标签: python scipy sparse-matrix diagonal


【解决方案1】:

sparse.dia_matrix 显然不支持索引。解决方法是将其转换为另一种格式。出于计算目的,tocsr() 是合适的。

dia_matrix 的文档是有限的,尽管我认为代码是可见的 Python。我必须仔细检查,但我认为它是一种矩阵构造工具,而不是一种完全开发的工作格式。

In [97]: M=sparse.dia_matrix(np.ones((3,4)),[0,-1,2])

In [98]: M[1,:]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-98-a74bcb661a8d> in <module>()
----> 1 M[1,:]

TypeError: 'dia_matrix' object is not subscriptable

In [99]: M.tocsr()[1,:]
Out[99]: 
<1x4 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>

dia_matrix 将其信息存储在.data.offsets 属性中,这是对输入参数的简单修改。它们不适合二维索引。

【讨论】:

  • 非常感谢,我没有意识到你可以像这样切换矩阵类型。
猜你喜欢
  • 2018-04-13
  • 2013-04-15
  • 1970-01-01
  • 2017-01-08
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 2012-10-15
相关资源
最近更新 更多