Metadata-Version: 2.4
Name: deblais
Version: 0.2.0
Summary: Exact optimal transport between point clouds: a header-only C++17 network simplex with multiscale starts and domain decomposition, for NumPy and PyTorch
Keywords: optimal transport,wasserstein,earth mover's distance,network simplex,linear assignment,numpy,pytorch,openmp
Author: Jean-Baptiste Keck
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: THIRD_PARTY.md
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Scientific/Engineering :: Mathematics
Project-URL: Homepage, https://github.com/keckj/deblais
Project-URL: Documentation, https://keckj.github.io/deblais/
Project-URL: Source, https://github.com/keckj/deblais
Project-URL: Issues, https://github.com/keckj/deblais/issues
Project-URL: Changelog, https://github.com/keckj/deblais/releases
Project-URL: remblais, https://github.com/keckj/remblais
Requires-Python: >=3.10
Requires-Dist: numpy
Provides-Extra: torch
Requires-Dist: torch; extra == "torch"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: scipy; extra == "test"
Provides-Extra: docs
Requires-Dist: mkdocs-material; extra == "docs"
Requires-Dist: mkdocstrings[python]; extra == "docs"
Requires-Dist: mkdocs-glightbox; extra == "docs"
Requires-Dist: ruff; extra == "docs"
Description-Content-Type: text/markdown

<h1 align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/keckj/deblais/v0.2.0/docs/logo-dark.svg">
    <img alt="deblais" src="https://raw.githubusercontent.com/keckj/deblais/v0.2.0/docs/logo.svg" width="760">
  </picture>
</h1>

deblais computes **exact optimal transport** between point clouds: the
optimal plan, its cost (the squared Wasserstein-2 distance) and the
Kantorovich potentials, for the squared Euclidean cost or any power of the
distance, |x - y|<sup>p</sup>. It is a header-only
C++17 library with no dependency, and a Python package on top of it that takes
NumPy arrays and PyTorch tensors.

The solver is a network simplex that never stores the cost matrix, started by
a multiscale scheme and by parallel sweeps of a domain decomposition. It
solves a million points against a million in the plane in 13 to 31 seconds
on 8 threads depending on the masses, in linear memory, and returns a certificate of
optimality.

deblais is the twin of [remblais](https://github.com/keckj/remblais), which
computes geometric losses (Sinkhorn divergences, kernel norms, Hausdorff
divergences):
[which one do I need?](https://github.com/keckj/deblais/blob/v0.2.0/README.md#deblais-and-remblais)

- Documentation: <https://keckj.github.io/deblais/>
- Getting started: <https://keckj.github.io/deblais/getting-started/>
- Example, ten million grains from the streets of Paris to the streets of
  London, in your browser: <https://keckj.github.io/deblais/demo/paris-london/>
- More examples (morphing, color transfer, stippling, a generative network
  trained with the exact distance): <https://keckj.github.io/deblais/examples/>

```python
import deblais

plan = deblais.solve(x, y)            # x: (n, d), y: (m, d), NumPy or PyTorch
plan.cost                             # W2^2, exact
plan.source, plan.target, plan.mass   # sparse optimal plan
plan.f, plan.g                        # dual potentials
```

```cpp
#include <deblais/deblais.hpp>

const deblais::Plan plan = deblais::solve(2, x, y);   // std::vector<double>, point after point
```

## Why deblais

- **Exact.** The result is an optimal vertex of the transport polytope: no
  regularization, no blur, no tolerance to tune. With uniform or integer
  masses the flows are computed in integer arithmetic. The plan comes with
  dual potentials that prove its optimality, and `deblais::certify` checks
  them independently of the solver.
- **Fast.** The time grows almost linearly with the number of points, in
  every dimension from 1 to 4. On 8 threads, a million points against a
  million take 13 to 31 seconds in the plane, ten million points 4 to 10
  minutes.
  At 100 000 points, deblais is 450 times faster than the network simplex it
  started from on one thread, and 1 000 times faster when both run on 16
  cores. See [Performance](https://keckj.github.io/deblais/performance/).
- **Large problems.** The cost matrix is never stored: memory is linear in the
  number of points. A dense solver needs 8 TB for the cost matrix of a
  million points; deblais solves that problem in seconds.
- **Automatic.** `method="auto"` picks the algorithm and its parameters from
  the dimension, the sizes and the masses: closed form on the line, plain
  simplex on small problems, multiscale domain decomposition on large ones,
  auction on assignment problems. `deblais.tune` times a few solves of your
  clouds and returns the fastest options on your machine. The automatic mode
  is tuned for the squared distance: for another exponent (`p=1`, `p=3`...),
  run `deblais.tune` once. See
  [Automatic mode](https://keckj.github.io/deblais/automatic-mode/).
- **Header-only C++.** One include, C++17, no dependency. OpenMP is used when
  the compiler has it. CMake target `deblais::deblais`, or just `-I include`.
- **NumPy and PyTorch.** Tensors go in on any device and come back on it. The
  cost is differentiable with respect to the points and the masses. The
  package shares the OpenMP runtime that PyTorch ships.
- **Permissive license.** MIT or Apache-2.0, no GPL code.

## Installation

Python, on x86-64 Linux (Python 3.10 or later):

```sh
pip install deblais
```

C++, with CMake:

```cmake
include(FetchContent)
FetchContent_Declare(deblais GIT_REPOSITORY https://github.com/keckj/deblais.git GIT_TAG v0.1.0)
FetchContent_MakeAvailable(deblais)
target_link_libraries(my_program PRIVATE deblais::deblais)
```

or without it: copy `include/` and compile with
`g++ -std=c++17 -O3 -march=native -fopenmp -I include`. The details, and the
build from source, are in [Getting started](https://keckj.github.io/deblais/getting-started/).

## Usage

### Python

```python
import numpy as np
import deblais

rng = np.random.default_rng(0)
x, y = rng.random((100_000, 3)), rng.random((80_000, 3))
a, b = rng.random(100_000), rng.random(80_000)

plan = deblais.solve(x, y, a / a.sum(), b / b.sum())

print(plan.cost, plan.status, plan.method)   # exact cost, 'optimal', 'decomposition'
T = plan.map()                               # barycentric map, shape (100000, 3)
P = plan.sparse()                            # scipy.sparse matrix, at most n + m - 1 entries
```

With PyTorch, as a loss:

```python
import torch

x = torch.rand(20_000, 2, device="cuda", requires_grad=True)
y = torch.rand(20_000, 2, device="cuda")

loss = deblais.wasserstein2(x, y)
loss.backward()
```

### C++

```cpp
#include <deblais/deblais.hpp>
#include <cstdio>
#include <vector>

// n source points and m target points in dimension 3, stored point after
// point (x0 y0 z0 x1 y1 z1 ...), with one mass per point
std::vector<double> x(3 * n), a(n), y(3 * m), b(m);

deblais::Cloud source(x.data(), n, a.data());   // views, nothing is copied
deblais::Cloud target(y.data(), m, b.data());

deblais::Options options;                       // method, threads, ...: all automatic by default
const deblais::Plan plan = deblais::solve<3>(source, target, options);

// The plan is a list of arcs: arc k moves plan.mass[k] from the source point
// plan.source[k] to the target point plan.target[k]
std::printf("cost %g, %zu arcs\n", plan.cost, plan.size());
for (std::size_t k = 0; k < plan.size(); ++k)
  std::printf("%g from source %d to target %d\n", plan.mass[k], plan.source[k], plan.target[k]);

const deblais::Certificate proof = deblais::certify<3>(source, target, plan);
assert(proof.optimal());
```

## Performance

Against [network_simplex](https://github.com/nbonneel/network_simplex), the
implementation deblais started from (the one behind POT's `ot.emd`), on its
own test case (dimension 2, random masses, two AMD EPYC 9655).

network_simplex grows like $n^{2.5}$ and stores the cost matrix (80 GB at
100 000 points); deblais grows like $n$ in linear memory, and on a single
thread it is 450 times faster at 100 000 points.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/keckj/deblais/v0.2.0/docs/perf/comparison-dark.png">
  <img alt="Time of network_simplex and deblais against the number of points, log-log scale" src="https://raw.githubusercontent.com/keckj/deblais/v0.2.0/docs/perf/comparison-light.png">
</picture>

| Points per cloud | network_simplex, 1 thread | network_simplex, 16 threads | deblais, 1 thread | deblais, 16 threads |
| ---: | ---: | ---: | ---: | ---: |
| 10 000 | 4.4 s | 3.4 s | 0.21 s | 0.092 s |
| 100 000 | 1 385 s | 658 s | 3.1 s | 0.72 s |
| 1 000 000 | | | 47 s | 8.4 s |

Larger problems, in every dimension: wall time of a complete solve in the
automatic mode, optimality certificate included, for a million points
against a million drawn uniformly in the unit cube, two AMD EPYC 9654 (192
threads, pinned), GCC 14.

| Masses | Dimension 1 | Dimension 2 | Dimension 3 | Dimension 4 |
| --- | ---: | ---: | ---: | ---: |
| uniform (assignment) | 0.19 s | 14 s | 11 s | 21 s |
| random integers | 0.33 s | 25 s | 33 s | 92 s |
| random reals | 0.36 s | 7.5 s | 15 s | 49 s |

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/keckj/deblais/v0.2.0/docs/perf/size-grid-dark.png">
  <img alt="Time against the number of points, one panel per dimension, log-log scale" src="https://raw.githubusercontent.com/keckj/deblais/v0.2.0/docs/perf/size-grid-light.png">
</picture>

The time grows like $n^\alpha$ with the number $n$ of points per cloud,
with $\alpha$ between 1.0 and 1.3 in every dimension, up to thirty million
points (a hundred million on the line).

The protocol, the fitted exponents, the three families of masses, the
scaling with the number of threads and the command lines that reproduce
these numbers are on the [Performance](https://keckj.github.io/deblais/performance/) page.

## deblais and remblais

deblais and [remblais](https://github.com/keckj/remblais) are twin projects:
two solvers for the two ways of computing discrete-discrete optimal transport.

| | **deblais** | **[remblais](https://github.com/keckj/remblais)** |
| --- | --- | --- |
| Problem | exact optimal transport | entropic transport: Sinkhorn divergences, kernel norms (MMD), Hausdorff |
| Algorithm | network simplex, domain decomposition | Sinkhorn iterations |
| Result | optimal sparse plan, exact cost, certificate | a smooth loss, with a blur that trades accuracy for speed |
| Runs on | CPUs | NVIDIA, AMD and Intel GPUs, several GPUs or nodes, CPUs |
| Interface | C++17 headers, NumPy, PyTorch | PyTorch, drop-in replacement of GeomLoss |

Take deblais for a plan, an assignment or a reference value; take remblais for
a loss to minimize, for other costs, unbalanced measures, images and
volumes. The page [deblais and remblais](https://keckj.github.io/deblais/remblais/) compares them in
detail and shows how to use them together.

## About the name

In 1781, Gaspard Monge asked how to move a pile of earth, the *déblais*, into
a hole of the same volume, the *remblais*, at the lowest cost: the founding
problem of optimal transport. deblais is where the mass comes from, and
[remblais](https://github.com/keckj/remblais) is where it ends up.

## License

At your option, [MIT](https://github.com/keckj/deblais/blob/v0.2.0/LICENSE-MIT) or [Apache-2.0](https://github.com/keckj/deblais/blob/v0.2.0/LICENSE-APACHE). deblais
contains no third-party code; the algorithms it implements are credited in
[`THIRD_PARTY.md`](https://github.com/keckj/deblais/blob/v0.2.0/THIRD_PARTY.md).

## Related projects

- remblais, the twin project: Sinkhorn divergences, kernel norms and
  Hausdorff divergences, a drop-in replacement of GeomLoss:
  <https://github.com/keckj/remblais>
- network_simplex by Nicolas Bonneel, the implementation deblais started
  from as a baseline: <https://github.com/nbonneel/network_simplex>
- LEMON, the graph library behind it: <https://lemon.cs.elte.hu>
- kernox, fused GPU and CPU reductions, the engine of remblais:
  <https://github.com/keckj/kernox>
