moscot 0.5.0__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 (81) hide show
  1. {moscot-0.5.0 → moscot-0.5.2}/.pre-commit-config.yaml +0 -5
  2. moscot-0.5.2/.readthedocs.yml +26 -0
  3. {moscot-0.5.0 → moscot-0.5.2}/PKG-INFO +5 -5
  4. {moscot-0.5.0 → moscot-0.5.2}/pyproject.toml +15 -12
  5. moscot-0.5.2/src/moscot/__init__.py +13 -0
  6. moscot-0.5.2/src/moscot/backends/ott/__init__.py +36 -0
  7. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/backends/ott/output.py +83 -1
  8. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/cost.py +1 -1
  9. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/output.py +163 -35
  10. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/problems/_mixins.py +2 -2
  11. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/datasets.py +9 -9
  12. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/time/_mixins.py +1 -1
  13. {moscot-0.5.0 → moscot-0.5.2}/src/moscot.egg-info/PKG-INFO +5 -5
  14. {moscot-0.5.0 → moscot-0.5.2}/src/moscot.egg-info/SOURCES.txt +3 -0
  15. {moscot-0.5.0 → moscot-0.5.2}/src/moscot.egg-info/requires.txt +0 -1
  16. moscot-0.5.2/src/moscot.egg-info/scm_file_list.json +175 -0
  17. moscot-0.5.2/src/moscot.egg-info/scm_version.json +8 -0
  18. moscot-0.5.2/uv.lock +6925 -0
  19. moscot-0.5.0/.readthedocs.yml +0 -21
  20. moscot-0.5.0/src/moscot/__init__.py +0 -13
  21. moscot-0.5.0/src/moscot/backends/ott/__init__.py +0 -22
  22. {moscot-0.5.0 → moscot-0.5.2}/.gitignore +0 -0
  23. {moscot-0.5.0 → moscot-0.5.2}/.gitmodules +0 -0
  24. {moscot-0.5.0 → moscot-0.5.2}/.run_notebooks.sh +0 -0
  25. {moscot-0.5.0 → moscot-0.5.2}/LICENSE +0 -0
  26. {moscot-0.5.0 → moscot-0.5.2}/MANIFEST.in +0 -0
  27. {moscot-0.5.0 → moscot-0.5.2}/README.rst +0 -0
  28. {moscot-0.5.0 → moscot-0.5.2}/codecov.yml +0 -0
  29. {moscot-0.5.0 → moscot-0.5.2}/setup.cfg +0 -0
  30. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/_constants.py +0 -0
  31. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/_logging.py +0 -0
  32. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/_registry.py +0 -0
  33. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/_types.py +0 -0
  34. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/backends/__init__.py +0 -0
  35. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/backends/ott/_utils.py +0 -0
  36. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/backends/ott/solver.py +0 -0
  37. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/backends/utils.py +0 -0
  38. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/__init__.py +0 -0
  39. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/problems/__init__.py +0 -0
  40. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/problems/_utils.py +0 -0
  41. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/problems/birth_death.py +0 -0
  42. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/problems/compound_problem.py +0 -0
  43. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/problems/manager.py +0 -0
  44. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/problems/problem.py +0 -0
  45. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/base/solver.py +0 -0
  46. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/costs/__init__.py +0 -0
  47. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/costs/_costs.py +0 -0
  48. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/costs/_utils.py +0 -0
  49. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/plotting/__init__.py +0 -0
  50. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/plotting/_plotting.py +0 -0
  51. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/plotting/_utils.py +0 -0
  52. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/__init__.py +0 -0
  53. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/_utils.py +0 -0
  54. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/cross_modality/__init__.py +0 -0
  55. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/cross_modality/_mixins.py +0 -0
  56. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/cross_modality/_translation.py +0 -0
  57. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/generic/__init__.py +0 -0
  58. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/generic/_generic.py +0 -0
  59. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/generic/_mixins.py +0 -0
  60. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/space/__init__.py +0 -0
  61. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/space/_alignment.py +0 -0
  62. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/space/_mapping.py +0 -0
  63. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/space/_mixins.py +0 -0
  64. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/spatiotemporal/__init__.py +0 -0
  65. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/spatiotemporal/_spatio_temporal.py +0 -0
  66. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/time/__init__.py +0 -0
  67. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/problems/time/_lineage.py +0 -0
  68. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/py.typed +0 -0
  69. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/__init__.py +0 -0
  70. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/_data/allTFs_dmel.txt +0 -0
  71. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/_data/allTFs_hg38.txt +0 -0
  72. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/_data/allTFs_mm.txt +0 -0
  73. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/_data/human_apoptosis.txt +0 -0
  74. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/_data/human_proliferation.txt +0 -0
  75. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/_data/mouse_apoptosis.txt +0 -0
  76. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/_data/mouse_proliferation.txt +0 -0
  77. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/data.py +0 -0
  78. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/subset_policy.py +0 -0
  79. {moscot-0.5.0 → moscot-0.5.2}/src/moscot/utils/tagged_array.py +0 -0
  80. {moscot-0.5.0 → moscot-0.5.2}/src/moscot.egg-info/dependency_links.txt +0 -0
  81. {moscot-0.5.0 → moscot-0.5.2}/src/moscot.egg-info/top_level.txt +0 -0
@@ -41,11 +41,6 @@ repos:
41
41
  - id: check-docstring-first
42
42
  - id: check-yaml
43
43
  - id: check-toml
44
- - repo: https://github.com/asottile/pyupgrade
45
- rev: v3.19.1
46
- hooks:
47
- - id: pyupgrade
48
- args: [--py3-plus, --py38-plus, --keep-runtime-typing]
49
44
  - repo: https://github.com/asottile/blacken-docs
50
45
  rev: 1.19.1
51
46
  hooks:
@@ -0,0 +1,26 @@
1
+ version: 2
2
+
3
+ build:
4
+ os: ubuntu-24.04
5
+ tools:
6
+ python: "3.12"
7
+ jobs:
8
+ pre_create_environment:
9
+ - asdf plugin add uv
10
+ - asdf install uv latest
11
+ - asdf global uv latest
12
+ create_environment:
13
+ - uv venv "${READTHEDOCS_VIRTUALENV_PATH}"
14
+ install:
15
+ # uv keeps memory usage low enough for RTD builders, unlike pip,
16
+ # which gets OOM-killed installing the jax/ott dependency stack.
17
+ - UV_PROJECT_ENVIRONMENT="${READTHEDOCS_VIRTUALENV_PATH}" uv pip install .[docs]
18
+
19
+ sphinx:
20
+ builder: html
21
+ configuration: docs/conf.py
22
+ fail_on_warning: true
23
+
24
+ submodules:
25
+ include: [docs/notebooks]
26
+ recursive: true
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: moscot
3
- Version: 0.5.0
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>
@@ -49,11 +49,12 @@ Classifier: Operating System :: MacOS :: MacOS X
49
49
  Classifier: Operating System :: Microsoft :: Windows
50
50
  Classifier: Typing :: Typed
51
51
  Classifier: Programming Language :: Python :: 3
52
- Classifier: Programming Language :: Python :: 3.9
53
- Classifier: Programming Language :: Python :: 3.10
52
+ Classifier: Programming Language :: Python :: 3.11
53
+ Classifier: Programming Language :: Python :: 3.12
54
+ Classifier: Programming Language :: Python :: 3.13
54
55
  Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
55
56
  Classifier: Topic :: Scientific/Engineering :: Mathematics
56
- Requires-Python: >=3.10
57
+ Requires-Python: >=3.11
57
58
  Description-Content-Type: text/x-rst
58
59
  License-File: LICENSE
59
60
  Requires-Dist: numpy>=1.20.0
@@ -86,7 +87,6 @@ Requires-Dist: pytest-xdist>=3; extra == "test"
86
87
  Requires-Dist: pytest-mock>=3.5.0; extra == "test"
87
88
  Requires-Dist: pytest-cov>=4; extra == "test"
88
89
  Requires-Dist: coverage[toml]>=7; extra == "test"
89
- Requires-Dist: moscot[neural]; extra == "test"
90
90
  Provides-Extra: docs
91
91
  Requires-Dist: sphinx>=5.1.1; extra == "docs"
92
92
  Requires-Dist: sphinx_copybutton>=0.5.0; extra == "docs"
@@ -7,7 +7,7 @@ name = "moscot"
7
7
  dynamic = ["version"]
8
8
  description = "Multi-omic single-cell optimal transport tools"
9
9
  readme = "README.rst"
10
- requires-python = ">=3.10"
10
+ requires-python = ">=3.11"
11
11
  license = {file = "LICENSE"}
12
12
  classifiers = [
13
13
  "Development Status :: 4 - Beta",
@@ -19,8 +19,9 @@ classifiers = [
19
19
  "Operating System :: Microsoft :: Windows",
20
20
  "Typing :: Typed",
21
21
  "Programming Language :: Python :: 3",
22
- "Programming Language :: Python :: 3.9",
23
- "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
24
25
  "Topic :: Scientific/Engineering :: Bio-Informatics",
25
26
  "Topic :: Scientific/Engineering :: Mathematics"
26
27
  ]
@@ -81,7 +82,6 @@ test = [
81
82
  "pytest-mock>=3.5.0",
82
83
  "pytest-cov>=4",
83
84
  "coverage[toml]>=7",
84
- "moscot[neural]"
85
85
  ]
86
86
  docs = [
87
87
  "sphinx>=5.1.1",
@@ -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
 
@@ -270,11 +273,11 @@ max_line_length = 120
270
273
  legacy_tox_ini = """
271
274
  [tox]
272
275
  min_version = 4.0
273
- env_list = lint-code,py{3.10,3.11,3.12}
276
+ env_list = lint-code,py{3.11,3.12,3.13}
274
277
  skip_missing_interpreters = true
275
278
 
276
279
  [testenv]
277
- extras = test,neural
280
+ extras = test
278
281
  commands =
279
282
  python -m pytest {tty:--color=yes} {posargs: \
280
283
  --cov={env_site_packages_dir}{/}moscot --cov-config={tox_root}{/}pyproject.toml \
@@ -290,7 +293,7 @@ commands =
290
293
 
291
294
  [testenv:lint-docs]
292
295
  description = Lint the documentation.
293
- extras = docs,neural
296
+ extras = docs
294
297
  ignore_errors = true
295
298
  allowlist_externals = make
296
299
  pass_env = PYENCHANT_LIBRARY_PATH
@@ -310,7 +313,7 @@ deps =
310
313
  jupytext
311
314
  nbconvert
312
315
  leidenalg
313
- extras = docs,neural
316
+ extras = docs
314
317
  changedir = {tox_root}{/}docs
315
318
  commands =
316
319
  python -m ipykernel install --user --name=moscot
@@ -328,7 +331,7 @@ commands =
328
331
  [testenv:build-docs]
329
332
  description = Build the documentation.
330
333
  deps =
331
- extras = docs,neural
334
+ extras = docs
332
335
  allowlist_externals = make
333
336
  changedir = {tox_root}{/}docs
334
337
  commands =
@@ -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
@@ -0,0 +1,36 @@
1
+ # Compatibility shim for ott-jax<=0.6.0 with jax>=0.8.
2
+ # Released ott-jax (<=0.6.0) does `from jax.interpreters import batching` and then
3
+ # calls `batching.is_vmappable`, but jax removed that name from the public
4
+ # `jax.interpreters.batching` namespace after 0.7.2. The symbol still lives in the
5
+ # private module, which is exactly what ott switched to upstream (ott-jax#701).
6
+ # Re-expose it here so ott's `batched_vmap` works until that fix is released.
7
+ # TODO(moscot): drop this once a released ott-jax imports batching from jax._src.
8
+ import jax.interpreters.batching as _public_batching
9
+
10
+ if not hasattr(_public_batching, "is_vmappable"):
11
+ import jax._src.interpreters.batching as _src_batching
12
+
13
+ _public_batching.is_vmappable = _src_batching.is_vmappable
14
+
15
+ from ott.geometry import costs
16
+
17
+ from moscot.backends.ott._utils import sinkhorn_divergence
18
+ from moscot.backends.ott.output import GraphOTTOutput, OTTOutput
19
+ from moscot.backends.ott.solver import GWSolver, SinkhornSolver
20
+ from moscot.costs import register_cost
21
+
22
+ __all__ = [
23
+ "OTTOutput",
24
+ "GWSolver",
25
+ "SinkhornSolver",
26
+ "sinkhorn_divergence",
27
+ "GENOTLinSolver",
28
+ "GraphOTTOutput",
29
+ ]
30
+
31
+
32
+ register_cost("euclidean", backend="ott")(costs.Euclidean)
33
+ register_cost("sq_euclidean", backend="ott")(costs.SqEuclidean)
34
+ register_cost("cosine", backend="ott")(costs.Cosine)
35
+ register_cost("pnorm_p", backend="ott")(costs.PNormP)
36
+ register_cost("sq_pnorm", backend="ott")(costs.SqPNorm)
@@ -3,6 +3,7 @@ from typing import Any, Optional, Tuple, Union
3
3
  import jax
4
4
  import jax.numpy as jnp
5
5
  import numpy as np
6
+ from ott.geometry import geometry, low_rank, pointcloud
6
7
  from ott.solvers.linear import sinkhorn, sinkhorn_lr
7
8
  from ott.solvers.quadratic import gromov_wasserstein, gromov_wasserstein_lr
8
9
 
@@ -10,11 +11,79 @@ import matplotlib as mpl
10
11
  import matplotlib.pyplot as plt
11
12
 
12
13
  from moscot._types import ArrayLike, Device_t
13
- from moscot.base.output import BaseDiscreteSolverOutput
14
+ from moscot.base.output import (
15
+ BaseDiscreteSolverOutput,
16
+ RowMaterializer,
17
+ )
14
18
 
15
19
  __all__ = ["OTTOutput", "GraphOTTOutput"]
16
20
 
17
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
+
18
87
  class OTTOutput(BaseDiscreteSolverOutput):
19
88
  """Output of various :term:`OT` problems.
20
89
 
@@ -190,6 +259,10 @@ class OTTOutput(BaseDiscreteSolverOutput):
190
259
  def transport_matrix(self) -> ArrayLike: # noqa: D102
191
260
  return self._output.matrix
192
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
+
193
266
  @property
194
267
  def is_linear(self) -> bool: # noqa: D102
195
268
  return isinstance(self._output, (sinkhorn.SinkhornOutput, sinkhorn_lr.LRSinkhornOutput))
@@ -280,6 +353,15 @@ class GraphOTTOutput(OTTOutput):
280
353
  res = self._output.apply(x_expanded.T, axis=1 - forward, lse_mode=False).T
281
354
  return res[len(x) :] if forward else res[: -len(x)]
282
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
+
283
365
  def to(self, device: Optional[Device_t] = None) -> "GraphOTTOutput": # noqa: D102
284
366
  if device is None:
285
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,67 @@ 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
+
20
+
21
+ def _mass_select_block(rows: np.ndarray, *, value: float, max_k: Optional[int]) -> sp.csr_matrix:
22
+ """Keep, per row, the smallest set of entries capturing ``value`` of the row mass.
23
+
24
+ Parameters
25
+ ----------
26
+ rows
27
+ Dense block of shape ``[b, m]``; each row is a row of the transport matrix.
28
+ value
29
+ Target fraction of each row's mass to retain, in ``(0, 1]``.
30
+ max_k
31
+ Optional cap on the number of entries kept per row.
32
+
33
+ Returns
34
+ -------
35
+ Sparsified block as a :class:`~scipy.sparse.csr_matrix` of shape ``[b, m]``.
36
+ """
37
+ _, m = rows.shape
38
+ order = np.argsort(rows, axis=1)[:, ::-1] # descending
39
+ sorted_vals = np.take_along_axis(rows, order, axis=1)
40
+ totals = sorted_vals.sum(axis=1, keepdims=True)
41
+ cum = np.cumsum(sorted_vals, axis=1)
42
+ # `value >= 1` keeps everything (avoids float cumsum vs. sum mismatch -> exact reconstruction).
43
+ target = np.full_like(totals, np.inf) if value >= 1.0 else value * totals
44
+ # smallest prefix whose cumulative mass reaches the target (crossing entry included).
45
+ k_per_row = (cum < target).sum(axis=1) + 1
46
+ k_per_row = np.where(totals.ravel() <= 0.0, 0, k_per_row) # all-zero rows keep nothing
47
+ if max_k is not None:
48
+ k_per_row = np.minimum(k_per_row, max_k)
49
+ k_per_row = np.minimum(k_per_row, m)
50
+ keep_sorted = np.arange(m)[None, :] < k_per_row[:, None]
51
+ sel = np.zeros(rows.shape, dtype=bool)
52
+ np.put_along_axis(sel, order, keep_sorted, axis=1)
53
+ return sp.csr_matrix(np.where(sel, rows, 0.0))
54
+
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
+
67
+ def _sparsify_block(
68
+ rows: np.ndarray, *, mode: str, thr: Optional[float], value: Optional[float], max_k: Optional[int]
69
+ ) -> sp.csr_matrix:
70
+ """Apply the sparsification criterion to a block of transport-matrix rows."""
71
+ if mode == "mass":
72
+ assert value is not None # validated in `sparsify`
73
+ return _mass_select_block(rows, value=value, max_k=max_k)
74
+ rows = np.array(rows) # writable copy
75
+ rows[rows < thr] = 0.0
76
+ return sp.csr_matrix(rows)
77
+
17
78
 
18
79
  class BaseSolverOutput(abc.ABC):
19
80
  """Base class for all solver outputs."""
@@ -196,19 +257,49 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
196
257
 
197
258
  return op
198
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
+
199
280
  def sparsify(
200
281
  self,
201
- mode: Literal["threshold", "percentile", "min_row"],
282
+ mode: Literal["threshold", "percentile", "min_row", "mass"],
202
283
  value: Optional[float] = None,
203
284
  batch_size: int = 1024,
204
285
  n_samples: Optional[int] = None,
205
286
  seed: Optional[int] = None,
287
+ max_k: Optional[int] = None,
206
288
  ) -> MatrixSolverOutput:
207
289
  """Sparsify the :attr:`transport_matrix`.
208
290
 
209
- This function sets all entries of the transport matrix below a certain threshold to :math:`0` and
291
+ This function sets entries of the transport matrix to :math:`0` according to ``mode`` and
210
292
  returns a :class:`~moscot.base.output.MatrixSolverOutput` with sparsified transport matrix stored
211
- as a :class:`~scipy.sparse.csr_matrix`.
293
+ as a :class:`~scipy.sparse.csr_matrix`. The transport matrix is materialized in row blocks of
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.
212
303
 
213
304
  .. warning::
214
305
  This function only serves for interfacing software which has to instantiate the transport matrix,
@@ -217,63 +308,92 @@ class BaseDiscreteSolverOutput(BaseSolverOutput, abc.ABC):
217
308
  Parameters
218
309
  ----------
219
310
  mode
220
- How to determine the value below which entries are set to :math:`0`. Valid options are:
311
+ How to determine the entries that are set to :math:`0`. Valid options are:
221
312
 
222
313
  - `'threshold'` - ``value`` is the threshold below which entries are set to :math:`0`.
223
314
  - `'percentile'` - ``value`` is the percentile in :math:`[0, 100]` of the :attr:`transport_matrix`.
224
- below which entries are set to :math:`0`.
225
- - `'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.
319
+ - `'mass'` - per row, keep the largest entries capturing a fraction ``value`` of the row's mass
320
+ (at most ``max_k`` entries per row); ``value`` must be in :math:`(0, 1]`.
226
321
  value
227
- Value to use for sparsification.
322
+ Value to use for sparsification. Its meaning depends on ``mode`` (see above).
228
323
  batch_size
229
- How many rows to materialize when sparsifying the :attr:`transport_matrix`.
324
+ How many rows to materialize at a time when sparsifying the :attr:`transport_matrix`.
230
325
  n_samples
231
- If ``mode = 'percentile'``, determine the number of samples based on which the percentile is computed
232
- stochastically. Note this means that a matrix of shape `[n_samples, min(transport_matrix.shape)]`
233
- 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``.
234
329
  seed
235
330
  Random seed needed for sampling if ``mode = 'percentile'``.
331
+ max_k
332
+ Maximum number of entries to keep per row. Only valid when ``mode = 'mass'``.
236
333
 
237
334
  Returns
238
335
  -------
239
336
  Output with sparsified transport matrix.
240
337
  """
241
338
  n, m = self.shape
242
- if mode == "threshold":
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
+
342
+ thr: Optional[float] = None
343
+ if mode == "mass":
344
+ if value is None or not 0.0 < value <= 1.0:
345
+ raise ValueError("If `mode = 'mass'`, `value` must be in `(0, 1]`.")
346
+ if max_k is not None and max_k <= 0:
347
+ raise ValueError(f"`max_k` must be a positive integer, found `{max_k}`.")
348
+ elif mode == "threshold":
243
349
  if value is None:
244
- raise ValueError("If `mode = 'threshold'`, `threshold` cannot be `None`.")
350
+ raise ValueError("If `mode = 'threshold'`, `value` cannot be `None`.")
245
351
  thr = value
246
352
  elif mode == "percentile":
247
353
  if value is None:
248
- raise ValueError("If `mode = 'percentile'`, `threshold` cannot be `None`.")
354
+ raise ValueError("If `mode = 'percentile'`, `value` cannot be `None`.")
249
355
  rng = np.random.RandomState(seed=seed)
250
- n_samples = n_samples if n_samples is not None else batch_size
251
- k = min(n_samples, n)
252
- x = np.zeros((m, k))
253
- rows = rng.choice(m, size=k)
254
- x[rows, np.arange(k)] = 1.0
255
- res = self.pull(x, scale_by_marginals=False) # tmap @ indicator_vectors
256
- 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
257
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.
258
365
  thr = np.inf
259
- for batch in range(0, m, batch_size):
260
- x = np.eye(m, min(batch_size, m - batch), -(min(batch, m)))
261
- res = self.pull(x, scale_by_marginals=False) # tmap @ indicator_vectors
262
- 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()))
263
371
  else:
264
372
  raise NotImplementedError(f"Mode `{mode}` is not yet implemented.")
265
373
 
266
- k, func, fn_stack = (n, self.push, sp.vstack) if n < m else (m, self.pull, sp.hstack)
267
- tmaps_sparse: list[sp.csr_matrix] = []
268
-
269
- for batch in range(0, k, batch_size):
270
- x = np.eye(k, min(batch_size, k - batch), -(min(batch, k)), dtype=float)
271
- res = np.array(func(x, scale_by_marginals=False))
272
- res[res < thr] = 0.0
273
- tmaps_sparse.append(sp.csr_matrix(res.T if n < m else res))
374
+ if mode != "mass" and max_k is not None:
375
+ raise ValueError("`max_k` is only supported with `mode = 'mass'`.")
274
376
 
377
+ # Always iterate over source rows so that each block holds rows of the transport matrix.
378
+ # This keeps the per-row criteria (e.g. `mass`) well-defined and peak memory at `[batch_size, m]`.
379
+ tmaps_sparse: list[sp.csr_matrix] = []
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
+ )
390
+
391
+ transport_matrix = sp.vstack(tmaps_sparse).tocsr() if tmaps_sparse else sp.csr_matrix((n, m))
275
392
  return MatrixSolverOutput(
276
- transport_matrix=fn_stack(tmaps_sparse), cost=self.cost, converged=self.converged, is_linear=self.is_linear
393
+ transport_matrix=transport_matrix,
394
+ cost=self.cost,
395
+ converged=self.converged,
396
+ is_linear=self.is_linear,
277
397
  )
278
398
 
279
399
  @property
@@ -350,6 +470,14 @@ class MatrixSolverOutput(BaseDiscreteSolverOutput):
350
470
  def _apply_forward(self, x: ArrayLike) -> ArrayLike:
351
471
  return self._apply(x, forward=True)
352
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
+
353
481
  @property
354
482
  def transport_matrix(self) -> ArrayLike: # noqa: D102
355
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.")