vsparse 0.6.0__tar.gz → 0.7.0__tar.gz
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-0.6.0 → vsparse-0.7.0}/PKG-INFO +7 -1
- {vsparse-0.6.0 → vsparse-0.7.0}/README.md +6 -0
- {vsparse-0.6.0 → vsparse-0.7.0}/pyproject.toml +2 -1
- {vsparse-0.6.0 → vsparse-0.7.0}/pyproject.toml.orig +3 -3
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/__init__.py +12 -4
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_anndata_class.py +8 -2
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_base.py +314 -59
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_compression.py +80 -48
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_construct.py +73 -39
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_cuda.py +712 -127
- vsparse-0.7.0/src/vsparse/_gds.py +698 -0
- vsparse-0.7.0/src/vsparse/_grouped.py +183 -0
- vsparse-0.7.0/src/vsparse/_huffman.py +684 -0
- vsparse-0.7.0/src/vsparse/_indexutils.py +77 -0
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_io.py +67 -16
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_ivcsc.py +32 -15
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_norm_common.py +123 -15
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_ops.py +209 -64
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_vcs_matmul.py +130 -49
- vsparse-0.6.0/src/vsparse/_indexutils.py +0 -43
- vsparse-0.6.0/src/vsparse/_vcs_norm.py +0 -51
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_anndata.py +0 -0
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_rapid_load.py +0 -0
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/_stats.py +0 -0
- {vsparse-0.6.0 → vsparse-0.7.0}/src/vsparse/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: vsparse
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration
|
|
5
5
|
Keywords: anndata,single-cell,sparse,compression
|
|
6
6
|
Author: Aaron Meyer
|
|
@@ -119,6 +119,12 @@ y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
|
|
|
119
119
|
Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
|
|
120
120
|
Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
|
|
121
121
|
|
|
122
|
+
# Reductions, whole-matrix and per group of rows/columns
|
|
123
|
+
col_totals = v.sum(axis=0) # also mean/max/min/getnnz
|
|
124
|
+
cond_sums = v.group_sum(condition_idxs, n_cond) # (n_cond, n_cols) per-condition sums
|
|
125
|
+
cond_depth = v.group_sum(condition_idxs, n_cond, total=True) # (n_cond,) totals
|
|
126
|
+
cond_means = v.group_mean(condition_idxs, n_cond) # also group_nnz
|
|
127
|
+
|
|
122
128
|
# Slicing
|
|
123
129
|
col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
|
|
124
130
|
sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
|
|
@@ -85,6 +85,12 @@ y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
|
|
|
85
85
|
Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
|
|
86
86
|
Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
|
|
87
87
|
|
|
88
|
+
# Reductions, whole-matrix and per group of rows/columns
|
|
89
|
+
col_totals = v.sum(axis=0) # also mean/max/min/getnnz
|
|
90
|
+
cond_sums = v.group_sum(condition_idxs, n_cond) # (n_cond, n_cols) per-condition sums
|
|
91
|
+
cond_depth = v.group_sum(condition_idxs, n_cond, total=True) # (n_cond,) totals
|
|
92
|
+
cond_means = v.group_mean(condition_idxs, n_cond) # also group_nnz
|
|
93
|
+
|
|
88
94
|
# Slicing
|
|
89
95
|
col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
|
|
90
96
|
sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "vsparse"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.7.0"
|
|
4
4
|
description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12"
|
|
@@ -101,6 +101,7 @@ python-version = "3.12"
|
|
|
101
101
|
allowed-unresolved-imports = [
|
|
102
102
|
"cupy",
|
|
103
103
|
"cupyx.**",
|
|
104
|
+
"kvikio",
|
|
104
105
|
]
|
|
105
106
|
|
|
106
107
|
[tool.pytest.ini_options]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "vsparse"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.7.0"
|
|
4
4
|
description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
authors = [
|
|
@@ -82,8 +82,8 @@ ignore-words-list = "coo"
|
|
|
82
82
|
python-version = "3.12"
|
|
83
83
|
|
|
84
84
|
[tool.ty.analysis]
|
|
85
|
-
# CuPy
|
|
86
|
-
allowed-unresolved-imports = ["cupy", "cupyx.**"]
|
|
85
|
+
# CuPy and kvikio are optional CUDA extras; the lint job syncs without them.
|
|
86
|
+
allowed-unresolved-imports = ["cupy", "cupyx.**", "kvikio"]
|
|
87
87
|
|
|
88
88
|
[tool.pytest.ini_options]
|
|
89
89
|
testpaths = ["tests"]
|
|
@@ -8,16 +8,22 @@ AnnData subclass that holds a VCSC/VCSR array as ``X`` directly.
|
|
|
8
8
|
|
|
9
9
|
from vsparse._anndata import from_anndata, to_layer
|
|
10
10
|
from vsparse._anndata_class import VCSCAnnData
|
|
11
|
-
from vsparse._base import VCSCArray, VCSRArray
|
|
11
|
+
from vsparse._base import VCSCArray, VCSRArray, sampled_dot
|
|
12
12
|
from vsparse._cuda import CudaNormalizedView, cuda_is_available
|
|
13
|
-
from vsparse.
|
|
13
|
+
from vsparse._gds import CudaStreamedView, open_gpu_stream
|
|
14
|
+
from vsparse._norm_common import (
|
|
15
|
+
RECIPES,
|
|
16
|
+
Recipe,
|
|
17
|
+
VCSCArrayNormalized,
|
|
18
|
+
VCSRArrayNormalized,
|
|
19
|
+
)
|
|
14
20
|
from vsparse._rapid_load import load_packed
|
|
15
21
|
from vsparse._stats import VCSStats
|
|
16
|
-
from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
|
|
17
22
|
|
|
18
23
|
__all__ = [
|
|
19
24
|
"RECIPES",
|
|
20
25
|
"CudaNormalizedView",
|
|
26
|
+
"CudaStreamedView",
|
|
21
27
|
"Recipe",
|
|
22
28
|
"VCSCAnnData",
|
|
23
29
|
"VCSCArray",
|
|
@@ -28,7 +34,9 @@ __all__ = [
|
|
|
28
34
|
"cuda_is_available",
|
|
29
35
|
"from_anndata",
|
|
30
36
|
"load_packed",
|
|
37
|
+
"open_gpu_stream",
|
|
38
|
+
"sampled_dot",
|
|
31
39
|
"to_layer",
|
|
32
40
|
]
|
|
33
41
|
|
|
34
|
-
__version__ = "0.
|
|
42
|
+
__version__ = "0.7.0"
|
|
@@ -13,8 +13,14 @@ import scipy.sparse as sp
|
|
|
13
13
|
|
|
14
14
|
from vsparse import _compression, _io
|
|
15
15
|
from vsparse._base import VCSCArray, VCSRArray, _VCSBase
|
|
16
|
-
from vsparse._norm_common import
|
|
17
|
-
|
|
16
|
+
from vsparse._norm_common import (
|
|
17
|
+
DEFAULT_RECIPE,
|
|
18
|
+
Recipe,
|
|
19
|
+
VCSCArrayNormalized,
|
|
20
|
+
VCSRArrayNormalized,
|
|
21
|
+
_NormCache,
|
|
22
|
+
resolve_recipe,
|
|
23
|
+
)
|
|
18
24
|
|
|
19
25
|
if TYPE_CHECKING:
|
|
20
26
|
from collections.abc import Mapping
|
|
@@ -19,6 +19,7 @@ import scipy.sparse as sp
|
|
|
19
19
|
|
|
20
20
|
from vsparse import _construct, _ops, _stats
|
|
21
21
|
from vsparse._indexutils import is_full_slice as _is_full_slice
|
|
22
|
+
from vsparse._indexutils import nnz_blocks as _nnz_blocks
|
|
22
23
|
from vsparse._indexutils import normalize_major_idx as _normalize_major_idx
|
|
23
24
|
from vsparse._indexutils import smallest_index_dtype as _smallest_index_dtype
|
|
24
25
|
from vsparse._norm_common import DEFAULT_RECIPE as _DEFAULT_RECIPE
|
|
@@ -83,6 +84,26 @@ class _VCSBase:
|
|
|
83
84
|
self._norm_cache = _NormCache()
|
|
84
85
|
self._stats: _stats.VCSStats | None = None
|
|
85
86
|
|
|
87
|
+
@classmethod
|
|
88
|
+
def _from_validated(
|
|
89
|
+
cls,
|
|
90
|
+
shape: tuple[int, int],
|
|
91
|
+
major_ptr: np.ndarray,
|
|
92
|
+
values: np.ndarray,
|
|
93
|
+
value_ptr: np.ndarray,
|
|
94
|
+
indices: np.ndarray,
|
|
95
|
+
) -> _VCSBase:
|
|
96
|
+
"""Build without re-scanning ``indices`` for bounds (for internal ops on validated arrays)."""
|
|
97
|
+
self = object.__new__(cls)
|
|
98
|
+
self.shape = (int(shape[0]), int(shape[1]))
|
|
99
|
+
self.major_ptr = major_ptr
|
|
100
|
+
self.values = values
|
|
101
|
+
self.value_ptr = value_ptr
|
|
102
|
+
self.indices = indices
|
|
103
|
+
self._norm_cache = _NormCache()
|
|
104
|
+
self._stats = None
|
|
105
|
+
return self
|
|
106
|
+
|
|
86
107
|
# -- axis bookkeeping ------------------------------------------------
|
|
87
108
|
|
|
88
109
|
@classmethod
|
|
@@ -239,8 +260,11 @@ class _VCSBase:
|
|
|
239
260
|
:data:`~vsparse._norm_common.NORM_CACHE_MAXSIZE` recipes, and holds
|
|
240
261
|
each view weakly -- see :class:`~vsparse._norm_common._NormCache`.
|
|
241
262
|
"""
|
|
242
|
-
from vsparse._norm_common import
|
|
243
|
-
|
|
263
|
+
from vsparse._norm_common import (
|
|
264
|
+
VCSCArrayNormalized,
|
|
265
|
+
VCSRArrayNormalized,
|
|
266
|
+
resolve_recipe,
|
|
267
|
+
)
|
|
244
268
|
|
|
245
269
|
recipe = resolve_recipe(view)
|
|
246
270
|
cache = self._norm_cache
|
|
@@ -335,6 +359,122 @@ class _VCSBase:
|
|
|
335
359
|
denom = self.shape[0] if axis == 0 else self.shape[1]
|
|
336
360
|
return self.sum(axis=axis) / denom if denom else np.full(0, float("nan"))
|
|
337
361
|
|
|
362
|
+
def sampled_dot(self, u: Any, v: Any, *, gpu: bool = False) -> np.ndarray:
|
|
363
|
+
"""Sampled dense-dense dot product ``u[i] @ v[j]`` at every stored nonzero.
|
|
364
|
+
|
|
365
|
+
Returns a 1-D array of length :attr:`nnz` aligned with :attr:`indices`.
|
|
366
|
+
"""
|
|
367
|
+
return sampled_dot(self, u, v, gpu=gpu)
|
|
368
|
+
|
|
369
|
+
def as_linear_operator(self) -> Any:
|
|
370
|
+
"""Wrap this array in a :class:`scipy.sparse.linalg.LinearOperator`."""
|
|
371
|
+
from scipy.sparse.linalg import LinearOperator
|
|
372
|
+
|
|
373
|
+
op_cls: Any = LinearOperator
|
|
374
|
+
return op_cls(
|
|
375
|
+
shape=self.shape,
|
|
376
|
+
dtype=np.dtype(self.dtype),
|
|
377
|
+
matvec=lambda x: self @ x,
|
|
378
|
+
rmatvec=lambda x: x @ self,
|
|
379
|
+
matmat=lambda X: self @ X,
|
|
380
|
+
rmatmat=lambda Y: (Y.T @ self).T,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
# -- grouped (per-condition) reductions ---------------------------------
|
|
384
|
+
|
|
385
|
+
def group_sum(
|
|
386
|
+
self, group_idxs: Any, n_groups: int, axis: int = 0, *, total: bool = False
|
|
387
|
+
) -> np.ndarray:
|
|
388
|
+
"""Sum of values within each group of rows (``axis=0``) or columns (``axis=1``).
|
|
389
|
+
|
|
390
|
+
The grouped counterpart of :meth:`sum`: where ``sum(axis=0)``
|
|
391
|
+
collapses every row into one, ``group_sum(group_idxs, n_groups,
|
|
392
|
+
axis=0)`` collapses the rows into ``n_groups`` bins, one per label --
|
|
393
|
+
e.g. per-condition (per-sample) gene totals given each cell's
|
|
394
|
+
condition. See :mod:`vsparse._grouped` for the kernels.
|
|
395
|
+
|
|
396
|
+
Grouping along the major axis (rows for :class:`VCSRArray`, columns
|
|
397
|
+
for :class:`VCSCArray`) with ``total=True`` never reads ``indices``,
|
|
398
|
+
like :meth:`sum`'s major-axis path, so per-condition depth is nearly
|
|
399
|
+
free.
|
|
400
|
+
|
|
401
|
+
Parameters
|
|
402
|
+
----------
|
|
403
|
+
group_idxs : array-like of int
|
|
404
|
+
Group label, in ``[0, n_groups)``, of each row (``axis=0``,
|
|
405
|
+
length ``shape[0]``) or column (``axis=1``, length ``shape[1]``).
|
|
406
|
+
Labels need not be sorted or contiguous, and groups may be empty.
|
|
407
|
+
n_groups : int
|
|
408
|
+
The total number of groups.
|
|
409
|
+
axis : {0, 1}, default 0
|
|
410
|
+
The axis that ``group_idxs`` labels and that is collapsed into
|
|
411
|
+
groups.
|
|
412
|
+
total : bool, default False
|
|
413
|
+
If ``True``, also sum over the other axis, giving each group's
|
|
414
|
+
grand total.
|
|
415
|
+
|
|
416
|
+
Returns
|
|
417
|
+
-------
|
|
418
|
+
np.ndarray
|
|
419
|
+
``float64``. With ``total=False``, shape ``(n_groups, shape[1])``
|
|
420
|
+
for ``axis=0`` or ``(shape[0], n_groups)`` for ``axis=1``; with
|
|
421
|
+
``total=True``, shape ``(n_groups,)``.
|
|
422
|
+
|
|
423
|
+
Examples
|
|
424
|
+
--------
|
|
425
|
+
>>> import numpy as np, scipy.sparse as sp
|
|
426
|
+
>>> from vsparse import VCSRArray
|
|
427
|
+
>>> x = VCSRArray.from_scipy(sp.csr_array(np.array([[1, 0], [2, 3], [0, 4]])))
|
|
428
|
+
>>> x.group_sum([0, 1, 0], 2) # rows 0 and 2 form group 0
|
|
429
|
+
array([[1., 4.],
|
|
430
|
+
[2., 3.]])
|
|
431
|
+
>>> x.group_sum([0, 1, 0], 2, total=True)
|
|
432
|
+
array([5., 5.])
|
|
433
|
+
"""
|
|
434
|
+
from vsparse import _grouped
|
|
435
|
+
|
|
436
|
+
groups, n_groups, axis = _grouped.validate_groups(self, group_idxs, n_groups, axis)
|
|
437
|
+
return _grouped.group_reduce(self, groups, n_groups, axis, total=total, count=False)
|
|
438
|
+
|
|
439
|
+
def group_nnz(
|
|
440
|
+
self, group_idxs: Any, n_groups: int, axis: int = 0, *, total: bool = False
|
|
441
|
+
) -> np.ndarray:
|
|
442
|
+
"""Count of stored elements within each group of rows (``axis=0``) or columns (``axis=1``).
|
|
443
|
+
|
|
444
|
+
The grouped counterpart of :meth:`getnnz` -- e.g. per-condition
|
|
445
|
+
n-cells-by-counts for each gene. Takes the same arguments as
|
|
446
|
+
:meth:`group_sum` and returns the same shapes, as ``int64``. Like
|
|
447
|
+
:meth:`getnnz`, explicitly stored zeros are counted.
|
|
448
|
+
"""
|
|
449
|
+
from vsparse import _grouped
|
|
450
|
+
|
|
451
|
+
groups, n_groups, axis = _grouped.validate_groups(self, group_idxs, n_groups, axis)
|
|
452
|
+
out = _grouped.group_reduce(self, groups, n_groups, axis, total=total, count=True)
|
|
453
|
+
return out.astype(np.int64)
|
|
454
|
+
|
|
455
|
+
def group_mean(
|
|
456
|
+
self, group_idxs: Any, n_groups: int, axis: int = 0, *, total: bool = False
|
|
457
|
+
) -> np.ndarray:
|
|
458
|
+
"""Mean (including implicit zeros) within each group of rows (``axis=0``) or columns (``axis=1``).
|
|
459
|
+
|
|
460
|
+
The grouped counterpart of :meth:`mean`: :meth:`group_sum` divided by
|
|
461
|
+
the number of rows (or columns) in each group, and with
|
|
462
|
+
``total=True`` also by the length of the other axis. Takes the same
|
|
463
|
+
arguments as :meth:`group_sum` and returns the same shapes. An empty
|
|
464
|
+
group's mean is ``nan``.
|
|
465
|
+
"""
|
|
466
|
+
from vsparse import _grouped
|
|
467
|
+
|
|
468
|
+
groups, n_groups, axis = _grouped.validate_groups(self, group_idxs, n_groups, axis)
|
|
469
|
+
sums = _grouped.group_reduce(self, groups, n_groups, axis, total=total, count=False)
|
|
470
|
+
denom = _grouped.group_counts(groups, n_groups).astype(np.float64)
|
|
471
|
+
if total:
|
|
472
|
+
denom *= self.shape[1 - axis]
|
|
473
|
+
elif axis == 0:
|
|
474
|
+
denom = denom[:, None]
|
|
475
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
476
|
+
return sums / denom
|
|
477
|
+
|
|
338
478
|
def _reduce_initial(self, kind: str) -> Any:
|
|
339
479
|
"""Identity element for a max/min reduction over ``self.values.dtype``."""
|
|
340
480
|
dt = self.values.dtype
|
|
@@ -535,62 +675,112 @@ class _VCSBase:
|
|
|
535
675
|
return self._dot_left_mat(other_arr)
|
|
536
676
|
return NotImplemented
|
|
537
677
|
|
|
538
|
-
# --
|
|
678
|
+
# -- zero-copy block slicing (#77) ----------------------------------------
|
|
679
|
+
|
|
680
|
+
def major_slice(self, start: int, end: int) -> _VCSBase:
|
|
681
|
+
"""Zero-copy view of contiguous major-axis slices ``[start, end)``.
|
|
682
|
+
|
|
683
|
+
Shares ``values`` and ``indices`` buffers with ``self`` (no copy),
|
|
684
|
+
rebasing only the slice's ``major_ptr`` and ``value_ptr`` offsets.
|
|
685
|
+
"""
|
|
686
|
+
n_major = self.n_major
|
|
687
|
+
s = int(start)
|
|
688
|
+
e = int(end)
|
|
689
|
+
if s < 0:
|
|
690
|
+
s += n_major
|
|
691
|
+
if e < 0:
|
|
692
|
+
e += n_major
|
|
693
|
+
if not (0 <= s <= e <= n_major):
|
|
694
|
+
raise IndexError(f"major_slice bounds ({start}, {end}) out of range for {n_major}")
|
|
695
|
+
|
|
696
|
+
g0 = int(self.major_ptr[s])
|
|
697
|
+
g1 = int(self.major_ptr[e])
|
|
698
|
+
k0 = int(self.value_ptr[g0])
|
|
699
|
+
k1 = int(self.value_ptr[g1])
|
|
700
|
+
|
|
701
|
+
new_major_ptr = self.major_ptr[s : e + 1] - g0
|
|
702
|
+
new_values = self.values[g0:g1]
|
|
703
|
+
new_value_ptr = self.value_ptr[g0 : g1 + 1] - k0
|
|
704
|
+
new_indices = self.indices[k0:k1]
|
|
705
|
+
new_shape = (self.n_minor, e - s) if self._format == "csc" else (e - s, self.n_minor)
|
|
706
|
+
return type(self)._from_validated(
|
|
707
|
+
new_shape, new_major_ptr, new_values, new_value_ptr, new_indices
|
|
708
|
+
)
|
|
709
|
+
|
|
710
|
+
def nnz_blocks(self, max_nnz: int) -> list[tuple[int, int]]:
|
|
711
|
+
"""Partition the major axis into ``(start, end)`` ranges of at most ``max_nnz`` nonzeros.
|
|
712
|
+
|
|
713
|
+
If a single major slice exceeds ``max_nnz`` nonzeros, it is placed in
|
|
714
|
+
its own single-slice block ``(i, i + 1)``.
|
|
715
|
+
"""
|
|
716
|
+
return _nnz_blocks(self.major_ptr, self.value_ptr, max_nnz)
|
|
717
|
+
|
|
718
|
+
# -- indexing (#78) -------------------------------------------------------
|
|
539
719
|
|
|
540
720
|
def _select_major(self, key: Any) -> _VCSBase:
|
|
541
|
-
idx = _normalize_major_idx(key, self.n_major)
|
|
721
|
+
idx = np.ascontiguousarray(_normalize_major_idx(key, self.n_major), dtype=np.int64)
|
|
542
722
|
starts = self.major_ptr[idx]
|
|
543
723
|
ends = self.major_ptr[idx + 1]
|
|
544
724
|
counts = ends - starts
|
|
545
725
|
new_major_ptr = np.zeros(idx.shape[0] + 1, dtype=np.int64)
|
|
546
726
|
np.cumsum(counts, out=new_major_ptr[1:])
|
|
547
727
|
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
728
|
+
slice_nnz = self.value_ptr[ends] - self.value_ptr[starts]
|
|
729
|
+
slice_idx_offsets = np.zeros(idx.shape[0] + 1, dtype=np.int64)
|
|
730
|
+
np.cumsum(slice_nnz, out=slice_idx_offsets[1:])
|
|
731
|
+
|
|
732
|
+
n_slots = int(new_major_ptr[-1])
|
|
733
|
+
total_nnz = int(slice_idx_offsets[-1])
|
|
734
|
+
new_values = np.empty(n_slots, dtype=self.values.dtype)
|
|
735
|
+
new_value_ptr = np.empty(n_slots + 1, dtype=np.int64)
|
|
736
|
+
new_indices = np.empty(total_nnz, dtype=self.indices.dtype)
|
|
737
|
+
|
|
738
|
+
_ops.major_select_fill(
|
|
739
|
+
self.major_ptr,
|
|
740
|
+
self.values,
|
|
741
|
+
self.value_ptr,
|
|
742
|
+
self.indices,
|
|
743
|
+
idx,
|
|
744
|
+
new_major_ptr,
|
|
745
|
+
slice_idx_offsets,
|
|
746
|
+
new_values,
|
|
747
|
+
new_value_ptr,
|
|
748
|
+
new_indices,
|
|
552
749
|
)
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
new_value_ptr = np.zeros(value_slots.shape[0] + 1, dtype=np.int64)
|
|
559
|
-
np.cumsum(idx_counts, out=new_value_ptr[1:])
|
|
560
|
-
new_indices = (
|
|
561
|
-
np.concatenate([self.indices[s:e] for s, e in zip(v_starts, v_ends, strict=True)])
|
|
562
|
-
if value_slots.shape[0]
|
|
563
|
-
else np.empty(0, dtype=self.indices.dtype)
|
|
750
|
+
new_shape = (
|
|
751
|
+
(self.n_minor, idx.shape[0]) if self._format == "csc" else (idx.shape[0], self.n_minor)
|
|
752
|
+
)
|
|
753
|
+
return type(self)._from_validated(
|
|
754
|
+
new_shape, new_major_ptr, new_values, new_value_ptr, new_indices
|
|
564
755
|
)
|
|
565
756
|
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
757
|
+
def _select_both(self, major_key: Any, minor_key: Any) -> _VCSBase:
|
|
758
|
+
"""Combined major + minor selection in one pass without materializing the intermediate."""
|
|
759
|
+
maj_idx = np.ascontiguousarray(
|
|
760
|
+
_normalize_major_idx(major_key, self.n_major), dtype=np.int64
|
|
761
|
+
)
|
|
762
|
+
min_idx = np.ascontiguousarray(
|
|
763
|
+
_normalize_major_idx(minor_key, self.n_minor), dtype=np.int64
|
|
764
|
+
)
|
|
765
|
+
n_minor_new = min_idx.shape[0]
|
|
572
766
|
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
output positions.
|
|
576
|
-
"""
|
|
577
|
-
idx = _normalize_major_idx(key, self.n_minor)
|
|
578
|
-
n_minor_new = idx.shape[0]
|
|
767
|
+
slot_offsets = np.zeros(maj_idx.shape[0] + 1, dtype=np.int64)
|
|
768
|
+
np.cumsum(self.major_ptr[maj_idx + 1] - self.major_ptr[maj_idx], out=slot_offsets[1:])
|
|
579
769
|
|
|
580
|
-
|
|
581
|
-
fanout = np.bincount(idx, minlength=self.n_minor)
|
|
770
|
+
fanout = np.bincount(min_idx, minlength=self.n_minor)
|
|
582
771
|
offsets = np.zeros(self.n_minor + 1, dtype=np.int64)
|
|
583
772
|
np.cumsum(fanout, out=offsets[1:])
|
|
584
|
-
positions = np.argsort(
|
|
585
|
-
|
|
586
|
-
slot_counts = _ops.minor_select_counts(self.value_ptr, self.indices, fanout)
|
|
587
|
-
kept_slots = np.flatnonzero(slot_counts)
|
|
773
|
+
positions = np.argsort(min_idx, kind="stable").astype(np.int64, copy=False)
|
|
588
774
|
|
|
775
|
+
slot_ids, slot_counts = _ops.combined_select_counts(
|
|
776
|
+
self.major_ptr, self.value_ptr, self.indices, maj_idx, slot_offsets, fanout
|
|
777
|
+
)
|
|
778
|
+
nonempty = slot_counts > 0
|
|
779
|
+
kept_slots = slot_ids[nonempty]
|
|
589
780
|
new_values = self.values[kept_slots]
|
|
590
|
-
new_value_ptr = np.zeros(kept_slots.shape[0] + 1, dtype=np.int64)
|
|
591
|
-
np.cumsum(slot_counts[kept_slots], out=new_value_ptr[1:])
|
|
592
781
|
|
|
593
|
-
|
|
782
|
+
new_value_ptr = np.zeros(kept_slots.shape[0] + 1, dtype=np.int64)
|
|
783
|
+
np.cumsum(slot_counts[nonempty], out=new_value_ptr[1:])
|
|
594
784
|
new_indices = np.empty(int(new_value_ptr[-1]), dtype=self.indices.dtype)
|
|
595
785
|
_ops.minor_select_fill(
|
|
596
786
|
self.value_ptr,
|
|
@@ -602,17 +792,32 @@ class _VCSBase:
|
|
|
602
792
|
new_indices,
|
|
603
793
|
)
|
|
604
794
|
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
major_counts = np.bincount(major_of_slot, minlength=self.n_major)
|
|
609
|
-
new_major_ptr = np.zeros(self.n_major + 1, dtype=np.int64)
|
|
610
|
-
np.cumsum(major_counts, out=new_major_ptr[1:])
|
|
611
|
-
|
|
795
|
+
nonempty_before = np.zeros(slot_counts.shape[0] + 1, dtype=np.int64)
|
|
796
|
+
np.cumsum(nonempty, out=nonempty_before[1:])
|
|
797
|
+
new_major_ptr = nonempty_before[slot_offsets]
|
|
612
798
|
new_shape = (
|
|
613
|
-
(n_minor_new,
|
|
799
|
+
(n_minor_new, maj_idx.shape[0])
|
|
800
|
+
if self._format == "csc"
|
|
801
|
+
else (maj_idx.shape[0], n_minor_new)
|
|
802
|
+
)
|
|
803
|
+
return type(self)._from_validated(
|
|
804
|
+
new_shape, new_major_ptr, new_values, new_value_ptr, new_indices
|
|
614
805
|
)
|
|
615
|
-
|
|
806
|
+
|
|
807
|
+
def select(self, rows: Any = slice(None), cols: Any = slice(None)) -> _VCSBase:
|
|
808
|
+
"""Select ``rows`` and ``cols`` (single-pass when both axes are subset)."""
|
|
809
|
+
major_key, minor_key = (cols, rows) if self._format == "csc" else (rows, cols)
|
|
810
|
+
full_major = _is_full_slice(major_key)
|
|
811
|
+
full_minor = _is_full_slice(minor_key)
|
|
812
|
+
if full_major and full_minor:
|
|
813
|
+
return self.copy()
|
|
814
|
+
if full_minor:
|
|
815
|
+
return self._select_major(major_key)
|
|
816
|
+
return self._select_both(major_key, minor_key)
|
|
817
|
+
|
|
818
|
+
def _select_minor(self, key: Any) -> _VCSBase:
|
|
819
|
+
"""Select along the minor axis (rows for VCSC, columns for VCSR)."""
|
|
820
|
+
return self._select_both(slice(None), key)
|
|
616
821
|
|
|
617
822
|
def __getitem__(self, key):
|
|
618
823
|
if isinstance(key, tuple):
|
|
@@ -627,16 +832,7 @@ class _VCSBase:
|
|
|
627
832
|
if isinstance(row_key, int | np.integer) and isinstance(col_key, int | np.integer):
|
|
628
833
|
return self.to_scipy()[row_key, col_key]
|
|
629
834
|
|
|
630
|
-
|
|
631
|
-
if _is_full_slice(major_key) and _is_full_slice(minor_key):
|
|
632
|
-
return self.copy()
|
|
633
|
-
|
|
634
|
-
result = self
|
|
635
|
-
if not _is_full_slice(major_key):
|
|
636
|
-
result = result._select_major(major_key)
|
|
637
|
-
if not _is_full_slice(minor_key):
|
|
638
|
-
result = result._select_minor(minor_key)
|
|
639
|
-
return result
|
|
835
|
+
return self.select(row_key, col_key)
|
|
640
836
|
|
|
641
837
|
|
|
642
838
|
class VCSCArray(_VCSBase):
|
|
@@ -651,3 +847,62 @@ class VCSRArray(_VCSBase):
|
|
|
651
847
|
|
|
652
848
|
__slots__ = ()
|
|
653
849
|
_format = "csr"
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
def sampled_dot(x: Any, u: Any, v: Any, *, gpu: bool = False) -> np.ndarray:
|
|
853
|
+
"""Sampled dense-dense dot product ``u[i] @ v[j]`` at every stored nonzero of ``x``.
|
|
854
|
+
|
|
855
|
+
Supports :class:`VCSRArray`, :class:`VCSCArray`, and SciPy sparse arrays/matrices.
|
|
856
|
+
Returns a 1-D NumPy array of length ``x.nnz`` aligned with ``x.indices``
|
|
857
|
+
(for SciPy CSR, aligned with ``x.data``). Pass ``gpu=True`` to run on CUDA
|
|
858
|
+
via CuPy without allocating an ``(nnz, k)`` temporary.
|
|
859
|
+
"""
|
|
860
|
+
u_arr = np.ascontiguousarray(u)
|
|
861
|
+
v_arr = np.ascontiguousarray(v)
|
|
862
|
+
if u_arr.ndim != 2 or v_arr.ndim != 2:
|
|
863
|
+
raise ValueError(f"u and v must be 2-D, got shapes {u_arr.shape} and {v_arr.shape}")
|
|
864
|
+
if u_arr.shape[0] != x.shape[0] or v_arr.shape[0] != x.shape[1]:
|
|
865
|
+
raise ValueError(
|
|
866
|
+
f"Factor shapes {u_arr.shape} and {v_arr.shape} do not match matrix shape {x.shape}"
|
|
867
|
+
)
|
|
868
|
+
if u_arr.shape[1] != v_arr.shape[1]:
|
|
869
|
+
raise ValueError(
|
|
870
|
+
f"Inner dimensions of u ({u_arr.shape[1]}) and v ({v_arr.shape[1]}) must match"
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
out_dtype = np.result_type(u_arr.dtype, v_arr.dtype)
|
|
874
|
+
if not np.issubdtype(out_dtype, np.floating):
|
|
875
|
+
out_dtype = np.dtype(np.float64)
|
|
876
|
+
u_arr = np.ascontiguousarray(u_arr, dtype=out_dtype)
|
|
877
|
+
v_arr = np.ascontiguousarray(v_arr, dtype=out_dtype)
|
|
878
|
+
|
|
879
|
+
if isinstance(x, _VCSBase):
|
|
880
|
+
if x.nnz == 0:
|
|
881
|
+
return np.empty(0, dtype=out_dtype)
|
|
882
|
+
if gpu:
|
|
883
|
+
from vsparse._cuda import cuda_sampled_dot_vcs
|
|
884
|
+
|
|
885
|
+
return cuda_sampled_dot_vcs(x, u_arr, v_arr)
|
|
886
|
+
out = np.empty(x.nnz, dtype=out_dtype)
|
|
887
|
+
if x._format == "csr":
|
|
888
|
+
return _ops.sampled_dot_vcs_major_is_row(
|
|
889
|
+
x.major_ptr, x.value_ptr, x.indices, u_arr, v_arr, out
|
|
890
|
+
)
|
|
891
|
+
return _ops.sampled_dot_vcs_major_is_col(
|
|
892
|
+
x.major_ptr, x.value_ptr, x.indices, u_arr, v_arr, out
|
|
893
|
+
)
|
|
894
|
+
|
|
895
|
+
if sp.issparse(x):
|
|
896
|
+
x_csr = x if x.format == "csr" else x.tocsr()
|
|
897
|
+
if x_csr.nnz == 0:
|
|
898
|
+
return np.empty(0, dtype=out_dtype)
|
|
899
|
+
if gpu:
|
|
900
|
+
from vsparse._cuda import cuda_sampled_dot_csr
|
|
901
|
+
|
|
902
|
+
return cuda_sampled_dot_csr(x_csr, u_arr, v_arr)
|
|
903
|
+
out = np.empty(x_csr.nnz, dtype=out_dtype)
|
|
904
|
+
return _ops.sampled_dot_csr(x_csr.indptr, x_csr.indices, u_arr, v_arr, out)
|
|
905
|
+
|
|
906
|
+
raise TypeError(
|
|
907
|
+
f"sampled_dot expects a VCSRArray, VCSCArray, or SciPy sparse matrix, got {type(x)}"
|
|
908
|
+
)
|