Source code for cellflow.utils

from typing import Any, Literal

import jax
import jax.numpy as jnp
from ott.geometry import costs, pointcloud
from ott.problems.linear import linear_problem
from ott.solvers.linear import sinkhorn

ScaleCost_t = float | Literal["mean", "max_cost", "median"]

__all__ = ["match_linear", "default_prng_key"]


[docs] def match_linear( source_batch: jnp.ndarray, target_batch: jnp.ndarray, cost_fn: costs.CostFn | None = costs.SqEuclidean(), epsilon: float | None = 1.0, scale_cost: ScaleCost_t = "mean", tau_a: float = 1.0, tau_b: float = 1.0, threshold: float | None = None, **kwargs: Any, ) -> jnp.ndarray: """Compute solution to a linear OT problem. Parameters ---------- source_batch Source point cloud of shape ``[n, d]``. target_batch Target point cloud of shape ``[m, d]``. cost_fn Cost function to use for the linear OT problem. epsilon Regularization parameter. scale_cost Scaling of the cost matrix. tau_a Parameter in :math:`(0, 1]` that defines how unbalanced the problem is in the source distribution. If :math:`1`, the problem is balanced in the source distribution. tau_b Parameter in :math:`(0, 1]` that defines how unbalanced the problem is in the target distribution. If :math:`1`, the problem is balanced in the target distribution. threshold Convergence criterion for the Sinkhorn algorithm. kwargs Additional arguments for :class:`ott.solvers.linear.sinkhorn.Sinkhorn`. Returns ------- Optimal transport matrix between ``'source_batch'`` and ``'target_batch'``. """ if threshold is None: threshold = 1e-3 if (tau_a == 1.0 and tau_b == 1.0) else 1e-2 geom = pointcloud.PointCloud( source_batch, target_batch, cost_fn=cost_fn, epsilon=epsilon, scale_cost=scale_cost, ) problem = linear_problem.LinearProblem(geom, tau_a=tau_a, tau_b=tau_b) solver = sinkhorn.Sinkhorn(threshold=threshold, **kwargs) out = solver(problem) return out.matrix
def default_prng_key(rng: jax.Array | None) -> jax.Array: """Get the default PRNG key. Parameters ---------- rng: PRNG key. Returns ------- If ``rng = None``, returns the default PRNG key. Otherwise, it returns the unmodified ``rng`` key. """ return jax.random.key(0) if rng is None else rng