2015-09-03 213 views
0

我目前正在嘗試從下面的「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] 

此代碼也會產生相同的錯誤。

任何幫助是非常讚賞 感謝

+0

錯誤出現是因爲一個(或多個)變量('f','Bz','U2','z','eta')不可索引(它不是一個序列)。現在,我不知道這些是什麼,(也許代碼_calls_'Error_Indicators'和上面的一些行將幫助)。在這一點上,我只能建議採取這些變量中的每一個,並嘗試獲取它的第一個元素:例如'Error_Indicators'中的'f':'f [0]',並查看哪一個觸發了錯誤。 – CristiFati

+0

嗨,這是Bz矩陣,因爲它是由scipy.sparse.diags生成的,因此是dia_matrix的東西。所以我不知道如何從scipy.sparse.diags矩陣調用一行(甚至是單個組件)。我會再補充一點,以舉例說明我會怎麼稱呼他們 – malonej

回答

3

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

相關問題