将子矩阵插入Scipy稀疏矩阵

时间:2019-05-06 12:51:53

标签: python scipy sparse-matrix

如何将特定位置的子矩阵有效地插入稀疏矩阵?另外,对于这种增量构造,建议使用哪种稀疏矩阵类?

更具体地说,如何在下面的代码中填充矩阵M?

def rrd(mesh, rel_rotations, neighbors, R_0):
    M = scipy.sparse.lil_matrix((N_FACES*9*3,N_FACES*9))
    for i in range(0,N_FACES*27,27):
        for j in range(3):
            for k in range(0,N_FACES*9,9):
                M[i+j*9:i+(j+1)*9,k:k+9] = -np.eye(9)
    for i in range(len(rel_rotations)):
        diagonals = [
            rel_rotations[i][0][2],
            np.append(rel_rotations[i][0][1].repeat(3), rel_rotations[i][1][2].repeat(3)),
            np.append(rel_rotations[i][0][0].repeat(3), np.append(rel_rotations[i][1][1].repeat(3), 
            rel_rotations[i][2][2].repeat(3))),
            np.append(rel_rotations[i][1][0].repeat(3), rel_rotations[i][2][1].repeat(3)),
            rel_rotations[i][2][0].repeat(3)
        ]
        diag_rel_rotations = scipy.sparse.diags(diagonals, [-6,-3,0,3,6], shape=(9,9)).todense()
        mod = i % 3
        div = int((i-mod)/3)
        n_idx = neighbors[div][mod]
        M[i+mod*9:i+(mod+1)*9][n_idx*9:(n_idx+1)*9] = diag_rel_rotations

切片在这里不起作用,我查看了一些不同类型的稀疏矩阵,但无法弄清楚哪种方法适合解决此问题。

1 个答案:

答案 0 :(得分:0)

lil是最合适的分配对象。

In [553]: M = sparse.lil_matrix((9,9), dtype=int)                                    
In [554]: M                                                                          
Out[554]: 
<9x9 sparse matrix of type '<class 'numpy.int64'>'
    with 0 stored elements in LInked List format>

In [555]: M[2:5, 3:6] = np.eye(3)                                                    
In [556]: M                                                                          
Out[556]: 
<9x9 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in LInked List format>
In [557]: M.A                                                                        
Out[557]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0]])

In [558]: d = sparse.diags([[1,2],[1,2,3],[2,3]], [-1,0,1]) 
In [562]: M[0:3, 6:9] = d