Kwker

Sparse matrices

A sparse matrix is often collected as a list of (row, column, value) entries - the COO format - and then converted to CSR or CSC for computing. The conversion is a sort of the entries by position, so Kwker does it faster. Entries at the same position are combined.

Build a CSR matrix from entries

coo_to_csr takes the entries and the matrix shape and returns the three CSR arrays: row pointers, column indices and values. The two entries at (1, 0) are summed.

PythonRuns on your machine.
import numpy as np
import kwker

rows = np.array([1, 0, 1, 2])
cols = np.array([0, 2, 0, 1])
vals = np.array([1.0, 2.0, 3.0, 5.0])
indptr, indices, data = kwker.coo_to_csr(rows, cols, vals, (3, 3))
print(indptr, indices, data)
Output
[0 1 2 3] [2 0 1] [2. 4. 5.]

coo_to_csc returns the CSC arrays the same way. These are the arrays scipy.sparse.csr_matrix((data, indices, indptr), shape=...) and torch.sparse_csr_tensor take.

Combine duplicates another way

reduce= chooses how entries at one position combine: "sum" (the default), "prod", "min", "max" or "mean". coo_coalesce keeps the COO format, with one entry per position in row order, like PyTorch's coalesce().

PythonRuns on your machine.
import numpy as np
import kwker

rows = np.array([1, 0, 1])
cols = np.array([0, 2, 0])
vals = np.array([1.0, 2.0, 3.0])
print(kwker.coo_coalesce(rows, cols, vals, (2, 3), reduce="max"))
Output
(array([0, 1]), array([2, 0]), array([2., 3.]))

Convert between CSR and CSC

csr_to_csc and csc_to_csr switch formats without sorting the entries again. Pass threads= for large matrices.

PythonRuns on your machine.
import numpy as np
import kwker

indptr = np.array([0, 1, 2, 3])
indices = np.array([2, 0, 1])
data = np.array([2.0, 4.0, 5.0])
print(kwker.csr_to_csc(indptr, indices, data, (3, 3)))
Output
(array([0, 1, 2, 3]), array([1, 2, 0]), array([4., 5., 2.]))

Notes