TypeError:“dia_matrix”对象没有属性“\uuuu getitem\uuuu'-Python”

TypeError:“dia_matrix”对象没有属性“\uuuu getitem\uuuu'-Python”,python,scipy,sparse-matrix,diagonal,Python,Scipy,Sparse Matrix,Diagonal,我目前正试图从下面Poisson Stiffness中的scipy.sparse.diags函数形成的对角线矩阵中点积一行,但我在选择行时遇到问题,并出现以下错误: TypeError: 'dia_matrix' object has no attribute '__getitem__' 下面是我的代码 def Poisson_Stiffness(x0): """Finds the Poisson equation stiffness matrix with any non unifo

我目前正试图从下面Poisson Stiffness中的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]
此代码也将产生相同的错误

非常感谢您的帮助 谢谢

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

Diau 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>

直径矩阵将其信息存储在.data和.offset属性中,这是对输入参数的简单修改。它们不支持二维索引。

错误是因为一个或多个变量f、Bz、U2、z、eta不可索引,而不是序列。现在,我不知道这些是什么,也许调用Error_指示符的代码和上面的一些行会有所帮助。在这一点上,我只能建议采取这些变量中的每一个,并尝试获取它的第一个元素:例如,在您的错误指示器中的f:f[0],并查看哪些元素触发了错误。嗨,这是Bz矩阵,因为它是由scipy.sparse.diags生成的,因此是直径矩阵。因此,我不确定如何从scipy.sparse.diags矩阵中调用行甚至单个组件。我会再加上一点,给大家举个例子,告诉大家我是如何称呼它们的。多谢了,我没想到你们可以像这样切换矩阵类型。