moscot 0.5.1__tar.gz → 0.5.2__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.2}/PKG-INFO +1 -1
  2. {moscot-0.5.1 → moscot-0.5.2}/pyproject.toml +6 -3
  3. moscot-0.5.2/src/moscot/__init__.py +13 -0
  4. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/backends/ott/output.py +84 -42
  5. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/cost.py +1 -1
  6. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/output.py +85 -23
  7. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/problems/_mixins.py +2 -2
  8. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/datasets.py +9 -9
  9. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/time/_mixins.py +1 -1
  10. {moscot-0.5.1 → moscot-0.5.2}/src/moscot.egg-info/PKG-INFO +1 -1
  11. {moscot-0.5.1 → moscot-0.5.2}/src/moscot.egg-info/SOURCES.txt +3 -0
  12. moscot-0.5.2/src/moscot.egg-info/scm_file_list.json +175 -0
  13. moscot-0.5.2/src/moscot.egg-info/scm_version.json +8 -0
  14. moscot-0.5.2/uv.lock +6925 -0
  15. moscot-0.5.1/src/moscot/__init__.py +0 -13
  16. {moscot-0.5.1 → moscot-0.5.2}/.gitignore +0 -0
  17. {moscot-0.5.1 → moscot-0.5.2}/.gitmodules +0 -0
  18. {moscot-0.5.1 → moscot-0.5.2}/.pre-commit-config.yaml +0 -0
  19. {moscot-0.5.1 → moscot-0.5.2}/.readthedocs.yml +0 -0
  20. {moscot-0.5.1 → moscot-0.5.2}/.run_notebooks.sh +0 -0
  21. {moscot-0.5.1 → moscot-0.5.2}/LICENSE +0 -0
  22. {moscot-0.5.1 → moscot-0.5.2}/MANIFEST.in +0 -0
  23. {moscot-0.5.1 → moscot-0.5.2}/README.rst +0 -0
  24. {moscot-0.5.1 → moscot-0.5.2}/codecov.yml +0 -0
  25. {moscot-0.5.1 → moscot-0.5.2}/setup.cfg +0 -0
  26. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/_constants.py +0 -0
  27. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/_logging.py +0 -0
  28. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/_registry.py +0 -0
  29. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/_types.py +0 -0
  30. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/backends/__init__.py +0 -0
  31. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/backends/ott/__init__.py +0 -0
  32. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/backends/ott/_utils.py +0 -0
  33. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/backends/ott/solver.py +0 -0
  34. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/backends/utils.py +0 -0
  35. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/__init__.py +0 -0
  36. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/problems/__init__.py +0 -0
  37. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/problems/_utils.py +0 -0
  38. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/problems/birth_death.py +0 -0
  39. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/problems/compound_problem.py +0 -0
  40. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/problems/manager.py +0 -0
  41. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/problems/problem.py +0 -0
  42. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/base/solver.py +0 -0
  43. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/costs/__init__.py +0 -0
  44. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/costs/_costs.py +0 -0
  45. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/costs/_utils.py +0 -0
  46. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/plotting/__init__.py +0 -0
  47. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/plotting/_plotting.py +0 -0
  48. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/plotting/_utils.py +0 -0
  49. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/__init__.py +0 -0
  50. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/_utils.py +0 -0
  51. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/cross_modality/__init__.py +0 -0
  52. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/cross_modality/_mixins.py +0 -0
  53. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/cross_modality/_translation.py +0 -0
  54. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/generic/__init__.py +0 -0
  55. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/generic/_generic.py +0 -0
  56. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/generic/_mixins.py +0 -0
  57. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/space/__init__.py +0 -0
  58. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/space/_alignment.py +0 -0
  59. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/space/_mapping.py +0 -0
  60. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/space/_mixins.py +0 -0
  61. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/spatiotemporal/__init__.py +0 -0
  62. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/spatiotemporal/_spatio_temporal.py +0 -0
  63. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/time/__init__.py +0 -0
  64. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/problems/time/_lineage.py +0 -0
  65. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/py.typed +0 -0
  66. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/__init__.py +0 -0
  67. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/_data/allTFs_dmel.txt +0 -0
  68. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/_data/allTFs_hg38.txt +0 -0
  69. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/_data/allTFs_mm.txt +0 -0
  70. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/_data/human_apoptosis.txt +0 -0
  71. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/_data/human_proliferation.txt +0 -0
  72. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/_data/mouse_apoptosis.txt +0 -0
  73. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/_data/mouse_proliferation.txt +0 -0
  74. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/data.py +0 -0
  75. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/subset_policy.py +0 -0
  76. {moscot-0.5.1 → moscot-0.5.2}/src/moscot/utils/tagged_array.py +0 -0
  77. {moscot-0.5.1 → moscot-0.5.2}/src/moscot.egg-info/dependency_links.txt +0 -0
  78. {moscot-0.5.1 → moscot-0.5.2}/src/moscot.egg-info/requires.txt +0 -0
  79. {moscot-0.5.1 → moscot-0.5.2}/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.2
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,9 @@
1
- from typing import Any, Literal, Optional, Tuple, Union
1
+ from typing import Any, Optional, Tuple, Union
2
2
 
3
3
  import jax
4
4
  import jax.numpy as jnp
5
5
  import numpy as np
6
- from ott.geometry import pointcloud
7
- from ott.problems.linear import linear_problem
6
+ from ott.geometry import geometry, low_rank, pointcloud
8
7
  from ott.solvers.linear import sinkhorn, sinkhorn_lr
9
8
  from ott.solvers.quadratic import gromov_wasserstein, gromov_wasserstein_lr
10
9
 
@@ -12,11 +11,79 @@ import matplotlib as mpl
12
11
  import matplotlib.pyplot as plt
13
12
 
14
13
  from moscot._types import ArrayLike, Device_t
15
- from moscot.base.output import BaseDiscreteSolverOutput, MatrixSolverOutput
14
+ from moscot.base.output import (
15
+ BaseDiscreteSolverOutput,
16
+ RowMaterializer,
17
+ )
16
18
 
17
19
  __all__ = ["OTTOutput", "GraphOTTOutput"]
18
20
 
19
21
 
22
+ def _rows_from_potentials(f: jnp.ndarray, g: jnp.ndarray, geom: Any) -> Optional[RowMaterializer]:
23
+ r"""Rows of :math:`\exp((f_i + g_j - C_{ij}) / \varepsilon)`, as :mod:`ott` computes the full matrix.
24
+
25
+ The parent geometry's resolved :attr:`epsilon` and :attr:`inv_scale_cost` are captured once:
26
+ :meth:`~ott.geometry.geometry.Geometry.subset` carries ``scale_cost``/``relative_epsilon`` as
27
+ unevaluated strings, so a subset geometry would silently re-derive both from the subset.
28
+
29
+ Returns :obj:`None` if the geometry cannot produce a row block without materializing everything,
30
+ in which case the caller falls back to pushing indicator columns.
31
+ """
32
+ eps = geom.epsilon
33
+ if isinstance(geom, pointcloud.PointCloud):
34
+ x, y, cost_fn, inv_scale = geom.x, geom.y, geom.cost_fn, geom.inv_scale_cost
35
+
36
+ def cost_rows(ixs: np.ndarray) -> jnp.ndarray:
37
+ return cost_fn.all_pairs(x[ixs], y) * inv_scale
38
+
39
+ elif isinstance(geom, low_rank.LRCGeometry):
40
+ # `subset` is silently wrong here (it slices the two factors as if they were cost/kernel)
41
+ cost_1, cost_2, bias = geom.cost_1, geom.cost_2, geom.bias
42
+
43
+ def cost_rows(ixs: np.ndarray) -> jnp.ndarray:
44
+ return cost_1[ixs] @ cost_2.T + bias
45
+
46
+ elif type(geom) is geometry.Geometry: # dense cost; hoisted out of the block loop
47
+ cost = geom.cost_matrix
48
+
49
+ def cost_rows(ixs: np.ndarray) -> jnp.ndarray:
50
+ return cost[ixs]
51
+
52
+ else: # e.g. `Geodesic`, whose cost is never materialized
53
+ return None
54
+
55
+ def rows(ixs: np.ndarray) -> jnp.ndarray:
56
+ return jnp.exp((f[ixs][:, None] + g[None, :] - cost_rows(ixs)) / eps)
57
+
58
+ return rows
59
+
60
+
61
+ def _ott_row_materializer(out: Any) -> Optional[RowMaterializer]:
62
+ """Materialize rows of an :mod:`ott` output's transport matrix, or :obj:`None` if unsupported."""
63
+ if isinstance(out, (sinkhorn_lr.LRSinkhornOutput, gromov_wasserstein_lr.LRGWOutput)):
64
+ # `T = Q diag(1 / g) R^T`, as in `ott`'s `matrix`; never touches a geometry, which matters
65
+ # because `LRGWOutput.geom` re-linearizes on every access
66
+ qg, r = out.q * (1.0 / out.g), out.r
67
+
68
+ def rows(ixs: np.ndarray) -> jnp.ndarray:
69
+ return qg[ixs] @ r.T
70
+
71
+ return rows
72
+ if isinstance(out, sinkhorn.SinkhornOutput):
73
+ return _rows_from_potentials(out.f, out.g, out.geom)
74
+ if isinstance(out, gromov_wasserstein.GWOutput):
75
+ inner = _ott_row_materializer(out.linear_state)
76
+ if inner is None:
77
+ return None
78
+ scale = out._rescale_factor # `GWOutput.matrix`/`apply` rescale the linearization; so must we
79
+
80
+ def rows(ixs: np.ndarray) -> jnp.ndarray:
81
+ return scale * inner(ixs)
82
+
83
+ return rows
84
+ return None
85
+
86
+
20
87
  class OTTOutput(BaseDiscreteSolverOutput):
21
88
  """Output of various :term:`OT` problems.
22
89
 
@@ -192,6 +259,10 @@ class OTTOutput(BaseDiscreteSolverOutput):
192
259
  def transport_matrix(self) -> ArrayLike: # noqa: D102
193
260
  return self._output.matrix
194
261
 
262
+ def _row_materializer(self) -> RowMaterializer: # noqa: D102
263
+ materialize = _ott_row_materializer(self._output)
264
+ return super()._row_materializer() if materialize is None else materialize
265
+
195
266
  @property
196
267
  def is_linear(self) -> bool: # noqa: D102
197
268
  return isinstance(self._output, (sinkhorn.SinkhornOutput, sinkhorn_lr.LRSinkhornOutput))
@@ -228,44 +299,6 @@ class OTTOutput(BaseDiscreteSolverOutput):
228
299
  return self._output.f, self._output.g
229
300
  return None
230
301
 
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
302
  @property
270
303
  def rank(self) -> int: # noqa: D102
271
304
  output = self._output.linear_state if isinstance(self._output, gromov_wasserstein.GWOutput) else self._output
@@ -320,6 +353,15 @@ class GraphOTTOutput(OTTOutput):
320
353
  res = self._output.apply(x_expanded.T, axis=1 - forward, lse_mode=False).T
321
354
  return res[len(x) :] if forward else res[: -len(x)]
322
355
 
356
+ def _row_materializer(self) -> RowMaterializer:
357
+ """Materialize rows by pushing indicator columns.
358
+
359
+ :attr:`shape` is a sub-block of the expanded ``[n + m, n + m]`` graph problem, so the wrapped
360
+ output's potentials do not index this output's rows. Pushing is cheap here anyway: applying a
361
+ (sparse) graph kernel costs ``nnz`` per column, not ``n * m``.
362
+ """
363
+ return BaseDiscreteSolverOutput._row_materializer(self)
364
+
323
365
  def to(self, device: Optional[Device_t] = None) -> "GraphOTTOutput": # noqa: D102
324
366
  if device is None:
325
367
  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.
@@ -50,6 +53,17 @@ def _mass_select_block(rows: np.ndarray, *, value: float, max_k: Optional[int])
50
53
  return sp.csr_matrix(np.where(sel, rows, 0.0))
51
54
 
52
55
 
56
+ def _massless_rows(rows: np.ndarray) -> np.ndarray:
57
+ """Mask of rows carrying no mass.
58
+
59
+ Such rows cannot be kept non-empty by any threshold, so every sparsification mode treats them
60
+ the same way: they keep no entries, and they are excluded from the statistics that determine a
61
+ threshold. Letting them take part would drag any row-based threshold down to :math:`0` and
62
+ disable sparsification altogether, without making the row usable.
63
+ """
64
+ return ~(rows.max(axis=1) > 0.0)
65
+
66
+
53
67
  def _sparsify_block(
54
68
  rows: np.ndarray, *, mode: str, thr: Optional[float], value: Optional[float], max_k: Optional[int]
55
69
  ) -> sp.csr_matrix:
@@ -243,6 +257,26 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
243
257
 
244
258
  return op
245
259
 
260
+ def _row_materializer(self) -> RowMaterializer:
261
+ """Build a callable materializing rows of the :attr:`transport_matrix`.
262
+
263
+ The callable maps row indices to a dense ``[len(ixs), m]`` array. It is built once per
264
+ :meth:`sparsify` call, so subclasses can hoist per-output work (e.g. resolving a geometry)
265
+ out of the block loop.
266
+
267
+ This default pushes indicator columns, which is correct for any output but costs
268
+ ``n * m * len(ixs)`` whenever :meth:`push` materializes a dense tensor - as :mod:`ott`'s
269
+ log-sum-exp apply does. Subclasses that can slice or recompute rows directly override it.
270
+ """
271
+ n = self.shape[0]
272
+
273
+ def materialize(ixs: np.ndarray) -> ArrayLike:
274
+ x = np.zeros((n, len(ixs)), dtype=float)
275
+ x[ixs, np.arange(len(ixs))] = 1.0
276
+ return np.asarray(self.push(x, scale_by_marginals=False)).T
277
+
278
+ return materialize
279
+
246
280
  def sparsify(
247
281
  self,
248
282
  mode: Literal["threshold", "percentile", "min_row", "mass"],
@@ -257,7 +291,15 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
257
291
  This function sets entries of the transport matrix to :math:`0` according to ``mode`` and
258
292
  returns a :class:`~moscot.base.output.MatrixSolverOutput` with sparsified transport matrix stored
259
293
  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``.
294
+ ``batch_size`` rows; outputs that can build rows directly - :mod:`ott` :term:`Sinkhorn`,
295
+ :term:`Gromov-Wasserstein`/:term:`fused Gromov-Wasserstein`, their :term:`low-rank` counterparts,
296
+ and already materialized matrices - never hold more than ``[batch_size, m]`` at a time. Other
297
+ outputs fall back to pushing indicator columns, whose cost depends on the output's :meth:`push`.
298
+
299
+ Rows carrying no mass keep no entries and take no part in choosing a threshold, whichever
300
+ ``mode`` is used - no threshold can make them non-empty, and letting them take part would
301
+ drag the threshold down to :math:`0`. A warning is emitted when any are present, since the
302
+ result then cannot be normalized into a Markov transition matrix.
261
303
 
262
304
  .. warning::
263
305
  This function only serves for interfacing software which has to instantiate the transport matrix,
@@ -270,8 +312,10 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
270
312
 
271
313
  - `'threshold'` - ``value`` is the threshold below which entries are set to :math:`0`.
272
314
  - `'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.
315
+ below which entries are set to :math:`0`, estimated from ``n_samples`` randomly sampled rows.
316
+ - `'min_row'` - ``value`` is not used, it is set to ``min_i max_j T_ij``, the largest
317
+ threshold for which every row keeps at least 1 non-zero entry. It does not depend on
318
+ ``batch_size``; the rows are materialized twice, once for the threshold and once for the values.
275
319
  - `'mass'` - per row, keep the largest entries capturing a fraction ``value`` of the row's mass
276
320
  (at most ``max_k`` entries per row); ``value`` must be in :math:`(0, 1]`.
277
321
  value
@@ -279,9 +323,9 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
279
323
  batch_size
280
324
  How many rows to materialize at a time when sparsifying the :attr:`transport_matrix`.
281
325
  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``.
326
+ If ``mode = 'percentile'``, the number of rows sampled to estimate the percentile stochastically.
327
+ Note this means that a matrix of shape `[n_samples, m]` has to be instantiated.
328
+ If `None`, ``n_samples`` is set to ``batch_size``.
285
329
  seed
286
330
  Random seed needed for sampling if ``mode = 'percentile'``.
287
331
  max_k
@@ -292,6 +336,9 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
292
336
  Output with sparsified transport matrix.
293
337
  """
294
338
  n, m = self.shape
339
+ materialize = self._row_materializer()
340
+ row_blocks = [np.arange(start, min(start + batch_size, n)) for start in range(0, n, batch_size)]
341
+
295
342
  thr: Optional[float] = None
296
343
  if mode == "mass":
297
344
  if value is None or not 0.0 < value <= 1.0:
@@ -306,19 +353,21 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
306
353
  if value is None:
307
354
  raise ValueError("If `mode = 'percentile'`, `value` cannot be `None`.")
308
355
  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)
356
+ k = min(n_samples if n_samples is not None else batch_size, n)
357
+ ixs = np.sort(rng.choice(n, size=k, replace=False))
358
+ sample = np.asarray(materialize(ixs))
359
+ sample = sample[~_massless_rows(sample)]
360
+ thr = float(np.percentile(sample, value)) if sample.size else np.inf
316
361
  elif mode == "min_row":
362
+ # exact rule `min_i max_j T_ij`: every block holds whole rows, so each row's maximum is
363
+ # exact and the threshold does not depend on `batch_size`. Computing it from the same
364
+ # blocks that produce the values also keeps the two consistent to the last bit.
317
365
  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()))
366
+ for ixs in row_blocks:
367
+ maxima = np.asarray(materialize(ixs)).max(axis=1)
368
+ maxima = maxima[maxima > 0.0] # see `_massless_rows`
369
+ if maxima.size:
370
+ thr = min(thr, float(maxima.min()))
322
371
  else:
323
372
  raise NotImplementedError(f"Mode `{mode}` is not yet implemented.")
324
373
 
@@ -328,11 +377,16 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
328
377
  # Always iterate over source rows so that each block holds rows of the transport matrix.
329
378
  # This keeps the per-row criteria (e.g. `mass`) well-defined and peak memory at `[batch_size, m]`.
330
379
  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))
380
+ n_massless = 0
381
+ for ixs in row_blocks:
382
+ block = np.asarray(materialize(ixs))
383
+ n_massless += int(_massless_rows(block).sum())
384
+ tmaps_sparse.append(_sparsify_block(block, mode=mode, thr=thr, value=value, max_k=max_k))
385
+ if n_massless:
386
+ logger.warning(
387
+ f"`{n_massless}` row(s) of the transport matrix carry no mass and are left empty; "
388
+ f"the sparsified matrix cannot be normalized into a Markov transition matrix."
389
+ )
336
390
 
337
391
  transport_matrix = sp.vstack(tmaps_sparse).tocsr() if tmaps_sparse else sp.csr_matrix((n, m))
338
392
  return MatrixSolverOutput(
@@ -416,6 +470,14 @@ class MatrixSolverOutput(BaseDiscreteSolverOutput):
416
470
  def _apply_forward(self, x: ArrayLike) -> ArrayLike:
417
471
  return self._apply(x, forward=True)
418
472
 
473
+ def _row_materializer(self) -> RowMaterializer: # noqa: D102
474
+ tmap = self.transport_matrix
475
+ if sp.issparse(tmap):
476
+ sparse_tmap = cast(sp.spmatrix, tmap)
477
+ return lambda ixs: sparse_tmap[ixs].toarray()
478
+ dense_tmap = np.asarray(tmap) # e.g. `jax` arrays
479
+ return lambda ixs: dense_tmap[ixs]
480
+
419
481
  @property
420
482
  def transport_matrix(self) -> ArrayLike: # noqa: D102
421
483
  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.2
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