Debian Codegraph @

test/test_bregman.py

raw symbols SCIP
1 """Tests for module bregman on OT with bregman projections"""
2
3 # Author: Remi Flamary <[email protected]>
4 # Kilian Fatras <[email protected]>
5 # Quang Huy Tran <[email protected]>
6 # Eduardo Fernandes Montesuma <[email protected]>
7 #
8 # License: MIT License
9
10 import warnings
11 from itertools import product
12
13 import numpy as np
14 import pytest
15
16 import ot
17 from ot.backend import tf, torch
18 from ot.bregman import geomloss
19
20
21 @pytest.mark.parametrize("verbose, warn", product([True, False], [True, False]))
22 def test_sinkhorn(verbose, warn):
23 # test sinkhorn
24 n = 100
25 rng = np.random.RandomState(0)
26
27 x = rng.randn(n, 2)
28 u = ot.utils.unif(n)
29
30 M = ot.dist(x, x)
31
32 G = ot.sinkhorn(u, u, M, 1, stopThr=1e-10, verbose=verbose, warn=warn)
33
34 # check constraints
35 np.testing.assert_allclose(u, G.sum(1), atol=1e-05) # cf convergence sinkhorn
36 np.testing.assert_allclose(u, G.sum(0), atol=1e-05) # cf convergence sinkhorn
37
38 with pytest.warns(UserWarning):
39 ot.sinkhorn(u, u, M, 1, stopThr=0, numItermax=1)
40
41
42 @pytest.mark.parametrize(
43 "method",
44 [
45 "sinkhorn",
46 "sinkhorn_stabilized",
47 "sinkhorn_epsilon_scaling",
48 "greenkhorn",
49 "sinkhorn_log",
50 ],
51 )
52 def test_convergence_warning(method):
53 # test sinkhorn
54 n = 100
55 a1 = ot.datasets.make_1D_gauss(n, m=30, s=10)
56 a2 = ot.datasets.make_1D_gauss(n, m=40, s=10)
57 A = np.asarray([a1, a2]).T
58 M = ot.utils.dist0(n)
59
60 with pytest.warns(UserWarning):
61 ot.sinkhorn(a1, a2, M, 1.0, method=method, stopThr=0, numItermax=1)
62
63 if method in ["sinkhorn", "sinkhorn_stabilized", "sinkhorn_log"]:
64 with pytest.warns(UserWarning):
65 ot.barycenter(A, M, 1, method=method, stopThr=0, numItermax=1)
66 with pytest.warns(UserWarning):
67 ot.sinkhorn2(
68 a1, a2, M, 1, method=method, stopThr=0, numItermax=1, warn=True
69 )
70 with warnings.catch_warnings():
71 warnings.simplefilter("error")
72 ot.sinkhorn2(
73 a1, a2, M, 1, method=method, stopThr=0, numItermax=1, warn=False
74 )
75
76
77 def test_not_implemented_method():
78 # test sinkhorn
79 w = 10
80 n = w**2
81 rng = np.random.RandomState(42)
82 A_img = rng.rand(2, w, w)
83 A_flat = A_img.reshape(n, 2)
84 a1, a2 = A_flat.T
85 M_flat = ot.utils.dist0(n)
86 not_implemented = "new_method"
87 reg = 0.01
88 with pytest.raises(ValueError):
89 ot.sinkhorn(a1, a2, M_flat, reg, method=not_implemented)
90 with pytest.raises(ValueError):
91 ot.sinkhorn2(a1, a2, M_flat, reg, method=not_implemented)
92 with pytest.raises(ValueError):
93 ot.barycenter(A_flat, M_flat, reg, method=not_implemented)
94 with pytest.raises(ValueError):
95 ot.bregman.barycenter_debiased(A_flat, M_flat, reg, method=not_implemented)
96 with pytest.raises(ValueError):
97 ot.bregman.convolutional_barycenter2d(A_img, reg, method=not_implemented)
98 with pytest.raises(ValueError):
99 ot.bregman.convolutional_barycenter2d_debiased(
100 A_img, reg, method=not_implemented
101 )
102
103
104 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_stabilized"])
105 def test_nan_warning(method):
106 # test sinkhorn
107 n = 100
108 a1 = ot.datasets.make_1D_gauss(n, m=30, s=10)
109 a2 = ot.datasets.make_1D_gauss(n, m=40, s=10)
110
111 M = ot.utils.dist0(n)
112 reg = 0
113 with pytest.warns(UserWarning):
114 # warn set to False to avoid catching a convergence warning instead
115 ot.sinkhorn(a1, a2, M, reg, method=method, warn=False)
116
117
118 def test_sinkhorn_stabilization():
119 # test sinkhorn
120 n = 100
121 a1 = ot.datasets.make_1D_gauss(n, m=30, s=10)
122 a2 = ot.datasets.make_1D_gauss(n, m=40, s=10)
123 M = ot.utils.dist0(n)
124 reg = 1e-5
125 loss1 = ot.sinkhorn2(a1, a2, M, reg, method="sinkhorn_log")
126 loss2 = ot.sinkhorn2(a1, a2, M, reg, tau=1, method="sinkhorn_stabilized")
127 np.testing.assert_allclose(loss1, loss2, atol=1e-06) # cf convergence sinkhorn
128
129
130 @pytest.mark.parametrize(
131 "method, verbose, warn",
132 product(
133 ["sinkhorn", "sinkhorn_stabilized", "sinkhorn_log"],
134 [True, False],
135 [True, False],
136 ),
137 )
138 def test_sinkhorn_multi_b(method, verbose, warn):
139 # test sinkhorn
140 n = 10
141 rng = np.random.RandomState(0)
142
143 x = rng.randn(n, 2)
144 u = ot.utils.unif(n)
145
146 b = rng.rand(n, 3)
147 b = b / np.sum(b, 0, keepdims=True)
148
149 M = ot.dist(x, x)
150
151 loss0, log = ot.sinkhorn(u, b, M, 0.1, method=method, stopThr=1e-10, log=True)
152
153 loss = [
154 ot.sinkhorn2(
155 u, b[:, k], M, 0.1, method=method, stopThr=1e-10, verbose=verbose, warn=warn
156 )
157 for k in range(3)
158 ]
159 # check constraints
160 np.testing.assert_allclose(loss0, loss, atol=1e-4) # cf convergence sinkhorn
161
162
163 def test_sinkhorn_backends(nx):
164 n_samples = 100
165 n_features = 2
166 rng = np.random.RandomState(0)
167
168 x = rng.randn(n_samples, n_features)
169 y = rng.randn(n_samples, n_features)
170 a = ot.utils.unif(n_samples)
171
172 M = ot.dist(x, y)
173
174 G = ot.sinkhorn(a, a, M, 1)
175
176 ab, M_nx = nx.from_numpy(a, M)
177
178 Gb = ot.sinkhorn(ab, ab, M_nx, 1)
179
180 np.allclose(G, nx.to_numpy(Gb))
181
182
183 def test_sinkhorn2_backends(nx):
184 n_samples = 100
185 n_features = 2
186 rng = np.random.RandomState(0)
187
188 x = rng.randn(n_samples, n_features)
189 y = rng.randn(n_samples, n_features)
190 a = ot.utils.unif(n_samples)
191
192 M = ot.dist(x, y)
193
194 G = ot.sinkhorn(a, a, M, 1)
195
196 ab, M_nx = nx.from_numpy(a, M)
197
198 Gb = ot.sinkhorn2(ab, ab, M_nx, 1)
199
200 np.allclose(G, nx.to_numpy(Gb))
201
202
203 def test_sinkhorn2_gradients():
204 n_samples = 100
205 n_features = 2
206 rng = np.random.RandomState(0)
207
208 x = rng.randn(n_samples, n_features)
209 y = rng.randn(n_samples, n_features)
210 a = ot.utils.unif(n_samples)
211
212 M = ot.dist(x, y)
213
214 if torch:
215 a1 = torch.tensor(a, requires_grad=True)
216 b1 = torch.tensor(a, requires_grad=True)
217 M1 = torch.tensor(M, requires_grad=True)
218
219 val = ot.sinkhorn2(a1, b1, M1, 1)
220
221 val.backward()
222
223 assert a1.shape == a1.grad.shape
224 assert b1.shape == b1.grad.shape
225 assert M1.shape == M1.grad.shape
226
227
228 def test_sinkhorn_empty():
229 # test sinkhorn
230 n = 100
231 rng = np.random.RandomState(0)
232
233 x = rng.randn(n, 2)
234 u = ot.utils.unif(n)
235
236 M = ot.dist(x, x)
237
238 G, log = ot.sinkhorn(
239 [], [], M, 1, stopThr=1e-10, method="sinkhorn_log", verbose=True, log=True
240 )
241 # check constraints
242 np.testing.assert_allclose(u, G.sum(1), atol=1e-05)
243 np.testing.assert_allclose(u, G.sum(0), atol=1e-05)
244
245 G, log = ot.sinkhorn([], [], M, 1, stopThr=1e-10, verbose=True, log=True)
246 # check constraints
247 np.testing.assert_allclose(u, G.sum(1), atol=1e-05)
248 np.testing.assert_allclose(u, G.sum(0), atol=1e-05)
249
250 G, log = ot.sinkhorn(
251 [],
252 [],
253 M,
254 1,
255 stopThr=1e-10,
256 method="sinkhorn_stabilized",
257 verbose=True,
258 log=True,
259 )
260 # check constraints
261 np.testing.assert_allclose(u, G.sum(1), atol=1e-05)
262 np.testing.assert_allclose(u, G.sum(0), atol=1e-05)
263
264 G, log = ot.sinkhorn(
265 [],
266 [],
267 M,
268 1,
269 stopThr=1e-10,
270 method="sinkhorn_epsilon_scaling",
271 verbose=True,
272 log=True,
273 )
274 # check constraints
275 np.testing.assert_allclose(u, G.sum(1), atol=1e-05)
276 np.testing.assert_allclose(u, G.sum(0), atol=1e-05)
277
278 # test empty weights greenkhorn
279 ot.sinkhorn([], [], M, 1, method="greenkhorn", stopThr=1e-10, log=True)
280
281
282 @pytest.skip_backend("tf")
283 @pytest.skip_backend("jax")
284 def test_sinkhorn_variants(nx):
285 # test sinkhorn
286 n = 100
287 rng = np.random.RandomState(0)
288
289 x = rng.randn(n, 2)
290 u = ot.utils.unif(n)
291
292 M = ot.dist(x, x)
293
294 ub, M_nx = nx.from_numpy(u, M)
295
296 G = ot.sinkhorn(u, u, M, 1, method="sinkhorn", stopThr=1e-10)
297 Gl = nx.to_numpy(ot.sinkhorn(ub, ub, M_nx, 1, method="sinkhorn_log", stopThr=1e-10))
298 G0 = nx.to_numpy(ot.sinkhorn(ub, ub, M_nx, 1, method="sinkhorn", stopThr=1e-10))
299 Gs = nx.to_numpy(
300 ot.sinkhorn(ub, ub, M_nx, 1, method="sinkhorn_stabilized", stopThr=1e-10)
301 )
302 Ges = nx.to_numpy(
303 ot.sinkhorn(ub, ub, M_nx, 1, method="sinkhorn_epsilon_scaling", stopThr=1e-10)
304 )
305 G_green = nx.to_numpy(
306 ot.sinkhorn(ub, ub, M_nx, 1, method="greenkhorn", stopThr=1e-10)
307 )
308
309 # check values
310 np.testing.assert_allclose(G, G0, atol=1e-05)
311 np.testing.assert_allclose(G, Gl, atol=1e-05)
312 np.testing.assert_allclose(G0, Gs, atol=1e-05)
313 np.testing.assert_allclose(G0, Ges, atol=1e-05)
314 np.testing.assert_allclose(G0, G_green, atol=1e-5)
315
316
317 @pytest.mark.parametrize(
318 "method",
319 [
320 "sinkhorn",
321 "sinkhorn_stabilized",
322 "sinkhorn_epsilon_scaling",
323 "greenkhorn",
324 "sinkhorn_log",
325 ],
326 )
327 @pytest.skip_arg(
328 ("nx", "method"),
329 ("tf", "sinkhorn_epsilon_scaling"),
330 reason="tf does not support sinkhorn_epsilon_scaling",
331 getter=str,
332 )
333 @pytest.skip_arg(
334 ("nx", "method"),
335 ("tf", "greenkhorn"),
336 reason="tf does not support greenkhorn",
337 getter=str,
338 )
339 @pytest.skip_arg(
340 ("nx", "method"),
341 ("jax", "sinkhorn_epsilon_scaling"),
342 reason="jax does not support sinkhorn_epsilon_scaling",
343 getter=str,
344 )
345 @pytest.skip_arg(
346 ("nx", "method"),
347 ("jax", "greenkhorn"),
348 reason="jax does not support greenkhorn",
349 getter=str,
350 )
351 def test_sinkhorn_variants_dtype_device(nx, method):
352 n = 100
353
354 rng = np.random.RandomState(42)
355 x = rng.randn(n, 2)
356 u = ot.utils.unif(n)
357
358 M = ot.dist(x, x)
359
360 for tp in nx.__type_list__:
361 print(nx.dtype_device(tp))
362
363 ub, Mb = nx.from_numpy(u, M, type_as=tp)
364
365 Gb = ot.sinkhorn(ub, ub, Mb, 1, method=method, stopThr=1e-10)
366
367 nx.assert_same_dtype_device(Mb, Gb)
368
369
370 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_stabilized", "sinkhorn_log"])
371 def test_sinkhorn2_variants_dtype_device(nx, method):
372 n = 100
373
374 rng = np.random.RandomState(42)
375 x = rng.randn(n, 2)
376 u = ot.utils.unif(n)
377
378 M = ot.dist(x, x)
379
380 for tp in nx.__type_list__:
381 print(nx.dtype_device(tp))
382
383 ub, Mb = nx.from_numpy(u, M, type_as=tp)
384
385 lossb = ot.sinkhorn2(ub, ub, Mb, 1, method=method, stopThr=1e-10)
386
387 nx.assert_same_dtype_device(Mb, lossb)
388
389
390 @pytest.mark.skipif(not tf, reason="tf not installed")
391 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_stabilized", "sinkhorn_log"])
392 def test_sinkhorn2_variants_device_tf(method):
393 nx = ot.backend.TensorflowBackend()
394 n = 100
395 rng = np.random.RandomState(42)
396 x = rng.randn(n, 2)
397 u = ot.utils.unif(n)
398 M = ot.dist(x, x)
399
400 # Check that everything stays on the CPU
401 with tf.device("/CPU:0"):
402 ub, Mb = nx.from_numpy(u, M)
403 Gb = ot.sinkhorn(ub, ub, Mb, 1, method=method, stopThr=1e-10)
404 lossb = ot.sinkhorn2(ub, ub, Mb, 1, method=method, stopThr=1e-10)
405 nx.assert_same_dtype_device(Mb, Gb)
406 nx.assert_same_dtype_device(Mb, lossb)
407
408 # Check that everything happens on the GPU
409 ub, Mb = nx.from_numpy(u, M)
410 Gb = ot.sinkhorn(ub, ub, Mb, 1, method=method, stopThr=1e-10)
411 lossb = ot.sinkhorn2(ub, ub, Mb, 1, method=method, stopThr=1e-10)
412 nx.assert_same_dtype_device(Mb, Gb)
413 nx.assert_same_dtype_device(Mb, lossb)
414
415 # Check this only if GPU is available
416 if len(tf.config.list_physical_devices("GPU")) > 0:
417 assert nx.dtype_device(Gb)[1].startswith("GPU")
418
419
420 @pytest.skip_backend("tf")
421 @pytest.skip_backend("jax")
422 def test_sinkhorn_variants_multi_b(nx):
423 # test sinkhorn
424 n = 50
425 rng = np.random.RandomState(0)
426
427 x = rng.randn(n, 2)
428 u = ot.utils.unif(n)
429
430 b = rng.rand(n, 3)
431 b = b / np.sum(b, 0, keepdims=True)
432
433 M = ot.dist(x, x)
434
435 ub, bb, M_nx = nx.from_numpy(u, b, M)
436
437 G = ot.sinkhorn(u, b, M, 1, method="sinkhorn", stopThr=1e-10)
438 Gl = nx.to_numpy(ot.sinkhorn(ub, bb, M_nx, 1, method="sinkhorn_log", stopThr=1e-10))
439 G0 = nx.to_numpy(ot.sinkhorn(ub, bb, M_nx, 1, method="sinkhorn", stopThr=1e-10))
440 Gs = nx.to_numpy(
441 ot.sinkhorn(ub, bb, M_nx, 1, method="sinkhorn_stabilized", stopThr=1e-10)
442 )
443
444 # check values
445 np.testing.assert_allclose(G, G0, atol=1e-05)
446 np.testing.assert_allclose(G, Gl, atol=1e-05)
447 np.testing.assert_allclose(G0, Gs, atol=1e-05)
448
449
450 @pytest.skip_backend("tf")
451 @pytest.skip_backend("jax")
452 def test_sinkhorn2_variants_multi_b(nx):
453 # test sinkhorn
454 n = 50
455 rng = np.random.RandomState(0)
456
457 x = rng.randn(n, 2)
458 u = ot.utils.unif(n)
459
460 b = rng.rand(n, 3)
461 b = b / np.sum(b, 0, keepdims=True)
462
463 M = ot.dist(x, x)
464
465 ub, bb, M_nx = nx.from_numpy(u, b, M)
466
467 G = ot.sinkhorn2(u, b, M, 1, method="sinkhorn", stopThr=1e-10)
468 Gl = nx.to_numpy(
469 ot.sinkhorn2(ub, bb, M_nx, 1, method="sinkhorn_log", stopThr=1e-10)
470 )
471 G0 = nx.to_numpy(ot.sinkhorn2(ub, bb, M_nx, 1, method="sinkhorn", stopThr=1e-10))
472 Gs = nx.to_numpy(
473 ot.sinkhorn2(ub, bb, M_nx, 1, method="sinkhorn_stabilized", stopThr=1e-10)
474 )
475
476 # check values
477 np.testing.assert_allclose(G, G0, atol=1e-05)
478 np.testing.assert_allclose(G, Gl, atol=1e-05)
479 np.testing.assert_allclose(G0, Gs, atol=1e-05)
480
481
482 def test_sinkhorn_variants_log():
483 # test sinkhorn
484 n = 50
485 rng = np.random.RandomState(0)
486
487 x = rng.randn(n, 2)
488 u = ot.utils.unif(n)
489
490 M = ot.dist(x, x)
491
492 G0, log0 = ot.sinkhorn(u, u, M, 1, method="sinkhorn", stopThr=1e-10, log=True)
493 Gl, logl = ot.sinkhorn(u, u, M, 1, method="sinkhorn_log", stopThr=1e-10, log=True)
494 Gs, logs = ot.sinkhorn(
495 u, u, M, 1, method="sinkhorn_stabilized", stopThr=1e-10, log=True
496 )
497 Ges, loges = ot.sinkhorn(
498 u,
499 u,
500 M,
501 1,
502 method="sinkhorn_epsilon_scaling",
503 stopThr=1e-10,
504 log=True,
505 )
506 G_green, loggreen = ot.sinkhorn(
507 u, u, M, 1, method="greenkhorn", stopThr=1e-10, log=True
508 )
509
510 # check values
511 np.testing.assert_allclose(G0, Gs, atol=1e-05)
512 np.testing.assert_allclose(G0, Gl, atol=1e-05)
513 np.testing.assert_allclose(G0, Ges, atol=1e-05)
514 np.testing.assert_allclose(G0, G_green, atol=1e-5)
515
516
517 @pytest.mark.parametrize("verbose, warn", product([True, False], [True, False]))
518 def test_sinkhorn_variants_log_multib(verbose, warn):
519 # test sinkhorn
520 n = 50
521 rng = np.random.RandomState(0)
522
523 x = rng.randn(n, 2)
524 u = ot.utils.unif(n)
525 b = rng.rand(n, 3)
526 b = b / np.sum(b, 0, keepdims=True)
527
528 M = ot.dist(x, x)
529
530 G0, log0 = ot.sinkhorn(u, b, M, 1, method="sinkhorn", stopThr=1e-10, log=True)
531 Gl, logl = ot.sinkhorn(
532 u,
533 b,
534 M,
535 1,
536 method="sinkhorn_log",
537 stopThr=1e-10,
538 log=True,
539 verbose=verbose,
540 warn=warn,
541 )
542 Gs, logs = ot.sinkhorn(
543 u,
544 b,
545 M,
546 1,
547 method="sinkhorn_stabilized",
548 stopThr=1e-10,
549 log=True,
550 verbose=verbose,
551 warn=warn,
552 )
553
554 # check values
555 np.testing.assert_allclose(G0, Gs, atol=1e-05)
556 np.testing.assert_allclose(G0, Gl, atol=1e-05)
557
558
559 @pytest.mark.parametrize(
560 "method, verbose, warn",
561 product(
562 ["sinkhorn", "sinkhorn_stabilized", "sinkhorn_log"],
563 [True, False],
564 [True, False],
565 ),
566 )
567 def test_barycenter(nx, method, verbose, warn):
568 n_bins = 100 # nb bins
569
570 # Gaussian distributions
571 a1 = ot.datasets.make_1D_gauss(n_bins, m=30, s=10) # m= mean, s= std
572 a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)
573
574 # creating matrix A containing all distributions
575 A = np.vstack((a1, a2)).T
576
577 # loss matrix + normalization
578 M = ot.utils.dist0(n_bins)
579 M /= M.max()
580
581 alpha = 0.5 # 0<=alpha<=1
582 weights = np.array([1 - alpha, alpha])
583
584 A_nx, M_nx, weights_nx = nx.from_numpy(A, M, weights)
585 reg = 1e-2
586
587 if nx.__name__ in ("jax", "tf") and method == "sinkhorn_log":
588 with pytest.raises(NotImplementedError):
589 ot.bregman.barycenter(A_nx, M_nx, reg, weights, method=method)
590 else:
591 # wasserstein
592 bary_wass_np = ot.bregman.barycenter(
593 A, M, reg, weights, method=method, verbose=verbose, warn=warn
594 )
595 bary_wass, _ = ot.bregman.barycenter(
596 A_nx, M_nx, reg, weights_nx, method=method, log=True
597 )
598 bary_wass = nx.to_numpy(bary_wass)
599
600 np.testing.assert_allclose(1, np.sum(bary_wass))
601 np.testing.assert_allclose(bary_wass, bary_wass_np)
602
603 ot.bregman.barycenter(A_nx, M_nx, reg, log=True)
604
605
606 def test_free_support_sinkhorn_barycenter():
607 measures_locations = [
608 np.array([-1.0]).reshape((1, 1)), # First dirac support
609 np.array([1.0]).reshape((1, 1)), # Second dirac support
610 ]
611
612 measures_weights = [
613 np.array([1.0]), # First dirac sample weights
614 np.array([1.0]), # Second dirac sample weights
615 ]
616
617 # Barycenter initialization
618 X_init = np.array([-12.0]).reshape((1, 1))
619
620 # Obvious barycenter locations. Take a look on test_ot.py, test_free_support_barycenter
621 bar_locations = np.array([0.0]).reshape((1, 1))
622
623 # Calculate free support barycenter w/ Sinkhorn algorithm. We set the entropic regularization
624 # term to 1, but this should be, in general, fine-tuned to the problem.
625 X = ot.bregman.free_support_sinkhorn_barycenter(
626 measures_locations, measures_weights, X_init, reg=1
627 )
628
629 # Verifies if calculated barycenter matches ground-truth
630 np.testing.assert_allclose(X, bar_locations, rtol=1e-5, atol=1e-7)
631
632
633 @pytest.mark.parametrize(
634 "method, verbose, warn",
635 product(
636 ["sinkhorn", "sinkhorn_stabilized", "sinkhorn_log"],
637 [True, False],
638 [True, False],
639 ),
640 )
641 def test_barycenter_assymetric_cost(nx, method, verbose, warn):
642 n_bins = 20 # nb bins
643
644 # Gaussian distributions
645 A = ot.datasets.make_1D_gauss(n_bins, m=30, s=10) # m= mean, s= std
646
647 # creating matrix A containing all distributions
648 A = A[:, None]
649
650 # assymetric loss matrix + normalization
651 rng = np.random.RandomState(42)
652 M = rng.randn(n_bins, n_bins) ** 2
653 M /= M.max()
654
655 A_nx, M_nx = nx.from_numpy(A, M)
656 reg = 1e-2
657
658 if nx.__name__ in ("jax", "tf") and method == "sinkhorn_log":
659 with pytest.raises(NotImplementedError):
660 ot.bregman.barycenter(A_nx, M_nx, reg, method=method)
661 else:
662 # wasserstein
663 bary_wass_np = ot.bregman.barycenter(
664 A, M, reg, method=method, verbose=verbose, warn=warn
665 )
666 bary_wass, _ = ot.bregman.barycenter(A_nx, M_nx, reg, method=method, log=True)
667 bary_wass = nx.to_numpy(bary_wass)
668
669 np.testing.assert_allclose(1, np.sum(bary_wass))
670 np.testing.assert_allclose(bary_wass, bary_wass_np)
671
672 ot.bregman.barycenter(A_nx, M_nx, reg, log=True)
673
674
675 @pytest.mark.parametrize(
676 "method, verbose, warn",
677 product(["sinkhorn", "sinkhorn_log"], [True, False], [True, False]),
678 )
679 def test_barycenter_debiased(nx, method, verbose, warn):
680 n_bins = 100 # nb bins
681
682 # Gaussian distributions
683 a1 = ot.datasets.make_1D_gauss(n_bins, m=30, s=10) # m= mean, s= std
684 a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)
685
686 # creating matrix A containing all distributions
687 A = np.vstack((a1, a2)).T
688
689 # loss matrix + normalization
690 M = ot.utils.dist0(n_bins)
691 M /= M.max()
692
693 alpha = 0.5 # 0<=alpha<=1
694 weights = np.array([1 - alpha, alpha])
695
696 A_nx, M_nx, weights_nx = nx.from_numpy(A, M, weights)
697
698 # wasserstein
699 reg = 1e-2
700 if nx.__name__ in ("jax", "tf") and method == "sinkhorn_log":
701 with pytest.raises(NotImplementedError):
702 ot.bregman.barycenter_debiased(A_nx, M_nx, reg, weights, method=method)
703 else:
704 bary_wass_np = ot.bregman.barycenter_debiased(
705 A, M, reg, weights, method=method, verbose=verbose, warn=warn
706 )
707 bary_wass, _ = ot.bregman.barycenter_debiased(
708 A_nx, M_nx, reg, weights_nx, method=method, log=True
709 )
710 bary_wass = nx.to_numpy(bary_wass)
711
712 np.testing.assert_allclose(1, np.sum(bary_wass), atol=1e-3)
713 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-5)
714
715 ot.bregman.barycenter_debiased(A_nx, M_nx, reg, log=True, verbose=False)
716
717
718 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_log"])
719 def test_convergence_warning_barycenters(method):
720 w = 10
721 n_bins = w**2 # nb bins
722
723 # Gaussian distributions
724 a1 = ot.datasets.make_1D_gauss(n_bins, m=30, s=10) # m= mean, s= std
725 a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)
726
727 # creating matrix A containing all distributions
728 A = np.vstack((a1, a2)).T
729 A_img = A.reshape(2, w, w)
730 A_img /= A_img.sum((1, 2))[:, None, None]
731
732 # loss matrix + normalization
733 M = ot.utils.dist0(n_bins)
734 M /= M.max()
735
736 alpha = 0.5 # 0<=alpha<=1
737 weights = np.array([1 - alpha, alpha])
738 reg = 0.1
739 with pytest.warns(UserWarning):
740 ot.bregman.barycenter_debiased(A, M, reg, weights, method=method, numItermax=1)
741 with pytest.warns(UserWarning):
742 ot.bregman.barycenter(A, M, reg, weights, method=method, numItermax=1)
743 with pytest.warns(UserWarning):
744 ot.bregman.convolutional_barycenter2d(
745 A_img, reg, weights, method=method, numItermax=1
746 )
747 with pytest.warns(UserWarning):
748 ot.bregman.convolutional_barycenter2d_debiased(
749 A_img, reg, weights, method=method, numItermax=1
750 )
751
752
753 def test_barycenter_stabilization(nx):
754 n_bins = 100 # nb bins
755
756 # Gaussian distributions
757 a1 = ot.datasets.make_1D_gauss(n_bins, m=30, s=10) # m= mean, s= std
758 a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)
759
760 # creating matrix A containing all distributions
761 A = np.vstack((a1, a2)).T
762
763 # loss matrix + normalization
764 M = ot.utils.dist0(n_bins)
765 M /= M.max()
766
767 alpha = 0.5 # 0<=alpha<=1
768 weights = np.array([1 - alpha, alpha])
769
770 A_nx, M_nx, weights_b = nx.from_numpy(A, M, weights)
771
772 # wasserstein
773 reg = 1e-2
774 bar_np = ot.bregman.barycenter(
775 A, M, reg, weights, method="sinkhorn", stopThr=1e-8, verbose=True
776 )
777 bar_stable = nx.to_numpy(
778 ot.bregman.barycenter(
779 A_nx,
780 M_nx,
781 reg,
782 weights_b,
783 method="sinkhorn_stabilized",
784 stopThr=1e-8,
785 verbose=True,
786 )
787 )
788 bar = nx.to_numpy(
789 ot.bregman.barycenter(
790 A_nx, M_nx, reg, weights_b, method="sinkhorn", stopThr=1e-8, verbose=True
791 )
792 )
793 np.testing.assert_allclose(bar, bar_stable)
794 np.testing.assert_allclose(bar, bar_np)
795
796
797 def create_random_images_dist(seed, size=20):
798 """Creates an array of two random images of size (size, size). Returns an array of shape (2, size, size)."""
799 rng = np.random.RandomState(seed)
800
801 # First image
802 a1 = rng.rand(size, size)
803 a1 += a1.min()
804 a1 = a1 / np.sum(a1) # Ensure that it is a probability distribution
805
806 # Second image
807 a2 = rng.rand(size, size)
808 a2 += a2.min()
809 a2 = a2 / np.sum(a2)
810
811 # Creating matrix A containing all distributions
812 A = np.zeros((2, size, size))
813 A[0, :, :] = a1
814 A[1, :, :] = a2
815
816 return A
817
818
819 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_log"])
820 def test_wasserstein_bary_2d(nx, method):
821 # Create the array of images to test
822 A = create_random_images_dist(42, size=20)
823
824 A_nx = nx.from_numpy(A)
825
826 # wasserstein
827 reg = 1e-2
828 if nx.__name__ in ("jax", "tf") and method == "sinkhorn_log":
829 with pytest.raises(NotImplementedError):
830 ot.bregman.convolutional_barycenter2d(A_nx, reg, method=method)
831 else:
832 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d(
833 A, reg, method=method, verbose=True, log=True
834 )
835 bary_wass = nx.to_numpy(
836 ot.bregman.convolutional_barycenter2d(A_nx, reg, method=method)
837 )
838
839 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
840 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-3)
841
842 # help in checking if log and verbose do not bug the function
843 ot.bregman.convolutional_barycenter2d(A, reg, log=True, verbose=True)
844
845
846 @pytest.skip_backend("tf")
847 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_log"])
848 def test_wasserstein_bary_2d_dtype_device(nx, method):
849 # Create the array of images to test
850 A = create_random_images_dist(42, size=20)
851
852 for tp in nx.__type_list__:
853 print(nx.dtype_device(tp))
854
855 Ab = nx.from_numpy(A, type_as=tp)
856
857 # wasserstein
858 reg = 1e-2
859 if nx.__name__ in ("jax", "tf") and method == "sinkhorn_log":
860 with pytest.raises(NotImplementedError):
861 ot.bregman.convolutional_barycenter2d(Ab, reg, method=method)
862 else:
863 # Compute the barycenter with numpy
864 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d(
865 A, reg, method=method, verbose=True, log=True
866 )
867 # Compute the barycenter with the backend
868 bary_wass_b = ot.bregman.convolutional_barycenter2d(Ab, reg, method=method)
869 # Convert the backend result to numpy, to compare with the numpy result
870 bary_wass = nx.to_numpy(bary_wass_b)
871
872 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
873 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-3)
874
875 # help in checking if log and verbose do not bug the function
876 ot.bregman.convolutional_barycenter2d(A, reg, log=True, verbose=True)
877
878 # Test that the dtype and device are the same after the computation
879 nx.assert_same_dtype_device(Ab, bary_wass_b)
880
881
882 @pytest.mark.skipif(not tf, reason="tf not installed")
883 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_log"])
884 def test_wasserstein_bary_2d_device_tf(method):
885 # Using the Tensorflow backend
886 nx = ot.backend.TensorflowBackend()
887
888 # Create the array of images to test
889 A = create_random_images_dist(42, size=20)
890
891 # Check that everything stays on the CPU
892 with tf.device("/CPU:0"):
893 Ab = nx.from_numpy(A)
894
895 # wasserstein
896 reg = 1e-2
897 if method == "sinkhorn_log":
898 with pytest.raises(NotImplementedError):
899 ot.bregman.convolutional_barycenter2d(Ab, reg, method=method)
900 else:
901 # Compute the barycenter with numpy
902 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d(
903 A, reg, method=method, verbose=True, log=True
904 )
905 # Compute the barycenter with the backend
906 bary_wass_b = ot.bregman.convolutional_barycenter2d(Ab, reg, method=method)
907 # Convert the backend result to numpy, to compare with the numpy result
908 bary_wass = nx.to_numpy(bary_wass_b)
909
910 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
911 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-3)
912
913 # help in checking if log and verbose do not bug the function
914 ot.bregman.convolutional_barycenter2d(A, reg, log=True, verbose=True)
915
916 # Test that the dtype and device are the same after the computation
917 nx.assert_same_dtype_device(Ab, bary_wass_b)
918
919 # Check that everything happens on the GPU
920 Ab = nx.from_numpy(A)
921
922 # wasserstein
923 reg = 1e-2
924 if method == "sinkhorn_log":
925 with pytest.raises(NotImplementedError):
926 ot.bregman.convolutional_barycenter2d(Ab, reg, method=method)
927 else:
928 # Compute the barycenter with numpy
929 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d(
930 A, reg, method=method, verbose=True, log=True
931 )
932 # Compute the barycenter with the backend
933 bary_wass_b = ot.bregman.convolutional_barycenter2d(Ab, reg, method=method)
934 # Convert the backend result to numpy, to compare with the numpy result
935 bary_wass = nx.to_numpy(bary_wass_b)
936
937 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
938 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-3)
939
940 # help in checking if log and verbose do not bug the function
941 ot.bregman.convolutional_barycenter2d(A, reg, log=True, verbose=True)
942
943 # Test that the dtype and device are the same after the computation
944 nx.assert_same_dtype_device(Ab, bary_wass_b)
945
946 # Check this only if GPU is available
947 if len(tf.config.list_physical_devices("GPU")) > 0:
948 assert nx.dtype_device(bary_wass_b)[1].startswith("GPU")
949
950
951 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_log"])
952 def test_wasserstein_bary_2d_debiased(nx, method):
953 # Create the array of images to test
954 A = create_random_images_dist(42, size=20)
955
956 A_nx = nx.from_numpy(A)
957
958 # wasserstein
959 reg = 1e-2
960 if nx.__name__ in ("jax", "tf") and method == "sinkhorn_log":
961 with pytest.raises(NotImplementedError):
962 ot.bregman.convolutional_barycenter2d_debiased(A_nx, reg, method=method)
963 else:
964 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d_debiased(
965 A, reg, method=method, verbose=True, log=True
966 )
967 bary_wass = nx.to_numpy(
968 ot.bregman.convolutional_barycenter2d_debiased(A_nx, reg, method=method)
969 )
970
971 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
972 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-3)
973
974 # help in checking if log and verbose do not bug the function
975 ot.bregman.convolutional_barycenter2d_debiased(A, reg, log=True, verbose=True)
976
977
978 @pytest.skip_backend("tf")
979 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_log"])
980 def test_wasserstein_bary_2d_debiased_dtype_device(nx, method):
981 # Create the array of images to test
982 A = create_random_images_dist(42, size=20)
983
984 for tp in nx.__type_list__:
985 print(nx.dtype_device(tp))
986
987 Ab = nx.from_numpy(A, type_as=tp)
988
989 # wasserstein
990 reg = 1e-2
991 if nx.__name__ in ("jax", "tf") and method == "sinkhorn_log":
992 with pytest.raises(NotImplementedError):
993 ot.bregman.convolutional_barycenter2d_debiased(Ab, reg, method=method)
994 else:
995 # Compute the barycenter with numpy
996 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d_debiased(
997 A, reg, method=method, verbose=True, log=True
998 )
999 # Compute the barycenter with the backend
1000 bary_wass_b = ot.bregman.convolutional_barycenter2d_debiased(
1001 Ab, reg, method=method
1002 )
1003 # Convert the backend result to numpy, to compare with the numpy result
1004 bary_wass = nx.to_numpy(bary_wass_b)
1005
1006 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
1007 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-3)
1008
1009 # help in checking if log and verbose do not bug the function
1010 ot.bregman.convolutional_barycenter2d_debiased(
1011 A, reg, log=True, verbose=True
1012 )
1013
1014 # Test that the dtype and device are the same after the computation
1015 nx.assert_same_dtype_device(Ab, bary_wass_b)
1016
1017
1018 @pytest.mark.skipif(not tf, reason="tf not installed")
1019 @pytest.mark.parametrize("method", ["sinkhorn", "sinkhorn_log"])
1020 def test_wasserstein_bary_2d_debiased_device_tf(method):
1021 # Using the Tensorflow backend
1022 nx = ot.backend.TensorflowBackend()
1023
1024 # Create the array of images to test
1025 A = create_random_images_dist(42, size=20)
1026
1027 # Check that everything stays on the CPU
1028 with tf.device("/CPU:0"):
1029 Ab = nx.from_numpy(A)
1030
1031 # wasserstein
1032 reg = 1e-2
1033 if method == "sinkhorn_log":
1034 with pytest.raises(NotImplementedError):
1035 ot.bregman.convolutional_barycenter2d_debiased(Ab, reg, method=method)
1036 else:
1037 # Compute the barycenter with numpy
1038 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d_debiased(
1039 A, reg, method=method, verbose=True, log=True
1040 )
1041 # Compute the barycenter with the backend
1042 bary_wass_b = ot.bregman.convolutional_barycenter2d_debiased(
1043 Ab, reg, method=method
1044 )
1045 # Convert the backend result to numpy, to compare with the numpy result
1046 bary_wass = nx.to_numpy(bary_wass_b)
1047
1048 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
1049 np.testing.assert_allclose(bary_wass, bary_wass_np, atol=1e-3)
1050
1051 # help in checking if log and verbose do not bug the function
1052 ot.bregman.convolutional_barycenter2d_debiased(
1053 A, reg, log=True, verbose=True
1054 )
1055
1056 # Test that the dtype and device are the same after the computation
1057 nx.assert_same_dtype_device(Ab, bary_wass_b)
1058
1059 # Check that everything happens on the GPU
1060 Ab = nx.from_numpy(A)
1061
1062 # wasserstein
1063 reg = 1e-2
1064 if method == "sinkhorn_log":
1065 with pytest.raises(NotImplementedError):
1066 ot.bregman.convolutional_barycenter2d_debiased(Ab, reg, method=method)
1067 else:
1068 # Compute the barycenter with numpy
1069 bary_wass_np, log_np = ot.bregman.convolutional_barycenter2d_debiased(
1070 A, reg, method=method, verbose=True, log=True
1071 )
1072 # Compute the barycenter with the backend
1073 bary_wass_b = ot.bregman.convolutional_barycenter2d_debiased(
1074 Ab, reg, method=method
1075 )
1076 # Convert the backend result to numpy, to compare with the numpy result
1077 bary_wass = nx.to_numpy(bary_wass_b)
1078
1079 np.testing.assert_allclose(1, np.sum(bary_wass), rtol=1e-3)
1080
1081
1082 def test_unmix(nx):
1083 n_bins = 50 # nb bins
1084
1085 # Gaussian distributions
1086 a1 = ot.datasets.make_1D_gauss(n_bins, m=20, s=10) # m= mean, s= std
1087 a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)
1088
1089 a = ot.datasets.make_1D_gauss(n_bins, m=30, s=10)
1090
1091 # creating matrix A containing all distributions
1092 D = np.vstack((a1, a2)).T
1093
1094 # loss matrix + normalization
1095 M = ot.utils.dist0(n_bins)
1096 M /= M.max()
1097
1098 M0 = ot.utils.dist0(2)
1099 M0 /= M0.max()
1100 h0 = ot.unif(2)
1101
1102 ab, Db, M_nx, M0b, h0b = nx.from_numpy(a, D, M, M0, h0)
1103
1104 # wasserstein
1105 reg = 1e-3
1106 um_np = ot.bregman.unmix(a, D, M, M0, h0, reg, 1, alpha=0.01)
1107 um = nx.to_numpy(ot.bregman.unmix(ab, Db, M_nx, M0b, h0b, reg, 1, alpha=0.01))
1108
1109 np.testing.assert_allclose(1, np.sum(um), rtol=1e-03, atol=1e-03)
1110 np.testing.assert_allclose([0.5, 0.5], um, rtol=1e-03, atol=1e-03)
1111 np.testing.assert_allclose(um, um_np)
1112
1113 ot.bregman.unmix(ab, Db, M_nx, M0b, h0b, reg, 1, alpha=0.01, log=True, verbose=True)
1114
1115
1116 def test_empirical_sinkhorn(nx):
1117 # test sinkhorn
1118 n = 10
1119 a = ot.unif(n)
1120 b = ot.unif(n)
1121
1122 X_s = np.reshape(1.0 * np.arange(n), (n, 1))
1123 X_t = np.reshape(1.0 * np.arange(0, n), (n, 1))
1124 M = ot.dist(X_s, X_t)
1125 M_m = ot.dist(X_s, X_t, metric="euclidean")
1126
1127 ab, bb, X_sb, X_tb, M_nx, M_mb = nx.from_numpy(a, b, X_s, X_t, M, M_m)
1128
1129 G_sqe = nx.to_numpy(ot.bregman.empirical_sinkhorn(X_sb, X_tb, 1))
1130 sinkhorn_sqe = nx.to_numpy(ot.sinkhorn(ab, bb, M_nx, 1))
1131
1132 G_log, log_es = ot.bregman.empirical_sinkhorn(X_sb, X_tb, 0.1, log=True)
1133 G_log = nx.to_numpy(G_log)
1134 sinkhorn_log, log_s = ot.sinkhorn(ab, bb, M_nx, 0.1, log=True)
1135 sinkhorn_log = nx.to_numpy(sinkhorn_log)
1136
1137 G_m = nx.to_numpy(ot.bregman.empirical_sinkhorn(X_sb, X_tb, 1, metric="euclidean"))
1138 sinkhorn_m = nx.to_numpy(ot.sinkhorn(ab, bb, M_mb, 1))
1139
1140 loss_emp_sinkhorn = nx.to_numpy(ot.bregman.empirical_sinkhorn2(X_sb, X_tb, 1))
1141 loss_sinkhorn = nx.to_numpy(ot.sinkhorn2(ab, bb, M_nx, 1))
1142
1143 # check constraints
1144 np.testing.assert_allclose(
1145 sinkhorn_sqe.sum(1), G_sqe.sum(1), atol=1e-05
1146 ) # metric sqeuclidian
1147 np.testing.assert_allclose(
1148 sinkhorn_sqe.sum(0), G_sqe.sum(0), atol=1e-05
1149 ) # metric sqeuclidian
1150 np.testing.assert_allclose(sinkhorn_log.sum(1), G_log.sum(1), atol=1e-05) # log
1151 np.testing.assert_allclose(sinkhorn_log.sum(0), G_log.sum(0), atol=1e-05) # log
1152 np.testing.assert_allclose(
1153 sinkhorn_m.sum(1), G_m.sum(1), atol=1e-05
1154 ) # metric euclidian
1155 np.testing.assert_allclose(
1156 sinkhorn_m.sum(0), G_m.sum(0), atol=1e-05
1157 ) # metric euclidian
1158 np.testing.assert_allclose(loss_emp_sinkhorn, loss_sinkhorn, atol=1e-05)
1159
1160
1161 @pytest.mark.skipif(not geomloss, reason="pytorch not installed")
1162 @pytest.skip_backend("tf")
1163 @pytest.skip_backend("cupy")
1164 @pytest.skip_backend("jax")
1165 @pytest.mark.parametrize("metric", ["sqeuclidean", "euclidean"])
1166 def test_geomloss_solver(nx, metric):
1167 # test sinkhorn
1168 n = 10
1169 a = ot.unif(n)
1170 b = ot.unif(n)
1171
1172 X_s = np.reshape(1.0 * np.arange(n), (n, 1))
1173 X_t = np.reshape(1.0 * np.arange(0, n), (n, 1))
1174
1175 ab, bb, X_sb, X_tb = nx.from_numpy(a, b, X_s, X_t)
1176
1177 G_sqe = nx.to_numpy(ot.bregman.empirical_sinkhorn(X_sb, X_tb, 1, metric=metric))
1178
1179 value, log = ot.bregman.empirical_sinkhorn2_geomloss(
1180 X_sb, X_tb, 1, metric=metric, log=True
1181 )
1182 G_geomloss = nx.to_numpy(log["lazy_plan"][:])
1183
1184 print(value)
1185
1186 # call with log = False
1187 ot.bregman.empirical_sinkhorn2_geomloss(X_sb, X_tb, 1, metric=metric)
1188
1189 # check equality of plans
1190 np.testing.assert_allclose(G_sqe, G_geomloss, atol=1e-03) # metric sqeuclidian
1191
1192 # check error on wrong metric
1193 with pytest.raises(ValueError):
1194 ot.bregman.empirical_sinkhorn2_geomloss(X_sb, X_tb, 1, metric="wrong_metric")
1195
1196
1197 def test_lazy_empirical_sinkhorn(nx):
1198 # test sinkhorn
1199 n = 10
1200 a = ot.unif(n)
1201 b = ot.unif(n)
1202 numIterMax = 1000
1203
1204 X_s = np.reshape(np.arange(n, dtype=np.float64), (n, 1))
1205 X_t = np.reshape(np.arange(0, n, dtype=np.float64), (n, 1))
1206 M = ot.dist(X_s, X_t)
1207 M_m = ot.dist(X_s, X_t, metric="euclidean")
1208
1209 ab, bb, X_sb, X_tb, M_nx, M_mb = nx.from_numpy(a, b, X_s, X_t, M, M_m)
1210
1211 f, g = ot.bregman.empirical_sinkhorn(
1212 X_sb,
1213 X_tb,
1214 1,
1215 numIterMax=numIterMax,
1216 isLazy=True,
1217 batchSize=(1, 3),
1218 verbose=True,
1219 )
1220 f, g = nx.to_numpy(f), nx.to_numpy(g)
1221 G_sqe = np.exp(f[:, None] + g[None, :] - M / 1)
1222 sinkhorn_sqe = nx.to_numpy(ot.sinkhorn(ab, bb, M_nx, 1))
1223
1224 f, g, log_es = ot.bregman.empirical_sinkhorn(
1225 X_sb, X_tb, 1, numIterMax=numIterMax, isLazy=True, batchSize=5, log=True
1226 )
1227 f, g = nx.to_numpy(f), nx.to_numpy(g)
1228 G_log = np.exp(f[:, None] + g[None, :] - M / 1)
1229 sinkhorn_log, log_s = ot.sinkhorn(ab, bb, M_nx, 1, log=True)
1230 sinkhorn_log = nx.to_numpy(sinkhorn_log)
1231
1232 f, g = ot.bregman.empirical_sinkhorn(
1233 X_sb,
1234 X_tb,
1235 1,
1236 metric="euclidean",
1237 numIterMax=numIterMax,
1238 isLazy=True,
1239 batchSize=1,
1240 )
1241 f, g = nx.to_numpy(f), nx.to_numpy(g)
1242 G_m = np.exp(f[:, None] + g[None, :] - M_m / 1)
1243 sinkhorn_m = nx.to_numpy(ot.sinkhorn(ab, bb, M_mb, 1))
1244
1245 loss_emp_sinkhorn, log = ot.bregman.empirical_sinkhorn2(
1246 X_sb, X_tb, 1, numIterMax=numIterMax, isLazy=True, batchSize=5, log=True
1247 )
1248 G_lazy = nx.to_numpy(log["lazy_plan"][:])
1249 loss_emp_sinkhorn = nx.to_numpy(loss_emp_sinkhorn)
1250 loss_sinkhorn = nx.to_numpy(ot.sinkhorn2(ab, bb, M_nx, 1))
1251
1252 loss_emp_sinkhorn = ot.bregman.empirical_sinkhorn2(
1253 X_sb, X_tb, 1, numIterMax=numIterMax, isLazy=True, batchSize=1, log=False
1254 )
1255
1256 # check constraints
1257 np.testing.assert_allclose(
1258 sinkhorn_sqe.sum(1), G_sqe.sum(1), atol=1e-05
1259 ) # metric sqeuclidian
1260 np.testing.assert_allclose(
1261 sinkhorn_sqe.sum(0), G_sqe.sum(0), atol=1e-05
1262 ) # metric sqeuclidian
1263 np.testing.assert_allclose(sinkhorn_log.sum(1), G_log.sum(1), atol=1e-05) # log
1264 np.testing.assert_allclose(sinkhorn_log.sum(0), G_log.sum(0), atol=1e-05) # log
1265 np.testing.assert_allclose(
1266 sinkhorn_m.sum(1), G_m.sum(1), atol=1e-05
1267 ) # metric euclidian
1268 np.testing.assert_allclose(
1269 sinkhorn_m.sum(0), G_m.sum(0), atol=1e-05
1270 ) # metric euclidian
1271 np.testing.assert_allclose(loss_emp_sinkhorn, loss_sinkhorn, atol=1e-05)
1272 np.testing.assert_allclose(G_log, G_lazy, atol=1e-05)
1273
1274
1275 def test_empirical_sinkhorn_divergence(nx):
1276 # Test sinkhorn divergence
1277 n = 10
1278 a = np.linspace(1, n, n)
1279 a /= a.sum()
1280 b = ot.unif(n)
1281 X_s = np.reshape(np.arange(n, dtype=np.float64), (n, 1))
1282 X_t = np.reshape(np.arange(0, n * 2, 2, dtype=np.float64), (n, 1))
1283 M = ot.dist(X_s, X_t)
1284 M_s = ot.dist(X_s, X_s)
1285 M_t = ot.dist(X_t, X_t)
1286
1287 ab, bb, X_sb, X_tb, M_nx, M_sb, M_tb = nx.from_numpy(a, b, X_s, X_t, M, M_s, M_t)
1288
1289 emp_sinkhorn_div = nx.to_numpy(
1290 ot.bregman.empirical_sinkhorn_divergence(X_sb, X_tb, 1, a=ab, b=bb)
1291 )
1292 sinkhorn_div = nx.to_numpy(
1293 ot.sinkhorn2(ab, bb, M_nx, 1)
1294 - 1 / 2 * ot.sinkhorn2(ab, ab, M_sb, 1)
1295 - 1 / 2 * ot.sinkhorn2(bb, bb, M_tb, 1)
1296 )
1297 emp_sinkhorn_div_np = ot.bregman.empirical_sinkhorn_divergence(
1298 X_s, X_t, 1, a=a, b=b
1299 )
1300
1301 # check constraints
1302 np.testing.assert_allclose(emp_sinkhorn_div, emp_sinkhorn_div_np, atol=1e-05)
1303 np.testing.assert_allclose(
1304 emp_sinkhorn_div, sinkhorn_div, atol=1e-05
1305 ) # cf conv emp sinkhorn
1306
1307 ot.bregman.empirical_sinkhorn_divergence(X_sb, X_tb, 1, a=ab, b=bb, log=True)
1308
1309
1310 @pytest.mark.skipif(not torch, reason="No torch available")
1311 def test_empirical_sinkhorn_divergence_gradient():
1312 # Test sinkhorn divergence
1313 n = 10
1314 a = np.linspace(1, n, n)
1315 a /= a.sum()
1316 b = ot.unif(n)
1317 X_s = np.reshape(np.arange(n, dtype=np.float64), (n, 1))
1318 X_t = np.reshape(np.arange(0, n * 2, 2, dtype=np.float64), (n, 1))
1319
1320 nx = ot.backend.TorchBackend()
1321
1322 ab, bb, X_sb, X_tb = nx.from_numpy(a, b, X_s, X_t)
1323
1324 ab.requires_grad = True
1325 bb.requires_grad = True
1326 X_sb.requires_grad = True
1327 X_tb.requires_grad = True
1328
1329 emp_sinkhorn_div = ot.bregman.empirical_sinkhorn_divergence(
1330 X_sb, X_tb, 1, a=ab, b=bb
1331 )
1332
1333 emp_sinkhorn_div.backward()
1334
1335 assert ab.grad is not None
1336 assert bb.grad is not None
1337 assert X_sb.grad is not None
1338 assert X_tb.grad is not None
1339
1340
1341 def test_stabilized_vs_sinkhorn_multidim(nx):
1342 # test if stable version matches sinkhorn
1343 # for multidimensional inputs
1344 n = 100
1345
1346 # Gaussian distributions
1347 a = ot.datasets.make_1D_gauss(n, m=20, s=5) # m= mean, s= std
1348 b1 = ot.datasets.make_1D_gauss(n, m=60, s=8)
1349 b2 = ot.datasets.make_1D_gauss(n, m=30, s=4)
1350
1351 # creating matrix A containing all distributions
1352 b = np.vstack((b1, b2)).T
1353
1354 M = ot.utils.dist0(n)
1355 M /= np.median(M)
1356 epsilon = 0.1
1357
1358 ab, bb, M_nx = nx.from_numpy(a, b, M)
1359
1360 G_np, _ = ot.bregman.sinkhorn(a, b, M, reg=epsilon, method="sinkhorn", log=True)
1361 G, log = ot.bregman.sinkhorn(
1362 ab, bb, M_nx, reg=epsilon, method="sinkhorn_stabilized", log=True
1363 )
1364 G = nx.to_numpy(G)
1365 G2, log2 = ot.bregman.sinkhorn(ab, bb, M_nx, epsilon, method="sinkhorn", log=True)
1366 G2 = nx.to_numpy(G2)
1367
1368 np.testing.assert_allclose(G_np, G2)
1369 np.testing.assert_allclose(G, G2)
1370
1371
1372 def test_implemented_methods():
1373 IMPLEMENTED_METHODS = ["sinkhorn", "sinkhorn_stabilized"]
1374 ONLY_1D_methods = ["greenkhorn", "sinkhorn_epsilon_scaling"]
1375 NOT_VALID_TOKENS = ["foo"]
1376 # test generalized sinkhorn for unbalanced OT barycenter
1377 n = 3
1378 rng = np.random.RandomState(42)
1379
1380 x = rng.randn(n, 2)
1381 a = ot.utils.unif(n)
1382
1383 # make dists unbalanced
1384 b = ot.utils.unif(n)
1385 A = rng.rand(n, 2)
1386 A /= A.sum(0, keepdims=True)
1387 M = ot.dist(x, x)
1388 epsilon = 1.0
1389
1390 for method in IMPLEMENTED_METHODS:
1391 ot.bregman.sinkhorn(a, b, M, epsilon, method=method)
1392 ot.bregman.sinkhorn2(a, b, M, epsilon, method=method)
1393 ot.bregman.barycenter(A, M, reg=epsilon, method=method)
1394 with pytest.raises(ValueError):
1395 for method in set(NOT_VALID_TOKENS):
1396 ot.bregman.sinkhorn(a, b, M, epsilon, method=method)
1397 ot.bregman.sinkhorn2(a, b, M, epsilon, method=method)
1398 ot.bregman.barycenter(A, M, reg=epsilon, method=method)
1399 for method in ONLY_1D_methods:
1400 ot.bregman.sinkhorn(a, b, M, epsilon, method=method)
1401 with pytest.raises(ValueError):
1402 ot.bregman.sinkhorn2(a, b, M, epsilon, method=method)
1403
1404
1405 @pytest.skip_backend("tf")
1406 @pytest.skip_backend("cupy")
1407 @pytest.skip_backend("jax")
1408 @pytest.mark.filterwarnings("ignore:Bottleneck")
1409 def test_screenkhorn(nx):
1410 # test screenkhorn
1411 rng = np.random.RandomState(0)
1412 n = 100
1413 a = ot.unif(n)
1414 b = ot.unif(n)
1415
1416 x = rng.randn(n, 2)
1417 M = ot.dist(x, x)
1418
1419 ab, bb, M_nx = nx.from_numpy(a, b, M)
1420
1421 # sinkhorn
1422 G_sink = nx.to_numpy(ot.sinkhorn(ab, bb, M_nx, 1e-1))
1423 # screenkhorn
1424 G_screen = nx.to_numpy(
1425 ot.bregman.screenkhorn(ab, bb, M_nx, 1e-1, uniform=True, verbose=True)
1426 )
1427 # check marginals
1428 np.testing.assert_allclose(G_sink.sum(0), G_screen.sum(0), atol=1e-02)
1429 np.testing.assert_allclose(G_sink.sum(1), G_screen.sum(1), atol=1e-02)
1430
1431
1432 def test_convolutional_barycenter_non_square(nx):
1433 # test for image with height not equal width
1434 A = np.ones((2, 2, 3)) / (2 * 3)
1435 A_nx = nx.from_numpy(A)
1436
1437 b_np = ot.bregman.convolutional_barycenter2d(A, 1e-03)
1438 b = nx.to_numpy(ot.bregman.convolutional_barycenter2d(A_nx, 1e-03))
1439
1440 np.testing.assert_allclose(np.ones((2, 3)) / (2 * 3), b, atol=1e-02)
1441 np.testing.assert_allclose(np.ones((2, 3)) / (2 * 3), b, atol=1e-02)
1442 np.testing.assert_allclose(b, b_np)
1443
1444
1445 def test_sinkhorn_warmstart():
1446 m, n = 10, 20
1447 a = ot.unif(m)
1448 b = ot.unif(n)
1449
1450 Xs = np.arange(m) * 1.0
1451 Xt = np.arange(n) * 1.0
1452 M = ot.dist(Xs.reshape(-1, 1), Xt.reshape(-1, 1))
1453
1454 # Generate warmstart from dual vectors of unregularized OT
1455 _, log = ot.lp.emd(a, b, M, log=True)
1456 warmstart = (log["u"], log["v"])
1457
1458 reg = 1
1459
1460 # Optimal plan with uniform warmstart
1461 pi_unif, _ = ot.bregman.sinkhorn(
1462 a, b, M, reg, method="sinkhorn", log=True, warmstart=None
1463 )
1464 # Optimal plan with warmstart generated from unregularized OT
1465 pi_sh, _ = ot.bregman.sinkhorn(
1466 a, b, M, reg, method="sinkhorn", log=True, warmstart=warmstart
1467 )
1468 pi_sh_log, _ = ot.bregman.sinkhorn(
1469 a, b, M, reg, method="sinkhorn_log", log=True, warmstart=warmstart
1470 )
1471 pi_sh_stab, _ = ot.bregman.sinkhorn(
1472 a, b, M, reg, method="sinkhorn_stabilized", log=True, warmstart=warmstart
1473 )
1474 pi_sh_sc, _ = ot.bregman.sinkhorn(
1475 a, b, M, reg, method="sinkhorn_epsilon_scaling", log=True, warmstart=warmstart
1476 )
1477
1478 np.testing.assert_allclose(pi_unif, pi_sh, atol=1e-05)
1479 np.testing.assert_allclose(pi_unif, pi_sh_log, atol=1e-05)
1480 np.testing.assert_allclose(pi_unif, pi_sh_stab, atol=1e-05)
1481 np.testing.assert_allclose(pi_unif, pi_sh_sc, atol=1e-05)
1482
1483
1484 def test_empirical_sinkhorn_warmstart():
1485 m, n = 10, 20
1486 Xs = np.arange(m).reshape(-1, 1) * 1.0
1487 Xt = np.arange(n).reshape(-1, 1) * 1.0
1488 M = ot.dist(Xs, Xt)
1489
1490 # Generate warmstart from dual vectors of unregularized OT
1491 a = ot.unif(m)
1492 b = ot.unif(n)
1493 _, log = ot.lp.emd(a, b, M, log=True)
1494 warmstart = (log["u"], log["v"])
1495
1496 reg = 1
1497
1498 # Optimal plan with uniform warmstart
1499 f, g, _ = ot.bregman.empirical_sinkhorn(
1500 X_s=Xs, X_t=Xt, reg=reg, isLazy=True, log=True, warmstart=None
1501 )
1502 pi_unif = np.exp(f[:, None] + g[None, :] - M / reg)
1503 # Optimal plan with warmstart generated from unregularized OT
1504 f, g, _ = ot.bregman.empirical_sinkhorn(
1505 X_s=Xs, X_t=Xt, reg=reg, isLazy=True, log=True, warmstart=warmstart
1506 )
1507 pi_ws_lazy = np.exp(f[:, None] + g[None, :] - M / reg)
1508 pi_ws_not_lazy, _ = ot.bregman.empirical_sinkhorn(
1509 X_s=Xs, X_t=Xt, reg=reg, isLazy=False, log=True, warmstart=warmstart
1510 )
1511
1512 np.testing.assert_allclose(pi_unif, pi_ws_lazy, atol=1e-05)
1513 np.testing.assert_allclose(pi_unif, pi_ws_not_lazy, atol=1e-05)
1514
1515
1516 def test_empirical_sinkhorn_divergence_warmstart():
1517 m, n = 10, 20
1518 Xs = np.arange(m).reshape(-1, 1) * 1.0
1519 Xt = np.arange(n).reshape(-1, 1) * 1.0
1520 M = ot.dist(Xs, Xt)
1521
1522 # Generate warmstart from dual vectors of unregularized OT
1523 a = ot.unif(m)
1524 b = ot.unif(n)
1525 _, log = ot.lp.emd(a, b, M, log=True)
1526 warmstart = (log["u"], log["v"])
1527
1528 reg = 1
1529
1530 # Optimal plan with uniform warmstart
1531 sd_unif, _ = ot.bregman.empirical_sinkhorn_divergence(
1532 X_s=Xs, X_t=Xt, reg=reg, isLazy=True, log=True, warmstart=None
1533 )
1534 # Optimal plan with warmstart generated from unregularized OT
1535 sd_ws_lazy, _ = ot.bregman.empirical_sinkhorn_divergence(
1536 X_s=Xs, X_t=Xt, reg=reg, isLazy=True, log=True, warmstart=warmstart
1537 )
1538 sd_ws_not_lazy, _ = ot.bregman.empirical_sinkhorn_divergence(
1539 X_s=Xs, X_t=Xt, reg=reg, isLazy=False, log=True, warmstart=warmstart
1540 )
1541
1542 np.testing.assert_allclose(sd_unif, sd_ws_lazy, atol=1e-05)
1543 np.testing.assert_allclose(sd_unif, sd_ws_not_lazy, atol=1e-05)