Skip to content

Python API reference

Generated from the docstrings of the package. For explanations and examples, start with Getting started and Concepts.

Solving

deblais.solve

solve(
    x,
    y,
    a=None,
    b=None,
    *,
    p=2,
    method="auto",
    threads=0,
    potentials=True,
    flows="auto",
    mass_tolerance=1e-06,
    sweeps=-1,
    cell=0,
    auction=True,
    pool=0,
    helpers=-1,
    min_size=0,
)

Exact optimal transport between two weighted point clouds, cost \(|x - y|^p\).

Solves

\[ \min_{P \ge 0} \; \sum_{i,j} P_{ij} \, |x_i - y_j|^p \quad \text{subject to} \quad \sum_j P_{ij} = a_i, \qquad \sum_i P_{ij} = b_j . \]

with marginals \(a\) and \(b\). The result is an optimal vertex of the transport polytope, not an approximation: there is no regularization and no tolerance to tune. The cost matrix is never stored, so the memory is linear in the number of points.

Parameters:

  • x –

    source points, shape (n, d) or (n,): a NumPy array (or anything numpy.asarray accepts) or a PyTorch tensor, on any device. The solve itself runs on the CPU in double precision.

  • y –

    target points, shape (m, d) or (m,).

  • a –

    masses of the sources, shape (n,), non negative. By default the uniform probability measure.

  • b –

    masses of the targets, shape (m,). The totals of a and b must agree up to mass_tolerance; b is rescaled to the total of a.

  • p (float, default: 2 ) –

    exponent of the cost, positive. The default, 2, is the squared Euclidean cost of the Wasserstein-2 distance, on which the automatic mode was tuned. Any other exponent is solved exactly, but the automatic mode is not always the fastest there: tune finds better options for a given shape of problem.

  • method (str, default: 'auto' ) –

    "auto" chooses from the dimension and the sizes (see recipe): "line" (closed form, \(d = 1\) and \(p \ge 1\)), "simplex", "multiscale" or "decomposition". All of them are exact.

  • threads (int, default: 0 ) –

    number of threads, 0 for the OpenMP default.

  • potentials (bool, default: True ) –

    also return the Kantorovich potentials.

  • flows (str, default: 'auto' ) –

    "auto" uses integer flows when the masses are uniform or integers and real flows otherwise; "real" or "integer" force one.

  • mass_tolerance (float, default: 1e-06 ) –

    largest relative difference between the totals of a and b.

  • sweeps (int, default: -1 ) –

    sweeps of the domain decomposition per level, < 0: automatic (2).

  • cell (int, default: 0 ) –

    sources per basic cell of the domain decomposition, 0: automatic (512).

  • auction (bool, default: True ) –

    solve the levels of assignment problems by an auction.

  • pool (int, default: 0 ) –

    arcs kept per source by the simplex, 0: automatic (48).

  • helpers (int, default: -1 ) –

    pricing helper threads of the simplex, < 0: automatic.

  • min_size (int, default: 0 ) –

    size of the coarsest level of the multiscale start, 0: automatic (100 to 3000, a sixth of the points at most).

Returns:

  • Plan –

    the optimal Plan.

Raises:

  • ValueError –

    on invalid shapes, masses or options.

deblais.wasserstein2

wasserstein2(x, y, a=None, b=None, **options)

Squared Wasserstein-2 distance \(W_2^2\) between two weighted point clouds.

Shorthand for solve(x, y, a, b, **options).cost: a float for NumPy inputs, a differentiable scalar tensor for PyTorch inputs. With masses that sum to one, its square root is the Wasserstein-2 distance \(W_2\). The gradient with respect to the points is that of the envelope theorem, \(\nabla_{x_i} W_2^2 = 2 a_i \, (x_i - T(x_i))\) with \(T\) the barycentric projection of Plan.map.

For the cost \(|x - y|^p\) with another exponent, use solve(x, y, a, b, p=p).cost.

The result

deblais.Plan

An optimal transport plan and its dual certificate.

The plan is sparse: at most \(n + m - 1\) arcs for \(n\) sources and \(m\) targets. The arc k ships mass[k] from the point source[k] of x to the point target[k] of y; the arcs are sorted by source, then by target.

The arrays have the type of the inputs of solve: NumPy arrays, or PyTorch tensors on the device of x.

Attributes:

  • cost –

    transport cost \(\sum_k \mathrm{mass}_k \, |x_{\mathrm{source}_k} - y_{\mathrm{target}_k}|^p\). With PyTorch inputs it is a tensor that can be differentiated with respect to x, y, a and b.

  • source –

    indices of the source points of the arcs (int64).

  • target –

    indices of the target points of the arcs (int64).

  • mass –

    masses shipped by the arcs.

  • potential_source –

    Kantorovich potential \(f\) of the sources, or None.

  • potential_target –

    Kantorovich potential \(g\) of the targets, or None. \(f_i + g_j \le |x_i - y_j|^p\) for every pair, with equality on the arcs, and \(\mathrm{cost} = \sum_i a_i f_i + \sum_j b_j g_j\).

  • p –

    exponent of the cost, the p of solve.

  • status –

    "optimal", or "stalled" when optimality is only certified up to stats["max_violation"] (rounding).

  • method –

    the method that ran: "line", "simplex", "multiscale" or "decomposition".

  • shape –

    (n, m), the numbers \(n\) and \(m\) of source and target points.

  • stats –

    counters of the solve (seconds, pivots, passes, levels, local_problems, auction_bids, threads, integer_flows, max_violation).

f property

f

Alias of potential_source.

g property

g

Alias of potential_target.

sparse

sparse()

The plan as a sparse matrix of shape (n, m).

Returns:

  • –

    a scipy.sparse.coo_array for NumPy inputs (SciPy is needed), a sparse COO tensor for PyTorch inputs.

dense

dense()

The plan as a dense matrix of shape (n, m): small problems only.

map

map(y=None)

Barycentric projection of the plan: where the mass of each source goes on average.

\[ T(x_i) = \frac{\sum_j P_{ij} \, y_j}{\sum_j P_{ij}} . \]

For an assignment (as many targets as sources, uniform masses) it is the optimal map itself.

Parameters:

  • y –

    values carried by the targets, of shape (m,) or (m, ...). By default the target points given to solve.

Returns:

  • –

    an array of shape (n, ...); the rows of the sources of zero mass are NaN.

assignment

assignment()

The target of every source, when the plan is a one-to-one matching.

Returns:

  • –

    sigma of shape (n,) with x[i] matched to y[sigma[i]].

Raises:

  • ValueError –

    if a source ships to several targets (the plan splits mass: unequal sizes or non uniform masses).

Automatic mode, tuning and runtime

deblais.recipe

recipe(dim, n, m, p=2)

What method="auto" chooses for n sources and m targets of dimension dim.

It is a prediction from the sizes alone, measured for the cost p = 2; tune measures on the clouds, for any cost. The exponent p only matters on the line, where the closed form needs \(p \ge 1\).

Returns:

  • dict –

    {"method": ..., "sweeps": ..., "cell": ..., "min_size": ...}.

deblais.tune

tune(x, y, a=None, b=None, *, max_seconds=0, margin=0.03, **options)

The fastest options of solve for these clouds on this machine, found by timing solves.

recipe predicts what method="auto" does from the dimension and the sizes alone; tune measures instead. It solves the problem in the automatic mode, then changes one choice at a time and keeps a change when the solve gets faster by at least margin: the method, the number of threads (halved while the time does not grow by more than margin, to free the rest of the machine), the coarsest level of the multiscale start, the auctions of assignment problems and the sweeps of the domain decomposition. Short solves are repeated and the fastest time is kept.

Every configuration is an exact solve, so the search costs 5 to 15 solves: it pays off when many problems of the same size and shape follow, as in a training loop.

t = deblais.tune(x, y)
for x, y in batches:
    loss = deblais.wasserstein2(x, y, **t["options"])

Parameters:

  • x –

    source points, as in solve.

  • y –

    target points.

  • a –

    masses of the sources.

  • b –

    masses of the targets.

  • max_seconds (float, default: 0 ) –

    no new configuration is tried after this time, 0: no limit.

  • margin (float, default: 0.03 ) –

    relative gain needed to change a choice.

  • options –

    starting options of solve, among them the exponent p of the cost. An explicit method is kept, a positive threads is the largest number of threads tried.

Returns:

  • dict –

    options (keyword arguments of solve, with p when it is not 2), seconds (time of a solve with them), seconds_automatic (time in the automatic mode), trials (every configuration timed, with its options and seconds) and plan (the Plan of the clouds).

deblais.openmp_info

openmp_info()

The parallel runtime of the compiled core.

Returns:

  • dict –

    enabled (built with OpenMP), threads (default number of threads) and runtime (path of the OpenMP library in use: the one of PyTorch when it is installed, see the installation guide).

Constants

  • deblais.__version__: version of the package.
  • deblais.max_dim: largest dimension of the points the compiled module accepts (8 in the wheels; DEBLAIS_PYTHON_MAX_DIM when building from source).