From 3d9c3f288969a35b3181f0123a5d0aed5ebe1af2 Mon Sep 17 00:00:00 2001 From: Aaron Meyer Date: Sun, 22 Nov 2026 19:54:23 -0800 Subject: [PATCH] Add group_sum/group_nnz/group_mean grouped reductions on VCSC/VCSR (#81) Collapse rows (axis=0) or columns (axis=1) into n_groups bins given a group label per row/column, e.g. per-condition sums, nonzero counts and means. total=True also reduces the other axis; grouping along the major axis with total=True reads only the value groups, never indices. Kernels are race-free: groups along the major axis are processed group- owned per thread (or with small per-thread buffers when there are fewer groups than threads); groups along the minor axis are scattered per major slice. --- README.md | 6 + docs/usage.md | 43 ++++++++ src/vsparse/_base.py | 95 ++++++++++++++++ src/vsparse/_grouped.py | 183 +++++++++++++++++++++++++++++++ tests/test_grouped_reductions.py | 159 +++++++++++++++++++++++++++ 5 files changed, 486 insertions(+) create mode 100644 src/vsparse/_grouped.py create mode 100644 tests/test_grouped_reductions.py diff --git a/README.md b/README.md index 4776e58..b38edbc 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,12 @@ y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,) Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k) Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols) +# Reductions, whole-matrix and per group of rows/columns +col_totals = v.sum(axis=0) # also mean/max/min/getnnz +cond_sums = v.group_sum(condition_idxs, n_cond) # (n_cond, n_cols) per-condition sums +cond_depth = v.group_sum(condition_idxs, n_cond, total=True) # (n_cond,) totals +cond_means = v.group_mean(condition_idxs, n_cond) # also group_nnz + # Slicing col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray) sub = v[0:10, 0:10] # 2D slicing (falls back to scipy) diff --git a/docs/usage.md b/docs/usage.md index 5de94cf..041aa9b 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -56,6 +56,49 @@ Attach a decompressed result back onto an `AnnData` object as a layer: vsparse.to_layer(adata, v, key="vcsc_roundtrip") ``` +### Reductions + +`sum`, `mean`, `max`, `min` and `getnnz` take `axis=None|0|1` like their numpy/scipy +counterparts. Summing along the major axis (columns for `VCSCArray`, rows for +`VCSRArray`) reads only the deduplicated values, never `indices`. + +### Grouped (per-condition) reductions + +Multi-sample methods (e.g. PARAFAC2 over `condition_unique_idxs`) need reductions per +sample or condition rather than over the whole matrix. `group_sum`, `group_nnz` and +`group_mean` collapse one axis into `n_groups` bins given a group label for each row +(`axis=0`, the default) or column (`axis=1`): + +```python +import numpy as np + +# condition_idxs[i] in [0, n_cond) is the condition of row (cell) i +cond_sums = v.group_sum(condition_idxs, n_cond) # (n_cond, n_cols) +cond_nnz = v.group_nnz(condition_idxs, n_cond) # (n_cond, n_cols), int64 +cond_means = v.group_mean(condition_idxs, n_cond) # (n_cond, n_cols), implicit zeros included + +# total=True also reduces the other axis: one number per group +cond_depth = v.group_sum(condition_idxs, n_cond, total=True) # (n_cond,) +cells_per_cond = np.bincount(condition_idxs, minlength=n_cond) + +# Grouping columns instead, e.g. gene sets: (n_rows, n_sets) +set_scores = v.group_sum(gene_set_idxs, n_sets, axis=1) +``` + +They generalize the whole-matrix reductions: with every label `0` and `n_groups=1`, +`v.group_sum(labels, 1, axis=0)[0]` equals `v.sum(axis=0)`. Labels need not be sorted +or contiguous, and empty groups are allowed (their sums and counts are `0` and their +means `nan`). Sums and means are returned as `float64`, counts as `int64`. Like `getnnz`, +`group_nnz` counts explicitly stored zeros. + +Grouping along the major axis with `total=True` (e.g. per-condition depth for a +`VCSRArray` grouped by row) never reads `indices`, so it costs about as much as +`v.sum(axis=1)`. Otherwise each reduction is a single parallel pass over the stored +values, with no scratch memory proportional to the number of threads, except when there +are fewer groups than threads. In that case each thread keeps its own +`(n_groups, n_minor)` buffer, within the same memory budget as the other minor-axis +reductions. + ## `VCSCAnnData`: X backed directly by a VCSCArray `vsparse.VCSCAnnData` is an `AnnData` subclass whose `X` (and, separately, `raw_X`) *is* a diff --git a/src/vsparse/_base.py b/src/vsparse/_base.py index b8d2a31..5ca05d0 100644 --- a/src/vsparse/_base.py +++ b/src/vsparse/_base.py @@ -335,6 +335,101 @@ def mean(self, axis: int | None = None) -> np.ndarray | float: denom = self.shape[0] if axis == 0 else self.shape[1] return self.sum(axis=axis) / denom if denom else np.full(0, float("nan")) + # -- grouped (per-condition) reductions --------------------------------- + + def group_sum( + self, group_idxs: Any, n_groups: int, axis: int = 0, *, total: bool = False + ) -> np.ndarray: + """Sum of values within each group of rows (``axis=0``) or columns (``axis=1``). + + The grouped counterpart of :meth:`sum`: where ``sum(axis=0)`` + collapses every row into one, ``group_sum(group_idxs, n_groups, + axis=0)`` collapses the rows into ``n_groups`` bins, one per label -- + e.g. per-condition (per-sample) gene totals given each cell's + condition. See :mod:`vsparse._grouped` for the kernels. + + Grouping along the major axis (rows for :class:`VCSRArray`, columns + for :class:`VCSCArray`) with ``total=True`` never reads ``indices``, + like :meth:`sum`'s major-axis path, so per-condition depth is nearly + free. + + Parameters + ---------- + group_idxs : array-like of int + Group label, in ``[0, n_groups)``, of each row (``axis=0``, + length ``shape[0]``) or column (``axis=1``, length ``shape[1]``). + Labels need not be sorted or contiguous, and groups may be empty. + n_groups : int + The total number of groups. + axis : {0, 1}, default 0 + The axis that ``group_idxs`` labels and that is collapsed into + groups. + total : bool, default False + If ``True``, also sum over the other axis, giving each group's + grand total. + + Returns + ------- + np.ndarray + ``float64``. With ``total=False``, shape ``(n_groups, shape[1])`` + for ``axis=0`` or ``(shape[0], n_groups)`` for ``axis=1``; with + ``total=True``, shape ``(n_groups,)``. + + Examples + -------- + >>> import numpy as np, scipy.sparse as sp + >>> from vsparse import VCSRArray + >>> x = VCSRArray.from_scipy(sp.csr_array(np.array([[1, 0], [2, 3], [0, 4]]))) + >>> x.group_sum([0, 1, 0], 2) # rows 0 and 2 form group 0 + array([[1., 4.], + [2., 3.]]) + >>> x.group_sum([0, 1, 0], 2, total=True) + array([5., 5.]) + """ + from vsparse import _grouped + + groups, n_groups, axis = _grouped.validate_groups(self, group_idxs, n_groups, axis) + return _grouped.group_reduce(self, groups, n_groups, axis, total=total, count=False) + + def group_nnz( + self, group_idxs: Any, n_groups: int, axis: int = 0, *, total: bool = False + ) -> np.ndarray: + """Count of stored elements within each group of rows (``axis=0``) or columns (``axis=1``). + + The grouped counterpart of :meth:`getnnz` -- e.g. per-condition + n-cells-by-counts for each gene. Takes the same arguments as + :meth:`group_sum` and returns the same shapes, as ``int64``. Like + :meth:`getnnz`, explicitly stored zeros are counted. + """ + from vsparse import _grouped + + groups, n_groups, axis = _grouped.validate_groups(self, group_idxs, n_groups, axis) + out = _grouped.group_reduce(self, groups, n_groups, axis, total=total, count=True) + return out.astype(np.int64) + + def group_mean( + self, group_idxs: Any, n_groups: int, axis: int = 0, *, total: bool = False + ) -> np.ndarray: + """Mean (including implicit zeros) within each group of rows (``axis=0``) or columns (``axis=1``). + + The grouped counterpart of :meth:`mean`: :meth:`group_sum` divided by + the number of rows (or columns) in each group, and with + ``total=True`` also by the length of the other axis. Takes the same + arguments as :meth:`group_sum` and returns the same shapes. An empty + group's mean is ``nan``. + """ + from vsparse import _grouped + + groups, n_groups, axis = _grouped.validate_groups(self, group_idxs, n_groups, axis) + sums = _grouped.group_reduce(self, groups, n_groups, axis, total=total, count=False) + denom = _grouped.group_counts(groups, n_groups).astype(np.float64) + if total: + denom *= self.shape[1 - axis] + elif axis == 0: + denom = denom[:, None] + with np.errstate(invalid="ignore", divide="ignore"): + return sums / denom + def _reduce_initial(self, kind: str) -> Any: """Identity element for a max/min reduction over ``self.values.dtype``.""" dt = self.values.dtype diff --git a/src/vsparse/_grouped.py b/src/vsparse/_grouped.py new file mode 100644 index 0000000..04d84c3 --- /dev/null +++ b/src/vsparse/_grouped.py @@ -0,0 +1,183 @@ +"""Grouped (per-condition) reductions on :class:`~vsparse.VCSCArray`/:class:`~vsparse.VCSRArray`. + +``group_sum``/``group_nnz``/``group_mean`` collapse one axis of a raw (not +normalized) array into ``n_groups`` bins given a group label per row (or +column) -- the per-sample/per-condition sums, nonzero counts and means that +multi-condition methods such as PARAFAC2 work with. + +Which kernel runs depends on whether the grouped axis is the major axis +(the value-compressed one: columns for VCSC, rows for VCSR): + +* **Major axis, per-group totals** (``total=True``): one ``bincount`` over + the per-major-slice totals, which come from the value groups alone -- + ``indices`` is never read, exactly like :meth:`sum`'s major-axis path. +* **Major axis, full** (``total=False``): each major slice is added into its + group's output row. With at least as many groups as threads, slices are + ordered by group (a stable ``argsort``; already-grouped data, as sorted by + condition, then walks memory in order) and each thread owns whole groups, + so no output is shared and no scratch memory is needed. With fewer groups + than threads, each thread instead accumulates into a private + ``(n_groups, n_minor)`` block, capped by the same budget as the minor-axis + scatters in :mod:`vsparse._ops`. +* **Minor axis**: every major slice owns its own output row, so the scatter + of ``indices`` through the group labels parallelizes over slices without + any scratch memory. Per-group totals are a ``bincount`` over the minor + sums. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numba +import numpy as np + +from vsparse import _ops + +if TYPE_CHECKING: + from vsparse._base import _VCSBase + +__all__ = ["group_counts", "group_reduce", "validate_groups"] + + +# -- kernels ------------------------------------------------------------------- +# +# ``count`` selects nonzero counting (every stored element contributes 1) +# instead of summing values, so ``group_nnz`` shares these kernels without +# allocating an all-ones copy of ``values``. + + +@numba.njit(cache=True, inline="always") +def _add_major_slice(row, j, major_ptr, values, value_ptr, indices, count): + """Add major slice ``j`` into the dense minor-axis vector ``row``.""" + for u in range(major_ptr[j], major_ptr[j + 1]): + v = 1.0 if count else np.float64(values[u]) + for k in range(value_ptr[u], value_ptr[u + 1]): + row[indices[k]] += v + + +@numba.njit(cache=True, parallel=True) +def _major_by_group_owned( + major_ptr, values, value_ptr, indices, order, group_ptr, n_groups, n_minor, count +): + """Per-group minor-axis totals; each thread owns whole groups (no shared writes).""" + out = np.zeros((n_groups, n_minor), dtype=np.float64) + for g in numba.prange(n_groups): # ty: ignore[not-iterable] + row = out[g] + for p in range(group_ptr[g], group_ptr[g + 1]): + _add_major_slice(row, order[p], major_ptr, values, value_ptr, indices, count) + return out + + +@numba.njit(cache=True, parallel=True) +def _major_by_group_partial( + major_ptr, values, value_ptr, indices, groups, n_groups, n_minor, nthreads, count +): + """Per-group minor-axis totals via one private ``(n_groups, n_minor)`` block per thread.""" + n_major = major_ptr.shape[0] - 1 + span = (n_major + nthreads - 1) // nthreads + partial = np.zeros((nthreads, n_groups, n_minor), dtype=np.float64) + for t in numba.prange(nthreads): # ty: ignore[not-iterable] + local = partial[t] + for j in range(t * span, min(n_major, (t + 1) * span)): + _add_major_slice(local[groups[j]], j, major_ptr, values, value_ptr, indices, count) + return partial.sum(axis=0) + + +@numba.njit(cache=True, parallel=True) +def _minor_by_group(major_ptr, values, value_ptr, indices, groups, n_groups, count): + """Per-major-slice totals of each minor-axis group; each slice owns its output row.""" + n_major = major_ptr.shape[0] - 1 + out = np.zeros((n_major, n_groups), dtype=np.float64) + for j in numba.prange(n_major): # ty: ignore[not-iterable] + row = out[j] + for u in range(major_ptr[j], major_ptr[j + 1]): + v = 1.0 if count else np.float64(values[u]) + for k in range(value_ptr[u], value_ptr[u + 1]): + row[groups[indices[k]]] += v + return out + + +# -- dispatch ------------------------------------------------------------------ + + +def validate_groups( + arr: _VCSBase, group_idxs: Any, n_groups: Any, axis: Any +) -> tuple[np.ndarray, int, int]: + """Check and normalize ``group_sum``-style arguments. + + Returns ``(groups, n_groups, axis)`` with ``groups`` as an ``int64`` array. + """ + if axis not in (0, 1): + raise ValueError(f"axis must be 0 or 1, got {axis!r}") + n_groups = int(n_groups) + if n_groups < 0: + raise ValueError(f"n_groups must be non-negative, got {n_groups}") + groups = np.asarray(group_idxs) + if groups.ndim != 1 or groups.shape[0] != arr.shape[axis]: + raise ValueError( + f"group_idxs must be 1-D with length {arr.shape[axis]} (shape[{axis}]), " + f"got shape {groups.shape}" + ) + if groups.size and groups.dtype.kind not in "iu": + raise TypeError(f"group_idxs must be integers, got dtype {groups.dtype}") + groups = groups.astype(np.int64, copy=False) + if not _ops.indices_in_bounds(groups, n_groups): + raise ValueError(f"group_idxs must lie in [0, n_groups) = [0, {n_groups})") + return groups, n_groups, axis + + +def group_counts(groups: np.ndarray, n_groups: int) -> np.ndarray: + """Number of rows (or columns) labeled with each group.""" + return np.bincount(groups, minlength=n_groups).astype(np.int64) + + +def _major_full(arr: _VCSBase, groups: np.ndarray, n_groups: int, count: bool) -> np.ndarray: + """``(n_groups, n_minor)`` per-group totals for groups along the major axis.""" + n_minor = arr.n_minor + if n_groups == 0 or n_minor == 0: + return np.zeros((n_groups, n_minor), dtype=np.float64) + args = (arr.major_ptr, arr.values, arr.value_ptr, arr.indices) + if n_groups >= numba.get_num_threads(): + order = np.argsort(groups, kind="stable") + group_ptr = np.zeros(n_groups + 1, dtype=np.int64) + np.cumsum(group_counts(groups, n_groups), out=group_ptr[1:]) + return _major_by_group_owned(*args, order, group_ptr, n_groups, n_minor, count) + nthreads = _ops.accumulator_threads(n_groups * n_minor) + return _major_by_group_partial(*args, groups, n_groups, n_minor, nthreads, count) + + +def _major_totals(arr: _VCSBase, groups: np.ndarray, n_groups: int, count: bool) -> np.ndarray: + """``(n_groups,)`` per-group totals for groups along the major axis -- skips ``indices``.""" + per_major = arr._major_nnz() if count else arr._major_sums() + return np.bincount(groups, weights=per_major, minlength=n_groups) + + +def _minor_totals(arr: _VCSBase, groups: np.ndarray, n_groups: int, count: bool) -> np.ndarray: + """``(n_groups,)`` per-group totals for groups along the minor axis.""" + per_minor = arr._minor_nnz() if count else arr._minor_sums() + return np.bincount(groups, weights=per_minor, minlength=n_groups) + + +def group_reduce( + arr: _VCSBase, groups: np.ndarray, n_groups: int, axis: int, *, total: bool, count: bool +) -> np.ndarray: + """Grouped sum (``count=False``) or stored-element count (``count=True``) of ``arr``. + + ``groups``/``n_groups``/``axis`` must already have passed + :func:`validate_groups`. Returns ``float64``; callers cast counts. + """ + major_axis = 0 if arr._format == "csr" else 1 + on_major = axis == major_axis + if total: + reducer = _major_totals if on_major else _minor_totals + return reducer(arr, groups, n_groups, count) + if on_major: + out = _major_full(arr, groups, n_groups, count) # (n_groups, n_minor) + else: + out = _minor_by_group( + arr.major_ptr, arr.values, arr.value_ptr, arr.indices, groups, n_groups, count + ) # (n_major, n_groups) + # Both kernels are laid out along (major, minor); flip to (rows, cols) for VCSC. + out = out if arr._format == "csr" else out.T + return np.ascontiguousarray(out) diff --git a/tests/test_grouped_reductions.py b/tests/test_grouped_reductions.py new file mode 100644 index 0000000..a78b7d5 --- /dev/null +++ b/tests/test_grouped_reductions.py @@ -0,0 +1,159 @@ +"""Tests for group_sum/group_nnz/group_mean on VCSCArray/VCSRArray (#81).""" + +from __future__ import annotations + +import warnings + +import numpy as np +import pytest +import scipy.sparse as sp +from _hypothesis_strategies import dense_matrices, slow_first_call +from hypothesis import given +from hypothesis import strategies as st + +from vsparse import VCSCArray, VCSRArray, _grouped + + +@pytest.fixture(params=[VCSCArray, VCSRArray]) +def vcls(request): + return request.param + + +def _reference(dense, groups, n_groups, axis, reducer): + """Dense per-group reduction: ``reducer`` over each group's rows/columns along ``axis``.""" + parts = [] + for g in range(n_groups): + sel = np.take(dense, np.flatnonzero(groups == g), axis=axis) + parts.append(reducer(sel, axis=axis)) + if not parts: + other = dense.shape[1 - axis] + return np.zeros((0, other)) if axis == 0 else np.zeros((other, 0)) + return np.stack(parts, axis=axis) + + +def _check_all(v, dense, groups, n_groups, axis): + with warnings.catch_warnings(), np.errstate(invalid="ignore", divide="ignore"): + warnings.simplefilter("ignore", RuntimeWarning) + exp_mean = _reference(dense, groups, n_groups, axis, np.mean) + exp_total_mean = np.array( + [np.take(dense, np.flatnonzero(groups == g), axis=axis).mean() for g in range(n_groups)] + ) + exp_sum = _reference(dense, groups, n_groups, axis, np.sum) + exp_nnz = _reference(dense != 0, groups, n_groups, axis, np.sum) + + np.testing.assert_allclose(v.group_sum(groups, n_groups, axis=axis), exp_sum) + np.testing.assert_array_equal(v.group_nnz(groups, n_groups, axis=axis), exp_nnz) + np.testing.assert_allclose(v.group_mean(groups, n_groups, axis=axis), exp_mean) + + np.testing.assert_allclose( + v.group_sum(groups, n_groups, axis=axis, total=True), exp_sum.sum(axis=1 - axis) + ) + np.testing.assert_array_equal( + v.group_nnz(groups, n_groups, axis=axis, total=True), exp_nnz.sum(axis=1 - axis) + ) + np.testing.assert_allclose( + v.group_mean(groups, n_groups, axis=axis, total=True), exp_total_mean.reshape(-1) + ) + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("vcls", [VCSCArray, VCSRArray]) +@slow_first_call +@given(dense=dense_matrices(), data=st.data()) +def test_grouped_matches_dense(vcls, axis, dense, data): + n_groups = data.draw(st.integers(0 if dense.shape[axis] == 0 else 1, 6), label="n_groups") + groups = np.array( + data.draw( + st.lists( + st.integers(0, max(n_groups - 1, 0)), + min_size=dense.shape[axis], + max_size=dense.shape[axis], + ), + label="groups", + ), + dtype=np.int64, + ) + _check_all(vcls.from_scipy(sp.csr_array(dense)), dense, groups, n_groups, axis) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_major_full_both_kernels(dense, vcls, axis, rng, monkeypatch): + """The group-owned and per-thread-partial kernels must agree with the dense reference.""" + v = vcls.from_scipy(sp.csr_array(dense)) + n_groups = 3 + groups = rng.integers(0, n_groups, size=dense.shape[axis]) + expected = _reference(dense, groups, n_groups, axis, np.sum) + # Few groups vs. many threads -> partial kernel; patched thread count -> owned kernel. + for fake_threads in (n_groups + 1, 1): + monkeypatch.setattr(_grouped.numba, "get_num_threads", lambda n=fake_threads: n) + np.testing.assert_allclose(v.group_sum(groups, n_groups, axis=axis), expected) + + +def test_single_group_matches_sum(dense, vcls): + v = vcls.from_scipy(sp.csr_array(dense)) + for axis in (0, 1): + ones = np.zeros(dense.shape[axis], dtype=np.int64) + np.testing.assert_allclose(v.group_sum(ones, 1, axis=axis).reshape(-1), v.sum(axis=axis)) + np.testing.assert_allclose(v.group_mean(ones, 1, axis=axis).reshape(-1), v.mean(axis=axis)) + np.testing.assert_array_equal( + v.group_nnz(ones, 1, axis=axis).reshape(-1), v.getnnz(axis=axis) + ) + assert v.group_sum(ones, 1, axis=axis, total=True)[0] == pytest.approx(v.sum()) + + +def test_sorted_and_shuffled_groups_agree(vcls, rng): + """Contiguous-by-condition data and the same labels shuffled give identical results.""" + dense = rng.poisson(1.0, size=(60, 9)).astype(np.float64) + groups = np.repeat(np.arange(5), 12) + perm = rng.permutation(60) + v_sorted = vcls.from_scipy(sp.csr_array(dense)) + v_shuffled = vcls.from_scipy(sp.csr_array(dense[perm])) + np.testing.assert_allclose(v_sorted.group_sum(groups, 5), v_shuffled.group_sum(groups[perm], 5)) + + +def test_empty_group_mean_is_nan(vcls): + dense = np.array([[1.0, 0.0], [2.0, 3.0]]) + v = vcls.from_scipy(sp.csr_array(dense)) + means = v.group_mean([0, 0], 2) + np.testing.assert_allclose(means[0], [1.5, 1.5]) + assert np.isnan(means[1]).all() + np.testing.assert_array_equal(v.group_sum([0, 0], 2)[1], [0.0, 0.0]) + assert np.isnan(v.group_mean([0, 0], 2, total=True)[1]) + + +def test_return_dtypes(vcls): + v = vcls.from_scipy(sp.csr_array(np.array([[1, 0], [2, 3]], dtype=np.int32))) + assert v.group_sum([0, 1], 2).dtype == np.float64 + assert v.group_nnz([0, 1], 2).dtype == np.int64 + assert v.group_nnz([0, 1], 2, total=True).dtype == np.int64 + + +@pytest.mark.parametrize( + ("group_idxs", "n_groups", "axis", "exc"), + [ + ([0, 1], 2, 2, ValueError), # bad axis + ([0, 1], -1, 0, ValueError), # negative n_groups + ([0, 1, 0], 2, 0, ValueError), # wrong length + ([[0, 1]], 2, 0, ValueError), # not 1-D + ([0, 2], 2, 0, ValueError), # label out of range + ([0, -1], 2, 0, ValueError), # negative label + ([0.0, 1.0], 2, 0, TypeError), # non-integer labels + ], +) +def test_invalid_arguments(vcls, group_idxs, n_groups, axis, exc): + v = vcls.from_scipy(sp.csr_array(np.eye(2))) + for method in (v.group_sum, v.group_nnz, v.group_mean): + with pytest.raises(exc): + method(group_idxs, n_groups, axis=axis) + + +def test_major_totals_skip_indices(vcls): + """Per-group totals along the major axis come from value groups alone.""" + dense = np.array([[1.0, 0.0, 2.0], [0.0, 3.0, 0.0], [4.0, 0.0, 5.0]]) + v = vcls.from_scipy(sp.csr_array(dense)) + major_axis = 0 if vcls is VCSRArray else 1 + groups = np.array([1, 0, 1]) + expected = _reference(dense, groups, 2, major_axis, np.sum).sum(axis=1 - major_axis) + # Corrupt indices: a path that read them would scatter into the wrong place. + v.indices = np.zeros_like(v.indices) + np.testing.assert_allclose(v.group_sum(groups, 2, axis=major_axis, total=True), expected)