我目前正在嘗試從下面的「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]
此代碼也會產生相同的錯誤。
任何幫助是非常讚賞 感謝
錯誤出現是因爲一個(或多個)變量('f','Bz','U2','z','eta')不可索引(它不是一個序列)。現在,我不知道這些是什麼,(也許代碼_calls_'Error_Indicators'和上面的一些行將幫助)。在這一點上,我只能建議採取這些變量中的每一個,並嘗試獲取它的第一個元素:例如'Error_Indicators'中的'f':'f [0]',並查看哪一個觸發了錯誤。 – CristiFati
嗨,這是Bz矩陣,因爲它是由scipy.sparse.diags生成的,因此是dia_matrix的東西。所以我不知道如何從scipy.sparse.diags矩陣調用一行(甚至是單個組件)。我會再補充一點,以舉例說明我會怎麼稱呼他們 – malonej