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
3 changes: 2 additions & 1 deletion src/vsparse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from vsparse._anndata import from_anndata, to_layer
from vsparse._anndata_class import VCSCAnnData
from vsparse._base import VCSCArray, VCSRArray
from vsparse._base import VCSCArray, VCSRArray, sampled_dot
from vsparse._cuda import CudaNormalizedView, cuda_is_available
from vsparse._gds import CudaStreamedView, open_gpu_stream
from vsparse._norm_common import (
Expand All @@ -35,6 +35,7 @@
"from_anndata",
"load_packed",
"open_gpu_stream",
"sampled_dot",
"to_layer",
]

Expand Down
80 changes: 80 additions & 0 deletions src/vsparse/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,27 @@ 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"))

def sampled_dot(self, u: Any, v: Any, *, gpu: bool = False) -> np.ndarray:
"""Sampled dense-dense dot product ``u[i] @ v[j]`` at every stored nonzero.

Returns a 1-D array of length :attr:`nnz` aligned with :attr:`indices`.
"""
return sampled_dot(self, u, v, gpu=gpu)

def as_linear_operator(self) -> Any:
"""Wrap this array in a :class:`scipy.sparse.linalg.LinearOperator`."""
from scipy.sparse.linalg import LinearOperator

op_cls: Any = LinearOperator
return op_cls(
shape=self.shape,
dtype=np.dtype(self.dtype),
matvec=lambda x: self @ x,
rmatvec=lambda x: x @ self,
matmat=lambda X: self @ X,
rmatmat=lambda Y: (Y.T @ self).T,
)

# -- grouped (per-condition) reductions ---------------------------------

def group_sum(
Expand Down Expand Up @@ -826,3 +847,62 @@ class VCSRArray(_VCSBase):

__slots__ = ()
_format = "csr"


def sampled_dot(x: Any, u: Any, v: Any, *, gpu: bool = False) -> np.ndarray:
"""Sampled dense-dense dot product ``u[i] @ v[j]`` at every stored nonzero of ``x``.

Supports :class:`VCSRArray`, :class:`VCSCArray`, and SciPy sparse arrays/matrices.
Returns a 1-D NumPy array of length ``x.nnz`` aligned with ``x.indices``
(for SciPy CSR, aligned with ``x.data``). Pass ``gpu=True`` to run on CUDA
via CuPy without allocating an ``(nnz, k)`` temporary.
"""
u_arr = np.ascontiguousarray(u)
v_arr = np.ascontiguousarray(v)
if u_arr.ndim != 2 or v_arr.ndim != 2:
raise ValueError(f"u and v must be 2-D, got shapes {u_arr.shape} and {v_arr.shape}")
if u_arr.shape[0] != x.shape[0] or v_arr.shape[0] != x.shape[1]:
raise ValueError(
f"Factor shapes {u_arr.shape} and {v_arr.shape} do not match matrix shape {x.shape}"
)
if u_arr.shape[1] != v_arr.shape[1]:
raise ValueError(
f"Inner dimensions of u ({u_arr.shape[1]}) and v ({v_arr.shape[1]}) must match"
)

out_dtype = np.result_type(u_arr.dtype, v_arr.dtype)
if not np.issubdtype(out_dtype, np.floating):
out_dtype = np.dtype(np.float64)
u_arr = np.ascontiguousarray(u_arr, dtype=out_dtype)
v_arr = np.ascontiguousarray(v_arr, dtype=out_dtype)

if isinstance(x, _VCSBase):
if x.nnz == 0:
return np.empty(0, dtype=out_dtype)
if gpu:
from vsparse._cuda import cuda_sampled_dot_vcs

return cuda_sampled_dot_vcs(x, u_arr, v_arr)
out = np.empty(x.nnz, dtype=out_dtype)
if x._format == "csr":
return _ops.sampled_dot_vcs_major_is_row(
x.major_ptr, x.value_ptr, x.indices, u_arr, v_arr, out
)
return _ops.sampled_dot_vcs_major_is_col(
x.major_ptr, x.value_ptr, x.indices, u_arr, v_arr, out
)

if sp.issparse(x):
x_csr = x if x.format == "csr" else x.tocsr()
if x_csr.nnz == 0:
return np.empty(0, dtype=out_dtype)
if gpu:
from vsparse._cuda import cuda_sampled_dot_csr

return cuda_sampled_dot_csr(x_csr, u_arr, v_arr)
out = np.empty(x_csr.nnz, dtype=out_dtype)
return _ops.sampled_dot_csr(x_csr.indptr, x_csr.indices, u_arr, v_arr, out)

raise TypeError(
f"sampled_dot expects a VCSRArray, VCSCArray, or SciPy sparse matrix, got {type(x)}"
)
Loading