这是我非常简单的功能,可以消除bc_id
矩阵行中的所有条目,只保留对角线条目。这就是我通常设置边界条件的方式。我密集地使用它。我知道它不是最优的,它不是很优雅,但是每当我分析我的代码时,这个函数从来都不是问题。可能最好包含一个断言来检查矩阵是否是平方的。
from scipy import sparse
import numpy as np
import matplotlib.pyplot as plt
def set_diag(A,bc_id):
ndofs = A.shape[0]
diago = A.diagonal()
uno = np.ones((ndofs))
uno[bc_id] = 0
uno = sparse.dia_matrix((uno,0), shape = (ndofs,ndofs))
# up to here I delete the rows
# I multiply A by an identity matrix
# where i set to zero the rows I want
# to delete
A = uno.dot(A)
new_diag_entries = np.zeros((ndofs))
# here I set the diagonal entries
# equals to the value on the diagonal.
# Use the second line if you want to
# to set the diagonal entry to one
new_diag_entries[bc_id] = diago[bc_id]
#new_diag_entries[bc_id] = uno[bc_id]
uno = sparse.dia_matrix((new_diag_entries,0), shape = (ndofs,ndofs))
A = A+uno # here I set the diagonal entry
return A
A = sparse.csr_matrix([[1, 2, 3, 10], [4,5, 6,11], [7, 8, 9,12],[13,14,15,16]])
bc_id = np.array([2,3])
A = set_diag(A,bc_id)
print A
