| 1 |
|
| 2 |
""" |
| 3 |
Solvers for the original linear program OT problem. |
| 4 |
|
| 5 |
""" |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
import numpy as np |
| 12 |
import warnings |
| 13 |
|
| 14 |
from . import cvx |
| 15 |
from .cvx import barycenter |
| 16 |
from .dmmot import dmmot_monge_1dgrid_loss, dmmot_monge_1dgrid_optimize |
| 17 |
|
| 18 |
|
| 19 |
from .emd_wrap import emd_c, check_result, emd_1d_sorted |
| 20 |
from .solver_1d import ( |
| 21 |
emd_1d, |
| 22 |
emd2_1d, |
| 23 |
wasserstein_1d, |
| 24 |
binary_search_circle, |
| 25 |
wasserstein_circle, |
| 26 |
semidiscrete_wasserstein2_unif_circle, |
| 27 |
) |
| 28 |
|
| 29 |
from ..utils import dist, list_to_array |
| 30 |
from ..backend import get_backend |
| 31 |
|
| 32 |
__all__ = [ |
| 33 |
"emd", |
| 34 |
"emd2", |
| 35 |
"barycenter", |
| 36 |
"free_support_barycenter", |
| 37 |
"cvx", |
| 38 |
"emd_1d_sorted", |
| 39 |
"emd_1d", |
| 40 |
"emd2_1d", |
| 41 |
"wasserstein_1d", |
| 42 |
"generalized_free_support_barycenter", |
| 43 |
"binary_search_circle", |
| 44 |
"wasserstein_circle", |
| 45 |
"semidiscrete_wasserstein2_unif_circle", |
| 46 |
"dmmot_monge_1dgrid_loss", |
| 47 |
"dmmot_monge_1dgrid_optimize", |
| 48 |
] |
| 49 |
|
| 50 |
|
| 51 |
def check_number_threads(numThreads): |
| 52 |
"""Checks whether or not the requested number of threads has a valid value. |
| 53 |
|
| 54 |
Parameters |
| 55 |
---------- |
| 56 |
numThreads : int or str |
| 57 |
The requested number of threads, should either be a strictly positive integer or "max" or None |
| 58 |
|
| 59 |
Returns |
| 60 |
------- |
| 61 |
numThreads : int |
| 62 |
Corrected number of threads |
| 63 |
""" |
| 64 |
if (numThreads is None) or ( |
| 65 |
isinstance(numThreads, str) and numThreads.lower() == "max" |
| 66 |
): |
| 67 |
return -1 |
| 68 |
if (not isinstance(numThreads, int)) or numThreads < 1: |
| 69 |
raise ValueError( |
| 70 |
'numThreads should either be "max" or a strictly positive integer' |
| 71 |
) |
| 72 |
return numThreads |
| 73 |
|
| 74 |
|
| 75 |
def center_ot_dual(alpha0, beta0, a=None, b=None): |
| 76 |
r"""Center dual OT potentials w.r.t. their weights |
| 77 |
|
| 78 |
The main idea of this function is to find unique dual potentials |
| 79 |
that ensure some kind of centering/fairness. The main idea is to find dual potentials that lead to the same final objective value for both source and targets (see below for more details). It will help having |
| 80 |
stability when multiple calling of the OT solver with small changes. |
| 81 |
|
| 82 |
Basically we add another constraint to the potential that will not |
| 83 |
change the objective value but will ensure unicity. The constraint |
| 84 |
is the following: |
| 85 |
|
| 86 |
.. math:: |
| 87 |
\alpha^T \mathbf{a} = \beta^T \mathbf{b} |
| 88 |
|
| 89 |
in addition to the OT problem constraints. |
| 90 |
|
| 91 |
since :math:`\sum_i a_i=\sum_j b_j` this can be solved by adding/removing |
| 92 |
a constant from both :math:`\alpha_0` and :math:`\beta_0`. |
| 93 |
|
| 94 |
.. math:: |
| 95 |
c &= \frac{\beta_0^T \mathbf{b} - \alpha_0^T \mathbf{a}}{\mathbf{1}^T \mathbf{b} + \mathbf{1}^T \mathbf{a}} |
| 96 |
|
| 97 |
\alpha &= \alpha_0 + c |
| 98 |
|
| 99 |
\beta &= \beta_0 + c |
| 100 |
|
| 101 |
Parameters |
| 102 |
---------- |
| 103 |
alpha0 : (ns,) numpy.ndarray, float64 |
| 104 |
Source dual potential |
| 105 |
beta0 : (nt,) numpy.ndarray, float64 |
| 106 |
Target dual potential |
| 107 |
a : (ns,) numpy.ndarray, float64 |
| 108 |
Source histogram (uniform weight if empty list) |
| 109 |
b : (nt,) numpy.ndarray, float64 |
| 110 |
Target histogram (uniform weight if empty list) |
| 111 |
|
| 112 |
Returns |
| 113 |
------- |
| 114 |
alpha : (ns,) numpy.ndarray, float64 |
| 115 |
Source centered dual potential |
| 116 |
beta : (nt,) numpy.ndarray, float64 |
| 117 |
Target centered dual potential |
| 118 |
|
| 119 |
""" |
| 120 |
|
| 121 |
if a is None: |
| 122 |
a = np.ones(alpha0.shape[0]) / alpha0.shape[0] |
| 123 |
if b is None: |
| 124 |
b = np.ones(beta0.shape[0]) / beta0.shape[0] |
| 125 |
|
| 126 |
|
| 127 |
c = (b.dot(beta0) - a.dot(alpha0)) / (a.sum() + b.sum()) |
| 128 |
|
| 129 |
|
| 130 |
alpha = alpha0 + c |
| 131 |
beta = beta0 - c |
| 132 |
|
| 133 |
return alpha, beta |
| 134 |
|
| 135 |
|
| 136 |
def estimate_dual_null_weights(alpha0, beta0, a, b, M): |
| 137 |
r"""Estimate feasible values for 0-weighted dual potentials |
| 138 |
|
| 139 |
The feasible values are computed efficiently but rather coarsely. |
| 140 |
|
| 141 |
.. warning:: |
| 142 |
This function is necessary because the C++ solver in `emd_c` |
| 143 |
discards all samples in the distributions with |
| 144 |
zeros weights. This means that while the primal variable (transport |
| 145 |
matrix) is exact, the solver only returns feasible dual potentials |
| 146 |
on the samples with weights different from zero. |
| 147 |
|
| 148 |
First we compute the constraints violations: |
| 149 |
|
| 150 |
.. math:: |
| 151 |
\mathbf{V} = \alpha + \beta^T - \mathbf{M} |
| 152 |
|
| 153 |
Next we compute the max amount of violation per row (:math:`\alpha`) and |
| 154 |
columns (:math:`beta`) |
| 155 |
|
| 156 |
.. math:: |
| 157 |
\mathbf{v^a}_i = \max_j \mathbf{V}_{i,j} |
| 158 |
|
| 159 |
\mathbf{v^b}_j = \max_i \mathbf{V}_{i,j} |
| 160 |
|
| 161 |
Finally we update the dual potential with 0 weights if a |
| 162 |
constraint is violated |
| 163 |
|
| 164 |
.. math:: |
| 165 |
\alpha_i = \alpha_i - \mathbf{v^a}_i \quad \text{ if } \mathbf{a}_i=0 \text{ and } \mathbf{v^a}_i>0 |
| 166 |
|
| 167 |
\beta_j = \beta_j - \mathbf{v^b}_j \quad \text{ if } \mathbf{b}_j=0 \text{ and } \mathbf{v^b}_j > 0 |
| 168 |
|
| 169 |
In the end the dual potentials are centered using function |
| 170 |
:py:func:`ot.lp.center_ot_dual`. |
| 171 |
|
| 172 |
Note that all those updates do not change the objective value of the |
| 173 |
solution but provide dual potentials that do not violate the constraints. |
| 174 |
|
| 175 |
Parameters |
| 176 |
---------- |
| 177 |
alpha0 : (ns,) numpy.ndarray, float64 |
| 178 |
Source dual potential |
| 179 |
beta0 : (nt,) numpy.ndarray, float64 |
| 180 |
Target dual potential |
| 181 |
alpha0 : (ns,) numpy.ndarray, float64 |
| 182 |
Source dual potential |
| 183 |
beta0 : (nt,) numpy.ndarray, float64 |
| 184 |
Target dual potential |
| 185 |
a : (ns,) numpy.ndarray, float64 |
| 186 |
Source distribution (uniform weights if empty list) |
| 187 |
b : (nt,) numpy.ndarray, float64 |
| 188 |
Target distribution (uniform weights if empty list) |
| 189 |
M : (ns,nt) numpy.ndarray, float64 |
| 190 |
Loss matrix (c-order array with type float64) |
| 191 |
|
| 192 |
Returns |
| 193 |
------- |
| 194 |
alpha : (ns,) numpy.ndarray, float64 |
| 195 |
Source corrected dual potential |
| 196 |
beta : (nt,) numpy.ndarray, float64 |
| 197 |
Target corrected dual potential |
| 198 |
|
| 199 |
""" |
| 200 |
|
| 201 |
|
| 202 |
asel = a != 0 |
| 203 |
bsel = b != 0 |
| 204 |
|
| 205 |
|
| 206 |
constraint_violation = alpha0[:, None] + beta0[None, :] - M |
| 207 |
|
| 208 |
|
| 209 |
aviol = np.max(constraint_violation, 1) |
| 210 |
bviol = np.max(constraint_violation, 0) |
| 211 |
|
| 212 |
|
| 213 |
alpha_up = -1 * ~asel * np.maximum(aviol, 0) |
| 214 |
beta_up = -1 * ~bsel * np.maximum(bviol, 0) |
| 215 |
|
| 216 |
alpha = alpha0 + alpha_up |
| 217 |
beta = beta0 + beta_up |
| 218 |
|
| 219 |
return center_ot_dual(alpha, beta, a, b) |
| 220 |
|
| 221 |
|
| 222 |
def emd( |
| 223 |
a, |
| 224 |
b, |
| 225 |
M, |
| 226 |
numItermax=100000, |
| 227 |
log=False, |
| 228 |
center_dual=True, |
| 229 |
numThreads=1, |
| 230 |
check_marginals=True, |
| 231 |
): |
| 232 |
r"""Solves the Earth Movers distance problem and returns the OT matrix |
| 233 |
|
| 234 |
|
| 235 |
.. math:: |
| 236 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F |
| 237 |
|
| 238 |
s.t. \ \gamma \mathbf{1} = \mathbf{a} |
| 239 |
|
| 240 |
\gamma^T \mathbf{1} = \mathbf{b} |
| 241 |
|
| 242 |
\gamma \geq 0 |
| 243 |
|
| 244 |
where : |
| 245 |
|
| 246 |
- :math:`\mathbf{M}` is the metric cost matrix |
| 247 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are the sample weights |
| 248 |
|
| 249 |
.. warning:: Note that the :math:`\mathbf{M}` matrix in numpy needs to be a C-order |
| 250 |
numpy.array in float64 format. It will be converted if not in this |
| 251 |
format |
| 252 |
|
| 253 |
.. note:: This function is backend-compatible and will work on arrays |
| 254 |
from all compatible backends. But the algorithm uses the C++ CPU backend |
| 255 |
which can lead to copy overhead on GPU arrays. |
| 256 |
|
| 257 |
.. note:: This function will cast the computed transport plan to the data type |
| 258 |
of the provided input with the following priority: :math:`\mathbf{a}`, |
| 259 |
then :math:`\mathbf{b}`, then :math:`\mathbf{M}` if marginals are not provided. |
| 260 |
Casting to an integer tensor might result in a loss of precision. |
| 261 |
If this behaviour is unwanted, please make sure to provide a |
| 262 |
floating point input. |
| 263 |
|
| 264 |
.. note:: An error will be raised if the vectors :math:`\mathbf{a}` and :math:`\mathbf{b}` do not sum to the same value. |
| 265 |
|
| 266 |
Uses the algorithm proposed in :ref:`[1] <references-emd>`. |
| 267 |
|
| 268 |
Parameters |
| 269 |
---------- |
| 270 |
a : (ns,) array-like, float |
| 271 |
Source histogram (uniform weight if empty list) |
| 272 |
b : (nt,) array-like, float |
| 273 |
Target histogram (uniform weight if empty list) |
| 274 |
M : (ns,nt) array-like, float |
| 275 |
Loss matrix (c-order array in numpy with type float64) |
| 276 |
numItermax : int, optional (default=100000) |
| 277 |
The maximum number of iterations before stopping the optimization |
| 278 |
algorithm if it has not converged. |
| 279 |
log: bool, optional (default=False) |
| 280 |
If True, returns a dictionary containing the cost and dual variables. |
| 281 |
Otherwise returns only the optimal transportation matrix. |
| 282 |
center_dual: boolean, optional (default=True) |
| 283 |
If True, centers the dual potential using function |
| 284 |
:py:func:`ot.lp.center_ot_dual`. |
| 285 |
numThreads: int or "max", optional (default=1, i.e. OpenMP is not used) |
| 286 |
If compiled with OpenMP, chooses the number of threads to parallelize. |
| 287 |
"max" selects the highest number possible. |
| 288 |
check_marginals: bool, optional (default=True) |
| 289 |
If True, checks that the marginals mass are equal. If False, skips the |
| 290 |
check. |
| 291 |
|
| 292 |
|
| 293 |
Returns |
| 294 |
------- |
| 295 |
gamma: array-like, shape (ns, nt) |
| 296 |
Optimal transportation matrix for the given |
| 297 |
parameters |
| 298 |
log: dict, optional |
| 299 |
If input log is true, a dictionary containing the |
| 300 |
cost and dual variables and exit status |
| 301 |
|
| 302 |
|
| 303 |
Examples |
| 304 |
-------- |
| 305 |
|
| 306 |
Simple example with obvious solution. The function emd accepts lists and |
| 307 |
perform automatic conversion to numpy arrays |
| 308 |
|
| 309 |
>>> import ot |
| 310 |
>>> a=[.5,.5] |
| 311 |
>>> b=[.5,.5] |
| 312 |
>>> M=[[0.,1.],[1.,0.]] |
| 313 |
>>> ot.emd(a, b, M) |
| 314 |
array([[0.5, 0. ], |
| 315 |
[0. , 0.5]]) |
| 316 |
|
| 317 |
|
| 318 |
.. _references-emd: |
| 319 |
References |
| 320 |
---------- |
| 321 |
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, |
| 322 |
December). Displacement interpolation using Lagrangian mass transport. |
| 323 |
In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. |
| 324 |
|
| 325 |
See Also |
| 326 |
-------- |
| 327 |
ot.bregman.sinkhorn : Entropic regularized OT |
| 328 |
ot.optim.cg : General regularized OT |
| 329 |
""" |
| 330 |
|
| 331 |
a, b, M = list_to_array(a, b, M) |
| 332 |
nx = get_backend(M, a, b) |
| 333 |
|
| 334 |
if len(a) != 0: |
| 335 |
type_as = a |
| 336 |
elif len(b) != 0: |
| 337 |
type_as = b |
| 338 |
else: |
| 339 |
type_as = M |
| 340 |
|
| 341 |
|
| 342 |
if len(a) == 0: |
| 343 |
a = nx.ones((M.shape[0],), type_as=type_as) / M.shape[0] |
| 344 |
if len(b) == 0: |
| 345 |
b = nx.ones((M.shape[1],), type_as=type_as) / M.shape[1] |
| 346 |
|
| 347 |
|
| 348 |
M, a, b = nx.to_numpy(M, a, b) |
| 349 |
|
| 350 |
|
| 351 |
a = np.asarray(a, dtype=np.float64) |
| 352 |
b = np.asarray(b, dtype=np.float64) |
| 353 |
M = np.asarray(M, dtype=np.float64, order="C") |
| 354 |
|
| 355 |
|
| 356 |
if len(a) == 0: |
| 357 |
a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] |
| 358 |
if len(b) == 0: |
| 359 |
b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] |
| 360 |
|
| 361 |
assert ( |
| 362 |
a.shape[0] == M.shape[0] and b.shape[0] == M.shape[1] |
| 363 |
), "Dimension mismatch, check dimensions of M with a and b" |
| 364 |
|
| 365 |
|
| 366 |
if check_marginals: |
| 367 |
np.testing.assert_almost_equal( |
| 368 |
a.sum(0), |
| 369 |
b.sum(0), |
| 370 |
err_msg="a and b vector must have the same sum", |
| 371 |
decimal=6, |
| 372 |
) |
| 373 |
b = b * a.sum() / b.sum() |
| 374 |
|
| 375 |
asel = a != 0 |
| 376 |
bsel = b != 0 |
| 377 |
|
| 378 |
numThreads = check_number_threads(numThreads) |
| 379 |
|
| 380 |
G, cost, u, v, result_code = emd_c(a, b, M, numItermax, numThreads) |
| 381 |
|
| 382 |
if center_dual: |
| 383 |
u, v = center_ot_dual(u, v, a, b) |
| 384 |
|
| 385 |
if np.any(~asel) or np.any(~bsel): |
| 386 |
u, v = estimate_dual_null_weights(u, v, a, b, M) |
| 387 |
|
| 388 |
result_code_string = check_result(result_code) |
| 389 |
if not nx.is_floating_point(type_as): |
| 390 |
warnings.warn( |
| 391 |
"Input histogram consists of integer. The transport plan will be " |
| 392 |
"casted accordingly, possibly resulting in a loss of precision. " |
| 393 |
"If this behaviour is unwanted, please make sure your input " |
| 394 |
"histogram consists of floating point elements.", |
| 395 |
stacklevel=2, |
| 396 |
) |
| 397 |
if log: |
| 398 |
log = {} |
| 399 |
log["cost"] = cost |
| 400 |
log["u"] = nx.from_numpy(u, type_as=type_as) |
| 401 |
log["v"] = nx.from_numpy(v, type_as=type_as) |
| 402 |
log["warning"] = result_code_string |
| 403 |
log["result_code"] = result_code |
| 404 |
return nx.from_numpy(G, type_as=type_as), log |
| 405 |
return nx.from_numpy(G, type_as=type_as) |
| 406 |
|
| 407 |
|
| 408 |
def emd2( |
| 409 |
a, |
| 410 |
b, |
| 411 |
M, |
| 412 |
processes=1, |
| 413 |
numItermax=100000, |
| 414 |
log=False, |
| 415 |
return_matrix=False, |
| 416 |
center_dual=True, |
| 417 |
numThreads=1, |
| 418 |
check_marginals=True, |
| 419 |
): |
| 420 |
r"""Solves the Earth Movers distance problem and returns the loss |
| 421 |
|
| 422 |
.. math:: |
| 423 |
\min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F |
| 424 |
|
| 425 |
s.t. \ \gamma \mathbf{1} = \mathbf{a} |
| 426 |
|
| 427 |
\gamma^T \mathbf{1} = \mathbf{b} |
| 428 |
|
| 429 |
\gamma \geq 0 |
| 430 |
|
| 431 |
where : |
| 432 |
|
| 433 |
- :math:`\mathbf{M}` is the metric cost matrix |
| 434 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are the sample weights |
| 435 |
|
| 436 |
.. note:: This function is backend-compatible and will work on arrays |
| 437 |
from all compatible backends. But the algorithm uses the C++ CPU backend |
| 438 |
which can lead to copy overhead on GPU arrays. |
| 439 |
|
| 440 |
.. note:: This function will cast the computed transport plan and |
| 441 |
transportation loss to the data type of the provided input with the |
| 442 |
following priority: :math:`\mathbf{a}`, then :math:`\mathbf{b}`, |
| 443 |
then :math:`\mathbf{M}` if marginals are not provided. |
| 444 |
Casting to an integer tensor might result in a loss of precision. |
| 445 |
If this behaviour is unwanted, please make sure to provide a |
| 446 |
floating point input. |
| 447 |
|
| 448 |
.. note:: An error will be raised if the vectors :math:`\mathbf{a}` and :math:`\mathbf{b}` do not sum to the same value. |
| 449 |
|
| 450 |
Uses the algorithm proposed in :ref:`[1] <references-emd2>`. |
| 451 |
|
| 452 |
Parameters |
| 453 |
---------- |
| 454 |
a : (ns,) array-like, float64 |
| 455 |
Source histogram (uniform weight if empty list) |
| 456 |
b : (nt,) array-like, float64 |
| 457 |
Target histogram (uniform weight if empty list) |
| 458 |
M : (ns,nt) array-like, float64 |
| 459 |
Loss matrix (for numpy c-order array with type float64) |
| 460 |
processes : int, optional (default=1) |
| 461 |
Nb of processes used for multiple emd computation (deprecated) |
| 462 |
numItermax : int, optional (default=100000) |
| 463 |
The maximum number of iterations before stopping the optimization |
| 464 |
algorithm if it has not converged. |
| 465 |
log: boolean, optional (default=False) |
| 466 |
If True, returns a dictionary containing dual |
| 467 |
variables. Otherwise returns only the optimal transportation cost. |
| 468 |
return_matrix: boolean, optional (default=False) |
| 469 |
If True, returns the optimal transportation matrix in the log. |
| 470 |
center_dual: boolean, optional (default=True) |
| 471 |
If True, centers the dual potential using function |
| 472 |
:py:func:`ot.lp.center_ot_dual`. |
| 473 |
numThreads: int or "max", optional (default=1, i.e. OpenMP is not used) |
| 474 |
If compiled with OpenMP, chooses the number of threads to parallelize. |
| 475 |
"max" selects the highest number possible. |
| 476 |
check_marginals: bool, optional (default=True) |
| 477 |
If True, checks that the marginals mass are equal. If False, skips the |
| 478 |
check. |
| 479 |
|
| 480 |
|
| 481 |
Returns |
| 482 |
------- |
| 483 |
W: float, array-like |
| 484 |
Optimal transportation loss for the given parameters |
| 485 |
log: dict |
| 486 |
If input log is true, a dictionary containing dual |
| 487 |
variables and exit status |
| 488 |
|
| 489 |
|
| 490 |
Examples |
| 491 |
-------- |
| 492 |
|
| 493 |
Simple example with obvious solution. The function emd accepts lists and |
| 494 |
perform automatic conversion to numpy arrays |
| 495 |
|
| 496 |
|
| 497 |
>>> import ot |
| 498 |
>>> a=[.5,.5] |
| 499 |
>>> b=[.5,.5] |
| 500 |
>>> M=[[0.,1.],[1.,0.]] |
| 501 |
>>> ot.emd2(a,b,M) |
| 502 |
0.0 |
| 503 |
|
| 504 |
|
| 505 |
.. _references-emd2: |
| 506 |
References |
| 507 |
---------- |
| 508 |
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. |
| 509 |
(2011, December). Displacement interpolation using Lagrangian mass |
| 510 |
transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. |
| 511 |
158). ACM. |
| 512 |
|
| 513 |
See Also |
| 514 |
-------- |
| 515 |
ot.bregman.sinkhorn : Entropic regularized OT |
| 516 |
ot.optim.cg : General regularized OT |
| 517 |
""" |
| 518 |
|
| 519 |
a, b, M = list_to_array(a, b, M) |
| 520 |
nx = get_backend(M, a, b) |
| 521 |
|
| 522 |
if len(a) != 0: |
| 523 |
type_as = a |
| 524 |
elif len(b) != 0: |
| 525 |
type_as = b |
| 526 |
else: |
| 527 |
type_as = M |
| 528 |
|
| 529 |
|
| 530 |
if len(a) == 0: |
| 531 |
a = nx.ones((M.shape[0],), type_as=type_as) / M.shape[0] |
| 532 |
if len(b) == 0: |
| 533 |
b = nx.ones((M.shape[1],), type_as=type_as) / M.shape[1] |
| 534 |
|
| 535 |
|
| 536 |
a0, b0, M0 = a, b, M |
| 537 |
|
| 538 |
|
| 539 |
M, a, b = nx.to_numpy(M, a, b) |
| 540 |
|
| 541 |
a = np.asarray(a, dtype=np.float64) |
| 542 |
b = np.asarray(b, dtype=np.float64) |
| 543 |
M = np.asarray(M, dtype=np.float64, order="C") |
| 544 |
|
| 545 |
assert ( |
| 546 |
a.shape[0] == M.shape[0] and b.shape[0] == M.shape[1] |
| 547 |
), "Dimension mismatch, check dimensions of M with a and b" |
| 548 |
|
| 549 |
|
| 550 |
if check_marginals: |
| 551 |
np.testing.assert_almost_equal( |
| 552 |
a.sum(0), |
| 553 |
b.sum(0, keepdims=True), |
| 554 |
err_msg="a and b vector must have the same sum", |
| 555 |
decimal=6, |
| 556 |
) |
| 557 |
b = b * a.sum(0) / b.sum(0, keepdims=True) |
| 558 |
|
| 559 |
asel = a != 0 |
| 560 |
|
| 561 |
numThreads = check_number_threads(numThreads) |
| 562 |
|
| 563 |
if log or return_matrix: |
| 564 |
|
| 565 |
def f(b): |
| 566 |
bsel = b != 0 |
| 567 |
|
| 568 |
G, cost, u, v, result_code = emd_c(a, b, M, numItermax, numThreads) |
| 569 |
|
| 570 |
if center_dual: |
| 571 |
u, v = center_ot_dual(u, v, a, b) |
| 572 |
|
| 573 |
if np.any(~asel) or np.any(~bsel): |
| 574 |
u, v = estimate_dual_null_weights(u, v, a, b, M) |
| 575 |
|
| 576 |
result_code_string = check_result(result_code) |
| 577 |
log = {} |
| 578 |
if not nx.is_floating_point(type_as): |
| 579 |
warnings.warn( |
| 580 |
"Input histogram consists of integer. The transport plan will be " |
| 581 |
"casted accordingly, possibly resulting in a loss of precision. " |
| 582 |
"If this behaviour is unwanted, please make sure your input " |
| 583 |
"histogram consists of floating point elements.", |
| 584 |
stacklevel=2, |
| 585 |
) |
| 586 |
G = nx.from_numpy(G, type_as=type_as) |
| 587 |
if return_matrix: |
| 588 |
log["G"] = G |
| 589 |
log["u"] = nx.from_numpy(u, type_as=type_as) |
| 590 |
log["v"] = nx.from_numpy(v, type_as=type_as) |
| 591 |
log["warning"] = result_code_string |
| 592 |
log["result_code"] = result_code |
| 593 |
cost = nx.set_gradients( |
| 594 |
nx.from_numpy(cost, type_as=type_as), |
| 595 |
(a0, b0, M0), |
| 596 |
(log["u"] - nx.mean(log["u"]), log["v"] - nx.mean(log["v"]), G), |
| 597 |
) |
| 598 |
return [cost, log] |
| 599 |
else: |
| 600 |
|
| 601 |
def f(b): |
| 602 |
bsel = b != 0 |
| 603 |
G, cost, u, v, result_code = emd_c(a, b, M, numItermax, numThreads) |
| 604 |
|
| 605 |
if center_dual: |
| 606 |
u, v = center_ot_dual(u, v, a, b) |
| 607 |
|
| 608 |
if np.any(~asel) or np.any(~bsel): |
| 609 |
u, v = estimate_dual_null_weights(u, v, a, b, M) |
| 610 |
|
| 611 |
if not nx.is_floating_point(type_as): |
| 612 |
warnings.warn( |
| 613 |
"Input histogram consists of integer. The transport plan will be " |
| 614 |
"casted accordingly, possibly resulting in a loss of precision. " |
| 615 |
"If this behaviour is unwanted, please make sure your input " |
| 616 |
"histogram consists of floating point elements.", |
| 617 |
stacklevel=2, |
| 618 |
) |
| 619 |
G = nx.from_numpy(G, type_as=type_as) |
| 620 |
cost = nx.set_gradients( |
| 621 |
nx.from_numpy(cost, type_as=type_as), |
| 622 |
(a0, b0, M0), |
| 623 |
( |
| 624 |
nx.from_numpy(u - np.mean(u), type_as=type_as), |
| 625 |
nx.from_numpy(v - np.mean(v), type_as=type_as), |
| 626 |
G, |
| 627 |
), |
| 628 |
) |
| 629 |
|
| 630 |
check_result(result_code) |
| 631 |
return cost |
| 632 |
|
| 633 |
if len(b.shape) == 1: |
| 634 |
return f(b) |
| 635 |
nb = b.shape[1] |
| 636 |
|
| 637 |
if processes > 1: |
| 638 |
warnings.warn( |
| 639 |
"The 'processes' parameter has been deprecated. " |
| 640 |
"Multiprocessing should be done outside of POT." |
| 641 |
) |
| 642 |
res = list(map(f, [b[:, i].copy() for i in range(nb)])) |
| 643 |
|
| 644 |
return res |
| 645 |
|
| 646 |
|
| 647 |
def free_support_barycenter( |
| 648 |
measures_locations, |
| 649 |
measures_weights, |
| 650 |
X_init, |
| 651 |
b=None, |
| 652 |
weights=None, |
| 653 |
numItermax=100, |
| 654 |
stopThr=1e-7, |
| 655 |
verbose=False, |
| 656 |
log=None, |
| 657 |
numThreads=1, |
| 658 |
): |
| 659 |
r""" |
| 660 |
Solves the free support (locations of the barycenters are optimized, not the weights) Wasserstein barycenter problem (i.e. the weighted Frechet mean for the 2-Wasserstein distance), formally: |
| 661 |
|
| 662 |
.. math:: |
| 663 |
\min_\mathbf{X} \quad \sum_{i=1}^N w_i W_2^2(\mathbf{b}, \mathbf{X}, \mathbf{a}_i, \mathbf{X}_i) |
| 664 |
|
| 665 |
where : |
| 666 |
|
| 667 |
- :math:`w \in \mathbb{(0, 1)}^{N}`'s are the barycenter weights and sum to one |
| 668 |
- `measure_weights` denotes the :math:`\mathbf{a}_i \in \mathbb{R}^{k_i}`: empirical measures weights (on simplex) |
| 669 |
- `measures_locations` denotes the :math:`\mathbf{X}_i \in \mathbb{R}^{k_i, d}`: empirical measures atoms locations |
| 670 |
- :math:`\mathbf{b} \in \mathbb{R}^{k}` is the desired weights vector of the barycenter |
| 671 |
|
| 672 |
This problem is considered in :ref:`[20] <references-free-support-barycenter>` (Algorithm 2). |
| 673 |
There are two differences with the following codes: |
| 674 |
|
| 675 |
- we do not optimize over the weights |
| 676 |
- we do not do line search for the locations updates, we use i.e. :math:`\theta = 1` in |
| 677 |
:ref:`[20] <references-free-support-barycenter>` (Algorithm 2). This can be seen as a discrete |
| 678 |
implementation of the fixed-point algorithm of |
| 679 |
:ref:`[43] <references-free-support-barycenter>` proposed in the continuous setting. |
| 680 |
|
| 681 |
Parameters |
| 682 |
---------- |
| 683 |
measures_locations : list of N (k_i,d) array-like |
| 684 |
The discrete support of a measure supported on :math:`k_i` locations of a `d`-dimensional space |
| 685 |
(:math:`k_i` can be different for each element of the list) |
| 686 |
measures_weights : list of N (k_i,) array-like |
| 687 |
Numpy arrays where each numpy array has :math:`k_i` non-negatives values summing to one |
| 688 |
representing the weights of each discrete input measure |
| 689 |
|
| 690 |
X_init : (k,d) array-like |
| 691 |
Initialization of the support locations (on `k` atoms) of the barycenter |
| 692 |
b : (k,) array-like |
| 693 |
Initialization of the weights of the barycenter (non-negatives, sum to 1) |
| 694 |
weights : (N,) array-like |
| 695 |
Initialization of the coefficients of the barycenter (non-negatives, sum to 1) |
| 696 |
|
| 697 |
numItermax : int, optional |
| 698 |
Max number of iterations |
| 699 |
stopThr : float, optional |
| 700 |
Stop threshold on error (>0) |
| 701 |
verbose : bool, optional |
| 702 |
Print information along iterations |
| 703 |
log : bool, optional |
| 704 |
record log if True |
| 705 |
numThreads: int or "max", optional (default=1, i.e. OpenMP is not used) |
| 706 |
If compiled with OpenMP, chooses the number of threads to parallelize. |
| 707 |
"max" selects the highest number possible. |
| 708 |
|
| 709 |
|
| 710 |
Returns |
| 711 |
------- |
| 712 |
X : (k,d) array-like |
| 713 |
Support locations (on k atoms) of the barycenter |
| 714 |
|
| 715 |
|
| 716 |
.. _references-free-support-barycenter: |
| 717 |
|
| 718 |
References |
| 719 |
---------- |
| 720 |
.. [20] Cuturi, Marco, and Arnaud Doucet. "Fast computation of Wasserstein barycenters." International Conference on Machine Learning. 2014. |
| 721 |
|
| 722 |
.. [43] Álvarez-Esteban, Pedro C., et al. "A fixed-point approach to barycenters in Wasserstein space." Journal of Mathematical Analysis and Applications 441.2 (2016): 744-762. |
| 723 |
|
| 724 |
""" |
| 725 |
|
| 726 |
nx = get_backend(*measures_locations, *measures_weights, X_init) |
| 727 |
|
| 728 |
iter_count = 0 |
| 729 |
|
| 730 |
N = len(measures_locations) |
| 731 |
k = X_init.shape[0] |
| 732 |
d = X_init.shape[1] |
| 733 |
if b is None: |
| 734 |
b = nx.ones((k,), type_as=X_init) / k |
| 735 |
if weights is None: |
| 736 |
weights = nx.ones((N,), type_as=X_init) / N |
| 737 |
|
| 738 |
X = X_init |
| 739 |
|
| 740 |
log_dict = {} |
| 741 |
displacement_square_norms = [] |
| 742 |
|
| 743 |
displacement_square_norm = stopThr + 1.0 |
| 744 |
|
| 745 |
while displacement_square_norm > stopThr and iter_count < numItermax: |
| 746 |
T_sum = nx.zeros((k, d), type_as=X_init) |
| 747 |
|
| 748 |
for measure_locations_i, measure_weights_i, weight_i in zip( |
| 749 |
measures_locations, measures_weights, weights |
| 750 |
): |
| 751 |
M_i = dist(X, measure_locations_i) |
| 752 |
T_i = emd(b, measure_weights_i, M_i, numThreads=numThreads) |
| 753 |
T_sum = T_sum + weight_i * 1.0 / b[:, None] * nx.dot( |
| 754 |
T_i, measure_locations_i |
| 755 |
) |
| 756 |
|
| 757 |
displacement_square_norm = nx.sum((T_sum - X) ** 2) |
| 758 |
if log: |
| 759 |
displacement_square_norms.append(displacement_square_norm) |
| 760 |
|
| 761 |
X = T_sum |
| 762 |
|
| 763 |
if verbose: |
| 764 |
print( |
| 765 |
"iteration %d, displacement_square_norm=%f\n", |
| 766 |
iter_count, |
| 767 |
displacement_square_norm, |
| 768 |
) |
| 769 |
|
| 770 |
iter_count += 1 |
| 771 |
|
| 772 |
if log: |
| 773 |
log_dict["displacement_square_norms"] = displacement_square_norms |
| 774 |
return X, log_dict |
| 775 |
else: |
| 776 |
return X |
| 777 |
|
| 778 |
|
| 779 |
def generalized_free_support_barycenter( |
| 780 |
X_list, |
| 781 |
a_list, |
| 782 |
P_list, |
| 783 |
n_samples_bary, |
| 784 |
Y_init=None, |
| 785 |
b=None, |
| 786 |
weights=None, |
| 787 |
numItermax=100, |
| 788 |
stopThr=1e-7, |
| 789 |
verbose=False, |
| 790 |
log=None, |
| 791 |
numThreads=1, |
| 792 |
eps=0, |
| 793 |
): |
| 794 |
r""" |
| 795 |
Solves the free support generalized Wasserstein barycenter problem: finding a barycenter (a discrete measure with |
| 796 |
a fixed amount of points of uniform weights) whose respective projections fit the input measures. |
| 797 |
More formally: |
| 798 |
|
| 799 |
.. math:: |
| 800 |
\min_\gamma \quad \sum_{i=1}^p w_i W_2^2(\nu_i, \mathbf{P}_i\#\gamma) |
| 801 |
|
| 802 |
where : |
| 803 |
|
| 804 |
- :math:`\gamma = \sum_{l=1}^n b_l\delta_{y_l}` is the desired barycenter with each :math:`y_l \in \mathbb{R}^d` |
| 805 |
- :math:`\mathbf{b} \in \mathbb{R}^{n}` is the desired weights vector of the barycenter |
| 806 |
- The input measures are :math:`\nu_i = \sum_{j=1}^{k_i}a_{i,j}\delta_{x_{i,j}}` |
| 807 |
- The :math:`\mathbf{a}_i \in \mathbb{R}^{k_i}` are the respective empirical measures weights (on the simplex) |
| 808 |
- The :math:`\mathbf{X}_i \in \mathbb{R}^{k_i, d_i}` are the respective empirical measures atoms locations |
| 809 |
- :math:`w = (w_1, \cdots w_p)` are the barycenter coefficients (on the simplex) |
| 810 |
- Each :math:`\mathbf{P}_i \in \mathbb{R}^{d, d_i}`, and :math:`P_i\#\nu_i = \sum_{j=1}^{k_i}a_{i,j}\delta_{P_ix_{i,j}}` |
| 811 |
|
| 812 |
As show by :ref:`[42] <references-generalized-free-support-barycenter>`, |
| 813 |
this problem can be re-written as a Wasserstein Barycenter problem, |
| 814 |
which we solve using the free support method :ref:`[20] <references-generalized-free-support-barycenter>` |
| 815 |
(Algorithm 2). |
| 816 |
|
| 817 |
Parameters |
| 818 |
---------- |
| 819 |
X_list : list of p (k_i,d_i) array-like |
| 820 |
Discrete supports of the input measures: each consists of :math:`k_i` locations of a `d_i`-dimensional space |
| 821 |
(:math:`k_i` can be different for each element of the list) |
| 822 |
a_list : list of p (k_i,) array-like |
| 823 |
Measure weights: each element is a vector (k_i) on the simplex |
| 824 |
P_list : list of p (d_i,d) array-like |
| 825 |
Each :math:`P_i` is a linear map :math:`\mathbb{R}^{d} \rightarrow \mathbb{R}^{d_i}` |
| 826 |
n_samples_bary : int |
| 827 |
Number of barycenter points |
| 828 |
Y_init : (n_samples_bary,d) array-like |
| 829 |
Initialization of the support locations (on `k` atoms) of the barycenter |
| 830 |
b : (n_samples_bary,) array-like |
| 831 |
Initialization of the weights of the barycenter measure (on the simplex) |
| 832 |
weights : (p,) array-like |
| 833 |
Initialization of the coefficients of the barycenter (on the simplex) |
| 834 |
numItermax : int, optional |
| 835 |
Max number of iterations |
| 836 |
stopThr : float, optional |
| 837 |
Stop threshold on error (>0) |
| 838 |
verbose : bool, optional |
| 839 |
Print information along iterations |
| 840 |
log : bool, optional |
| 841 |
record log if True |
| 842 |
numThreads: int or "max", optional (default=1, i.e. OpenMP is not used) |
| 843 |
If compiled with OpenMP, chooses the number of threads to parallelize. |
| 844 |
"max" selects the highest number possible. |
| 845 |
eps: Stability coefficient for the change of variable matrix inversion |
| 846 |
If the :math:`\mathbf{P}_i^T` matrices don't span :math:`\mathbb{R}^d`, the problem is ill-defined and a matrix |
| 847 |
inversion will fail. In this case one may set eps=1e-8 and get a solution anyway (which may make little sense) |
| 848 |
|
| 849 |
|
| 850 |
Returns |
| 851 |
------- |
| 852 |
Y : (n_samples_bary,d) array-like |
| 853 |
Support locations (on n_samples_bary atoms) of the barycenter |
| 854 |
|
| 855 |
|
| 856 |
.. _references-generalized-free-support-barycenter: |
| 857 |
References |
| 858 |
---------- |
| 859 |
.. [20] Cuturi, M. and Doucet, A.. "Fast computation of Wasserstein barycenters." International Conference on Machine Learning. 2014. |
| 860 |
|
| 861 |
.. [42] Delon, J., Gozlan, N., and Saint-Dizier, A.. Generalized Wasserstein barycenters between probability measures living on different subspaces. arXiv preprint arXiv:2105.09755, 2021. |
| 862 |
|
| 863 |
""" |
| 864 |
nx = get_backend(*X_list, *a_list, *P_list) |
| 865 |
d = P_list[0].shape[1] |
| 866 |
p = len(X_list) |
| 867 |
|
| 868 |
if weights is None: |
| 869 |
weights = nx.ones(p, type_as=X_list[0]) / p |
| 870 |
|
| 871 |
|
| 872 |
A = eps * nx.eye( |
| 873 |
d, type_as=X_list[0] |
| 874 |
) |
| 875 |
for P_i, lambda_i in zip(P_list, weights): |
| 876 |
A = A + lambda_i * P_i.T @ P_i |
| 877 |
B = nx.inv(nx.sqrtm(A)) |
| 878 |
|
| 879 |
Z_list = [ |
| 880 |
x @ Pi @ B.T for (x, Pi) in zip(X_list, P_list) |
| 881 |
] |
| 882 |
|
| 883 |
if Y_init is None: |
| 884 |
Y_init = nx.randn(n_samples_bary, d, type_as=X_list[0]) |
| 885 |
|
| 886 |
if b is None: |
| 887 |
b = nx.ones(n_samples_bary, type_as=X_list[0]) / n_samples_bary |
| 888 |
|
| 889 |
out = free_support_barycenter( |
| 890 |
Z_list, |
| 891 |
a_list, |
| 892 |
Y_init, |
| 893 |
b, |
| 894 |
numItermax=numItermax, |
| 895 |
stopThr=stopThr, |
| 896 |
verbose=verbose, |
| 897 |
log=log, |
| 898 |
numThreads=numThreads, |
| 899 |
) |
| 900 |
|
| 901 |
if log: |
| 902 |
Y, log_dict = out |
| 903 |
else: |
| 904 |
Y = out |
| 905 |
log_dict = None |
| 906 |
Y = Y @ B.T |
| 907 |
|
| 908 |
if log: |
| 909 |
return Y, log_dict |
| 910 |
else: |
| 911 |
return Y |