Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions RELEASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

#### New features

- Allow a rectangular cost matrix in `ot.lp.barycenter` to prescribe a separate output grid.


- `ot.dr.wda` gains `solver='torch'`, a PyTorch autodiff solver with Riemannian gradient descent, usable on installations without autograd or pymanopt, and accepting torch tensors directly (PR #858, Issue #806)
- `ot.dr` dependencies (autograd, pymanopt, scikit-learn, torch) are now imported optionally, so importing `ot.dr` no longer requires all of them; each function raises an explicit `ImportError` naming what it needs (PR #858)
Expand Down
4 changes: 4 additions & 0 deletions docs/source/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,10 @@ function uses :any:`scipy.optimize.linprog`, but more efficient LP solvers from
requires to solve a very large linear program and can be very slow in
practice.

The rows of the cost matrix correspond to the input bins and the columns to
the allowed barycenter bins. These supports can have different sizes, as in
:ref:`sphx_glr_auto_examples_barycenters_plot_barycenter_output_grid.py`.

Similarly to the OT problem, OT barycenters can be computed in the regularized
case. When entropic regularization is used, the problem can be solved with a
generalization of the Sinkhorn algorithm based on Bregman projections [3]_. This
Expand Down
27 changes: 27 additions & 0 deletions examples/barycenters/plot_barycenter_output_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
Compute a barycenter on a coarser reporting grid
================================================

Fine-grained measurements may need to be summarized on a common set of
reporting bins. The columns of the cost matrix specify which positions the
barycenter may occupy. Each input histogram retains its original bins.
"""

import matplotlib.pyplot as plt
import numpy as np
import ot

source = np.arange(40)
target = np.arange(2, 40, 5)
a = np.exp(-(((source - 9) / 4) ** 2))
b = np.exp(-(((source - 26) / 6) ** 2))
histograms = np.column_stack((a / a.sum(), b / b.sum()))
cost = (source[:, None] - target) ** 2
mass = ot.lp.barycenter(histograms, cost)

plt.plot(source, histograms, alpha=0.7)
plt.bar(target, mass / 5, width=5, alpha=0.4, label="Barycenter")
plt.xlabel("Position")
plt.ylabel("Mass per unit width")
plt.legend()
plt.show()
50 changes: 25 additions & 25 deletions ot/lp/_barycenter_solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,27 +33,25 @@ def scipy_sparse_to_spmatrix(A):
def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm"):
r"""Compute the Wasserstein barycenter of distributions A

The function solves the following optimization problem [16]:
The function solves the following optimization problem [16]:

.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{1}(\mathbf{a},\mathbf{a}_i)
\min_{\mathbf{a}} \sum_i w_i\,\mathrm{OT}_M(\mathbf{a}_i, \mathbf{a})

where :

- :math:`W_1(\cdot,\cdot)` is the Wasserstein distance (see ot.emd.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`

The linear program is solved using the interior point solver from scipy.optimize.
If cvxopt solver if installed it can use cvxopt
where :math:`\mathrm{OT}_M` is the transport cost from a column
:math:`\mathbf{a}_i` of :math:`\mathbf{A}` to the barycenter
:math:`\mathbf{a}` using the cost matrix :math:`M`.

Note that this problem do not scale well (both in memory and computational time).
The linear program is solved with SciPy or CVXOPT and can be large
even for a moderate number of bins.

Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
M : np.ndarray (d,m)
Cost from each input bin (row) to each prescribed barycenter bin
(column). The two supports need not have the same size.
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coordinates)
verbose : bool, optional
Expand All @@ -66,7 +64,7 @@ def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm")

Returns
-------
a : (d,) ndarray
a : (m,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
Expand All @@ -88,30 +86,32 @@ def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm")
n_distributions = A.shape[1]
n = A.shape[0]

n2 = n * n
if M.ndim != 2 or M.shape[0] != n or M.shape[1] == 0:
raise ValueError("M must have one row per input bin and at least one column.")
m = M.shape[1]
c = np.zeros((0))
b_eq1 = np.zeros((0))
for i in range(n_distributions):
c = np.concatenate((c, M.ravel() * weights[i]))
b_eq1 = np.concatenate((b_eq1, A[:, i]))
c = np.concatenate((c, np.zeros(n)))
c = np.concatenate((c, np.zeros(m)))

lst_idiag1 = [sps.kron(sps.eye(n), np.ones((1, n))) for i in range(n_distributions)]
lst_idiag1 = [sps.kron(sps.eye(n), np.ones((1, m))) for i in range(n_distributions)]
# row constraints
A_eq1 = sps.hstack(
(sps.block_diag(lst_idiag1), sps.coo_matrix((n_distributions * n, n)))
(sps.block_diag(lst_idiag1), sps.coo_matrix((n_distributions * n, m)))
)

# columns constraints
lst_idiag2 = []
lst_eye = []
for i in range(n_distributions):
if i == 0:
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n)))
lst_eye.append(-sps.eye(n))
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(m)))
lst_eye.append(-sps.eye(m))
else:
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n - 1, n)))
lst_eye.append(-sps.eye(n - 1, n))
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(m - 1, m)))
lst_eye.append(-sps.eye(m - 1, m))

A_eq2 = sps.hstack((sps.block_diag(lst_idiag2), sps.vstack(lst_eye)))
b_eq2 = np.zeros((A_eq2.shape[0]))
Expand All @@ -131,11 +131,11 @@ def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm")
c, A_eq=A_eq, b_eq=b_eq, method=solver, options=options
)
x = sol.x
b = x[-n:]
b = x[-m:]

else:
h = np.zeros((n_distributions * n2 + n))
G = -sps.eye(n_distributions * n2 + n)
h = np.zeros((n_distributions * n * m + m))
G = -sps.eye(n_distributions * n * m + m)

sol = solvers.lp(
matrix(c),
Expand All @@ -147,7 +147,7 @@ def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm")
)

x = np.array(sol["x"])
b = x[-n:].ravel()
b = x[-m:].ravel()

if log:
return b, sol
Expand Down
27 changes: 27 additions & 0 deletions test/test_ot.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,33 @@ def test_lp_barycenter():
np.testing.assert_allclose(bary.sum(), 1)


@pytest.mark.parametrize("solver", ["highs-ipm", "highs-ds", None])
@pytest.mark.parametrize("m", [1, 3, 7])
def test_lp_barycenter_rectangular_cost(solver, m):
if solver is None and not ot.lp._barycenter_solvers.cvxopt:
pytest.skip("cvxopt is not installed")
# A Dirac in each input column forces its transport plan to put all
# the corresponding mass on the optimal barycenter bin.
A = np.eye(4)[:, [0, 2]]
weights = np.array([0.25, 0.75])
bins = np.linspace(0.1, 2.8, m)
M = (np.arange(4)[:, None] - bins) ** 2
expected = np.zeros(m)
expected[np.argmin(weights @ M[[0, 2]])] = 1
result, _ = ot.lp.barycenter(A, M, weights, solver=solver, log=True)
np.testing.assert_allclose(result, expected, atol=1e-6)


def test_lp_barycenter_on_a_coarser_grid():
A = np.array([[0.2, 0.1], [0.3, 0.4], [0.5, 0.5]])
# Both inputs send their first two bins to output bin 0, their last to 1.
M = np.array([[0.0, 9.0], [1.0, 4.0], [9.0, 0.0]])
result = ot.lp.barycenter(A, M)
np.testing.assert_allclose(result, [0.5, 0.5])
with pytest.raises(ValueError, match="one row per input bin"):
ot.lp.barycenter(A, M.T)


def test_free_support_barycenter():
measures_locations = [
np.array([-1.0]).reshape((1, 1)),
Expand Down
Loading