TypeError:'dia_matrix'对象没有属性'__getitem__' - Python
问题描述:
我目前正在尝试从下面的“Poisson Stiffness”中的scipy.sparse.diags函数形成的对角矩阵中产生一行,但我有麻烦选择行和正在以下错误:TypeError:'dia_matrix'对象没有属性'__getitem__' - Python
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()
将是适当的。
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索引。
+0
非常感谢您,我没有意识到您可以切换矩阵类型。 – malonej
错误出现是因为一个(或多个)变量('f','Bz','U2','z','eta')不可索引(它不是一个序列)。现在,我不知道这些是什么,(也许代码_calls_'Error_Indicators'和上面的一些行将帮助)。在这一点上,我只能建议采取这些变量中的每一个,并尝试获取它的第一个元素:例如'Error_Indicators'中的'f':'f [0]',并查看哪一个触发了错误。 – CristiFati
嗨,这是Bz矩阵,因为它是由scipy.sparse.diags生成的,因此是dia_matrix的东西。所以我不知道如何从scipy.sparse.diags矩阵调用一行(甚至是单个组件)。我会再补充一点,以举例说明我会怎么称呼他们 – malonej