gpt4 book ai didi

python - 类型错误 : 'dia_matrix' object has no attribute '__getitem__' - Python

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:48 26 4
gpt4 key购买 nike

我目前正在尝试从下面“泊松刚度”中的 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() 是合适的。

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

关于python - 类型错误 : 'dia_matrix' object has no attribute '__getitem__' - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com