如何防止对稀疏矩阵进行原位修改?

时间:2019-03-05 13:06:35

标签: python scipy

对于创建为的稀疏矩阵

from scipy import sparse
M = sparse.rand(100, 100, format='csr')

有没有一种方法可以防止在构造后对其进行修改?也就是说,禁止执行诸如M[0, 0] = 1之类的操作。

我的动机是将M存储在对象G中,该对象具有依赖于M的其他属性。如果M发生变化,则必须重新计算这些属性,否则G将处于非相干状态。当M完全定义G时,我宁愿禁止修改,并迫使我的用户从他们的新G实例化另一个M。在代码中:

class G:
    def __init__(self, M):
        self.M = M
        self.d = M.sum(axis=0)

# Normal usage.
g = G(M)
print(g.M.toarray())
print(g.d)

# Modification out of my control that leads to an incoherent state.
M[0, 0] = 1
print(g.M.toarray())
print(g.d)

0 个答案:

没有答案