Debian Codegraph @

ot/utils.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Various useful functions
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 #
8 # License: MIT License
9
10 from functools import reduce
11 import time
12
13 import numpy as np
14 from scipy.spatial.distance import cdist
15 import sys
16 import warnings
17 from inspect import signature
18 from .backend import get_backend, Backend, NumpyBackend, JaxBackend
19
20 __time_tic_toc = time.time()
21
22
23 def tic():
24 r"""Python implementation of Matlab tic() function"""
25 global __time_tic_toc
26 __time_tic_toc = time.time()
27
28
29 def toc(message="Elapsed time : {} s"):
30 r"""Python implementation of Matlab toc() function"""
31 t = time.time()
32 print(message.format(t - __time_tic_toc))
33 return t - __time_tic_toc
34
35
36 def toq():
37 r"""Python implementation of Julia toc() function"""
38 t = time.time()
39 return t - __time_tic_toc
40
41
42 def kernel(x1, x2, method="gaussian", sigma=1, **kwargs):
43 r"""Compute kernel matrix"""
44
45 nx = get_backend(x1, x2)
46
47 if method.lower() in ["gaussian", "gauss", "rbf"]:
48 K = nx.exp(-dist(x1, x2) / (2 * sigma**2))
49 return K
50
51
52 def laplacian(x):
53 r"""Compute Laplacian matrix"""
54 nx = get_backend(x)
55 L = nx.diag(nx.sum(x, axis=0)) - x
56 return L
57
58
59 def list_to_array(*lst, nx=None):
60 r"""Convert a list if in numpy format"""
61 lst_not_empty = [a for a in lst if len(a) > 0 and not isinstance(a, list)]
62 if nx is None: # find backend
63 if len(lst_not_empty) == 0:
64 type_as = np.zeros(0)
65 nx = get_backend(type_as)
66 else:
67 nx = get_backend(*lst_not_empty)
68 type_as = lst_not_empty[0]
69 else:
70 if len(lst_not_empty) == 0:
71 type_as = None
72 else:
73 type_as = lst_not_empty[0]
74 if len(lst) > 1:
75 return [
76 nx.from_numpy(np.array(a), type_as=type_as) if isinstance(a, list) else a
77 for a in lst
78 ]
79 else:
80 if isinstance(lst[0], list):
81 return nx.from_numpy(np.array(lst[0]), type_as=type_as)
82 else:
83 return lst[0]
84
85
86 def proj_simplex(v, z=1):
87 r"""Compute the closest point (orthogonal projection) on the
88 generalized `(n-1)`-simplex of a vector :math:`\mathbf{v}` wrt. to the Euclidean
89 distance, thus solving:
90
91 .. math::
92 \mathcal{P}(w) \in \mathop{\arg \min}_\gamma \| \gamma - \mathbf{v} \|_2
93
94 s.t. \ \gamma^T \mathbf{1} = z
95
96 \gamma \geq 0
97
98 If :math:`\mathbf{v}` is a 2d array, compute all the projections wrt. axis 0
99
100 .. note:: This function is backend-compatible and will work on arrays
101 from all compatible backends.
102
103 Parameters
104 ----------
105 v : {array-like}, shape (n, d)
106 z : int, optional
107 'size' of the simplex (each vectors sum to z, 1 by default)
108
109 Returns
110 -------
111 h : ndarray, shape (`n`, `d`)
112 Array of projections on the simplex
113 """
114 nx = get_backend(v)
115 n = v.shape[0]
116 if v.ndim == 1:
117 d1 = 1
118 v = v[:, None]
119 else:
120 d1 = 0
121 d = v.shape[1]
122
123 # sort u in ascending order
124 u = nx.sort(v, axis=0)
125 # take the descending order
126 u = nx.flip(u, 0)
127 cssv = nx.cumsum(u, axis=0) - z
128 ind = nx.arange(n, type_as=v)[:, None] + 1
129 cond = u - cssv / ind > 0
130 rho = nx.sum(cond, 0)
131 theta = cssv[rho - 1, nx.arange(d)] / rho
132 w = nx.maximum(v - theta[None, :], nx.zeros(v.shape, type_as=v))
133 if d1:
134 return w[:, 0]
135 else:
136 return w
137
138
139 def projection_sparse_simplex(V, max_nz, z=1, axis=None, nx=None):
140 r"""Projection of :math:`\mathbf{V}` onto the simplex with cardinality constraint (maximum number of non-zero elements) and then scaled by `z`.
141
142 .. math::
143 P\left(\mathbf{V}, max_nz, z\right) = \mathop{\arg \min}_{\substack{\mathbf{y} >= 0 \\ \sum_i \mathbf{y}_i = z} \\ ||p||_0 \le \text{max_nz}} \quad \|\mathbf{y} - \mathbf{V}\|^2
144
145 Parameters
146 ----------
147 V: 1-dim or 2-dim ndarray
148 z: float or array
149 If array, len(z) must be compatible with :math:`\mathbf{V}`
150 axis: None or int
151 - axis=None: project :math:`\mathbf{V}` by :math:`P(\mathbf{V}.\mathrm{ravel}(), max_nz, z)`
152 - axis=1: project each :math:`\mathbf{V}_i` by :math:`P(\mathbf{V}_i, max_nz, z_i)`
153 - axis=0: project each :math:`\mathbf{V}_{:, j}` by :math:`P(\mathbf{V}_{:, j}, max_nz, z_j)`
154
155 Returns
156 -------
157 projection: ndarray, shape :math:`\mathbf{V}`.shape
158
159 References:
160 Sparse projections onto the simplex
161 Anastasios Kyrillidis, Stephen Becker, Volkan Cevher and, Christoph Koch
162 ICML 2013
163 https://arxiv.org/abs/1206.1529
164 """
165 if nx is None:
166 nx = get_backend(V)
167 if V.ndim == 1:
168 return projection_sparse_simplex(
169 # V[nx.newaxis, :], max_nz, z, axis=1).ravel()
170 V[None, :],
171 max_nz,
172 z,
173 axis=1,
174 ).ravel()
175
176 if V.ndim > 2:
177 raise ValueError("V.ndim must be <= 2")
178
179 if axis == 1:
180 # For each row of V, find top max_nz values; arrange the
181 # corresponding column indices such that their values are
182 # in a descending order.
183 max_nz_indices = nx.argsort(V, axis=1)[:, -max_nz:]
184 max_nz_indices = nx.flip(max_nz_indices, axis=1)
185
186 row_indices = nx.arange(V.shape[0])
187 row_indices = row_indices.reshape(-1, 1)
188 print(row_indices.shape)
189 # Extract the top max_nz values for each row
190 # and then project to simplex.
191 U = V[row_indices, max_nz_indices]
192 z = nx.ones(len(U)) * z
193 cssv = nx.cumsum(U, axis=1) - z[:, None]
194 ind = nx.arange(max_nz) + 1
195 cond = U - cssv / ind > 0
196 # rho = nx.count_nonzero(cond, axis=1)
197 rho = nx.sum(cond, axis=1)
198 theta = cssv[nx.arange(len(U)), rho - 1] / rho
199 nz_projection = nx.maximum(U - theta[:, None], 0)
200
201 # Put the projection of max_nz_values to their original column indices
202 # while keeping other values zero.
203 sparse_projection = nx.zeros(V.shape, type_as=nz_projection)
204
205 if isinstance(nx, JaxBackend):
206 # in Jax, we need to use the `at` property of `jax.numpy.ndarray`
207 # to do in-place array modifications.
208 sparse_projection = sparse_projection.at[row_indices, max_nz_indices].set(
209 nz_projection
210 )
211 else:
212 sparse_projection[row_indices, max_nz_indices] = nz_projection
213 return sparse_projection
214
215 elif axis == 0:
216 return projection_sparse_simplex(V.T, max_nz, z, axis=1).T
217
218 else:
219 V = V.ravel().reshape(1, -1)
220 return projection_sparse_simplex(V, max_nz, z, axis=1).ravel()
221
222
223 def unif(n, type_as=None):
224 r"""
225 Return a uniform histogram of length `n` (simplex).
226
227 Parameters
228 ----------
229 n : int
230 number of bins in the histogram
231 type_as : array_like
232 array of the same type of the expected output (numpy/pytorch/jax)
233
234 Returns
235 -------
236 h : array_like (`n`,)
237 histogram of length `n` such that :math:`\forall i, \mathbf{h}_i = \frac{1}{n}`
238 """
239 if type_as is None:
240 return np.ones((n,)) / n
241 else:
242 nx = get_backend(type_as)
243 return nx.ones((n,), type_as=type_as) / n
244
245
246 def clean_zeros(a, b, M):
247 r"""Remove all components with zeros weights in :math:`\mathbf{a}` and :math:`\mathbf{b}`"""
248 M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd)
249 a2 = a[a > 0]
250 b2 = b[b > 0]
251 return a2, b2, M2
252
253
254 def euclidean_distances(X, Y, squared=False):
255 r"""
256 Considering the rows of :math:`\mathbf{X}` (and :math:`\mathbf{Y} = \mathbf{X}`) as vectors, compute the
257 distance matrix between each pair of vectors.
258
259 .. note:: This function is backend-compatible and will work on arrays
260 from all compatible backends.
261
262 Parameters
263 ----------
264 X : array-like, shape (n_samples_1, n_features)
265 Y : array-like, shape (n_samples_2, n_features)
266 squared : boolean, optional
267 Return squared Euclidean distances.
268
269 Returns
270 -------
271 distances : array-like, shape (`n_samples_1`, `n_samples_2`)
272 """
273
274 nx = get_backend(X, Y)
275
276 a2 = nx.einsum("ij,ij->i", X, X)
277 b2 = nx.einsum("ij,ij->i", Y, Y)
278
279 c = -2 * nx.dot(X, Y.T)
280 c += a2[:, None]
281 c += b2[None, :]
282
283 c = nx.maximum(c, 0)
284
285 if not squared:
286 c = nx.sqrt(c)
287
288 if X is Y:
289 c = c * (1 - nx.eye(X.shape[0], type_as=c))
290
291 return c
292
293
294 def dist(x1, x2=None, metric="sqeuclidean", p=2, w=None):
295 r"""Compute distance between samples in :math:`\mathbf{x_1}` and :math:`\mathbf{x_2}`
296
297 .. note:: This function is backend-compatible and will work on arrays
298 from all compatible backends.
299
300 Parameters
301 ----------
302
303 x1 : array-like, shape (n1,d)
304 matrix with `n1` samples of size `d`
305 x2 : array-like, shape (n2,d), optional
306 matrix with `n2` samples of size `d` (if None then :math:`\mathbf{x_2} = \mathbf{x_1}`)
307 metric : str | callable, optional
308 'sqeuclidean' or 'euclidean' on all backends. On numpy the function also
309 accepts from the scipy.spatial.distance.cdist function : 'braycurtis',
310 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice',
311 'euclidean', 'hamming', 'jaccard', 'kulczynski1', 'mahalanobis',
312 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
313 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'.
314 p : float, optional
315 p-norm for the Minkowski and the Weighted Minkowski metrics. Default value is 2.
316 w : array-like, rank 1
317 Weights for the weighted metrics.
318
319
320 Returns
321 -------
322
323 M : array-like, shape (`n1`, `n2`)
324 distance matrix computed with given metric
325
326 """
327 if x2 is None:
328 x2 = x1
329 if metric == "sqeuclidean":
330 return euclidean_distances(x1, x2, squared=True)
331 elif metric == "euclidean":
332 return euclidean_distances(x1, x2, squared=False)
333 else:
334 if not get_backend(x1, x2).__name__ == "numpy":
335 raise NotImplementedError()
336 else:
337 if isinstance(metric, str) and metric.endswith("minkowski"):
338 return cdist(x1, x2, metric=metric, p=p, w=w)
339 if w is not None:
340 return cdist(x1, x2, metric=metric, w=w)
341 return cdist(x1, x2, metric=metric)
342
343
344 def dist0(n, method="lin_square"):
345 r"""Compute standard cost matrices of size (`n`, `n`) for OT problems
346
347 Parameters
348 ----------
349 n : int
350 Size of the cost matrix.
351 method : str, optional
352 Type of loss matrix chosen from:
353
354 * 'lin_square' : linear sampling between 0 and `n-1`, quadratic loss
355
356 Returns
357 -------
358 M : ndarray, shape (`n1`, `n2`)
359 Distance matrix computed with given metric.
360 """
361 res = 0
362 if method == "lin_square":
363 x = np.arange(n, dtype=np.float64).reshape((n, 1))
364 res = dist(x, x)
365 return res
366
367
368 def cost_normalization(C, norm=None, return_value=False, value=None):
369 r"""Apply normalization to the loss matrix
370
371 Parameters
372 ----------
373 C : ndarray, shape (n1, n2)
374 The cost matrix to normalize.
375 norm : str
376 Type of normalization from 'median', 'max', 'log', 'loglog'. Any
377 other value do not normalize.
378
379 Returns
380 -------
381 C : ndarray, shape (`n1`, `n2`)
382 The input cost matrix normalized according to given norm.
383 """
384
385 nx = get_backend(C)
386
387 if norm is None:
388 pass
389 elif norm == "median":
390 if value is None:
391 value = nx.median(C)
392 C /= value
393 elif norm == "max":
394 if value is None:
395 value = nx.max(C)
396 C /= float(value)
397 elif norm == "log":
398 C = nx.log(1 + C)
399 elif norm == "loglog":
400 C = nx.log(1 + nx.log(1 + C))
401 else:
402 raise ValueError(
403 "Norm %s is not a valid option.\n"
404 "Valid options are:\n"
405 "median, max, log, loglog" % norm
406 )
407 if return_value:
408 return C, value
409 else:
410 return C
411
412
413 def dots(*args):
414 r"""dots function for multiple matrix multiply"""
415 nx = get_backend(*args)
416 return reduce(nx.dot, args)
417
418
419 def is_all_finite(*args):
420 r"""Tests element-wise for finiteness in all arguments."""
421 nx = get_backend(*args)
422 return all(not nx.any(~nx.isfinite(arg)) for arg in args)
423
424
425 def label_normalization(y, start=0, nx=None):
426 r"""Transform labels to start at a given value
427
428 Parameters
429 ----------
430 y : array-like, shape (n, )
431 The vector of labels to be normalized.
432 start : int
433 Desired value for the smallest label in :math:`\mathbf{y}` (default=0)
434 nx : Backend, optional
435 Backend to perform computations on. If omitted, the backend defaults to that of `y`.
436
437 Returns
438 -------
439 y : array-like, shape (`n1`, )
440 The input vector of labels normalized according to given start value.
441 """
442 if nx is None:
443 nx = get_backend(y)
444 diff = nx.min(y) - start
445 return y if diff == 0 else (y - diff)
446
447
448 def labels_to_masks(y, type_as=None, nx=None):
449 r"""Transforms (n_samples,) vector of labels into a (n_samples, n_labels) matrix of masks.
450
451 Parameters
452 ----------
453 y : array-like, shape (n_samples, )
454 The vector of labels.
455 type_as : array_like
456 Array of the same type of the expected output.
457 nx : Backend, optional
458 Backend to perform computations on. If omitted, the backend defaults to that of `y`.
459
460 Returns
461 -------
462 masks : array-like, shape (n_samples, n_labels)
463 The (n_samples, n_labels) matrix of label masks.
464 """
465 if nx is None:
466 nx = get_backend(y)
467 if type_as is None:
468 type_as = y
469 labels_u, labels_idx = nx.unique(y, return_inverse=True)
470 n_labels = labels_u.shape[0]
471 masks = nx.eye(n_labels, type_as=type_as)[labels_idx]
472 return masks
473
474
475 def parmap(f, X, nprocs="default"):
476 r"""parallel map for multiprocessing.
477 The function has been deprecated and only performs a regular map.
478 """
479 return list(map(f, X))
480
481
482 def check_params(**kwargs):
483 r"""check_params: check whether some parameters are missing"""
484
485 missing_params = []
486 check = True
487
488 for param in kwargs:
489 if kwargs[param] is None:
490 missing_params.append(param)
491
492 if len(missing_params) > 0:
493 print("POT - Warning: following necessary parameters are missing")
494 for p in missing_params:
495 print("\n", p)
496
497 check = False
498
499 return check
500
501
502 def check_random_state(seed):
503 r"""Turn `seed` into a np.random.RandomState instance
504
505 Parameters
506 ----------
507 seed : None | int | instance of RandomState
508 If `seed` is None, return the RandomState singleton used by np.random.
509 If `seed` is an int, return a new RandomState instance seeded with `seed`.
510 If `seed` is already a RandomState instance, return it.
511 Otherwise raise ValueError.
512 """
513 if seed is None or seed is np.random:
514 return np.random.mtrand._rand
515 if isinstance(seed, (int, np.integer)):
516 return np.random.RandomState(seed)
517 if isinstance(seed, np.random.RandomState):
518 return seed
519 raise ValueError(
520 "{} cannot be used to seed a numpy.random.RandomState" " instance".format(seed)
521 )
522
523
524 def get_coordinate_circle(x):
525 r"""For :math:`x\in S^1 \subset \mathbb{R}^2`, returns the coordinates in
526 turn (in [0,1[).
527
528 .. math::
529 u = \frac{\pi + \mathrm{atan2}(-x_2,-x_1)}{2\pi}
530
531 Parameters
532 ----------
533 x: ndarray, shape (n, 2)
534 Samples on the circle with ambient coordinates
535
536 Returns
537 -------
538 x_t: ndarray, shape (n,)
539 Coordinates on [0,1[
540
541 Examples
542 --------
543 >>> u = np.array([[0.2,0.5,0.8]]) * (2 * np.pi)
544 >>> x1, y1 = np.cos(u), np.sin(u)
545 >>> x = np.concatenate([x1, y1]).T
546 >>> get_coordinate_circle(x)
547 array([0.2, 0.5, 0.8])
548 """
549 nx = get_backend(x)
550 x_t = (nx.atan2(-x[:, 1], -x[:, 0]) + np.pi) / (2 * np.pi)
551 return x_t
552
553
554 def reduce_lazytensor(a, func, axis=None, nx=None, batch_size=100):
555 """Reduce a LazyTensor along an axis with function fun using batches.
556
557 When axis=None, reduce the LazyTensor to a scalar as a sum of fun over
558 batches taken along dim.
559
560 .. warning::
561 This function works for tensor of any order but the reduction can be done
562 only along the first two axis (or global). Also, in order to work, it requires that the slice of size `batch_size` along the axis to reduce (or axis 0 if `axis=None`) is can be computed and fits in memory.
563
564
565 Parameters
566 ----------
567 a : LazyTensor
568 LazyTensor to reduce
569 func : callable
570 Function to apply to the LazyTensor
571 axis : int, optional
572 Axis along which to reduce the LazyTensor. If None, reduce the
573 LazyTensor to a scalar as a sum of fun over batches taken along axis 0.
574 If 0 or 1 reduce the LazyTensor to a vector/matrix as a sum of fun over
575 batches taken along axis.
576 nx : Backend, optional
577 Backend to use for the reduction
578 batch_size : int, optional
579 Size of the batches to use for the reduction (default=100)
580
581 Returns
582 -------
583 res : array-like
584 Result of the reduction
585
586 """
587
588 if nx is None:
589 nx = get_backend(a[0:1])
590
591 if axis is None:
592 res = 0.0
593 for i in range(0, a.shape[0], batch_size):
594 res += func(a[i : i + batch_size])
595 return res
596 elif axis == 0:
597 res = nx.zeros(a.shape[1:], type_as=a[0])
598 if nx.__name__ in ["jax", "tf"]:
599 lst = []
600 for j in range(0, a.shape[1], batch_size):
601 lst.append(func(a[:, j : j + batch_size], 0))
602 return nx.concatenate(lst, axis=0)
603 else:
604 for j in range(0, a.shape[1], batch_size):
605 res[j : j + batch_size] = func(a[:, j : j + batch_size], axis=0)
606 return res
607 elif axis == 1:
608 if len(a.shape) == 2:
609 shape = a.shape[0]
610 else:
611 shape = (a.shape[0], *a.shape[2:])
612 res = nx.zeros(shape, type_as=a[0])
613 if nx.__name__ in ["jax", "tf"]:
614 lst = []
615 for i in range(0, a.shape[0], batch_size):
616 lst.append(func(a[i : i + batch_size], 1))
617 return nx.concatenate(lst, axis=0)
618 else:
619 for i in range(0, a.shape[0], batch_size):
620 res[i : i + batch_size] = func(a[i : i + batch_size], axis=1)
621 return res
622
623 else:
624 raise (NotImplementedError("Only axis=None, 0 or 1 is implemented for now."))
625
626
627 def get_lowrank_lazytensor(Q, R, d=None, nx=None):
628 """Get a low rank LazyTensor T=Q@R^T or T=Q@diag(d)@R^T
629
630 Parameters
631 ----------
632 Q : ndarray, shape (n, r)
633 First factor of the lowrank tensor
634 R : ndarray, shape (m, r)
635 Second factor of the lowrank tensor
636 d : ndarray, shape (r,), optional
637 Diagonal of the lowrank tensor
638 nx : Backend, optional
639 Backend to use for the reduction
640
641 Returns
642 -------
643 T : LazyTensor
644 Lowrank tensor T=Q@R^T or T=Q@diag(d)@R^T
645 """
646
647 if nx is None:
648 nx = get_backend(Q, R, d)
649
650 shape = (Q.shape[0], R.shape[0])
651
652 if d is None:
653
654 def func(i, j, Q, R):
655 return nx.dot(Q[i], R[j].T)
656
657 T = LazyTensor(shape, func, Q=Q, R=R)
658
659 else:
660
661 def func(i, j, Q, R, d):
662 return nx.dot(Q[i] * d[None, :], R[j].T)
663
664 T = LazyTensor(shape, func, Q=Q, R=R, d=d)
665
666 return T
667
668
669 def get_parameter_pair(parameter):
670 r"""Extract a pair of parameters from a given parameter
671 Used in unbalanced OT and COOT solvers
672 to handle marginal regularization and entropic regularization.
673
674 Parameters
675 ----------
676 parameter : float or indexable object
677 nx : backend object
678
679 Returns
680 -------
681 param_1 : float
682 param_2 : float
683 """
684
685 if isinstance(parameter, float) or isinstance(parameter, int):
686 param_1, param_2 = parameter, parameter
687 elif len(parameter) == 1:
688 param_1, param_2 = parameter[0], parameter[0]
689 else:
690 if len(parameter) > 2:
691 raise ValueError(
692 "Parameter must be either a scalar, \
693 or an indexable object of length 1 or 2."
694 )
695 else:
696 param_1, param_2 = parameter[0], parameter[1]
697
698 return param_1, param_2
699
700
701 class deprecated(object):
702 r"""Decorator to mark a function or class as deprecated.
703
704 deprecated class from scikit-learn package
705 https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/deprecation.py
706 Issue a warning when the function is called/the class is instantiated and
707 adds a warning to the docstring.
708 The optional extra argument will be appended to the deprecation message
709 and the docstring.
710
711 .. note::
712 To use this with the default value for extra, use empty parentheses:
713
714 >>> from ot.deprecation import deprecated # doctest: +SKIP
715 >>> @deprecated() # doctest: +SKIP
716 ... def some_function(): pass # doctest: +SKIP
717
718 Parameters
719 ----------
720 extra : str
721 To be added to the deprecation messages.
722 """
723
724 # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary,
725 # but with many changes.
726
727 def __init__(self, extra=""):
728 self.extra = extra
729
730 def __call__(self, obj):
731 r"""Call method
732 Parameters
733 ----------
734 obj : object
735 """
736 if isinstance(obj, type):
737 return self._decorate_class(obj)
738 else:
739 return self._decorate_fun(obj)
740
741 def _decorate_class(self, cls):
742 msg = "Class %s is deprecated" % cls.__name__
743 if self.extra:
744 msg += "; %s" % self.extra
745
746 # FIXME: we should probably reset __new__ for full generality
747 init = cls.__init__
748
749 def wrapped(*args, **kwargs):
750 warnings.warn(msg, category=DeprecationWarning)
751 return init(*args, **kwargs)
752
753 cls.__init__ = wrapped
754
755 wrapped.__name__ = "__init__"
756 wrapped.__doc__ = self._update_doc(init.__doc__)
757 wrapped.deprecated_original = init
758
759 return cls
760
761 def _decorate_fun(self, fun):
762 r"""Decorate function fun"""
763
764 msg = "Function %s is deprecated" % fun.__name__
765 if self.extra:
766 msg += "; %s" % self.extra
767
768 def wrapped(*args, **kwargs):
769 warnings.warn(msg, category=DeprecationWarning)
770 return fun(*args, **kwargs)
771
772 wrapped.__name__ = fun.__name__
773 wrapped.__dict__ = fun.__dict__
774 wrapped.__doc__ = self._update_doc(fun.__doc__)
775
776 return wrapped
777
778 def _update_doc(self, olddoc):
779 newdoc = "DEPRECATED"
780 if self.extra:
781 newdoc = "%s: %s" % (newdoc, self.extra)
782 if olddoc:
783 newdoc = "%s\n\n%s" % (newdoc, olddoc)
784 return newdoc
785
786
787 def _is_deprecated(func):
788 r"""Helper to check if func is wrapped by our deprecated decorator"""
789 if sys.version_info < (3, 5):
790 raise NotImplementedError("This is only available for python3.5 " "or above")
791 closures = getattr(func, "__closure__", [])
792 if closures is None:
793 closures = []
794 is_deprecated = "deprecated" in "".join(
795 [c.cell_contents for c in closures if isinstance(c.cell_contents, str)]
796 )
797 return is_deprecated
798
799
800 class BaseEstimator(object):
801 r"""Base class for most objects in POT
802
803 Code adapted from sklearn BaseEstimator class
804
805 Notes
806 -----
807 All estimators should specify all the parameters that can be set
808 at the class level in their ``__init__`` as explicit keyword
809 arguments (no ``*args`` or ``**kwargs``).
810 """
811
812 nx: Backend = None
813
814 def _get_backend(self, *arrays):
815 nx = get_backend(*[input_ for input_ in arrays if input_ is not None])
816 if nx.__name__ in ("tf",):
817 raise TypeError("Domain adaptation does not support TF backend.")
818 self.nx = nx
819 return nx
820
821 @classmethod
822 def _get_param_names(cls):
823 r"""Get parameter names for the estimator"""
824
825 # fetch the constructor or the original constructor before
826 # deprecation wrapping if any
827 init = getattr(cls.__init__, "deprecated_original", cls.__init__)
828 if init is object.__init__:
829 # No explicit constructor to introspect
830 return []
831
832 # introspect the constructor arguments to find the model parameters
833 # to represent
834 init_signature = signature(init)
835 # Consider the constructor parameters excluding 'self'
836 parameters = [
837 p
838 for p in init_signature.parameters.values()
839 if p.name != "self" and p.kind != p.VAR_KEYWORD
840 ]
841 for p in parameters:
842 if p.kind == p.VAR_POSITIONAL:
843 raise RuntimeError(
844 "POT estimators should always "
845 "specify their parameters in the signature"
846 " of their __init__ (no varargs)."
847 " %s with constructor %s doesn't "
848 " follow this convention." % (cls, init_signature)
849 )
850 # Extract and sort argument names excluding 'self'
851 return sorted([p.name for p in parameters])
852
853 def get_params(self, deep=True):
854 r"""Get parameters for this estimator.
855
856 Parameters
857 ----------
858 deep : bool, optional
859 If True, will return the parameters for this estimator and
860 contained subobjects that are estimators.
861
862 Returns
863 -------
864 params : mapping of string to any
865 Parameter names mapped to their values.
866 """
867 out = dict()
868 for key in self._get_param_names():
869 # We need deprecation warnings to always be on in order to
870 # catch deprecated param values.
871 # This is set in utils/__init__.py but it gets overwritten
872 # when running under python3 somehow.
873 warnings.simplefilter("always", DeprecationWarning)
874 try:
875 with warnings.catch_warnings(record=True) as w:
876 value = getattr(self, key, None)
877 if len(w) and isinstance(w[0].category, DeprecationWarning):
878 # if the parameter is deprecated, don't show it
879 continue
880 finally:
881 warnings.filters.pop(0)
882
883 # XXX: should we rather test if instance of estimator?
884 if deep and hasattr(value, "get_params"):
885 deep_items = value.get_params().items()
886 out.update((key + "__" + k, val) for k, val in deep_items)
887 out[key] = value
888 return out
889
890 def set_params(self, **params):
891 r"""Set the parameters of this estimator.
892
893 The method works on simple estimators as well as on nested objects
894 (such as pipelines). The latter have parameters of the form
895 ``<component>__<parameter>`` so that it's possible to update each
896 component of a nested object.
897
898 Returns
899 -------
900 self
901 """
902 if not params:
903 # Simple optimisation to gain speed (inspect is slow)
904 return self
905 valid_params = self.get_params(deep=True)
906 # for key, value in iteritems(params):
907 for key, value in params.items():
908 split = key.split("__", 1)
909 if len(split) > 1:
910 # nested objects case
911 name, sub_name = split
912 if name not in valid_params:
913 raise ValueError(
914 "Invalid parameter %s for estimator %s. "
915 "Check the list of available parameters "
916 "with `estimator.get_params().keys()`." % (name, self)
917 )
918 sub_object = valid_params[name]
919 sub_object.set_params(**{sub_name: value})
920 else:
921 # simple objects case
922 if key not in valid_params:
923 raise ValueError(
924 "Invalid parameter %s for estimator %s. "
925 "Check the list of available parameters "
926 "with `estimator.get_params().keys()`."
927 % (key, self.__class__.__name__)
928 )
929 setattr(self, key, value)
930 return self
931
932
933 class UndefinedParameter(Exception):
934 r"""
935 Aim at raising an Exception when a undefined parameter is called
936
937 """
938
939 pass
940
941
942 class OTResult:
943 """Base class for OT results.
944
945 Parameters
946 ----------
947
948 potentials : tuple of array-like, shape (`n1`, `n2`)
949 Dual potentials, i.e. Lagrange multipliers for the marginal constraints.
950 This pair of arrays has the same shape, numerical type
951 and properties as the input weights "a" and "b".
952 value : float, array-like
953 Full transport cost, including possible regularization terms and
954 quadratic term for Gromov Wasserstein solutions.
955 value_linear : float, array-like
956 The linear part of the transport cost, i.e. the product between the
957 transport plan and the cost.
958 value_quad : float, array-like
959 The quadratic part of the transport cost for Gromov-Wasserstein
960 solutions.
961 plan : array-like, shape (`n1`, `n2`)
962 Transport plan, encoded as a dense array.
963 log : dict
964 Dictionary containing potential information about the solver.
965 backend : Backend
966 Backend used to compute the results.
967 sparse_plan : array-like, shape (`n1`, `n2`)
968 Transport plan, encoded as a sparse array.
969 lazy_plan : LazyTensor
970 Transport plan, encoded as a symbolic POT or KeOps LazyTensor.
971 status : int or str
972 Status of the solver.
973 batch_size : int
974 Batch size used to compute the results/marginals for LazyTensor.
975
976 Attributes
977 ----------
978
979 potentials : tuple of array-like, shape (`n1`, `n2`)
980 Dual potentials, i.e. Lagrange multipliers for the marginal constraints.
981 This pair of arrays has the same shape, numerical type
982 and properties as the input weights "a" and "b".
983 potential_a : array-like, shape (`n1`,)
984 First dual potential, associated to the "source" measure "a".
985 potential_b : array-like, shape (`n2`,)
986 Second dual potential, associated to the "target" measure "b".
987 value : float, array-like
988 Full transport cost, including possible regularization terms and
989 quadratic term for Gromov Wasserstein solutions.
990 value_linear : float, array-like
991 The linear part of the transport cost, i.e. the product between the
992 transport plan and the cost.
993 value_quad : float, array-like
994 The quadratic part of the transport cost for Gromov-Wasserstein
995 solutions.
996 plan : array-like, shape (`n1`, `n2`)
997 Transport plan, encoded as a dense array.
998 sparse_plan : array-like, shape (`n1`, `n2`)
999 Transport plan, encoded as a sparse array.
1000 lazy_plan : LazyTensor
1001 Transport plan, encoded as a symbolic POT or KeOps LazyTensor.
1002 marginals : tuple of array-like, shape (`n1`,), (`n2`,)
1003 Marginals of the transport plan: should be very close to "a" and "b"
1004 for balanced OT.
1005 marginal_a : array-like, shape (`n1`,)
1006 Marginal of the transport plan for the "source" measure "a".
1007 marginal_b : array-like, shape (`n2`,)
1008 Marginal of the transport plan for the "target" measure "b".
1009
1010 """
1011
1012 def __init__(
1013 self,
1014 potentials=None,
1015 value=None,
1016 value_linear=None,
1017 value_quad=None,
1018 plan=None,
1019 log=None,
1020 backend=None,
1021 sparse_plan=None,
1022 lazy_plan=None,
1023 status=None,
1024 batch_size=100,
1025 ):
1026 self._potentials = potentials
1027 self._value = value
1028 self._value_linear = value_linear
1029 self._value_quad = value_quad
1030 self._plan = plan
1031 self._log = log
1032 self._sparse_plan = sparse_plan
1033 self._lazy_plan = lazy_plan
1034 self._backend = backend if backend is not None else NumpyBackend()
1035 self._status = status
1036 self._batch_size = batch_size
1037
1038 # I assume that other solvers may return directly
1039 # some primal objects?
1040 # In the code below, let's define the main quantities
1041 # that may be of interest to users.
1042 # An OT solver returns an object that inherits from OTResult
1043 # (e.g. SinkhornOTResult) and implements the relevant
1044 # methods (e.g. "plan" and "lazy_plan" but not "sparse_plan", etc.).
1045 # log is a dictionary containing potential information about the solver
1046
1047 # Dual potentials --------------------------------------------
1048
1049 def __repr__(self):
1050 s = "OTResult("
1051 if self._value is not None:
1052 s += "value={},".format(self._value)
1053 if self._value_linear is not None:
1054 s += "value_linear={},".format(self._value_linear)
1055 if self._plan is not None:
1056 s += "plan={}(shape={}),".format(
1057 self._plan.__class__.__name__, self._plan.shape
1058 )
1059 if self._lazy_plan is not None:
1060 s += "lazy_plan={}(shape={}),".format(
1061 self._lazy_plan.__class__.__name__, self._lazy_plan.shape
1062 )
1063 if s[-1] != "(":
1064 s = s[:-1] + ")"
1065 else:
1066 s = s + ")"
1067 return s
1068
1069 @property
1070 def potentials(self):
1071 """Dual potentials, i.e. Lagrange multipliers for the marginal constraints.
1072
1073 This pair of arrays has the same shape, numerical type
1074 and properties as the input weights "a" and "b".
1075 """
1076 return self._potentials
1077
1078 @property
1079 def potential_a(self):
1080 """First dual potential, associated to the "source" measure "a"."""
1081 if self._potentials is not None:
1082 return self._potentials[0]
1083 else:
1084 return None
1085
1086 @property
1087 def potential_b(self):
1088 """Second dual potential, associated to the "target" measure "b"."""
1089 if self._potentials is not None:
1090 return self._potentials[1]
1091 else:
1092 return None
1093
1094 # Transport plan -------------------------------------------
1095 @property
1096 def plan(self):
1097 """Transport plan, encoded as a dense array."""
1098 # N.B.: We may catch out-of-memory errors and suggest
1099 # the use of lazy_plan or sparse_plan when appropriate.
1100
1101 return self._plan
1102
1103 @property
1104 def sparse_plan(self):
1105 """Transport plan, encoded as a sparse array."""
1106 if self._sparse_plan is not None:
1107 return self._sparse_plan
1108 elif self._plan is not None:
1109 return self._backend.tocsr(self._plan)
1110 else:
1111 return None
1112
1113 @property
1114 def lazy_plan(self):
1115 """Transport plan, encoded as a symbolic KeOps LazyTensor."""
1116 return self._lazy_plan
1117
1118 # Loss values --------------------------------
1119
1120 @property
1121 def value(self):
1122 """Full transport cost, including possible regularization terms and
1123 quadratic term for Gromov Wasserstein solutions."""
1124 return self._value
1125
1126 @property
1127 def value_linear(self):
1128 """The "minimal" transport cost, i.e. the product between the transport plan and the cost."""
1129 return self._value_linear
1130
1131 @property
1132 def value_quad(self):
1133 """The quadratic part of the transport cost for Gromov-Wasserstein solutions."""
1134 return self._value_quad
1135
1136 # Marginal constraints -------------------------
1137 @property
1138 def marginals(self):
1139 """Marginals of the transport plan: should be very close to "a" and "b"
1140 for balanced OT."""
1141 if self._plan is not None:
1142 return self.marginal_a, self.marginal_b
1143 else:
1144 return None
1145
1146 @property
1147 def marginal_a(self):
1148 """First marginal of the transport plan, with the same shape as "a"."""
1149 if self._plan is not None:
1150 return self._backend.sum(self._plan, 1)
1151 elif self._lazy_plan is not None:
1152 lp = self._lazy_plan
1153 bs = self._batch_size
1154 nx = self._backend
1155 return reduce_lazytensor(lp, nx.sum, axis=1, nx=nx, batch_size=bs)
1156 else:
1157 return None
1158
1159 @property
1160 def marginal_b(self):
1161 """Second marginal of the transport plan, with the same shape as "b"."""
1162 if self._plan is not None:
1163 return self._backend.sum(self._plan, 0)
1164 elif self._lazy_plan is not None:
1165 lp = self._lazy_plan
1166 bs = self._batch_size
1167 nx = self._backend
1168 return reduce_lazytensor(lp, nx.sum, axis=0, nx=nx, batch_size=bs)
1169 else:
1170 return None
1171
1172 @property
1173 def status(self):
1174 """Optimization status of the solver."""
1175 return self._status
1176
1177 @property
1178 def log(self):
1179 """Dictionary containing potential information about the solver."""
1180 return self._log
1181
1182 # Barycentric mappings -------------------------
1183 # Return the displacement vectors as an array
1184 # that has the same shape as "xa"/"xb" (for samples)
1185 # or "a"/"b" * D (for images)?
1186
1187 @property
1188 def a_to_b(self):
1189 """Displacement vectors from the first to the second measure."""
1190 raise NotImplementedError()
1191
1192 @property
1193 def b_to_a(self):
1194 """Displacement vectors from the second to the first measure."""
1195 raise NotImplementedError()
1196
1197 # # Wasserstein barycenters ----------------------
1198 # @property
1199 # def masses(self):
1200 # """Masses for the Wasserstein barycenter."""
1201 # raise NotImplementedError()
1202
1203 # @property
1204 # def samples(self):
1205 # """Sample locations for the Wasserstein barycenter."""
1206 # raise NotImplementedError()
1207
1208 # Miscellaneous --------------------------------
1209
1210 @property
1211 def citation(self):
1212 """Appropriate citation(s) for this result, in plain text and BibTex formats."""
1213
1214 # The string below refers to the POT library:
1215 # successor methods may concatenate the relevant references
1216 # to the original definitions, solvers and underlying numerical backends.
1217 return """POT library:
1218
1219 POT Python Optimal Transport library, Journal of Machine Learning Research, 22(78):1−8, 2021.
1220 Website: https://pythonot.github.io/
1221 Rémi Flamary, Nicolas Courty, Alexandre Gramfort, Mokhtar Z. Alaya, Aurélie Boisbunon, Stanislas Chambon, Laetitia Chapel, Adrien Corenflos, Kilian Fatras, Nemo Fournier, Léo Gautheron, Nathalie T.H. Gayraud, Hicham Janati, Alain Rakotomamonjy, Ievgen Redko, Antoine Rolet, Antony Schutz, Vivien Seguy, Danica J. Sutherland, Romain Tavenard, Alexander Tong, Titouan Vayer;
1222
1223 @article{flamary2021pot,
1224 author = {R{\'e}mi Flamary and Nicolas Courty and Alexandre Gramfort and Mokhtar Z. Alaya and Aur{\'e}lie Boisbunon and Stanislas Chambon and Laetitia Chapel and Adrien Corenflos and Kilian Fatras and Nemo Fournier and L{\'e}o Gautheron and Nathalie T.H. Gayraud and Hicham Janati and Alain Rakotomamonjy and Ievgen Redko and Antoine Rolet and Antony Schutz and Vivien Seguy and Danica J. Sutherland and Romain Tavenard and Alexander Tong and Titouan Vayer},
1225 title = {{POT}: {Python} {Optimal} {Transport}},
1226 journal = {Journal of Machine Learning Research},
1227 year = {2021},
1228 volume = {22},
1229 number = {78},
1230 pages = {1-8},
1231 url = {http://jmlr.org/papers/v22/20-451.html}
1232 }
1233 """
1234
1235
1236 class LazyTensor(object):
1237 """A lazy tensor is a tensor that is not stored in memory. Instead, it is
1238 defined by a function that computes its values on the fly from slices.
1239
1240 Parameters
1241 ----------
1242
1243 shape : tuple
1244 shape of the tensor
1245 getitem : callable
1246 function that computes the values of the indices/slices and tensors
1247 as arguments
1248
1249 kwargs : dict
1250 named arguments for the function, those names will be used as attributed
1251 of the LazyTensor object
1252
1253 Examples
1254 --------
1255 >>> import numpy as np
1256 >>> v = np.arange(5)
1257 >>> def getitem(i,j, v):
1258 ... return v[i,None]+v[None,j]
1259 >>> T = LazyTensor((5,5),getitem, v=v)
1260 >>> T[1,2]
1261 array([3])
1262 >>> T[1,:]
1263 array([[1, 2, 3, 4, 5]])
1264 >>> T[:]
1265 array([[0, 1, 2, 3, 4],
1266 [1, 2, 3, 4, 5],
1267 [2, 3, 4, 5, 6],
1268 [3, 4, 5, 6, 7],
1269 [4, 5, 6, 7, 8]])
1270
1271 """
1272
1273 def __init__(self, shape, getitem, **kwargs):
1274 self._getitem = getitem
1275 self.shape = shape
1276 self.ndim = len(shape)
1277 self.kwargs = kwargs
1278
1279 # set attributes for named arguments/arrays
1280 for key, value in kwargs.items():
1281 setattr(self, key, value)
1282
1283 def __getitem__(self, key):
1284 k = []
1285 if isinstance(key, int) or isinstance(key, slice):
1286 k.append(key)
1287 for i in range(self.ndim - 1):
1288 k.append(slice(None))
1289 elif isinstance(key, tuple):
1290 k = list(key)
1291 for i in range(self.ndim - len(key)):
1292 k.append(slice(None))
1293 else:
1294 raise NotImplementedError(
1295 "Only integer, slice, and tuple indexing is supported"
1296 )
1297
1298 return self._getitem(*k, **self.kwargs)
1299
1300 def __repr__(self):
1301 return "LazyTensor(shape={},attributes=({}))".format(
1302 self.shape, ",".join(self.kwargs.keys())
1303 )
1304
1305
1306 def proj_SDP(S, nx=None, vmin=0.0):
1307 """
1308 Project a symmetric matrix onto the space of symmetric matrices with
1309 eigenvalues larger or equal to `vmin`.
1310
1311 Parameters
1312 ----------
1313 S : array_like (n, d, d) or (d, d)
1314 The input symmetric matrix or matrices.
1315 nx : module, optional
1316 The numerical backend module to use. If not provided, the backend will
1317 be fetched from the input matrix `S`.
1318 vmin : float, optional
1319 The minimum value for the eigenvalues. Eigenvalues below this value will
1320 be clipped to vmin.
1321
1322 .. note:: This function is backend-compatible and will work on arrays
1323 from all compatible backends.
1324
1325 Returns
1326 -------
1327 P : ndarray (n, d, d) or (d, d)
1328 The projected symmetric positive definite matrix.
1329
1330 """
1331 if nx is None:
1332 nx = get_backend(S)
1333
1334 w, P = nx.eigh(S)
1335 w = nx.clip(w, vmin, None)
1336
1337 if len(S.shape) == 2: # input was (d, d)
1338 return P @ nx.diag(w) @ P.T
1339
1340 else: # input was (n, d, d): broadcasting
1341 Q = nx.einsum("ijk,ik->ijk", P, w) # Q[i] = P[i] @ diag(w[i])
1342 # R[i] = Q[i] @ P[i].T
1343 return nx.einsum("ijk,ikl->ijl", Q, nx.transpose(P, (0, 2, 1)))