【发布时间】: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]
这段代码也会产生同样的错误。
非常感谢任何帮助 谢谢
【问题讨论】:
-
出现错误是因为一个(或多个)变量(
f、Bz、U2、z、eta)不可索引(它不是序列) .现在,我不知道这些是什么,(也许 调用Error_Indicators的代码和上面的一些行会有所帮助)。在这一点上,我只能建议采用这些变量中的每一个并尝试获取其第一个元素:f的示例:f[0]在您的Error_Indicators中并查看哪个(或多个)触发了错误。 -
嗨,它是 Bz 矩阵,因为它是由 scipy.sparse.diags 产生的,因此是 dia_matrix 的东西。所以我不确定如何从 scipy.sparse.diags 矩阵中调用一行(甚至是单个组件)。我将添加更多内容以举例说明我如何称呼它们
标签: python scipy sparse-matrix diagonal