Debian Codegraph @

ot/lp/solver_1d.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Exact solvers for the 1D Wasserstein distance using cvxopt
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 # Author: Nicolas Courty <[email protected]>
8 #
9 # License: MIT License
10
11 import numpy as np
12 import warnings
13
14 from .emd_wrap import emd_1d_sorted
15 from ..backend import get_backend
16 from ..utils import list_to_array
17
18
19 def quantile_function(qs, cws, xs):
20 r"""Computes the quantile function of an empirical distribution
21
22 Parameters
23 ----------
24 qs: array-like, shape (n,)
25 Quantiles at which the quantile function is evaluated
26 cws: array-like, shape (m, ...)
27 cumulative weights of the 1D empirical distribution, if batched, must be similar to xs
28 xs: array-like, shape (n, ...)
29 locations of the 1D empirical distribution, batched against the `xs.ndim - 1` first dimensions
30
31 Returns
32 -------
33 q: array-like, shape (..., n)
34 The quantiles of the distribution
35 """
36 nx = get_backend(qs, cws)
37 n = xs.shape[0]
38 if nx.__name__ == "torch":
39 # this is to ensure the best performance for torch searchsorted
40 # and avoid a warning related to non-contiguous arrays
41 cws = cws.T.contiguous()
42 qs = qs.T.contiguous()
43 else:
44 cws = cws.T
45 qs = qs.T
46 idx = nx.searchsorted(cws, qs).T
47 return nx.take_along_axis(xs, nx.clip(idx, 0, n - 1), axis=0)
48
49
50 def wasserstein_1d(
51 u_values, v_values, u_weights=None, v_weights=None, p=1, require_sort=True
52 ):
53 r"""
54 Computes the 1 dimensional OT loss [15] between two (batched) empirical
55 distributions
56
57 .. math:
58 OT_{loss} = \int_0^1 |cdf_u^{-1}(q) - cdf_v^{-1}(q)|^p dq
59
60 It is formally the p-Wasserstein distance raised to the power p.
61 We do so in a vectorized way by first building the individual quantile functions then integrating them.
62
63 This function should be preferred to `emd_1d` whenever the backend is
64 different to numpy, and when gradients over
65 either sample positions or weights are required.
66
67 Parameters
68 ----------
69 u_values: array-like, shape (n, ...)
70 locations of the first empirical distribution
71 v_values: array-like, shape (m, ...)
72 locations of the second empirical distribution
73 u_weights: array-like, shape (n, ...), optional
74 weights of the first empirical distribution, if None then uniform weights are used
75 v_weights: array-like, shape (m, ...), optional
76 weights of the second empirical distribution, if None then uniform weights are used
77 p: int, optional
78 order of the ground metric used, should be at least 1 (see [2, Chap. 2], default is 1
79 require_sort: bool, optional
80 sort the distributions atoms locations, if False we will consider they have been sorted prior to being passed to
81 the function, default is True
82
83 Returns
84 -------
85 cost: float/array-like, shape (...)
86 the batched EMD
87
88 References
89 ----------
90 .. [15] Peyré, G., & Cuturi, M. (2018). Computational Optimal Transport.
91
92 """
93
94 assert p >= 1, "The OT loss is only valid for p>=1, {p} was given".format(p=p)
95
96 if u_weights is not None and v_weights is not None:
97 nx = get_backend(u_values, v_values, u_weights, v_weights)
98 else:
99 nx = get_backend(u_values, v_values)
100
101 n = u_values.shape[0]
102 m = v_values.shape[0]
103
104 if u_weights is None:
105 u_weights = nx.full(u_values.shape, 1.0 / n, type_as=u_values)
106 elif u_weights.ndim != u_values.ndim:
107 u_weights = nx.repeat(u_weights[..., None], u_values.shape[-1], -1)
108 if v_weights is None:
109 v_weights = nx.full(v_values.shape, 1.0 / m, type_as=v_values)
110 elif v_weights.ndim != v_values.ndim:
111 v_weights = nx.repeat(v_weights[..., None], v_values.shape[-1], -1)
112
113 if require_sort:
114 u_sorter = nx.argsort(u_values, 0)
115 u_values = nx.take_along_axis(u_values, u_sorter, 0)
116
117 v_sorter = nx.argsort(v_values, 0)
118 v_values = nx.take_along_axis(v_values, v_sorter, 0)
119
120 u_weights = nx.take_along_axis(u_weights, u_sorter, 0)
121 v_weights = nx.take_along_axis(v_weights, v_sorter, 0)
122
123 u_cumweights = nx.cumsum(u_weights, 0)
124 v_cumweights = nx.cumsum(v_weights, 0)
125
126 qs = nx.sort(nx.concatenate((u_cumweights, v_cumweights), 0), 0)
127 u_quantiles = quantile_function(qs, u_cumweights, u_values)
128 v_quantiles = quantile_function(qs, v_cumweights, v_values)
129 qs = nx.zero_pad(qs, pad_width=[(1, 0)] + (qs.ndim - 1) * [(0, 0)])
130 delta = qs[1:, ...] - qs[:-1, ...]
131 diff_quantiles = nx.abs(u_quantiles - v_quantiles)
132
133 if p == 1:
134 return nx.sum(delta * diff_quantiles, axis=0)
135 return nx.sum(delta * nx.power(diff_quantiles, p), axis=0)
136
137
138 def emd_1d(
139 x_a,
140 x_b,
141 a=None,
142 b=None,
143 metric="sqeuclidean",
144 p=1.0,
145 dense=True,
146 log=False,
147 check_marginals=True,
148 ):
149 r"""Solves the Earth Movers distance problem between 1d measures and returns
150 the OT matrix
151
152
153 .. math::
154 \gamma = arg\min_\gamma \sum_i \sum_j \gamma_{ij} d(x_a[i], x_b[j])
155
156 s.t. \gamma 1 = a,
157 \gamma^T 1= b,
158 \gamma\geq 0
159
160 where :
161
162 - d is the metric
163 - x_a and x_b are the samples
164 - a and b are the sample weights
165
166 This implementation only supports metrics
167 of the form :math:`d(x, y) = |x - y|^p`.
168
169 Uses the algorithm detailed in [1]_
170
171 Parameters
172 ----------
173 x_a : (ns,) or (ns, 1) ndarray, float64
174 Source dirac locations (on the real line)
175 x_b : (nt,) or (ns, 1) ndarray, float64
176 Target dirac locations (on the real line)
177 a : (ns,) ndarray, float64, optional
178 Source histogram (default is uniform weight)
179 b : (nt,) ndarray, float64, optional
180 Target histogram (default is uniform weight)
181 metric: str, optional (default='sqeuclidean')
182 Metric to be used. Only works with either of the strings
183 `'sqeuclidean'`, `'minkowski'`, `'cityblock'`, or `'euclidean'`.
184 p: float, optional (default=1.0)
185 The p-norm to apply for if metric='minkowski'
186 dense: boolean, optional (default=True)
187 If True, returns math:`\gamma` as a dense ndarray of shape (ns, nt).
188 Otherwise returns a sparse representation using scipy's `coo_matrix`
189 format. Due to implementation details, this function runs faster when
190 `'sqeuclidean'`, `'minkowski'`, `'cityblock'`, or `'euclidean'` metrics
191 are used.
192 log: boolean, optional (default=False)
193 If True, returns a dictionary containing the cost.
194 Otherwise returns only the optimal transportation matrix.
195 check_marginals: bool, optional (default=True)
196 If True, checks that the marginals mass are equal. If False, skips the
197 check.
198
199 Returns
200 -------
201 gamma: (ns, nt) ndarray
202 Optimal transportation matrix for the given parameters
203 log: dict
204 If input log is True, a dictionary containing the cost
205
206
207 Examples
208 --------
209
210 Simple example with obvious solution. The function emd_1d accepts lists and
211 performs automatic conversion to numpy arrays
212
213 >>> import ot
214 >>> a=[.5, .5]
215 >>> b=[.5, .5]
216 >>> x_a = [2., 0.]
217 >>> x_b = [0., 3.]
218 >>> ot.emd_1d(x_a, x_b, a, b)
219 array([[0. , 0.5],
220 [0.5, 0. ]])
221 >>> ot.emd_1d(x_a, x_b)
222 array([[0. , 0.5],
223 [0.5, 0. ]])
224
225 References
226 ----------
227
228 .. [1] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
229 Transport", 2018.
230
231 See Also
232 --------
233 ot.lp.emd : EMD for multidimensional distributions
234 ot.lp.emd2_1d : EMD for 1d distributions (returns cost instead of the
235 transportation matrix)
236 """
237 x_a, x_b = list_to_array(x_a, x_b)
238 nx = get_backend(x_a, x_b)
239 if a is not None:
240 a = list_to_array(a, nx=nx)
241 if b is not None:
242 b = list_to_array(b, nx=nx)
243
244 assert (
245 x_a.ndim == 1 or x_a.ndim == 2 and x_a.shape[1] == 1
246 ), "emd_1d should only be used with monodimensional data"
247 assert (
248 x_b.ndim == 1 or x_b.ndim == 2 and x_b.shape[1] == 1
249 ), "emd_1d should only be used with monodimensional data"
250 if metric not in ["sqeuclidean", "minkowski", "cityblock", "euclidean"]:
251 raise ValueError(
252 "Solver for EMD in 1d only supports metrics "
253 + "from the following list: "
254 + "`['sqeuclidean', 'minkowski', 'cityblock', 'euclidean']`"
255 )
256
257 # if empty array given then use uniform distributions
258 if a is None or a.ndim == 0 or len(a) == 0:
259 a = nx.ones((x_a.shape[0],), type_as=x_a) / x_a.shape[0]
260 if b is None or b.ndim == 0 or len(b) == 0:
261 b = nx.ones((x_b.shape[0],), type_as=x_b) / x_b.shape[0]
262
263 # ensure that same mass
264 if check_marginals:
265 np.testing.assert_almost_equal(
266 nx.to_numpy(nx.sum(a, axis=0)),
267 nx.to_numpy(nx.sum(b, axis=0)),
268 err_msg="a and b vector must have the same sum",
269 decimal=6,
270 )
271 b = b * nx.sum(a) / nx.sum(b)
272
273 x_a_1d = nx.reshape(x_a, (-1,))
274 x_b_1d = nx.reshape(x_b, (-1,))
275 perm_a = nx.argsort(x_a_1d)
276 perm_b = nx.argsort(x_b_1d)
277
278 G_sorted, indices, cost = emd_1d_sorted(
279 nx.to_numpy(a[perm_a]).astype(np.float64),
280 nx.to_numpy(b[perm_b]).astype(np.float64),
281 nx.to_numpy(x_a_1d[perm_a]).astype(np.float64),
282 nx.to_numpy(x_b_1d[perm_b]).astype(np.float64),
283 metric=metric,
284 p=p,
285 )
286
287 G = nx.coo_matrix(
288 G_sorted,
289 perm_a[indices[:, 0]],
290 perm_b[indices[:, 1]],
291 shape=(a.shape[0], b.shape[0]),
292 type_as=x_a,
293 )
294 if dense:
295 G = nx.todense(G)
296 elif str(nx) == "jax":
297 warnings.warn("JAX does not support sparse matrices, converting to dense")
298 if log:
299 log = {"cost": nx.from_numpy(cost, type_as=x_a)}
300 return G, log
301 return G
302
303
304 def emd2_1d(
305 x_a, x_b, a=None, b=None, metric="sqeuclidean", p=1.0, dense=True, log=False
306 ):
307 r"""Solves the Earth Movers distance problem between 1d measures and returns
308 the loss
309
310
311 .. math::
312 \gamma = arg\min_\gamma \sum_i \sum_j \gamma_{ij} d(x_a[i], x_b[j])
313
314 s.t. \gamma 1 = a,
315 \gamma^T 1= b,
316 \gamma\geq 0
317
318 where :
319
320 - d is the metric
321 - x_a and x_b are the samples
322 - a and b are the sample weights
323
324 This implementation only supports metrics
325 of the form :math:`d(x, y) = |x - y|^p`.
326
327 Uses the algorithm detailed in [1]_
328
329 Parameters
330 ----------
331 x_a : (ns,) or (ns, 1) ndarray, float64
332 Source dirac locations (on the real line)
333 x_b : (nt,) or (ns, 1) ndarray, float64
334 Target dirac locations (on the real line)
335 a : (ns,) ndarray, float64, optional
336 Source histogram (default is uniform weight)
337 b : (nt,) ndarray, float64, optional
338 Target histogram (default is uniform weight)
339 metric: str, optional (default='sqeuclidean')
340 Metric to be used. Only works with either of the strings
341 `'sqeuclidean'`, `'minkowski'`, `'cityblock'`, or `'euclidean'`.
342 p: float, optional (default=1.0)
343 The p-norm to apply for if metric='minkowski'
344 dense: boolean, optional (default=True)
345 If True, returns math:`\gamma` as a dense ndarray of shape (ns, nt).
346 Otherwise returns a sparse representation using scipy's `coo_matrix`
347 format. Only used if log is set to True. Due to implementation details,
348 this function runs faster when dense is set to False.
349 log: boolean, optional (default=False)
350 If True, returns a dictionary containing the transportation matrix.
351 Otherwise returns only the loss.
352
353 Returns
354 -------
355 loss: float
356 Cost associated to the optimal transportation
357 log: dict
358 If input log is True, a dictionary containing the Optimal transportation
359 matrix for the given parameters
360
361
362 Examples
363 --------
364
365 Simple example with obvious solution. The function emd2_1d accepts lists and
366 performs automatic conversion to numpy arrays
367
368 >>> import ot
369 >>> a=[.5, .5]
370 >>> b=[.5, .5]
371 >>> x_a = [2., 0.]
372 >>> x_b = [0., 3.]
373 >>> ot.emd2_1d(x_a, x_b, a, b)
374 0.5
375 >>> ot.emd2_1d(x_a, x_b)
376 0.5
377
378 References
379 ----------
380
381 .. [1] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
382 Transport", 2018.
383
384 See Also
385 --------
386 ot.lp.emd2 : EMD for multidimensional distributions
387 ot.lp.emd_1d : EMD for 1d distributions (returns the transportation matrix
388 instead of the cost)
389 """
390 # If we do not return G (log==False), then we should not to cast it to dense
391 # (useless overhead)
392 G, log_emd = emd_1d(
393 x_a=x_a, x_b=x_b, a=a, b=b, metric=metric, p=p, dense=dense and log, log=True
394 )
395 cost = log_emd["cost"]
396 if log:
397 log_emd = {"G": G}
398 return cost, log_emd
399 return cost
400
401
402 def roll_cols(M, shifts):
403 r"""
404 Utils functions which allow to shift the order of each row of a 2d matrix
405
406 Parameters
407 ----------
408 M : (nr, nc) ndarray
409 Matrix to shift
410 shifts: int or (nr,) ndarray
411
412 Returns
413 -------
414 Shifted array
415
416 Examples
417 --------
418 >>> M = np.array([[1,2,3],[4,5,6],[7,8,9]])
419 >>> roll_cols(M, 2)
420 array([[2, 3, 1],
421 [5, 6, 4],
422 [8, 9, 7]])
423 >>> roll_cols(M, np.array([[1],[2],[1]]))
424 array([[3, 1, 2],
425 [5, 6, 4],
426 [9, 7, 8]])
427
428 References
429 ----------
430 https://stackoverflow.com/questions/66596699/how-to-shift-columns-or-rows-in-a-tensor-with-different-offsets-in-pytorch
431 """
432 nx = get_backend(M)
433
434 n_rows, n_cols = M.shape
435
436 arange1 = nx.tile(
437 nx.reshape(nx.arange(n_cols, type_as=shifts), (1, n_cols)), (n_rows, 1)
438 )
439 arange2 = (arange1 - shifts) % n_cols
440
441 return nx.take_along_axis(M, arange2, 1)
442
443
444 def derivative_cost_on_circle(theta, u_values, v_values, u_cdf, v_cdf, p=2):
445 r"""Computes the left and right derivative of the cost (Equation (6.3) and (6.4) of [1])
446
447 Parameters
448 ----------
449 theta: array-like, shape (n_batch, n)
450 Cuts on the circle
451 u_values: array-like, shape (n_batch, n)
452 locations of the first empirical distribution
453 v_values: array-like, shape (n_batch, n)
454 locations of the second empirical distribution
455 u_cdf: array-like, shape (n_batch, n)
456 cdf of the first empirical distribution
457 v_cdf: array-like, shape (n_batch, n)
458 cdf of the second empirical distribution
459 p: float, optional = 2
460 Power p used for computing the Wasserstein distance
461
462 Returns
463 -------
464 dCp: array-like, shape (n_batch, 1)
465 The batched right derivative
466 dCm: array-like, shape (n_batch, 1)
467 The batched left derivative
468
469 References
470 ---------
471 .. [44] Delon, Julie, Julien Salomon, and Andrei Sobolevski. "Fast transport optimization for Monge costs on the circle." SIAM Journal on Applied Mathematics 70.7 (2010): 2239-2258.
472 """
473 nx = get_backend(theta, u_values, v_values, u_cdf, v_cdf)
474
475 v_values = nx.copy(v_values)
476
477 n = u_values.shape[-1]
478 m_batch, m = v_values.shape
479
480 v_cdf_theta = v_cdf - (theta - nx.floor(theta))
481
482 mask_p = v_cdf_theta >= 0
483 mask_n = v_cdf_theta < 0
484
485 v_values[mask_n] += nx.floor(theta)[mask_n] + 1
486 v_values[mask_p] += nx.floor(theta)[mask_p]
487
488 if nx.any(mask_n) and nx.any(mask_p):
489 v_cdf_theta[mask_n] += 1
490
491 v_cdf_theta2 = nx.copy(v_cdf_theta)
492 v_cdf_theta2[mask_n] = np.inf
493 shift = -nx.argmin(v_cdf_theta2, axis=-1)
494
495 v_cdf_theta = roll_cols(v_cdf_theta, nx.reshape(shift, (-1, 1)))
496 v_values = roll_cols(v_values, nx.reshape(shift, (-1, 1)))
497 v_values = nx.concatenate(
498 [v_values, nx.reshape(v_values[:, 0], (-1, 1)) + 1], axis=1
499 )
500
501 if nx.__name__ == "torch":
502 # this is to ensure the best performance for torch searchsorted
503 # and avoid a warning related to non-contiguous arrays
504 u_cdf = u_cdf.contiguous()
505 v_cdf_theta = v_cdf_theta.contiguous()
506
507 # quantiles of F_u evaluated in F_v^\theta
508 u_index = nx.searchsorted(u_cdf, v_cdf_theta)
509 u_icdf_theta = nx.take_along_axis(u_values, nx.clip(u_index, 0, n - 1), -1)
510
511 # Deal with 1
512 u_cdfm = nx.concatenate([u_cdf, nx.reshape(u_cdf[:, 0], (-1, 1)) + 1], axis=1)
513 u_valuesm = nx.concatenate(
514 [u_values, nx.reshape(u_values[:, 0], (-1, 1)) + 1], axis=1
515 )
516
517 if nx.__name__ == "torch":
518 # this is to ensure the best performance for torch searchsorted
519 # and avoid a warning related to non-contiguous arrays
520 u_cdfm = u_cdfm.contiguous()
521 v_cdf_theta = v_cdf_theta.contiguous()
522
523 u_indexm = nx.searchsorted(u_cdfm, v_cdf_theta, side="right")
524 u_icdfm_theta = nx.take_along_axis(u_valuesm, nx.clip(u_indexm, 0, n), -1)
525
526 dCp = nx.sum(
527 nx.power(nx.abs(u_icdf_theta - v_values[:, 1:]), p)
528 - nx.power(nx.abs(u_icdf_theta - v_values[:, :-1]), p),
529 axis=-1,
530 )
531
532 dCm = nx.sum(
533 nx.power(nx.abs(u_icdfm_theta - v_values[:, 1:]), p)
534 - nx.power(nx.abs(u_icdfm_theta - v_values[:, :-1]), p),
535 axis=-1,
536 )
537
538 return dCp.reshape(-1, 1), dCm.reshape(-1, 1)
539
540
541 def ot_cost_on_circle(theta, u_values, v_values, u_cdf, v_cdf, p):
542 r"""Computes the the cost (Equation (6.2) of [1])
543
544 Parameters
545 ----------
546 theta: array-like, shape (n_batch, n)
547 Cuts on the circle
548 u_values: array-like, shape (n_batch, n)
549 locations of the first empirical distribution
550 v_values: array-like, shape (n_batch, n)
551 locations of the second empirical distribution
552 u_cdf: array-like, shape (n_batch, n)
553 cdf of the first empirical distribution
554 v_cdf: array-like, shape (n_batch, n)
555 cdf of the second empirical distribution
556 p: float, optional = 2
557 Power p used for computing the Wasserstein distance
558
559 Returns
560 -------
561 ot_cost: array-like, shape (n_batch,)
562 OT cost evaluated at theta
563
564 References
565 ---------
566 .. [44] Delon, Julie, Julien Salomon, and Andrei Sobolevski. "Fast transport optimization for Monge costs on the circle." SIAM Journal on Applied Mathematics 70.7 (2010): 2239-2258.
567 """
568 nx = get_backend(theta, u_values, v_values, u_cdf, v_cdf)
569
570 v_values = nx.copy(v_values)
571
572 m_batch, m = v_values.shape
573 n_batch, n = u_values.shape
574
575 v_cdf_theta = v_cdf - (theta - nx.floor(theta))
576
577 mask_p = v_cdf_theta >= 0
578 mask_n = v_cdf_theta < 0
579
580 v_values[mask_n] += nx.floor(theta)[mask_n] + 1
581 v_values[mask_p] += nx.floor(theta)[mask_p]
582
583 if nx.any(mask_n) and nx.any(mask_p):
584 v_cdf_theta[mask_n] += 1
585
586 # Put negative values at the end
587 v_cdf_theta2 = nx.copy(v_cdf_theta)
588 v_cdf_theta2[mask_n] = np.inf
589 shift = -nx.argmin(v_cdf_theta2, axis=-1)
590
591 v_cdf_theta = roll_cols(v_cdf_theta, nx.reshape(shift, (-1, 1)))
592 v_values = roll_cols(v_values, nx.reshape(shift, (-1, 1)))
593 v_values = nx.concatenate(
594 [v_values, nx.reshape(v_values[:, 0], (-1, 1)) + 1], axis=1
595 )
596
597 # Compute absciss
598 cdf_axis = nx.sort(nx.concatenate((u_cdf, v_cdf_theta), -1), -1)
599 cdf_axis_pad = nx.zero_pad(cdf_axis, pad_width=[(0, 0), (1, 0)])
600
601 delta = cdf_axis_pad[..., 1:] - cdf_axis_pad[..., :-1]
602
603 if nx.__name__ == "torch":
604 # this is to ensure the best performance for torch searchsorted
605 # and avoid a warning related to non-contiguous arrays
606 u_cdf = u_cdf.contiguous()
607 v_cdf_theta = v_cdf_theta.contiguous()
608 cdf_axis = cdf_axis.contiguous()
609
610 # Compute icdf
611 u_index = nx.searchsorted(u_cdf, cdf_axis)
612 u_icdf = nx.take_along_axis(u_values, u_index.clip(0, n - 1), -1)
613
614 v_values = nx.concatenate(
615 [v_values, nx.reshape(v_values[:, 0], (-1, 1)) + 1], axis=1
616 )
617 v_index = nx.searchsorted(v_cdf_theta, cdf_axis)
618 v_icdf = nx.take_along_axis(v_values, v_index.clip(0, m), -1)
619
620 if p == 1:
621 ot_cost = nx.sum(delta * nx.abs(u_icdf - v_icdf), axis=-1)
622 else:
623 ot_cost = nx.sum(delta * nx.power(nx.abs(u_icdf - v_icdf), p), axis=-1)
624
625 return ot_cost
626
627
628 def binary_search_circle(
629 u_values,
630 v_values,
631 u_weights=None,
632 v_weights=None,
633 p=1,
634 Lm=10,
635 Lp=10,
636 tm=-1,
637 tp=1,
638 eps=1e-6,
639 require_sort=True,
640 log=False,
641 ):
642 r"""Computes the Wasserstein distance on the circle using the Binary search algorithm proposed in [44].
643 Samples need to be in :math:`S^1\cong [0,1[`. If they are on :math:`\mathbb{R}`,
644 takes the value modulo 1.
645 If the values are on :math:`S^1\subset\mathbb{R}^2`, it is required to first find the coordinates
646 using e.g. the atan2 function.
647
648 .. math::
649 W_p^p(u,v) = \inf_{\theta\in\mathbb{R}}\int_0^1 |F_u^{-1}(q) - (F_v-\theta)^{-1}(q)|^p\ \mathrm{d}q
650
651 where:
652
653 - :math:`F_u` and :math:`F_v` are respectively the cdfs of :math:`u` and :math:`v`
654
655 For values :math:`x=(x_1,x_2)\in S^1`, it is required to first get their coordinates with
656
657 .. math::
658 u = \frac{\pi + \mathrm{atan2}(-x_2,-x_1)}{2\pi}
659
660 using e.g. ot.utils.get_coordinate_circle(x)
661
662 The function runs on backend but tensorflow and jax are not supported.
663
664 Parameters
665 ----------
666 u_values : ndarray, shape (n, ...)
667 samples in the source domain (coordinates on [0,1[)
668 v_values : ndarray, shape (n, ...)
669 samples in the target domain (coordinates on [0,1[)
670 u_weights : ndarray, shape (n, ...), optional
671 samples weights in the source domain
672 v_weights : ndarray, shape (n, ...), optional
673 samples weights in the target domain
674 p : float, optional (default=1)
675 Power p used for computing the Wasserstein distance
676 Lm : int, optional
677 Lower bound dC
678 Lp : int, optional
679 Upper bound dC
680 tm: float, optional
681 Lower bound theta
682 tp: float, optional
683 Upper bound theta
684 eps: float, optional
685 Stopping condition
686 require_sort: bool, optional
687 If True, sort the values.
688 log: bool, optional
689 If True, returns also the optimal theta
690
691 Returns
692 -------
693 loss: float
694 Cost associated to the optimal transportation
695 log: dict, optional
696 log dictionary returned only if log==True in parameters
697
698 Examples
699 --------
700 >>> u = np.array([[0.2,0.5,0.8]])%1
701 >>> v = np.array([[0.4,0.5,0.7]])%1
702 >>> binary_search_circle(u.T, v.T, p=1)
703 array([0.1])
704
705 References
706 ----------
707 .. [44] Delon, Julie, Julien Salomon, and Andrei Sobolevski. "Fast transport optimization for Monge costs on the circle." SIAM Journal on Applied Mathematics 70.7 (2010): 2239-2258.
708 .. Matlab Code: https://users.mccme.ru/ansobol/otarie/software.html
709 """
710 assert p >= 1, "The OT loss is only valid for p>=1, {p} was given".format(p=p)
711
712 if u_weights is not None and v_weights is not None:
713 nx = get_backend(u_values, v_values, u_weights, v_weights)
714 else:
715 nx = get_backend(u_values, v_values)
716
717 n = u_values.shape[0]
718 m = v_values.shape[0]
719
720 if len(u_values.shape) == 1:
721 u_values = nx.reshape(u_values, (n, 1))
722 if len(v_values.shape) == 1:
723 v_values = nx.reshape(v_values, (m, 1))
724
725 if u_values.shape[1] != v_values.shape[1]:
726 raise ValueError(
727 "u and v must have the same number of batches {} and {} respectively given".format(
728 u_values.shape[1], v_values.shape[1]
729 )
730 )
731
732 u_values = u_values % 1
733 v_values = v_values % 1
734
735 if u_weights is None:
736 u_weights = nx.full(u_values.shape, 1.0 / n, type_as=u_values)
737 elif u_weights.ndim != u_values.ndim:
738 u_weights = nx.repeat(u_weights[..., None], u_values.shape[-1], -1)
739 if v_weights is None:
740 v_weights = nx.full(v_values.shape, 1.0 / m, type_as=v_values)
741 elif v_weights.ndim != v_values.ndim:
742 v_weights = nx.repeat(v_weights[..., None], v_values.shape[-1], -1)
743
744 if require_sort:
745 u_sorter = nx.argsort(u_values, 0)
746 u_values = nx.take_along_axis(u_values, u_sorter, 0)
747
748 v_sorter = nx.argsort(v_values, 0)
749 v_values = nx.take_along_axis(v_values, v_sorter, 0)
750
751 u_weights = nx.take_along_axis(u_weights, u_sorter, 0)
752 v_weights = nx.take_along_axis(v_weights, v_sorter, 0)
753
754 u_cdf = nx.cumsum(u_weights, 0).T
755 v_cdf = nx.cumsum(v_weights, 0).T
756
757 u_values = u_values.T
758 v_values = v_values.T
759
760 L = max(Lm, Lp)
761
762 tm = tm * nx.reshape(nx.ones((u_values.shape[0],), type_as=u_values), (-1, 1))
763 tm = nx.tile(tm, (1, m))
764 tp = tp * nx.reshape(nx.ones((u_values.shape[0],), type_as=u_values), (-1, 1))
765 tp = nx.tile(tp, (1, m))
766 tc = (tm + tp) / 2
767
768 done = nx.zeros((u_values.shape[0], m))
769
770 cpt = 0
771 while nx.any(1 - done):
772 cpt += 1
773
774 dCp, dCm = derivative_cost_on_circle(tc, u_values, v_values, u_cdf, v_cdf, p)
775 done = ((dCp * dCm) <= 0) * 1
776
777 mask = ((tp - tm) < eps / L) * (1 - done)
778
779 if nx.any(mask):
780 # can probably be improved by computing only relevant values
781 dCptp, dCmtp = derivative_cost_on_circle(
782 tp, u_values, v_values, u_cdf, v_cdf, p
783 )
784 dCptm, dCmtm = derivative_cost_on_circle(
785 tm, u_values, v_values, u_cdf, v_cdf, p
786 )
787 Ctm = ot_cost_on_circle(tm, u_values, v_values, u_cdf, v_cdf, p).reshape(
788 -1, 1
789 )
790 Ctp = ot_cost_on_circle(tp, u_values, v_values, u_cdf, v_cdf, p).reshape(
791 -1, 1
792 )
793
794 mask_end = mask * (nx.abs(dCptm - dCmtp) > 0.001)
795 tc[mask_end > 0] = (
796 (Ctp - Ctm + tm * dCptm - tp * dCmtp) / (dCptm - dCmtp)
797 )[mask_end > 0]
798 done[nx.prod(mask, axis=-1) > 0] = 1
799 elif nx.any(1 - done):
800 tm[((1 - mask) * (dCp < 0)) > 0] = tc[((1 - mask) * (dCp < 0)) > 0]
801 tp[((1 - mask) * (dCp >= 0)) > 0] = tc[((1 - mask) * (dCp >= 0)) > 0]
802 tc[((1 - mask) * (1 - done)) > 0] = (
803 tm[((1 - mask) * (1 - done)) > 0] + tp[((1 - mask) * (1 - done)) > 0]
804 ) / 2
805
806 w = ot_cost_on_circle(nx.detach(tc), u_values, v_values, u_cdf, v_cdf, p)
807
808 if log:
809 return w, {"optimal_theta": tc[:, 0]}
810 return w
811
812
813 def wasserstein1_circle(
814 u_values, v_values, u_weights=None, v_weights=None, require_sort=True
815 ):
816 r"""Computes the 1-Wasserstein distance on the circle using the level median [45].
817 Samples need to be in :math:`S^1\cong [0,1[`. If they are on :math:`\mathbb{R}`,
818 takes the value modulo 1.
819 If the values are on :math:`S^1\subset\mathbb{R}^2`, first find the coordinates
820 using e.g. the atan2 function.
821 The function runs on backend but tensorflow and jax are not supported.
822
823 .. math::
824 W_1(u,v) = \int_0^1 |F_u(t)-F_v(t)-LevMed(F_u-F_v)|\ \mathrm{d}t
825
826 Parameters
827 ----------
828 u_values : ndarray, shape (n, ...)
829 samples in the source domain (coordinates on [0,1[)
830 v_values : ndarray, shape (n, ...)
831 samples in the target domain (coordinates on [0,1[)
832 u_weights : ndarray, shape (n, ...), optional
833 samples weights in the source domain
834 v_weights : ndarray, shape (n, ...), optional
835 samples weights in the target domain
836 require_sort: bool, optional
837 If True, sort the values.
838
839 Returns
840 -------
841 loss: float
842 Cost associated to the optimal transportation
843
844 Examples
845 --------
846 >>> u = np.array([[0.2,0.5,0.8]])%1
847 >>> v = np.array([[0.4,0.5,0.7]])%1
848 >>> wasserstein1_circle(u.T, v.T)
849 array([0.1])
850
851 References
852 ----------
853 .. [45] Hundrieser, Shayan, Marcel Klatt, and Axel Munk. "The statistics of circular optimal transport." Directional Statistics for Innovative Applications: A Bicentennial Tribute to Florence Nightingale. Singapore: Springer Nature Singapore, 2022. 57-82.
854 .. Code R: https://gitlab.gwdg.de/shundri/circularOT/-/tree/master/
855 """
856
857 if u_weights is not None and v_weights is not None:
858 nx = get_backend(u_values, v_values, u_weights, v_weights)
859 else:
860 nx = get_backend(u_values, v_values)
861
862 n = u_values.shape[0]
863 m = v_values.shape[0]
864
865 if len(u_values.shape) == 1:
866 u_values = nx.reshape(u_values, (n, 1))
867 if len(v_values.shape) == 1:
868 v_values = nx.reshape(v_values, (m, 1))
869
870 if u_values.shape[1] != v_values.shape[1]:
871 raise ValueError(
872 "u and v must have the same number of batchs {} and {} respectively given".format(
873 u_values.shape[1], v_values.shape[1]
874 )
875 )
876
877 u_values = u_values % 1
878 v_values = v_values % 1
879
880 if u_weights is None:
881 u_weights = nx.full(u_values.shape, 1.0 / n, type_as=u_values)
882 elif u_weights.ndim != u_values.ndim:
883 u_weights = nx.repeat(u_weights[..., None], u_values.shape[-1], -1)
884 if v_weights is None:
885 v_weights = nx.full(v_values.shape, 1.0 / m, type_as=v_values)
886 elif v_weights.ndim != v_values.ndim:
887 v_weights = nx.repeat(v_weights[..., None], v_values.shape[-1], -1)
888
889 if require_sort:
890 u_sorter = nx.argsort(u_values, 0)
891 u_values = nx.take_along_axis(u_values, u_sorter, 0)
892
893 v_sorter = nx.argsort(v_values, 0)
894 v_values = nx.take_along_axis(v_values, v_sorter, 0)
895
896 u_weights = nx.take_along_axis(u_weights, u_sorter, 0)
897 v_weights = nx.take_along_axis(v_weights, v_sorter, 0)
898
899 # Code inspired from https://gitlab.gwdg.de/shundri/circularOT/-/tree/master/
900 values_sorted, values_sorter = nx.sort2(nx.concatenate((u_values, v_values), 0), 0)
901
902 cdf_diff = nx.cumsum(
903 nx.take_along_axis(
904 nx.concatenate((u_weights, -v_weights), 0), values_sorter, 0
905 ),
906 0,
907 )
908 cdf_diff_sorted, cdf_diff_sorter = nx.sort2(cdf_diff, axis=0)
909
910 values_sorted = nx.zero_pad(values_sorted, pad_width=[(0, 1), (0, 0)], value=1)
911 delta = values_sorted[1:, ...] - values_sorted[:-1, ...]
912 weight_sorted = nx.take_along_axis(delta, cdf_diff_sorter, 0)
913
914 sum_weights = nx.cumsum(weight_sorted, axis=0) - 0.5
915 sum_weights[sum_weights < 0] = np.inf
916 inds = nx.argmin(sum_weights, axis=0)
917
918 levMed = nx.take_along_axis(cdf_diff_sorted, nx.reshape(inds, (1, -1)), 0)
919
920 return nx.sum(delta * nx.abs(cdf_diff - levMed), axis=0)
921
922
923 def wasserstein_circle(
924 u_values,
925 v_values,
926 u_weights=None,
927 v_weights=None,
928 p=1,
929 Lm=10,
930 Lp=10,
931 tm=-1,
932 tp=1,
933 eps=1e-6,
934 require_sort=True,
935 ):
936 r"""Computes the Wasserstein distance on the circle using either [45] for p=1 or
937 the binary search algorithm proposed in [44] otherwise.
938 Samples need to be in :math:`S^1\cong [0,1[`. If they are on :math:`\mathbb{R}`,
939 takes the value modulo 1.
940 If the values are on :math:`S^1\subset\mathbb{R}^2`, it requires to first find the coordinates
941 using e.g. the atan2 function.
942
943 General loss returned:
944
945 .. math::
946 OT_{loss} = \inf_{\theta\in\mathbb{R}}\int_0^1 |cdf_u^{-1}(q) - (cdf_v-\theta)^{-1}(q)|^p\ \mathrm{d}q
947
948 For p=1, [45]
949
950 .. math::
951 W_1(u,v) = \int_0^1 |F_u(t)-F_v(t)-LevMed(F_u-F_v)|\ \mathrm{d}t
952
953 For values :math:`x=(x_1,x_2)\in S^1`, it is required to first get their coordinates with
954
955 .. math::
956 u = \frac{\pi + \mathrm{atan2}(-x_2,-x_1)}{2\pi}
957
958 using e.g. ot.utils.get_coordinate_circle(x)
959
960 The function runs on backend but tensorflow and jax are not supported.
961
962 Parameters
963 ----------
964 u_values : ndarray, shape (n, ...)
965 samples in the source domain (coordinates on [0,1[)
966 v_values : ndarray, shape (n, ...)
967 samples in the target domain (coordinates on [0,1[)
968 u_weights : ndarray, shape (n, ...), optional
969 samples weights in the source domain
970 v_weights : ndarray, shape (n, ...), optional
971 samples weights in the target domain
972 p : float, optional (default=1)
973 Power p used for computing the Wasserstein distance
974 Lm : int, optional
975 Lower bound dC. For p>1.
976 Lp : int, optional
977 Upper bound dC. For p>1.
978 tm: float, optional
979 Lower bound theta. For p>1.
980 tp: float, optional
981 Upper bound theta. For p>1.
982 eps: float, optional
983 Stopping condition. For p>1.
984 require_sort: bool, optional
985 If True, sort the values.
986
987 Returns
988 -------
989 loss: float
990 Cost associated to the optimal transportation
991
992 Examples
993 --------
994 >>> u = np.array([[0.2,0.5,0.8]])%1
995 >>> v = np.array([[0.4,0.5,0.7]])%1
996 >>> wasserstein_circle(u.T, v.T)
997 array([0.1])
998
999 References
1000 ----------
1001 .. [44] Hundrieser, Shayan, Marcel Klatt, and Axel Munk. "The statistics of circular optimal transport." Directional Statistics for Innovative Applications: A Bicentennial Tribute to Florence Nightingale. Singapore: Springer Nature Singapore, 2022. 57-82.
1002 .. [45] Delon, Julie, Julien Salomon, and Andrei Sobolevski. "Fast transport optimization for Monge costs on the circle." SIAM Journal on Applied Mathematics 70.7 (2010): 2239-2258.
1003 """
1004 assert p >= 1, "The OT loss is only valid for p>=1, {p} was given".format(p=p)
1005
1006 if p == 1:
1007 return wasserstein1_circle(
1008 u_values, v_values, u_weights, v_weights, require_sort
1009 )
1010
1011 return binary_search_circle(
1012 u_values,
1013 v_values,
1014 u_weights,
1015 v_weights,
1016 p=p,
1017 Lm=Lm,
1018 Lp=Lp,
1019 tm=tm,
1020 tp=tp,
1021 eps=eps,
1022 require_sort=require_sort,
1023 )
1024
1025
1026 def semidiscrete_wasserstein2_unif_circle(u_values, u_weights=None):
1027 r"""Computes the closed-form for the 2-Wasserstein distance between samples and a uniform distribution on :math:`S^1`
1028 Samples need to be in :math:`S^1\cong [0,1[`. If they are on :math:`\mathbb{R}`,
1029 takes the value modulo 1.
1030 If the values are on :math:`S^1\subset\mathbb{R}^2`, it is required to first find the coordinates
1031 using e.g. the atan2 function.
1032
1033 .. math::
1034 W_2^2(\mu_n, \nu) = \sum_{i=1}^n \alpha_i x_i^2 - \left(\sum_{i=1}^n \alpha_i x_i\right)^2 + \sum_{i=1}^n \alpha_i x_i \left(1-\alpha_i-2\sum_{k=1}^{i-1}\alpha_k\right) + \frac{1}{12}
1035
1036 where:
1037
1038 - :math:`\nu=\mathrm{Unif}(S^1)` and :math:`\mu_n = \sum_{i=1}^n \alpha_i \delta_{x_i}`
1039
1040 For values :math:`x=(x_1,x_2)\in S^1`, it is required to first get their coordinates with
1041
1042 .. math::
1043 u = \frac{\pi + \mathrm{atan2}(-x_2,-x_1)}{2\pi},
1044
1045 using e.g. ot.utils.get_coordinate_circle(x)
1046
1047 Parameters
1048 ----------
1049 u_values: ndarray, shape (n, ...)
1050 Samples
1051 u_weights : ndarray, shape (n, ...), optional
1052 samples weights in the source domain
1053
1054 Returns
1055 -------
1056 loss: float
1057 Cost associated to the optimal transportation
1058
1059 Examples
1060 --------
1061 >>> x0 = np.array([[0], [0.2], [0.4]])
1062 >>> semidiscrete_wasserstein2_unif_circle(x0)
1063 array([0.02111111])
1064
1065 References
1066 ----------
1067 .. [46] Bonet, C., Berg, P., Courty, N., Septier, F., Drumetz, L., & Pham, M. T. (2023). Spherical sliced-wasserstein. International Conference on Learning Representations.
1068 """
1069
1070 if u_weights is not None:
1071 nx = get_backend(u_values, u_weights)
1072 else:
1073 nx = get_backend(u_values)
1074
1075 n = u_values.shape[0]
1076
1077 u_values = u_values % 1
1078
1079 if len(u_values.shape) == 1:
1080 u_values = nx.reshape(u_values, (n, 1))
1081
1082 if u_weights is None:
1083 u_weights = nx.full(u_values.shape, 1.0 / n, type_as=u_values)
1084 elif u_weights.ndim != u_values.ndim:
1085 u_weights = nx.repeat(u_weights[..., None], u_values.shape[-1], -1)
1086
1087 u_values = nx.sort(u_values, 0)
1088 u_cdf = nx.cumsum(u_weights, 0)
1089 u_cdf = nx.zero_pad(u_cdf, [(1, 0), (0, 0)])
1090
1091 cpt1 = nx.sum(u_weights * u_values**2, axis=0)
1092 u_mean = nx.sum(u_weights * u_values, axis=0)
1093
1094 ns = 1 - u_weights - 2 * u_cdf[:-1]
1095 cpt2 = nx.sum(u_values * u_weights * ns, axis=0)
1096
1097 return cpt1 - u_mean**2 + cpt2 + 1 / 12