From 29cf4fae3be4d392d93a0e4f3a0675a69343e48b Mon Sep 17 00:00:00 2001 From: cuteNBD <206630735+bingdongni@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:54:36 +0800 Subject: [PATCH 1/3] Support a separate output grid in the LP barycenter --- RELEASES.md | 2 ++ .../plot_barycenter_output_grid.py | 27 +++++++++++++++ ot/lp/_barycenter_solvers.py | 33 ++++++++++--------- test/test_ot.py | 27 +++++++++++++++ 4 files changed, 74 insertions(+), 15 deletions(-) create mode 100644 examples/barycenters/plot_barycenter_output_grid.py diff --git a/RELEASES.md b/RELEASES.md index 9317ee06c..6a0305742 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -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) diff --git a/examples/barycenters/plot_barycenter_output_grid.py b/examples/barycenters/plot_barycenter_output_grid.py new file mode 100644 index 000000000..86798f7a5 --- /dev/null +++ b/examples/barycenters/plot_barycenter_output_grid.py @@ -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() diff --git a/ot/lp/_barycenter_solvers.py b/ot/lp/_barycenter_solvers.py index 3efca42ef..9e84dc267 100644 --- a/ot/lp/_barycenter_solvers.py +++ b/ot/lp/_barycenter_solvers.py @@ -52,8 +52,9 @@ def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm") ---------- 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 @@ -66,7 +67,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 @@ -88,18 +89,20 @@ 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 @@ -107,11 +110,11 @@ def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm") 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])) @@ -131,11 +134,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), @@ -147,7 +150,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 diff --git a/test/test_ot.py b/test/test_ot.py index 0e189cc00..a3e4280da 100644 --- a/test/test_ot.py +++ b/test/test_ot.py @@ -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)), From 8108ebfd6b5edfdb14d9a2df23e0182ddbcbc04c Mon Sep 17 00:00:00 2001 From: cuteNBD <206630735+bingdongni@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:16:21 +0800 Subject: [PATCH 2/3] Document the direction of transport to the output grid --- docs/source/user_guide.rst | 4 ++++ ot/lp/_barycenter_solvers.py | 17 +++++++---------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/source/user_guide.rst b/docs/source/user_guide.rst index 8032bac08..31c95759e 100644 --- a/docs/source/user_guide.rst +++ b/docs/source/user_guide.rst @@ -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 diff --git a/ot/lp/_barycenter_solvers.py b/ot/lp/_barycenter_solvers.py index 9e84dc267..eb986890e 100644 --- a/ot/lp/_barycenter_solvers.py +++ b/ot/lp/_barycenter_solvers.py @@ -33,20 +33,17 @@ 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 ---------- From 9f7ba6087deeef759e79f7197ccbd2216278f9ce Mon Sep 17 00:00:00 2001 From: cuteNBD <206630735+bingdongni@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:28:56 +0800 Subject: [PATCH 3/3] Format the output-grid barycenter example --- examples/barycenters/plot_barycenter_output_grid.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/barycenters/plot_barycenter_output_grid.py b/examples/barycenters/plot_barycenter_output_grid.py index 86798f7a5..23a7381bb 100644 --- a/examples/barycenters/plot_barycenter_output_grid.py +++ b/examples/barycenters/plot_barycenter_output_grid.py @@ -13,8 +13,8 @@ source = np.arange(40) target = np.arange(2, 40, 5) -a = np.exp(-((source - 9) / 4) ** 2) -b = np.exp(-((source - 26) / 6) ** 2) +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)