繁体   English   中英

TypeError:'dia_matrix'对象没有属性'__getitem__'-Python

[英]TypeError: 'dia_matrix' object has no attribute '__getitem__' - Python

我目前正在尝试从下面的“泊松刚度”中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]

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

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

此代码也将产生相同的错误。

任何帮助都非常感谢

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属性中,这是对输入参数的简单修改。 它们不适用于2d索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM