我查看过去关于tridiagonals的问题,但似乎没有人遇到过我遇到的问题。我试图使用scipy.sparse.spdiags为非均匀Poisson方程形成三对角刚度矩阵,但结果似乎没有接收矩阵。
def Poisson_Stiffness(x0):
N = len(x0) - 1 #THE AMOUNT OF ELEMENTS (NOT THE AMOUNT OF POINTS) x0, x1, ... , x_N
h = np.zeros(N)
a = np.zeros(N+1)
b = np.zeros(N)
for i in range(N):
h[i] = x0[i+1] - x0[i] #Length of each nonuniform element
a[0] = 1/h[0]
for i in range(1,N):
a[i] = 1/h[i] + 1/h[i-1] #Main Diagonal of stiffness matrix
a[N] = 1/h[N-1]
for i in range(N):
b[i] = -1/h[i] #Upper and lower diagonal of stiffness matrix.
Tridiagonal_Data = np.array([[a],[b],[b]])
Positions = [0, 1, -1]
Stiffness_Matrix = scipy.sparse.spdiags(Tridiagonal_Data,Positions,N+1,N+1)
print Stiffness_Matrix
因此,x0 = [0,0.3,0.4,0.7,1];我得到刚度矩阵:
Jamess-MBP:Poisson jamesmalone$ python Poisson1d.py
(0, 0) [ 3.33333333 13.33333333 13.33333333 6.66666667 3.33333333]
(1, 0) [-3.33333333 -10. -3.33333333 -3.33333333]
我的问题是为什么它会像这样出来而不是以矩阵形式出现?
我尝试更改数据类型以查看是否存在问题,但我会收到错误,例如(for .toarray()):
Jamess-MBP:Poisson jamesmalone$ python Poisson1d.py
Traceback (most recent call last):
File "Poisson1d.py", line 33, in <module>
Poisson_Stiffness([0,0.3,0.4,0.7,1])
File "Poisson1d.py", line 29, in Poisson_Stiffness
Stiffness_Matrix = scipy.sparse.spdiags(Tridiagonal_Data,Positions,N+1,N+1).toarray()
File "/Users/jamesmalone/anaconda/lib/python2.7/site-packages/scipy/sparse/base.py", line 637, in toarray
return self.tocoo().toarray(order=order, out=out)
File "/Users/jamesmalone/anaconda/lib/python2.7/site-packages/scipy/sparse/coo.py", line 275, in toarray
B.ravel('A'), fortran)
RuntimeError: internal error: failed to resolve data types
提前致谢。
答案 0 :(得分:2)
尝试使用scipy.sparse.diags
。我还清理了你的代码,因为你没有利用numpy的优势(广播)与for循环。还根据PEP8清理了一些格式:
from scipy.sparse import diags
x0 = np.array(x0)
N = len(x0) - 1
h = x0[1:] - x0[:-1]
a = np.zeros(N+1)
a[0] = 1/h[0]
a[1:-1] = 1/h[1:] + 1/h[:-1]
a[-1] = 1/h[-1]
b = -1/h
data = [a.tolist(), b.tolist(), b.tolist()]
positions = [0, 1, -1]
stiffness_matrix = diags(data, positions, (N+1, N+1))
print stiffness_matrix.toarray()
使用x0 = [0, 0.3, 0.4, 0.7, 1]
,这会产生
[[ 3.33333333 -3.33333333 0. 0. 0. ]
[ -3.33333333 13.33333333 -10. 0. 0. ]
[ 0. -10. 13.33333333 -3.33333333 0. ]
[ 0. 0. -3.33333333 6.66666667 -3.33333333]
[ 0. 0. 0. -3.33333333 3.33333333]]