vsparse 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vsparse/__init__.py +27 -0
- vsparse/_anndata.py +68 -0
- vsparse/_anndata_class.py +346 -0
- vsparse/_base.py +589 -0
- vsparse/_compression.py +162 -0
- vsparse/_construct.py +194 -0
- vsparse/_indexutils.py +36 -0
- vsparse/_io.py +139 -0
- vsparse/_ivcsc.py +265 -0
- vsparse/_norm_common.py +304 -0
- vsparse/_ops.py +93 -0
- vsparse/_rapid_load.py +552 -0
- vsparse/_vcs_matmul.py +168 -0
- vsparse/_vcs_norm.py +62 -0
- vsparse/py.typed +0 -0
- vsparse-0.1.0.dist-info/METADATA +175 -0
- vsparse-0.1.0.dist-info/RECORD +18 -0
- vsparse-0.1.0.dist-info/WHEEL +4 -0
vsparse/_base.py
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
"""Value-Compressed Sparse Column/Row array types.
|
|
2
|
+
|
|
3
|
+
VCSC/VCSR are compressed-sparse layouts, inspired by IVSparse's VCSC
|
|
4
|
+
(https://github.com/Seth-Wolfgang/IVSparse), that additionally deduplicate
|
|
5
|
+
the stored values within each major-axis slice (columns for VCSC, rows for
|
|
6
|
+
VCSR). Instead of one stored value per nonzero, each unique value in a
|
|
7
|
+
slice is stored once alongside the list of minor-axis indices that share
|
|
8
|
+
it. This is a strict win in memory whenever values repeat heavily within a
|
|
9
|
+
slice, as is common for integer count matrices (e.g. single-cell RNA-seq
|
|
10
|
+
counts).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
import scipy.sparse as sp
|
|
19
|
+
|
|
20
|
+
from vsparse import _construct, _ops
|
|
21
|
+
from vsparse._indexutils import is_full_slice as _is_full_slice
|
|
22
|
+
from vsparse._indexutils import normalize_major_idx as _normalize_major_idx
|
|
23
|
+
|
|
24
|
+
__all__ = ["VCSCArray", "VCSRArray"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _VCSBase:
|
|
28
|
+
"""Shared implementation for :class:`VCSCArray` and :class:`VCSRArray`.
|
|
29
|
+
|
|
30
|
+
Subclasses fix ``_format`` to ``"csc"`` or ``"csr"``, which determines
|
|
31
|
+
whether the major axis (the axis whose slices are value-compressed) is
|
|
32
|
+
columns or rows.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
_format: str
|
|
36
|
+
|
|
37
|
+
# Tell numpy to defer binary operators (e.g. ndarray @ VCSCArray) to our
|
|
38
|
+
# __rmatmul__/__rmul__ instead of trying to broadcast us as an ndarray.
|
|
39
|
+
__array_ufunc__ = None
|
|
40
|
+
|
|
41
|
+
__slots__ = ("indices", "major_ptr", "shape", "value_ptr", "values")
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
shape: tuple[int, int],
|
|
46
|
+
major_ptr: np.ndarray,
|
|
47
|
+
values: np.ndarray,
|
|
48
|
+
value_ptr: np.ndarray,
|
|
49
|
+
indices: np.ndarray,
|
|
50
|
+
) -> None:
|
|
51
|
+
n_major, n_minor = self._swap(shape)
|
|
52
|
+
major_ptr = np.asarray(major_ptr, dtype=np.int64)
|
|
53
|
+
value_ptr = np.asarray(value_ptr, dtype=np.int64)
|
|
54
|
+
values = np.asarray(values)
|
|
55
|
+
indices = np.asarray(indices)
|
|
56
|
+
|
|
57
|
+
if major_ptr.shape[0] != n_major + 1:
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"major_ptr has length {major_ptr.shape[0]}, expected {n_major + 1}"
|
|
60
|
+
)
|
|
61
|
+
if value_ptr.shape[0] != values.shape[0] + 1:
|
|
62
|
+
raise ValueError("value_ptr must have length len(values) + 1")
|
|
63
|
+
if major_ptr[-1] != values.shape[0]:
|
|
64
|
+
raise ValueError("major_ptr[-1] must equal len(values)")
|
|
65
|
+
if value_ptr[-1] != indices.shape[0]:
|
|
66
|
+
raise ValueError("value_ptr[-1] must equal len(indices)")
|
|
67
|
+
if indices.shape[0] and (indices.min() < 0 or indices.max() >= n_minor):
|
|
68
|
+
raise ValueError("indices out of bounds for the given shape")
|
|
69
|
+
|
|
70
|
+
self.shape = (int(shape[0]), int(shape[1]))
|
|
71
|
+
self.major_ptr = major_ptr
|
|
72
|
+
self.values = values
|
|
73
|
+
self.value_ptr = value_ptr
|
|
74
|
+
self.indices = indices
|
|
75
|
+
|
|
76
|
+
# -- axis bookkeeping ------------------------------------------------
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def _swap(cls, shape: tuple[int, int]) -> tuple[int, int]:
|
|
80
|
+
"""Return ``(n_major, n_minor)`` for the given ``(n_rows, n_cols)``."""
|
|
81
|
+
n_rows, n_cols = shape
|
|
82
|
+
return (n_cols, n_rows) if cls._format == "csc" else (n_rows, n_cols)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def n_major(self) -> int:
|
|
86
|
+
return self._swap(self.shape)[0]
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def n_minor(self) -> int:
|
|
90
|
+
return self._swap(self.shape)[1]
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def nnz(self) -> int:
|
|
94
|
+
return int(self.indices.shape[0])
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def dtype(self) -> np.dtype:
|
|
98
|
+
return self.values.dtype
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def n_unique(self) -> int:
|
|
102
|
+
"""Number of stored (major-slice, unique-value) entries."""
|
|
103
|
+
return int(self.values.shape[0])
|
|
104
|
+
|
|
105
|
+
def __repr__(self) -> str: # pragma: no cover - cosmetic
|
|
106
|
+
cls = type(self).__name__
|
|
107
|
+
return (
|
|
108
|
+
f"<{cls} shape={self.shape} dtype={self.dtype} "
|
|
109
|
+
f"nnz={self.nnz} n_unique={self.n_unique}>"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def copy(self):
|
|
113
|
+
return type(self)(
|
|
114
|
+
self.shape,
|
|
115
|
+
self.major_ptr.copy(),
|
|
116
|
+
self.values.copy(),
|
|
117
|
+
self.value_ptr.copy(),
|
|
118
|
+
self.indices.copy(),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
# -- construction / conversion ---------------------------------------
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
def from_scipy(cls, mat) -> _VCSBase:
|
|
125
|
+
"""Build from any scipy sparse array/matrix (converted internally)."""
|
|
126
|
+
mat = mat.tocsc() if cls._format == "csc" else mat.tocsr()
|
|
127
|
+
n_major, _n_minor = cls._swap(mat.shape)
|
|
128
|
+
major_ptr, values, value_ptr, indices = _construct.compress(
|
|
129
|
+
mat.indptr, mat.indices, mat.data, n_major
|
|
130
|
+
)
|
|
131
|
+
return cls(mat.shape, major_ptr, values, value_ptr, indices)
|
|
132
|
+
|
|
133
|
+
def to_scipy(self):
|
|
134
|
+
"""Decompress to the equivalent scipy ``csc_array``/``csr_array``."""
|
|
135
|
+
n_major, _n_minor = self._swap(self.shape)
|
|
136
|
+
major_ptr, indices, data = _construct.decompress(
|
|
137
|
+
self.major_ptr, self.values, self.value_ptr, self.indices, n_major
|
|
138
|
+
)
|
|
139
|
+
cls = sp.csc_array if self._format == "csc" else sp.csr_array
|
|
140
|
+
return cls((data, indices, major_ptr), shape=self.shape)
|
|
141
|
+
|
|
142
|
+
def to_csc(self) -> sp.csc_array:
|
|
143
|
+
return self.to_scipy().tocsc()
|
|
144
|
+
|
|
145
|
+
def to_csr(self) -> sp.csr_array:
|
|
146
|
+
return self.to_scipy().tocsr()
|
|
147
|
+
|
|
148
|
+
def toarray(self) -> np.ndarray:
|
|
149
|
+
return self.to_scipy().toarray()
|
|
150
|
+
|
|
151
|
+
def astype(self, dtype: Any, copy: bool = True) -> _VCSBase:
|
|
152
|
+
"""Cast the stored values to ``dtype``. Structural zeros stay zero implicitly."""
|
|
153
|
+
dtype = np.dtype(dtype)
|
|
154
|
+
if not copy and dtype == self.dtype:
|
|
155
|
+
return self
|
|
156
|
+
return type(self)(
|
|
157
|
+
self.shape,
|
|
158
|
+
self.major_ptr.copy(),
|
|
159
|
+
self.values.astype(dtype),
|
|
160
|
+
self.value_ptr.copy(),
|
|
161
|
+
self.indices.copy(),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
# -- structural ops ----------------------------------------------------
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def T(self) -> _VCSBase:
|
|
168
|
+
"""Transpose. Free: shares buffers and swaps the VCSC/VCSR dual class."""
|
|
169
|
+
other_cls = VCSRArray if self._format == "csc" else VCSCArray
|
|
170
|
+
return other_cls(
|
|
171
|
+
(self.shape[1], self.shape[0]),
|
|
172
|
+
self.major_ptr,
|
|
173
|
+
self.values,
|
|
174
|
+
self.value_ptr,
|
|
175
|
+
self.indices,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
def transpose(self) -> _VCSBase:
|
|
179
|
+
return self.T
|
|
180
|
+
|
|
181
|
+
def _transpose_major(self) -> _VCSBase:
|
|
182
|
+
"""Convert to the other VCS format (VCSC<->VCSR) of the *same* shape.
|
|
183
|
+
|
|
184
|
+
Unlike :attr:`T` (free: reinterprets the same buffers as the
|
|
185
|
+
transposed matrix), this physically re-groups the stored values by
|
|
186
|
+
the other axis -- see :func:`vsparse._construct.transpose_major`. Used
|
|
187
|
+
to give a major-aligned (parallel-safe, no scatter) kernel something
|
|
188
|
+
to run against, in the direction the array wasn't built for.
|
|
189
|
+
"""
|
|
190
|
+
other_cls = VCSRArray if self._format == "csc" else VCSCArray
|
|
191
|
+
major_ptr, values, value_ptr, indices = _construct.transpose_major(
|
|
192
|
+
self.major_ptr, self.values, self.value_ptr, self.indices, self.n_minor
|
|
193
|
+
)
|
|
194
|
+
return other_cls(self.shape, major_ptr, values, value_ptr, indices)
|
|
195
|
+
|
|
196
|
+
def normalized(self) -> Any:
|
|
197
|
+
"""A read-depth-normalized, log-transformed, mean-centered *view* -- see :mod:`vsparse._vcs_norm`."""
|
|
198
|
+
from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
|
|
199
|
+
|
|
200
|
+
cls = VCSCArrayNormalized if self._format == "csc" else VCSRArrayNormalized
|
|
201
|
+
return cls(self)
|
|
202
|
+
|
|
203
|
+
def log1p(self) -> _VCSBase:
|
|
204
|
+
"""Elementwise ``log1p``. Structural zeros stay zero implicitly."""
|
|
205
|
+
return type(self)(
|
|
206
|
+
self.shape,
|
|
207
|
+
self.major_ptr.copy(),
|
|
208
|
+
np.log1p(self.values),
|
|
209
|
+
self.value_ptr.copy(),
|
|
210
|
+
self.indices.copy(),
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# -- reductions -----------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
def _major_sums(self) -> np.ndarray:
|
|
216
|
+
"""Per-major-slice totals -- cheap, doesn't touch ``indices``."""
|
|
217
|
+
group_sizes = np.diff(self.value_ptr)
|
|
218
|
+
weighted = self.values.astype(np.float64) * group_sizes
|
|
219
|
+
group_of_major = np.repeat(np.arange(self.n_major, dtype=np.int64), np.diff(self.major_ptr))
|
|
220
|
+
return np.bincount(group_of_major, weights=weighted, minlength=self.n_major)
|
|
221
|
+
|
|
222
|
+
def _minor_sums(self) -> np.ndarray:
|
|
223
|
+
"""Per-minor-index totals -- a scatter-add over every nonzero."""
|
|
224
|
+
group_sizes = np.diff(self.value_ptr)
|
|
225
|
+
expanded = np.repeat(self.values.astype(np.float64), group_sizes)
|
|
226
|
+
return np.bincount(self.indices, weights=expanded, minlength=self.n_minor)
|
|
227
|
+
|
|
228
|
+
def sum(self, axis: int | None = None) -> np.ndarray | float:
|
|
229
|
+
"""Sum of (structural) values along ``axis`` (0=rows, 1=columns), or overall if ``None``."""
|
|
230
|
+
if axis is None:
|
|
231
|
+
group_sizes = np.diff(self.value_ptr)
|
|
232
|
+
return float(np.sum(self.values.astype(np.float64) * group_sizes))
|
|
233
|
+
if axis not in (0, 1):
|
|
234
|
+
raise ValueError(f"axis must be None, 0, or 1, got {axis!r}")
|
|
235
|
+
# axis=0 reduces over rows (column totals); axis=1 reduces over
|
|
236
|
+
# columns (row totals). Major-slice totals are column totals for
|
|
237
|
+
# VCSC (major=columns) and row totals for VCSR (major=rows).
|
|
238
|
+
major_axis = 0 if self._format == "csc" else 1
|
|
239
|
+
return self._major_sums() if axis == major_axis else self._minor_sums()
|
|
240
|
+
|
|
241
|
+
def _major_nnz(self) -> np.ndarray:
|
|
242
|
+
"""Per-major-slice stored-element counts -- doesn't touch ``indices``."""
|
|
243
|
+
return (self.value_ptr[self.major_ptr[1:]] - self.value_ptr[self.major_ptr[:-1]]).astype(
|
|
244
|
+
np.int64
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def _minor_nnz(self) -> np.ndarray:
|
|
248
|
+
"""Per-minor-index stored-element counts -- a scatter-add over every nonzero."""
|
|
249
|
+
return np.bincount(self.indices, minlength=self.n_minor).astype(np.int64)
|
|
250
|
+
|
|
251
|
+
def getnnz(self, axis: int | None = None) -> np.ndarray | int:
|
|
252
|
+
"""Count of stored elements along ``axis``, or overall if ``None``."""
|
|
253
|
+
if axis is None:
|
|
254
|
+
return self.nnz
|
|
255
|
+
if axis not in (0, 1):
|
|
256
|
+
raise ValueError(f"axis must be None, 0, or 1, got {axis!r}")
|
|
257
|
+
major_axis = 0 if self._format == "csc" else 1
|
|
258
|
+
return self._major_nnz() if axis == major_axis else self._minor_nnz()
|
|
259
|
+
|
|
260
|
+
def count_nonzero(self) -> int:
|
|
261
|
+
"""Count of stored elements that are actually nonzero (unlike :attr:`nnz`/``getnnz``)."""
|
|
262
|
+
group_sizes = np.diff(self.value_ptr)
|
|
263
|
+
return int(np.sum(group_sizes[self.values != 0]))
|
|
264
|
+
|
|
265
|
+
def mean(self, axis: int | None = None) -> np.ndarray | float:
|
|
266
|
+
"""Mean of (structural + implicit-zero) values along ``axis``, or overall if ``None``."""
|
|
267
|
+
if axis is None:
|
|
268
|
+
total = self.shape[0] * self.shape[1]
|
|
269
|
+
return self.sum() / total if total else float("nan")
|
|
270
|
+
if axis not in (0, 1):
|
|
271
|
+
raise ValueError(f"axis must be None, 0, or 1, got {axis!r}")
|
|
272
|
+
denom = self.shape[0] if axis == 0 else self.shape[1]
|
|
273
|
+
return self.sum(axis=axis) / denom if denom else np.full(0, float("nan"))
|
|
274
|
+
|
|
275
|
+
def _reduce_initial(self, kind: str) -> Any:
|
|
276
|
+
"""Identity element for a max/min reduction over ``self.values.dtype``."""
|
|
277
|
+
dt = self.values.dtype
|
|
278
|
+
if np.issubdtype(dt, np.integer):
|
|
279
|
+
return np.iinfo(dt).min if kind == "max" else np.iinfo(dt).max
|
|
280
|
+
return -np.inf if kind == "max" else np.inf
|
|
281
|
+
|
|
282
|
+
def _major_reduce(self, ufunc: np.ufunc, initial: Any) -> np.ndarray:
|
|
283
|
+
"""Per-major-slice max/min, accounting for implicit zeros in sparse slices."""
|
|
284
|
+
out = np.full(self.n_major, initial, dtype=self.values.dtype)
|
|
285
|
+
group_of_major = np.repeat(np.arange(self.n_major, dtype=np.int64), np.diff(self.major_ptr))
|
|
286
|
+
ufunc.at(out, group_of_major, self.values)
|
|
287
|
+
nnz_per_major = self.value_ptr[self.major_ptr[1:]] - self.value_ptr[self.major_ptr[:-1]]
|
|
288
|
+
not_dense = nnz_per_major < self.n_minor
|
|
289
|
+
out[not_dense] = ufunc(out[not_dense], 0)
|
|
290
|
+
return out
|
|
291
|
+
|
|
292
|
+
def _minor_reduce(self, ufunc: np.ufunc, initial: Any) -> np.ndarray:
|
|
293
|
+
"""Per-minor-index max/min, accounting for implicit zeros in sparse slices."""
|
|
294
|
+
group_sizes = np.diff(self.value_ptr)
|
|
295
|
+
expanded = np.repeat(self.values, group_sizes)
|
|
296
|
+
out = np.full(self.n_minor, initial, dtype=self.values.dtype)
|
|
297
|
+
ufunc.at(out, self.indices, expanded)
|
|
298
|
+
counts = np.bincount(self.indices, minlength=self.n_minor)
|
|
299
|
+
not_dense = counts < self.n_major
|
|
300
|
+
out[not_dense] = ufunc(out[not_dense], 0)
|
|
301
|
+
return out
|
|
302
|
+
|
|
303
|
+
def _reduce(self, ufunc: np.ufunc, kind: str, axis: int | None) -> np.ndarray | Any:
|
|
304
|
+
initial = self._reduce_initial(kind)
|
|
305
|
+
if axis is None:
|
|
306
|
+
m = ufunc.reduce(self.values, initial=initial) if self.values.size else initial
|
|
307
|
+
if self.nnz < self.shape[0] * self.shape[1]:
|
|
308
|
+
m = ufunc(m, 0)
|
|
309
|
+
return m.item() if hasattr(m, "item") else m
|
|
310
|
+
if axis not in (0, 1):
|
|
311
|
+
raise ValueError(f"axis must be None, 0, or 1, got {axis!r}")
|
|
312
|
+
major_axis = 0 if self._format == "csc" else 1
|
|
313
|
+
return (
|
|
314
|
+
self._major_reduce(ufunc, initial)
|
|
315
|
+
if axis == major_axis
|
|
316
|
+
else self._minor_reduce(ufunc, initial)
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
def max(self, axis: int | None = None) -> np.ndarray | Any:
|
|
320
|
+
"""Maximum value (including implicit zeros) along ``axis``, or overall if ``None``."""
|
|
321
|
+
return self._reduce(np.maximum, "max", axis)
|
|
322
|
+
|
|
323
|
+
def min(self, axis: int | None = None) -> np.ndarray | Any:
|
|
324
|
+
"""Minimum value (including implicit zeros) along ``axis``, or overall if ``None``."""
|
|
325
|
+
return self._reduce(np.minimum, "min", axis)
|
|
326
|
+
|
|
327
|
+
# -- elementwise arithmetic ----------------------------------------------
|
|
328
|
+
|
|
329
|
+
def _elementwise(self, other: Any, op_name: str) -> _VCSBase | np.ndarray:
|
|
330
|
+
"""Fall back to scipy to compute an elementwise binary op, re-wrapping a sparse result."""
|
|
331
|
+
other_arg = other.to_scipy() if isinstance(other, _VCSBase) else other
|
|
332
|
+
self_scipy = self.to_scipy()
|
|
333
|
+
if op_name == "multiply":
|
|
334
|
+
result = self_scipy.multiply(other_arg)
|
|
335
|
+
else:
|
|
336
|
+
result = getattr(self_scipy, op_name)(other_arg)
|
|
337
|
+
if result is NotImplemented:
|
|
338
|
+
return NotImplemented
|
|
339
|
+
if sp.issparse(result):
|
|
340
|
+
return type(self).from_scipy(result)
|
|
341
|
+
return np.asarray(result)
|
|
342
|
+
|
|
343
|
+
def __add__(self, other):
|
|
344
|
+
if np.isscalar(other):
|
|
345
|
+
if other == 0:
|
|
346
|
+
return self.copy()
|
|
347
|
+
raise NotImplementedError(
|
|
348
|
+
"adding a nonzero scalar to a sparse array is not supported"
|
|
349
|
+
)
|
|
350
|
+
return self._elementwise(other, "__add__")
|
|
351
|
+
|
|
352
|
+
__radd__ = __add__
|
|
353
|
+
|
|
354
|
+
def __sub__(self, other):
|
|
355
|
+
if np.isscalar(other):
|
|
356
|
+
if other == 0:
|
|
357
|
+
return self.copy()
|
|
358
|
+
raise NotImplementedError(
|
|
359
|
+
"subtracting a nonzero scalar from a sparse array is not supported"
|
|
360
|
+
)
|
|
361
|
+
return self._elementwise(other, "__sub__")
|
|
362
|
+
|
|
363
|
+
def __rsub__(self, other):
|
|
364
|
+
if np.isscalar(other):
|
|
365
|
+
if other == 0:
|
|
366
|
+
return -self
|
|
367
|
+
raise NotImplementedError(
|
|
368
|
+
"subtracting a sparse array from a nonzero scalar is not supported"
|
|
369
|
+
)
|
|
370
|
+
other_arg = other.to_scipy() if isinstance(other, _VCSBase) else other
|
|
371
|
+
result = other_arg - self.to_scipy()
|
|
372
|
+
if sp.issparse(result):
|
|
373
|
+
return type(self).from_scipy(result)
|
|
374
|
+
return np.asarray(result)
|
|
375
|
+
|
|
376
|
+
def multiply(self, other) -> _VCSBase | np.ndarray:
|
|
377
|
+
"""Elementwise multiplication (matches scipy's sparse-array ``.multiply``)."""
|
|
378
|
+
return self * other
|
|
379
|
+
|
|
380
|
+
# -- scalar arithmetic --------------------------------------------------
|
|
381
|
+
|
|
382
|
+
def _empty_like(self) -> _VCSBase:
|
|
383
|
+
n_major, _ = self._swap(self.shape)
|
|
384
|
+
return type(self)(
|
|
385
|
+
self.shape,
|
|
386
|
+
np.zeros(n_major + 1, dtype=np.int64),
|
|
387
|
+
np.empty(0, dtype=self.values.dtype),
|
|
388
|
+
np.zeros(1, dtype=np.int64),
|
|
389
|
+
np.empty(0, dtype=self.indices.dtype),
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
def __mul__(self, other):
|
|
393
|
+
if np.isscalar(other):
|
|
394
|
+
if other == 0:
|
|
395
|
+
return self._empty_like()
|
|
396
|
+
return type(self)(
|
|
397
|
+
self.shape,
|
|
398
|
+
self.major_ptr.copy(),
|
|
399
|
+
self.values * other,
|
|
400
|
+
self.value_ptr.copy(),
|
|
401
|
+
self.indices.copy(),
|
|
402
|
+
)
|
|
403
|
+
return self._elementwise(other, "multiply")
|
|
404
|
+
|
|
405
|
+
__rmul__ = __mul__
|
|
406
|
+
|
|
407
|
+
def __truediv__(self, other):
|
|
408
|
+
if np.isscalar(other):
|
|
409
|
+
return type(self)(
|
|
410
|
+
self.shape,
|
|
411
|
+
self.major_ptr.copy(),
|
|
412
|
+
self.values / other,
|
|
413
|
+
self.value_ptr.copy(),
|
|
414
|
+
self.indices.copy(),
|
|
415
|
+
)
|
|
416
|
+
return self._elementwise(other, "__truediv__")
|
|
417
|
+
|
|
418
|
+
def __neg__(self):
|
|
419
|
+
return self * -1
|
|
420
|
+
|
|
421
|
+
# -- matrix products -----------------------------------------------------
|
|
422
|
+
|
|
423
|
+
def _dot_right(self, x: np.ndarray) -> np.ndarray:
|
|
424
|
+
"""Compute ``self @ x`` for 1-D ``x`` of length ``n_cols``."""
|
|
425
|
+
n_major, n_minor = self._swap(self.shape)
|
|
426
|
+
args = (self.major_ptr, self.values, self.value_ptr, self.indices)
|
|
427
|
+
if self._format == "csc":
|
|
428
|
+
return _ops.major_matvec(*args, x, n_major, n_minor)
|
|
429
|
+
return _ops.minor_matvec(*args, x, n_major)
|
|
430
|
+
|
|
431
|
+
def _dot_left(self, x: np.ndarray) -> np.ndarray:
|
|
432
|
+
"""Compute ``x @ self`` for 1-D ``x`` of length ``n_rows``."""
|
|
433
|
+
n_major, _n_minor = self._swap(self.shape)
|
|
434
|
+
args = (self.major_ptr, self.values, self.value_ptr, self.indices)
|
|
435
|
+
if self._format == "csc":
|
|
436
|
+
return _ops.minor_matvec(*args, x, n_major)
|
|
437
|
+
return _ops.major_matvec(*args, x, n_major, self.shape[1])
|
|
438
|
+
|
|
439
|
+
def _dot_right_mat(self, b: np.ndarray) -> np.ndarray:
|
|
440
|
+
n_major, n_minor = self._swap(self.shape)
|
|
441
|
+
args = (self.major_ptr, self.values, self.value_ptr, self.indices)
|
|
442
|
+
if self._format == "csc":
|
|
443
|
+
return _ops.major_matmat(*args, b, n_major, n_minor)
|
|
444
|
+
return _ops.minor_matmat(*args, b.T, n_major).T
|
|
445
|
+
|
|
446
|
+
def _dot_left_mat(self, b: np.ndarray) -> np.ndarray:
|
|
447
|
+
n_major, n_minor = self._swap(self.shape)
|
|
448
|
+
args = (self.major_ptr, self.values, self.value_ptr, self.indices)
|
|
449
|
+
if self._format == "csc":
|
|
450
|
+
return _ops.minor_matmat(*args, b, n_major)
|
|
451
|
+
return _ops.major_matmat(*args, b.T, n_major, n_minor).T
|
|
452
|
+
|
|
453
|
+
def __matmul__(self, other):
|
|
454
|
+
other_arr = np.asarray(other)
|
|
455
|
+
if other_arr.ndim == 1:
|
|
456
|
+
if other_arr.shape[0] != self.shape[1]:
|
|
457
|
+
raise ValueError(
|
|
458
|
+
f"shapes {self.shape} and {other_arr.shape} not aligned"
|
|
459
|
+
)
|
|
460
|
+
return self._dot_right(other_arr)
|
|
461
|
+
if other_arr.ndim == 2:
|
|
462
|
+
if other_arr.shape[0] != self.shape[1]:
|
|
463
|
+
raise ValueError(
|
|
464
|
+
f"shapes {self.shape} and {other_arr.shape} not aligned"
|
|
465
|
+
)
|
|
466
|
+
return self._dot_right_mat(other_arr)
|
|
467
|
+
return NotImplemented
|
|
468
|
+
|
|
469
|
+
def __rmatmul__(self, other):
|
|
470
|
+
other_arr = np.asarray(other)
|
|
471
|
+
if other_arr.ndim == 1:
|
|
472
|
+
if other_arr.shape[0] != self.shape[0]:
|
|
473
|
+
raise ValueError(
|
|
474
|
+
f"shapes {other_arr.shape} and {self.shape} not aligned"
|
|
475
|
+
)
|
|
476
|
+
return self._dot_left(other_arr)
|
|
477
|
+
if other_arr.ndim == 2:
|
|
478
|
+
if other_arr.shape[1] != self.shape[0]:
|
|
479
|
+
raise ValueError(
|
|
480
|
+
f"shapes {other_arr.shape} and {self.shape} not aligned"
|
|
481
|
+
)
|
|
482
|
+
return self._dot_left_mat(other_arr)
|
|
483
|
+
return NotImplemented
|
|
484
|
+
|
|
485
|
+
# -- indexing -------------------------------------------------------------
|
|
486
|
+
|
|
487
|
+
def _select_major(self, key: Any) -> _VCSBase:
|
|
488
|
+
idx = _normalize_major_idx(key, self.n_major)
|
|
489
|
+
starts = self.major_ptr[idx]
|
|
490
|
+
ends = self.major_ptr[idx + 1]
|
|
491
|
+
counts = ends - starts
|
|
492
|
+
new_major_ptr = np.zeros(idx.shape[0] + 1, dtype=np.int64)
|
|
493
|
+
np.cumsum(counts, out=new_major_ptr[1:])
|
|
494
|
+
|
|
495
|
+
value_slots = np.concatenate(
|
|
496
|
+
[np.arange(s, e) for s, e in zip(starts, ends, strict=True)]
|
|
497
|
+
) if idx.shape[0] else np.empty(0, dtype=np.int64)
|
|
498
|
+
new_values = self.values[value_slots]
|
|
499
|
+
|
|
500
|
+
v_starts = self.value_ptr[value_slots]
|
|
501
|
+
v_ends = self.value_ptr[value_slots + 1]
|
|
502
|
+
idx_counts = v_ends - v_starts
|
|
503
|
+
new_value_ptr = np.zeros(value_slots.shape[0] + 1, dtype=np.int64)
|
|
504
|
+
np.cumsum(idx_counts, out=new_value_ptr[1:])
|
|
505
|
+
new_indices = np.concatenate(
|
|
506
|
+
[self.indices[s:e] for s, e in zip(v_starts, v_ends, strict=True)]
|
|
507
|
+
) if value_slots.shape[0] else np.empty(0, dtype=self.indices.dtype)
|
|
508
|
+
|
|
509
|
+
n_minor = self.n_minor
|
|
510
|
+
new_shape = (
|
|
511
|
+
(n_minor, idx.shape[0]) if self._format == "csc" else (idx.shape[0], n_minor)
|
|
512
|
+
)
|
|
513
|
+
return type(self)(new_shape, new_major_ptr, new_values, new_value_ptr, new_indices)
|
|
514
|
+
|
|
515
|
+
def _select_minor(self, key: Any) -> _VCSBase:
|
|
516
|
+
"""Select along the minor axis (rows for VCSC, columns for VCSR).
|
|
517
|
+
|
|
518
|
+
Unlike :meth:`_select_major`, the kept elements aren't already
|
|
519
|
+
contiguous per major slice, so this filters/remaps ``indices`` and
|
|
520
|
+
drops any (major, unique-value) slot that no longer has any kept
|
|
521
|
+
index, shrinking ``major_ptr``/``value_ptr`` accordingly.
|
|
522
|
+
"""
|
|
523
|
+
idx = _normalize_major_idx(key, self.n_minor)
|
|
524
|
+
n_minor_new = idx.shape[0]
|
|
525
|
+
|
|
526
|
+
remap = np.full(self.n_minor, -1, dtype=np.int64)
|
|
527
|
+
remap[idx] = np.arange(n_minor_new, dtype=np.int64)
|
|
528
|
+
|
|
529
|
+
keep = remap[self.indices] >= 0
|
|
530
|
+
new_indices = remap[self.indices[keep]].astype(self.indices.dtype, copy=False)
|
|
531
|
+
|
|
532
|
+
n_unique = self.values.shape[0]
|
|
533
|
+
value_slot_of_index = np.repeat(np.arange(n_unique, dtype=np.int64), np.diff(self.value_ptr))
|
|
534
|
+
kept_per_slot = np.bincount(value_slot_of_index[keep], minlength=n_unique)
|
|
535
|
+
surviving = kept_per_slot > 0
|
|
536
|
+
|
|
537
|
+
new_values = self.values[surviving]
|
|
538
|
+
new_value_ptr = np.zeros(int(surviving.sum()) + 1, dtype=np.int64)
|
|
539
|
+
np.cumsum(kept_per_slot[surviving], out=new_value_ptr[1:])
|
|
540
|
+
|
|
541
|
+
group_of_major = np.repeat(np.arange(self.n_major, dtype=np.int64), np.diff(self.major_ptr))
|
|
542
|
+
major_counts = np.bincount(group_of_major[surviving], minlength=self.n_major)
|
|
543
|
+
new_major_ptr = np.zeros(self.n_major + 1, dtype=np.int64)
|
|
544
|
+
np.cumsum(major_counts, out=new_major_ptr[1:])
|
|
545
|
+
|
|
546
|
+
new_shape = (
|
|
547
|
+
(n_minor_new, self.n_major) if self._format == "csc" else (self.n_major, n_minor_new)
|
|
548
|
+
)
|
|
549
|
+
return type(self)(new_shape, new_major_ptr, new_values, new_value_ptr, new_indices)
|
|
550
|
+
|
|
551
|
+
def __getitem__(self, key):
|
|
552
|
+
if isinstance(key, tuple):
|
|
553
|
+
if len(key) != 2:
|
|
554
|
+
raise IndexError("VCSC/VCSR arrays are 2-D")
|
|
555
|
+
row_key, col_key = key
|
|
556
|
+
else:
|
|
557
|
+
row_key, col_key = key, slice(None)
|
|
558
|
+
|
|
559
|
+
# A bare int on *both* axes must collapse to a scalar, which a 2-D
|
|
560
|
+
# VCSC/VCSR array can't represent -- only that case needs to convert.
|
|
561
|
+
if isinstance(row_key, int | np.integer) and isinstance(col_key, int | np.integer):
|
|
562
|
+
return self.to_scipy()[row_key, col_key]
|
|
563
|
+
|
|
564
|
+
major_key, minor_key = (
|
|
565
|
+
(col_key, row_key) if self._format == "csc" else (row_key, col_key)
|
|
566
|
+
)
|
|
567
|
+
if _is_full_slice(major_key) and _is_full_slice(minor_key):
|
|
568
|
+
return self.copy()
|
|
569
|
+
|
|
570
|
+
result = self
|
|
571
|
+
if not _is_full_slice(major_key):
|
|
572
|
+
result = result._select_major(major_key)
|
|
573
|
+
if not _is_full_slice(minor_key):
|
|
574
|
+
result = result._select_minor(minor_key)
|
|
575
|
+
return result
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
class VCSCArray(_VCSBase):
|
|
579
|
+
"""Value-Compressed Sparse Column array. Values are deduplicated per column."""
|
|
580
|
+
|
|
581
|
+
__slots__ = ()
|
|
582
|
+
_format = "csc"
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
class VCSRArray(_VCSBase):
|
|
586
|
+
"""Value-Compressed Sparse Row array. Values are deduplicated per row."""
|
|
587
|
+
|
|
588
|
+
__slots__ = ()
|
|
589
|
+
_format = "csr"
|