Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
43 changes: 43 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
95 changes: 95 additions & 0 deletions src/vsparse/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
183 changes: 183 additions & 0 deletions src/vsparse/_grouped.py
Original file line number Diff line number Diff line change
@@ -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)
Loading