import numpy as np
import scipy.sparse as sparse
data = [1.0, 1.0, 1.0, 3.0, 4.4]
col = [0, 2, 2, 1, 1]
row = [0, 0, 0, 1, 2]
A = sparse.coo_matrix((data, (row, col)), shape=(3,3))
print(A.todense())
print(A.data.dtype, A.data.shape)
print(A.col.dtype, A.col.shape)
print(A.row.dtype, A.row.shape)
print(A.nnz)
print(A.format)
A = A.tocsr()
print(A.format)
print(A.data)
print(A.indices)
print(A.indptr)
A[0,0] = 0.0
print(A.todense())
print(A.nnz)
A.eliminate_zeros()
print(A.nnz)
Let's make a random sparse matrix
First we'll set the density so that $$ density = \frac{nnz(A)}{n^2} $$
n = 1000
density = 5.0 / n # 5 points per row
nnz = int(n*n*density)
print(nnz)
Now make the entries:
row = np.random.random_integers(low=0, high=n-1, size=nnz)
col = np.random.random_integers(low=0, high=n-1, size=nnz)
data = np.ones(nnz, dtype=float)
A = sparse.coo_matrix((data, (row, col)), shape=(n, n))
print(A.dtype)
import matplotlib.pyplot as plt
%matplotlib inline
plt.spy(A, marker='.', markersize=2)
print(A.shape, A.nnz)
But let's make it positive definite:
A.data[:] = -1.0 # -1 for off-diagonals
rowsum = -np.array(A.sum(axis=1)) # positive rowsum
rowsum = rowsum.ravel()
A.setdiag(rowsum)
u = np.random.rand(n)
v = np.random.rand(n)
%timeit v = A * u
B = A.toarray()
type(B)
%timeit v = B.dot(u)