Sparse matrices in Python
When most entries are zero, store only the ones that are not.
import numpy as np
from scipy import sparse
from scipy.sparse import linalg as splinalg
dense = np.array([[4.0, 0.0, 1.0], [0.0, 3.0, 0.0], [1.0, 0.0, 2.0]])
matrix = sparse.csr_array(dense)
print(matrix.shape, matrix.nnz, f"{matrix.nnz / dense.size:.0%} filled")
print(matrix.toarray()[0])
x = splinalg.spsolve(matrix.tocsc(), np.array([1.0, 2.0, 3.0]))
print(x.round(4), np.allclose(dense @ x, [1, 2, 3]))
identity = sparse.eye_array(3, format="csr")
print((matrix + identity).diagonal())
How it works
csr_arrayis the row-oriented format for arithmetic and solving.nnzandtoarrayshow what is stored against what it means.spsolvesolves a sparse system without densifying it.
Keywords and builtins used here
asformatprint
The run, in numbers
- Lines
- 15
- Characters to type
- 494
- Tokens
- 170
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 93 seconds.
Step 1 of 4 in Sparse & spatial, step 19 of 23 in Scientific computing with SciPy.