moscot 0.5.1__tar.gz → 0.5.3__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.
Files changed (79) hide show
  1. {moscot-0.5.1 → moscot-0.5.3}/PKG-INFO +1 -1
  2. {moscot-0.5.1 → moscot-0.5.3}/pyproject.toml +6 -3
  3. moscot-0.5.3/src/moscot/__init__.py +13 -0
  4. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/backends/ott/output.py +116 -42
  5. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/cost.py +1 -1
  6. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/output.py +123 -40
  7. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/problems/_mixins.py +2 -2
  8. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/datasets.py +9 -9
  9. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/time/_mixins.py +1 -1
  10. {moscot-0.5.1 → moscot-0.5.3}/src/moscot.egg-info/PKG-INFO +1 -1
  11. {moscot-0.5.1 → moscot-0.5.3}/src/moscot.egg-info/SOURCES.txt +3 -0
  12. moscot-0.5.3/src/moscot.egg-info/scm_file_list.json +175 -0
  13. moscot-0.5.3/src/moscot.egg-info/scm_version.json +8 -0
  14. moscot-0.5.3/uv.lock +6925 -0
  15. moscot-0.5.1/src/moscot/__init__.py +0 -13
  16. {moscot-0.5.1 → moscot-0.5.3}/.gitignore +0 -0
  17. {moscot-0.5.1 → moscot-0.5.3}/.gitmodules +0 -0
  18. {moscot-0.5.1 → moscot-0.5.3}/.pre-commit-config.yaml +0 -0
  19. {moscot-0.5.1 → moscot-0.5.3}/.readthedocs.yml +0 -0
  20. {moscot-0.5.1 → moscot-0.5.3}/.run_notebooks.sh +0 -0
  21. {moscot-0.5.1 → moscot-0.5.3}/LICENSE +0 -0
  22. {moscot-0.5.1 → moscot-0.5.3}/MANIFEST.in +0 -0
  23. {moscot-0.5.1 → moscot-0.5.3}/README.rst +0 -0
  24. {moscot-0.5.1 → moscot-0.5.3}/codecov.yml +0 -0
  25. {moscot-0.5.1 → moscot-0.5.3}/setup.cfg +0 -0
  26. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/_constants.py +0 -0
  27. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/_logging.py +0 -0
  28. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/_registry.py +0 -0
  29. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/_types.py +0 -0
  30. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/backends/__init__.py +0 -0
  31. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/backends/ott/__init__.py +0 -0
  32. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/backends/ott/_utils.py +0 -0
  33. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/backends/ott/solver.py +0 -0
  34. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/backends/utils.py +0 -0
  35. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/__init__.py +0 -0
  36. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/problems/__init__.py +0 -0
  37. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/problems/_utils.py +0 -0
  38. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/problems/birth_death.py +0 -0
  39. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/problems/compound_problem.py +0 -0
  40. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/problems/manager.py +0 -0
  41. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/problems/problem.py +0 -0
  42. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/base/solver.py +0 -0
  43. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/costs/__init__.py +0 -0
  44. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/costs/_costs.py +0 -0
  45. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/costs/_utils.py +0 -0
  46. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/plotting/__init__.py +0 -0
  47. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/plotting/_plotting.py +0 -0
  48. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/plotting/_utils.py +0 -0
  49. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/__init__.py +0 -0
  50. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/_utils.py +0 -0
  51. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/cross_modality/__init__.py +0 -0
  52. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/cross_modality/_mixins.py +0 -0
  53. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/cross_modality/_translation.py +0 -0
  54. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/generic/__init__.py +0 -0
  55. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/generic/_generic.py +0 -0
  56. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/generic/_mixins.py +0 -0
  57. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/space/__init__.py +0 -0
  58. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/space/_alignment.py +0 -0
  59. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/space/_mapping.py +0 -0
  60. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/space/_mixins.py +0 -0
  61. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/spatiotemporal/__init__.py +0 -0
  62. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/spatiotemporal/_spatio_temporal.py +0 -0
  63. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/time/__init__.py +0 -0
  64. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/problems/time/_lineage.py +0 -0
  65. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/py.typed +0 -0
  66. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/__init__.py +0 -0
  67. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/_data/allTFs_dmel.txt +0 -0
  68. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/_data/allTFs_hg38.txt +0 -0
  69. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/_data/allTFs_mm.txt +0 -0
  70. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/_data/human_apoptosis.txt +0 -0
  71. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/_data/human_proliferation.txt +0 -0
  72. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/_data/mouse_apoptosis.txt +0 -0
  73. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/_data/mouse_proliferation.txt +0 -0
  74. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/data.py +0 -0
  75. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/subset_policy.py +0 -0
  76. {moscot-0.5.1 → moscot-0.5.3}/src/moscot/utils/tagged_array.py +0 -0
  77. {moscot-0.5.1 → moscot-0.5.3}/src/moscot.egg-info/dependency_links.txt +0 -0
  78. {moscot-0.5.1 → moscot-0.5.3}/src/moscot.egg-info/requires.txt +0 -0
  79. {moscot-0.5.1 → moscot-0.5.3}/src/moscot.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: moscot
3
- Version: 0.5.1
3
+ Version: 0.5.3
4
4
  Summary: Multi-omic single-cell optimal transport tools
5
5
  Author: Dominik Klein, Giovanni Palla, Michal Klein, Zoe Piran, Marius Lange
6
6
  Maintainer-email: Dominik Klein <dominik.klein@helmholtz-muenchen.de>, Giovanni Palla <giovanni.palla@helmholtz-muenchen.de>, Michal Klein <michal.klein@helmholtz-muenchen.de>
@@ -185,7 +185,11 @@ known_bio = ["anndata", "scanpy", "squidpy"]
185
185
  known_plotting = ["IPython", "matplotlib", "mpl_toolkits", "seaborn"]
186
186
 
187
187
  [tool.pytest.ini_options]
188
- markers = ["fast: marks tests as fask"]
188
+ markers = [
189
+ "fast: marks tests as fask",
190
+ "memory: strict peak-memory tests; deselected by default, run with `pytest -m memory`",
191
+ ]
192
+ addopts = "-m 'not memory'"
189
193
  xfail_strict = true
190
194
  filterwarnings = [
191
195
  "ignore:No data for colormapping:UserWarning",
@@ -233,8 +237,7 @@ ignore_roles = [
233
237
 
234
238
  [tool.mypy]
235
239
  mypy_path = "$MYPY_CONFIG_FILE_DIR/src"
236
- python_version = "3.10"
237
- plugins = "numpy.typing.mypy_plugin"
240
+ python_version = "3.12"
238
241
 
239
242
  ignore_errors = false
240
243
 
@@ -0,0 +1,13 @@
1
+ from importlib import metadata
2
+
3
+ from moscot import backends, base, costs, datasets, plotting, problems, utils
4
+
5
+ try:
6
+ md = metadata.metadata(__name__)
7
+ __version__ = md.get("version", "")
8
+ __author__ = md.get("Author", "")
9
+ __maintainer__ = md.get("Maintainer-email", "")
10
+ except ImportError:
11
+ md = None
12
+
13
+ del metadata, md
@@ -1,10 +1,11 @@
1
- from typing import Any, Literal, Optional, Tuple, Union
1
+ import functools
2
+ from typing import Any, Optional, Tuple, Union
2
3
 
3
4
  import jax
4
5
  import jax.numpy as jnp
5
6
  import numpy as np
6
- from ott.geometry import pointcloud
7
- from ott.problems.linear import linear_problem
7
+ import scipy.sparse as sp
8
+ from ott.geometry import geometry, low_rank, pointcloud
8
9
  from ott.solvers.linear import sinkhorn, sinkhorn_lr
9
10
  from ott.solvers.quadratic import gromov_wasserstein, gromov_wasserstein_lr
10
11
 
@@ -12,11 +13,95 @@ import matplotlib as mpl
12
13
  import matplotlib.pyplot as plt
13
14
 
14
15
  from moscot._types import ArrayLike, Device_t
15
- from moscot.base.output import BaseDiscreteSolverOutput, MatrixSolverOutput
16
+ from moscot.base.output import (
17
+ BaseDiscreteSolverOutput,
18
+ RowMaterializer,
19
+ )
16
20
 
17
21
  __all__ = ["OTTOutput", "GraphOTTOutput"]
18
22
 
19
23
 
24
+ def _rows_from_potentials(f: jnp.ndarray, g: jnp.ndarray, geom: Any) -> Optional[RowMaterializer]:
25
+ r"""Rows of :math:`\exp((f_i + g_j - C_{ij}) / \varepsilon)`, as :mod:`ott` computes the full matrix.
26
+
27
+ The parent geometry's resolved :attr:`epsilon` and :attr:`inv_scale_cost` are captured once:
28
+ :meth:`~ott.geometry.geometry.Geometry.subset` carries ``scale_cost``/``relative_epsilon`` as
29
+ unevaluated strings, so a subset geometry would silently re-derive both from the subset.
30
+
31
+ Returns :obj:`None` if the geometry cannot produce a row block without materializing everything,
32
+ in which case the caller falls back to pushing indicator columns.
33
+ """
34
+ eps = geom.epsilon
35
+ if isinstance(geom, pointcloud.PointCloud):
36
+ x, y, cost_fn, inv_scale = geom.x, geom.y, geom.cost_fn, geom.inv_scale_cost
37
+
38
+ def cost_rows(ixs: np.ndarray) -> jnp.ndarray:
39
+ return cost_fn.all_pairs(x[ixs], y) * inv_scale
40
+
41
+ elif isinstance(geom, low_rank.LRCGeometry):
42
+ # `subset` is silently wrong here (it slices the two factors as if they were cost/kernel)
43
+ cost_1, cost_2, bias = geom.cost_1, geom.cost_2, geom.bias
44
+
45
+ def cost_rows(ixs: np.ndarray) -> jnp.ndarray:
46
+ return cost_1[ixs] @ cost_2.T + bias
47
+
48
+ elif type(geom) is geometry.Geometry: # dense cost; hoisted out of the block loop
49
+ cost = geom.cost_matrix
50
+
51
+ def cost_rows(ixs: np.ndarray) -> jnp.ndarray:
52
+ return cost[ixs]
53
+
54
+ else: # e.g. `Geodesic`, whose cost is never materialized
55
+ return None
56
+
57
+ def rows(ixs: np.ndarray) -> jnp.ndarray:
58
+ return jnp.exp((f[ixs][:, None] + g[None, :] - cost_rows(ixs)) / eps)
59
+
60
+ return rows
61
+
62
+
63
+ def _ott_row_materializer(out: Any) -> Optional[RowMaterializer]:
64
+ """Materialize rows of an :mod:`ott` output's transport matrix, or :obj:`None` if unsupported."""
65
+ if isinstance(out, (sinkhorn_lr.LRSinkhornOutput, gromov_wasserstein_lr.LRGWOutput)):
66
+ # `T = Q diag(1 / g) R^T`, as in `ott`'s `matrix`; never touches a geometry, which matters
67
+ # because `LRGWOutput.geom` re-linearizes on every access
68
+ qg, r = out.q * (1.0 / out.g), out.r
69
+
70
+ def rows(ixs: np.ndarray) -> jnp.ndarray:
71
+ return qg[ixs] @ r.T
72
+
73
+ return rows
74
+ if isinstance(out, sinkhorn.SinkhornOutput):
75
+ return _rows_from_potentials(out.f, out.g, out.geom)
76
+ if isinstance(out, gromov_wasserstein.GWOutput):
77
+ inner = _ott_row_materializer(out.linear_state)
78
+ if inner is None:
79
+ return None
80
+ scale = out._rescale_factor # `GWOutput.matrix`/`apply` rescale the linearization; so must we
81
+
82
+ def rows(ixs: np.ndarray) -> jnp.ndarray:
83
+ return scale * inner(ixs)
84
+
85
+ return rows
86
+ return None
87
+
88
+
89
+ def _mass_select_row(row: jnp.ndarray, *, value: float, k: int) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
90
+ """Select ``mode = 'mass'`` entries of one row: its ``k`` largest entries and how many to keep."""
91
+ vals, idx = jax.lax.top_k(row, k)
92
+ total = row.sum()
93
+ target = jnp.inf if value >= 1.0 else value * total
94
+ n_keep = jnp.minimum((jnp.cumsum(vals) < target).sum() + 1, k)
95
+ return vals, idx, jnp.where(row.max() > 0.0, n_keep, 0) # massless rows keep nothing
96
+
97
+
98
+ @functools.partial(jax.jit, static_argnames=("value", "k"))
99
+ def _mass_select_rows(rows: jnp.ndarray, *, value: float, k: int) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
100
+ # `top_k` over a whole block of long rows needs several times the block's memory; 256 rows at a
101
+ # time do not (and run ~3x faster on a 2048 x 92,507 block on an RTX 4090)
102
+ return jax.lax.map(functools.partial(_mass_select_row, value=value, k=k), rows, batch_size=256)
103
+
104
+
20
105
  class OTTOutput(BaseDiscreteSolverOutput):
21
106
  """Output of various :term:`OT` problems.
22
107
 
@@ -192,6 +277,24 @@ class OTTOutput(BaseDiscreteSolverOutput):
192
277
  def transport_matrix(self) -> ArrayLike: # noqa: D102
193
278
  return self._output.matrix
194
279
 
280
+ def _row_materializer(self) -> RowMaterializer: # noqa: D102
281
+ materialize = _ott_row_materializer(self._output)
282
+ return super()._row_materializer() if materialize is None else materialize
283
+
284
+ def _mass_select(self, rows: ArrayLike, *, value: float, max_k: Optional[int]) -> Tuple[sp.csr_matrix, int]:
285
+ # select on the device holding the rows; only `[b, max_k]` crosses to the host, not `[b, m]`
286
+ if max_k is None or not isinstance(rows, jax.Array):
287
+ return super()._mass_select(rows, value=value, max_k=max_k)
288
+ b, m = rows.shape
289
+ k = min(max_k, m)
290
+ vals, idx, n_keep = (np.asarray(x) for x in _mass_select_rows(rows, value=value, k=k))
291
+ keep = np.arange(k)[None, :] < n_keep[:, None]
292
+ row_ix = np.broadcast_to(np.arange(b)[:, None], keep.shape)
293
+ out = sp.csr_matrix((vals[keep], (row_ix[keep], idx[keep])), shape=(b, m))
294
+ out.eliminate_zeros()
295
+ out.sort_indices()
296
+ return out, int((n_keep == 0).sum())
297
+
195
298
  @property
196
299
  def is_linear(self) -> bool: # noqa: D102
197
300
  return isinstance(self._output, (sinkhorn.SinkhornOutput, sinkhorn_lr.LRSinkhornOutput))
@@ -228,44 +331,6 @@ class OTTOutput(BaseDiscreteSolverOutput):
228
331
  return self._output.f, self._output.g
229
332
  return None
230
333
 
231
- def _with_batch_size(self, batch_size: int) -> "OTTOutput":
232
- """Return a copy whose online geometry materializes the cost in ``batch_size`` chunks.
233
-
234
- Only :term:`Sinkhorn` outputs backed by an online :class:`~ott.geometry.pointcloud.PointCloud`
235
- recompute the cost lazily during :meth:`push`/:meth:`pull`; for those, the chunk size is fixed at
236
- ``solve`` time and governs peak memory. Rebuilding the geometry with a smaller ``batch_size`` lets
237
- :meth:`~moscot.base.output.BaseDiscreteSolverOutput.sparsify` bound its memory. Every other output
238
- (dense/offline geometry, :term:`low-rank`, :term:`GW`/:term:`FGW`) is returned unchanged, as its
239
- :meth:`apply` is already memory-bounded.
240
- """
241
- out = self._output
242
- if not isinstance(out, sinkhorn.SinkhornOutput):
243
- return self
244
- geom = out.geom
245
- if not isinstance(geom, pointcloud.PointCloud) or geom._batch_size is None:
246
- return self
247
- if geom._scale_cost == "median": # not implemented for online geometries in `ott`
248
- return self
249
- children, aux = geom.tree_flatten()
250
- new_geom = type(geom).tree_unflatten({**aux, "batch_size": batch_size}, children)
251
- prob = out.ot_prob
252
- new_prob = linear_problem.LinearProblem(new_geom, prob.a, prob.b, tau_a=prob.tau_a, tau_b=prob.tau_b)
253
- return OTTOutput(out.set(ot_prob=new_prob))
254
-
255
- def sparsify( # noqa: D102
256
- self,
257
- mode: Literal["threshold", "percentile", "min_row", "mass"],
258
- value: Optional[float] = None,
259
- batch_size: int = 1024,
260
- n_samples: Optional[int] = None,
261
- seed: Optional[int] = None,
262
- max_k: Optional[int] = None,
263
- ) -> MatrixSolverOutput:
264
- out = self._with_batch_size(batch_size)
265
- return BaseDiscreteSolverOutput.sparsify(
266
- out, mode=mode, value=value, batch_size=batch_size, n_samples=n_samples, seed=seed, max_k=max_k
267
- )
268
-
269
334
  @property
270
335
  def rank(self) -> int: # noqa: D102
271
336
  output = self._output.linear_state if isinstance(self._output, gromov_wasserstein.GWOutput) else self._output
@@ -320,6 +385,15 @@ class GraphOTTOutput(OTTOutput):
320
385
  res = self._output.apply(x_expanded.T, axis=1 - forward, lse_mode=False).T
321
386
  return res[len(x) :] if forward else res[: -len(x)]
322
387
 
388
+ def _row_materializer(self) -> RowMaterializer:
389
+ """Materialize rows by pushing indicator columns.
390
+
391
+ :attr:`shape` is a sub-block of the expanded ``[n + m, n + m]`` graph problem, so the wrapped
392
+ output's potentials do not index this output's rows. Pushing is cheap here anyway: applying a
393
+ (sparse) graph kernel costs ``nnz`` per column, not ``n * m``.
394
+ """
395
+ return BaseDiscreteSolverOutput._row_materializer(self)
396
+
323
397
  def to(self, device: Optional[Device_t] = None) -> "GraphOTTOutput": # noqa: D102
324
398
  if device is None:
325
399
  return GraphOTTOutput(jax.device_put(self._output, device=device), shape=self.shape)
@@ -58,7 +58,7 @@ class BaseCost(abc.ABC):
58
58
  f"Cost matrix contains `{np.sum(np.isnan(cost))}` NaN values, "
59
59
  f"setting them to the maximum value `{maxx}`."
60
60
  )
61
- cost = np.nan_to_num(cost, nan=maxx) # type: ignore[arg-type, type-var]
61
+ cost = np.nan_to_num(cost, nan=maxx) # type: ignore[arg-type]
62
62
  if np.any(cost < 0):
63
63
  raise ValueError(f"Cost matrix contains `{np.sum(cost < 0)}` negative values.")
64
64
  return cost
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  import abc
4
4
  import copy
5
5
  import functools
6
- from typing import Any, Callable, Iterable, Literal, Optional, Union
6
+ from typing import Any, Callable, Iterable, Literal, Optional, Union, cast
7
7
 
8
8
  import numpy as np
9
9
  import scipy.sparse as sp
@@ -14,6 +14,9 @@ from moscot._types import ArrayLike, Device_t, DTypeLike
14
14
 
15
15
  __all__ = ["BaseDiscreteSolverOutput", "MatrixSolverOutput"]
16
16
 
17
+ #: Materializes rows ``ixs`` of a transport matrix as a dense array of shape ``[len(ixs), m]``.
18
+ RowMaterializer = Callable[[np.ndarray], ArrayLike]
19
+
17
20
 
18
21
  def _mass_select_block(rows: np.ndarray, *, value: float, max_k: Optional[int]) -> sp.csr_matrix:
19
22
  """Keep, per row, the smallest set of entries capturing ``value`` of the row mass.
@@ -31,10 +34,17 @@ def _mass_select_block(rows: np.ndarray, *, value: float, max_k: Optional[int])
31
34
  -------
32
35
  Sparsified block as a :class:`~scipy.sparse.csr_matrix` of shape ``[b, m]``.
33
36
  """
34
- _, m = rows.shape
35
- order = np.argsort(rows, axis=1)[:, ::-1] # descending
36
- sorted_vals = np.take_along_axis(rows, order, axis=1)
37
- totals = sorted_vals.sum(axis=1, keepdims=True)
37
+ n, m = rows.shape
38
+ if max_k is not None and max_k < m:
39
+ # at most `max_k` entries are kept: sort only the `max_k` largest, not the whole row
40
+ top = np.argpartition(rows, m - max_k, axis=1)[:, m - max_k :]
41
+ order = np.take_along_axis(top, np.argsort(np.take_along_axis(rows, top, axis=1), axis=1)[:, ::-1], axis=1)
42
+ sorted_vals = np.take_along_axis(rows, order, axis=1)
43
+ totals = rows.sum(axis=1, keepdims=True)
44
+ else:
45
+ order = np.argsort(rows, axis=1)[:, ::-1] # descending
46
+ sorted_vals = np.take_along_axis(rows, order, axis=1)
47
+ totals = sorted_vals.sum(axis=1, keepdims=True)
38
48
  cum = np.cumsum(sorted_vals, axis=1)
39
49
  # `value >= 1` keeps everything (avoids float cumsum vs. sum mismatch -> exact reconstruction).
40
50
  target = np.full_like(totals, np.inf) if value >= 1.0 else value * totals
@@ -44,19 +54,27 @@ def _mass_select_block(rows: np.ndarray, *, value: float, max_k: Optional[int])
44
54
  if max_k is not None:
45
55
  k_per_row = np.minimum(k_per_row, max_k)
46
56
  k_per_row = np.minimum(k_per_row, m)
47
- keep_sorted = np.arange(m)[None, :] < k_per_row[:, None]
48
- sel = np.zeros(rows.shape, dtype=bool)
49
- np.put_along_axis(sel, order, keep_sorted, axis=1)
50
- return sp.csr_matrix(np.where(sel, rows, 0.0))
51
-
52
-
53
- def _sparsify_block(
54
- rows: np.ndarray, *, mode: str, thr: Optional[float], value: Optional[float], max_k: Optional[int]
55
- ) -> sp.csr_matrix:
56
- """Apply the sparsification criterion to a block of transport-matrix rows."""
57
- if mode == "mass":
58
- assert value is not None # validated in `sparsify`
59
- return _mass_select_block(rows, value=value, max_k=max_k)
57
+ keep_sorted = np.arange(order.shape[1])[None, :] < k_per_row[:, None]
58
+ row_ix = np.broadcast_to(np.arange(n)[:, None], order.shape)
59
+ out = sp.csr_matrix((sorted_vals[keep_sorted], (row_ix[keep_sorted], order[keep_sorted])), shape=(n, m))
60
+ out.eliminate_zeros()
61
+ out.sort_indices()
62
+ return out
63
+
64
+
65
+ def _massless_rows(rows: np.ndarray) -> np.ndarray:
66
+ """Mask of rows carrying no mass.
67
+
68
+ Such rows cannot be kept non-empty by any threshold, so every sparsification mode treats them
69
+ the same way: they keep no entries, and they are excluded from the statistics that determine a
70
+ threshold. Letting them take part would drag any row-based threshold down to :math:`0` and
71
+ disable sparsification altogether, without making the row usable.
72
+ """
73
+ return ~(rows.max(axis=1) > 0.0)
74
+
75
+
76
+ def _threshold_block(rows: np.ndarray, *, thr: float) -> sp.csr_matrix:
77
+ """Set the entries of a block of transport-matrix rows below ``thr`` to :math:`0`."""
60
78
  rows = np.array(rows) # writable copy
61
79
  rows[rows < thr] = 0.0
62
80
  return sp.csr_matrix(rows)
@@ -243,6 +261,35 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
243
261
 
244
262
  return op
245
263
 
264
+ def _row_materializer(self) -> RowMaterializer:
265
+ """Build a callable materializing rows of the :attr:`transport_matrix`.
266
+
267
+ The callable maps row indices to a dense ``[len(ixs), m]`` array. It is built once per
268
+ :meth:`sparsify` call, so subclasses can hoist per-output work (e.g. resolving a geometry)
269
+ out of the block loop.
270
+
271
+ This default pushes indicator columns, which is correct for any output but costs
272
+ ``n * m * len(ixs)`` whenever :meth:`push` materializes a dense tensor - as :mod:`ott`'s
273
+ log-sum-exp apply does. Subclasses that can slice or recompute rows directly override it.
274
+ """
275
+ n = self.shape[0]
276
+
277
+ def materialize(ixs: np.ndarray) -> ArrayLike:
278
+ x = np.zeros((n, len(ixs)), dtype=float)
279
+ x[ixs, np.arange(len(ixs))] = 1.0
280
+ return np.asarray(self.push(x, scale_by_marginals=False)).T
281
+
282
+ return materialize
283
+
284
+ def _mass_select(self, rows: ArrayLike, *, value: float, max_k: Optional[int]) -> tuple[sp.csr_matrix, int]:
285
+ """Apply ``mode = 'mass'`` to a block of rows from :meth:`_row_materializer`.
286
+
287
+ Returns the sparsified block and its number of rows carrying no mass. Outputs whose rows live
288
+ on an accelerator override this to select there and copy only the kept entries to the host.
289
+ """
290
+ rows = np.asarray(rows)
291
+ return _mass_select_block(rows, value=value, max_k=max_k), int(_massless_rows(rows).sum())
292
+
246
293
  def sparsify(
247
294
  self,
248
295
  mode: Literal["threshold", "percentile", "min_row", "mass"],
@@ -257,7 +304,17 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
257
304
  This function sets entries of the transport matrix to :math:`0` according to ``mode`` and
258
305
  returns a :class:`~moscot.base.output.MatrixSolverOutput` with sparsified transport matrix stored
259
306
  as a :class:`~scipy.sparse.csr_matrix`. The transport matrix is materialized in row blocks of
260
- ``batch_size`` rows, so peak memory is bounded by ``batch_size``.
307
+ ``batch_size`` rows; outputs that can build rows directly - :mod:`ott` :term:`Sinkhorn`,
308
+ :term:`Gromov-Wasserstein`/:term:`fused Gromov-Wasserstein`, their :term:`low-rank` counterparts,
309
+ and already materialized matrices - never hold more than ``[batch_size, m]`` at a time. Other
310
+ outputs fall back to pushing indicator columns, whose cost depends on the output's :meth:`push`.
311
+ For :mod:`ott` outputs, ``mode = 'mass'`` with ``max_k`` selects the entries on the device holding
312
+ the rows and copies only ``[batch_size, max_k]`` of each block to the host.
313
+
314
+ Rows carrying no mass keep no entries and take no part in choosing a threshold, whichever
315
+ ``mode`` is used - no threshold can make them non-empty, and letting them take part would
316
+ drag the threshold down to :math:`0`. A warning is emitted when any are present, since the
317
+ result then cannot be normalized into a Markov transition matrix.
261
318
 
262
319
  .. warning::
263
320
  This function only serves for interfacing software which has to instantiate the transport matrix,
@@ -270,8 +327,10 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
270
327
 
271
328
  - `'threshold'` - ``value`` is the threshold below which entries are set to :math:`0`.
272
329
  - `'percentile'` - ``value`` is the percentile in :math:`[0, 100]` of the :attr:`transport_matrix`.
273
- below which entries are set to :math:`0`.
274
- - `'min_row'` - ``value`` is not used, it is chosen such that each row has at least 1 non-zero entry.
330
+ below which entries are set to :math:`0`, estimated from ``n_samples`` randomly sampled rows.
331
+ - `'min_row'` - ``value`` is not used, it is set to ``min_i max_j T_ij``, the largest
332
+ threshold for which every row keeps at least 1 non-zero entry. It does not depend on
333
+ ``batch_size``; the rows are materialized twice, once for the threshold and once for the values.
275
334
  - `'mass'` - per row, keep the largest entries capturing a fraction ``value`` of the row's mass
276
335
  (at most ``max_k`` entries per row); ``value`` must be in :math:`(0, 1]`.
277
336
  value
@@ -279,9 +338,9 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
279
338
  batch_size
280
339
  How many rows to materialize at a time when sparsifying the :attr:`transport_matrix`.
281
340
  n_samples
282
- If ``mode = 'percentile'``, determine the number of samples based on which the percentile is computed
283
- stochastically. Note this means that a matrix of shape `[n_samples, min(transport_matrix.shape)]`
284
- has to be instantiated. If `None`, ``n_samples`` is set to ``batch_size``.
341
+ If ``mode = 'percentile'``, the number of rows sampled to estimate the percentile stochastically.
342
+ Note this means that a matrix of shape `[n_samples, m]` has to be instantiated.
343
+ If `None`, ``n_samples`` is set to ``batch_size``.
285
344
  seed
286
345
  Random seed needed for sampling if ``mode = 'percentile'``.
287
346
  max_k
@@ -292,6 +351,9 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
292
351
  Output with sparsified transport matrix.
293
352
  """
294
353
  n, m = self.shape
354
+ materialize = self._row_materializer()
355
+ row_blocks = [np.arange(start, min(start + batch_size, n)) for start in range(0, n, batch_size)]
356
+
295
357
  thr: Optional[float] = None
296
358
  if mode == "mass":
297
359
  if value is None or not 0.0 < value <= 1.0:
@@ -306,19 +368,21 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
306
368
  if value is None:
307
369
  raise ValueError("If `mode = 'percentile'`, `value` cannot be `None`.")
308
370
  rng = np.random.RandomState(seed=seed)
309
- n_samples = n_samples if n_samples is not None else batch_size
310
- k = min(n_samples, n)
311
- x = np.zeros((m, k))
312
- rows = rng.choice(m, size=k)
313
- x[rows, np.arange(k)] = 1.0
314
- res = self.pull(x, scale_by_marginals=False) # tmap @ indicator_vectors
315
- thr = np.percentile(res, value)
371
+ k = min(n_samples if n_samples is not None else batch_size, n)
372
+ ixs = np.sort(rng.choice(n, size=k, replace=False))
373
+ sample = np.asarray(materialize(ixs))
374
+ sample = sample[~_massless_rows(sample)]
375
+ thr = float(np.percentile(sample, value)) if sample.size else np.inf
316
376
  elif mode == "min_row":
377
+ # exact rule `min_i max_j T_ij`: every block holds whole rows, so each row's maximum is
378
+ # exact and the threshold does not depend on `batch_size`. Computing it from the same
379
+ # blocks that produce the values also keeps the two consistent to the last bit.
317
380
  thr = np.inf
318
- for batch in range(0, m, batch_size):
319
- x = np.eye(m, min(batch_size, m - batch), -(min(batch, m)))
320
- res = self.pull(x, scale_by_marginals=False) # tmap @ indicator_vectors
321
- thr = min(thr, float(res.max(axis=1).min()))
381
+ for ixs in row_blocks:
382
+ maxima = np.asarray(materialize(ixs)).max(axis=1)
383
+ maxima = maxima[maxima > 0.0] # see `_massless_rows`
384
+ if maxima.size:
385
+ thr = min(thr, float(maxima.min()))
322
386
  else:
323
387
  raise NotImplementedError(f"Mode `{mode}` is not yet implemented.")
324
388
 
@@ -328,11 +392,22 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
328
392
  # Always iterate over source rows so that each block holds rows of the transport matrix.
329
393
  # This keeps the per-row criteria (e.g. `mass`) well-defined and peak memory at `[batch_size, m]`.
330
394
  tmaps_sparse: list[sp.csr_matrix] = []
331
- for batch in range(0, n, batch_size):
332
- cols = min(batch_size, n - batch)
333
- x = np.eye(n, cols, -batch, dtype=float)
334
- rows = np.asarray(self.push(x, scale_by_marginals=False)).T # [cols, m] = rows of `T`
335
- tmaps_sparse.append(_sparsify_block(rows, mode=mode, thr=thr, value=value, max_k=max_k))
395
+ n_massless = 0
396
+ for ixs in row_blocks:
397
+ if mode == "mass":
398
+ assert value is not None # validated above
399
+ block, n_empty = self._mass_select(materialize(ixs), value=value, max_k=max_k)
400
+ else:
401
+ assert thr is not None
402
+ rows = np.asarray(materialize(ixs))
403
+ block, n_empty = _threshold_block(rows, thr=thr), int(_massless_rows(rows).sum())
404
+ n_massless += n_empty
405
+ tmaps_sparse.append(block)
406
+ if n_massless:
407
+ logger.warning(
408
+ f"`{n_massless}` row(s) of the transport matrix carry no mass and are left empty; "
409
+ f"the sparsified matrix cannot be normalized into a Markov transition matrix."
410
+ )
336
411
 
337
412
  transport_matrix = sp.vstack(tmaps_sparse).tocsr() if tmaps_sparse else sp.csr_matrix((n, m))
338
413
  return MatrixSolverOutput(
@@ -416,6 +491,14 @@ class MatrixSolverOutput(BaseDiscreteSolverOutput):
416
491
  def _apply_forward(self, x: ArrayLike) -> ArrayLike:
417
492
  return self._apply(x, forward=True)
418
493
 
494
+ def _row_materializer(self) -> RowMaterializer: # noqa: D102
495
+ tmap = self.transport_matrix
496
+ if sp.issparse(tmap):
497
+ sparse_tmap = cast(sp.spmatrix, tmap)
498
+ return lambda ixs: sparse_tmap[ixs].toarray()
499
+ dense_tmap = np.asarray(tmap) # e.g. `jax` arrays
500
+ return lambda ixs: dense_tmap[ixs]
501
+
419
502
  @property
420
503
  def transport_matrix(self) -> ArrayLike: # noqa: D102
421
504
  return self._transport_matrix
@@ -285,7 +285,7 @@ class AnalysisMixin(Generic[K, B], AbstractPushPullAdata, AbstractSolutionsProbl
285
285
  key_added=None,
286
286
  )
287
287
  v = np.array(tm_batch.argmax(0))
288
- out.extend(source_df[annotation_label][v[i]] for i in range(len(v)))
288
+ out.extend(source_df[annotation_label].iloc[v[i]] for i in range(len(v)))
289
289
 
290
290
  else:
291
291
  target_df = _get_df_cell_transition(
@@ -309,7 +309,7 @@ class AnalysisMixin(Generic[K, B], AbstractPushPullAdata, AbstractSolutionsProbl
309
309
  key_added=None,
310
310
  )
311
311
  v = np.array(tm_batch.argmax(0))
312
- out.extend(target_df[annotation_label][v[i]] for i in range(len(v)))
312
+ out.extend(target_df[annotation_label].iloc[v[i]] for i in range(len(v)))
313
313
  categories = pd.Categorical(out)
314
314
  return pd.DataFrame(categories, columns=[annotation_label])
315
315
  raise NotImplementedError(f"Mapping mode `{mapping_mode!r}` is not yet implemented.")
@@ -49,7 +49,7 @@ def mosta(
49
49
  force_download
50
50
  Whether to force-download the data.
51
51
  kwargs
52
- Keyword arguments for :func:`scanpy.read`.
52
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
53
53
 
54
54
  Returns
55
55
  -------
@@ -86,7 +86,7 @@ def hspc(
86
86
  force_download
87
87
  Whether to force-download the data.
88
88
  kwargs
89
- Keyword arguments for :func:`scanpy.read`.
89
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
90
90
 
91
91
  Returns
92
92
  -------
@@ -125,7 +125,7 @@ def drosophila(
125
125
  force_download
126
126
  Whether to force-download the data.
127
127
  kwargs
128
- Keyword arguments for :func:`scanpy.read`.
128
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
129
129
 
130
130
  Returns
131
131
  -------
@@ -169,7 +169,7 @@ def c_elegans(
169
169
  force_download
170
170
  Whether to force-download the data.
171
171
  kwargs
172
- Keyword arguments for :func:`scanpy.read`.
172
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
173
173
 
174
174
  Returns
175
175
  -------
@@ -207,7 +207,7 @@ def zebrafish(
207
207
  force_download
208
208
  Whether to force-download the data.
209
209
  kwargs
210
- Keyword arguments for :func:`scanpy.read`.
210
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
211
211
 
212
212
  Returns
213
213
  -------
@@ -250,7 +250,7 @@ def bone_marrow(
250
250
  force_download
251
251
  Whether to force-download the data.
252
252
  kwargs
253
- Keyword arguments for :func:`scanpy.read`.
253
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
254
254
 
255
255
  Returns
256
256
  -------
@@ -345,7 +345,7 @@ def tedsim(
345
345
  force_download
346
346
  Whether to force-download the data.
347
347
  kwargs
348
- Keyword arguments for :func:`scanpy.read`.
348
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
349
349
 
350
350
  Returns
351
351
  -------
@@ -378,7 +378,7 @@ def sciplex(
378
378
  force_download
379
379
  Whether to force-download the data.
380
380
  kwargs
381
- Keyword arguments for :func:`scanpy.read`.
381
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
382
382
 
383
383
  Returns
384
384
  -------
@@ -408,7 +408,7 @@ def sim_align(
408
408
  force_download
409
409
  Whether to force-download the data.
410
410
  kwargs
411
- Keyword arguments for :func:`scanpy.read`.
411
+ Keyword arguments for :func:`~anndata.io.read_h5ad`.
412
412
 
413
413
  Returns
414
414
  -------
@@ -806,7 +806,7 @@ class TemporalMixin(AnalysisMixin[K, B], AbstractSolutionsProblems):
806
806
  **kwargs,
807
807
  )
808
808
  )
809
- return np.mean(dist) # type: ignore[return-value]
809
+ return np.mean(dist)
810
810
 
811
811
  # TODO(@MUCDK) possibly offer two alternatives, once exact EMD with POT backend and once approximate,
812
812
  # faster with same solver as used for original problems
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: moscot
3
- Version: 0.5.1
3
+ Version: 0.5.3
4
4
  Summary: Multi-omic single-cell optimal transport tools
5
5
  Author: Dominik Klein, Giovanni Palla, Michal Klein, Zoe Piran, Marius Lange
6
6
  Maintainer-email: Dominik Klein <dominik.klein@helmholtz-muenchen.de>, Giovanni Palla <giovanni.palla@helmholtz-muenchen.de>, Michal Klein <michal.klein@helmholtz-muenchen.de>
@@ -8,6 +8,7 @@ MANIFEST.in
8
8
  README.rst
9
9
  codecov.yml
10
10
  pyproject.toml
11
+ uv.lock
11
12
  src/moscot/__init__.py
12
13
  src/moscot/_constants.py
13
14
  src/moscot/_logging.py
@@ -19,6 +20,8 @@ src/moscot.egg-info/PKG-INFO
19
20
  src/moscot.egg-info/SOURCES.txt
20
21
  src/moscot.egg-info/dependency_links.txt
21
22
  src/moscot.egg-info/requires.txt
23
+ src/moscot.egg-info/scm_file_list.json
24
+ src/moscot.egg-info/scm_version.json
22
25
  src/moscot.egg-info/top_level.txt
23
26
  src/moscot/backends/__init__.py
24
27
  src/moscot/backends/utils.py