Debian Codegraph @

test/test_solvers.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """Tests for ot solvers"""
2
3 # Author: Remi Flamary <[email protected]>
4 #
5 # License: MIT License
6
7 import itertools
8 import numpy as np
9 import pytest
10 import sys
11
12 import ot
13 from ot.bregman import geomloss
14 from ot.backend import torch
15
16
17 lst_reg = [None, 1]
18 lst_reg_type = ["KL", "entropy", "L2", "tuple"]
19 lst_unbalanced = [None, 0.9]
20 lst_unbalanced_type = ["KL", "L2", "TV"]
21
22 lst_reg_type_gromov = ["entropy"]
23 lst_gw_losses = ["L2", "KL"]
24 lst_unbalanced_type_gromov = ["KL", "semirelaxed", "partial"]
25 lst_unbalanced_gromov = [None, 0.9]
26 lst_alpha = [0, 0.4, 0.9, 1]
27
28 lst_method_params_solve_sample = [
29 {"method": "1d"},
30 {"method": "1d", "metric": "euclidean"},
31 {"method": "gaussian"},
32 {"method": "gaussian", "reg": 1},
33 {"method": "factored", "rank": 10},
34 {"method": "lowrank", "rank": 10},
35 ]
36
37 lst_parameters_solve_sample_NotImplemented = [
38 {"method": "1d", "metric": "any other one"}, # fail 1d on weird metrics
39 {
40 "method": "gaussian",
41 "metric": "euclidean",
42 }, # fail gaussian on metric not euclidean
43 {
44 "method": "factored",
45 "metric": "euclidean",
46 }, # fail factored on metric not euclidean
47 {
48 "method": "lowrank",
49 "metric": "euclidean",
50 }, # fail lowrank on metric not euclidean
51 {"lazy": True}, # fail lazy for non regularized
52 {"lazy": True, "unbalanced": 1}, # fail lazy for non regularized unbalanced
53 {
54 "lazy": True,
55 "reg": 1,
56 "unbalanced": 1,
57 }, # fail lazy for unbalanced and regularized
58 ]
59
60 # set readable ids for each param
61 lst_method_params_solve_sample = [
62 pytest.param(param, id=str(param)) for param in lst_method_params_solve_sample
63 ]
64 lst_parameters_solve_sample_NotImplemented = [
65 pytest.param(param, id=str(param))
66 for param in lst_parameters_solve_sample_NotImplemented
67 ]
68
69
70 def assert_allclose_sol(sol1, sol2):
71 lst_attr = [
72 "value",
73 "value_linear",
74 "plan",
75 "potential_a",
76 "potential_b",
77 "marginal_a",
78 "marginal_b",
79 ]
80
81 nx1 = sol1._backend if sol1._backend is not None else ot.backend.NumpyBackend()
82 nx2 = sol2._backend if sol2._backend is not None else ot.backend.NumpyBackend()
83
84 for attr in lst_attr:
85 if getattr(sol1, attr) is not None and getattr(sol2, attr) is not None:
86 try:
87 np.allclose(
88 nx1.to_numpy(getattr(sol1, attr)),
89 nx2.to_numpy(getattr(sol2, attr)),
90 equal_nan=True,
91 )
92 except NotImplementedError:
93 pass
94 elif getattr(sol1, attr) is None and getattr(sol2, attr) is None:
95 return True
96 else:
97 return False
98
99
100 def test_solve(nx):
101 n_samples_s = 10
102 n_samples_t = 7
103 n_features = 2
104 rng = np.random.RandomState(0)
105
106 x = rng.randn(n_samples_s, n_features)
107 y = rng.randn(n_samples_t, n_features)
108 a = ot.utils.unif(n_samples_s)
109 b = ot.utils.unif(n_samples_t)
110
111 M = ot.dist(x, y)
112 reg = 1e-1
113
114 # solve unif weights
115 sol0 = ot.solve(M, reg=reg)
116
117 print(sol0)
118
119 # solve signe weights
120 sol = ot.solve(M, a, b, reg=reg)
121
122 # check some attributes
123 sol.potentials
124 sol.sparse_plan
125 sol.marginals
126 sol.status
127
128 # print("dual = {}".format(sol.potentials))
129 # assert_allclose_sol(sol0, sol)
130
131 # solve in backend
132 ab, bb, Mb = nx.from_numpy(a, b, M)
133 solb = ot.solve(M, a, b)
134
135 assert_allclose_sol(sol, solb)
136
137 # test not implemented unbalanced and check raise
138 with pytest.raises(NotImplementedError):
139 sol0 = ot.solve(M, unbalanced=1, unbalanced_type="cryptic divergence")
140
141 # test not implemented reg_type and check raise
142 with pytest.raises(NotImplementedError):
143 sol0 = ot.solve(M, reg=1, reg_type="cryptic divergence")
144
145
146 @pytest.mark.skipif(not torch, reason="torch no installed")
147 def test_solve_envelope():
148 n_samples_s = 10
149 n_samples_t = 7
150 n_features = 2
151 rng = np.random.RandomState(0)
152
153 x = rng.randn(n_samples_s, n_features)
154 y = rng.randn(n_samples_t, n_features)
155 a = ot.utils.unif(n_samples_s)
156 b = ot.utils.unif(n_samples_t)
157 M = ot.dist(x, y)
158
159 a = torch.tensor(a, requires_grad=True)
160 b = torch.tensor(b, requires_grad=True)
161 M = torch.tensor(M, requires_grad=True)
162
163 sol0 = ot.solve(M, a, b, reg=10, grad="envelope")
164 sol0.value.backward()
165
166 gM0 = M.grad.clone()
167 ga0 = a.grad.clone()
168 gb0 = b.grad.clone()
169
170 a = torch.tensor(a, requires_grad=True)
171 b = torch.tensor(b, requires_grad=True)
172 M = torch.tensor(M, requires_grad=True)
173
174 sol = ot.solve(M, a, b, reg=10, grad="autodiff")
175 sol.value.backward()
176
177 gM = M.grad.clone()
178 ga = a.grad.clone()
179 gb = b.grad.clone()
180
181 # Note, gradients aer invariant to change in constant so we center them
182 assert torch.allclose(gM0, gM)
183 assert torch.allclose(ga0 - ga0.mean(), ga - ga.mean())
184 assert torch.allclose(gb0 - gb0.mean(), gb - gb.mean())
185
186
187 @pytest.mark.parametrize(
188 "reg,reg_type,unbalanced,unbalanced_type",
189 itertools.product(lst_reg, lst_reg_type, lst_unbalanced, lst_unbalanced_type),
190 )
191 def test_solve_grid(nx, reg, reg_type, unbalanced, unbalanced_type):
192 n_samples_s = 10
193 n_samples_t = 7
194 n_features = 2
195 rng = np.random.RandomState(0)
196
197 x = rng.randn(n_samples_s, n_features)
198 y = rng.randn(n_samples_t, n_features)
199 a = ot.utils.unif(n_samples_s)
200 b = ot.utils.unif(n_samples_t)
201
202 M = ot.dist(x, y)
203
204 try:
205 if reg_type == "tuple":
206
207 def f(G):
208 return np.sum(G**2)
209
210 def df(G):
211 return 2 * G
212
213 reg_type = (f, df)
214
215 # solve unif weights
216 sol0 = ot.solve(
217 M,
218 reg=reg,
219 reg_type=reg_type,
220 unbalanced=unbalanced,
221 unbalanced_type=unbalanced_type,
222 )
223
224 # solve signe weights
225 sol = ot.solve(
226 M,
227 a,
228 b,
229 reg=reg,
230 reg_type=reg_type,
231 unbalanced=unbalanced,
232 unbalanced_type=unbalanced_type,
233 )
234
235 assert_allclose_sol(sol0, sol)
236
237 # solve in backend
238 ab, bb, Mb = nx.from_numpy(a, b, M)
239
240 if isinstance(reg_type, tuple):
241
242 def f(G):
243 return nx.sum(G**2)
244
245 def df(G):
246 return 2 * G
247
248 reg_type = (f, df)
249
250 solb = ot.solve(
251 Mb,
252 ab,
253 bb,
254 reg=reg,
255 reg_type=reg_type,
256 unbalanced=unbalanced,
257 unbalanced_type=unbalanced_type,
258 )
259
260 assert_allclose_sol(sol, solb)
261
262 except NotImplementedError:
263 pytest.skip("Not implemented")
264
265
266 def test_solve_not_implemented(nx):
267 n_samples_s = 10
268 n_samples_t = 7
269 n_features = 2
270 rng = np.random.RandomState(0)
271
272 x = rng.randn(n_samples_s, n_features)
273 y = rng.randn(n_samples_t, n_features)
274
275 M = ot.dist(x, y)
276
277 # test not implemented and check raise
278 with pytest.raises(NotImplementedError):
279 ot.solve(M, reg=1.0, reg_type="cryptic divergence")
280 with pytest.raises(NotImplementedError):
281 ot.solve(M, unbalanced=1.0, unbalanced_type="cryptic divergence")
282
283
284 def test_solve_gromov(nx):
285 np.random.seed(0)
286
287 n_samples_s = 3
288 n_samples_t = 5
289
290 Ca = np.random.rand(n_samples_s, n_samples_s)
291 Ca = (Ca + Ca.T) / 2
292
293 Cb = np.random.rand(n_samples_t, n_samples_t)
294 Cb = (Cb + Cb.T) / 2
295
296 a = ot.utils.unif(n_samples_s)
297 b = ot.utils.unif(n_samples_t)
298
299 M = np.random.rand(n_samples_s, n_samples_t)
300
301 sol0 = ot.solve_gromov(Ca, Cb) # GW
302 sol = ot.solve_gromov(Ca, Cb, a=a, b=b) # GW
303 sol0_fgw = ot.solve_gromov(Ca, Cb, M) # FGW
304
305 # check some attributes
306 sol.potentials
307 sol.marginals
308
309 assert_allclose_sol(sol0, sol)
310
311 # solve in backend
312 ax, bx, Mx, Cax, Cbx = nx.from_numpy(a, b, M, Ca, Cb)
313
314 solx = ot.solve_gromov(Cax, Cbx, a=ax, b=bx) # GW
315 solx_fgw = ot.solve_gromov(Cax, Cbx, Mx) # FGW
316
317 assert_allclose_sol(sol, solx)
318 assert_allclose_sol(sol0_fgw, solx_fgw)
319
320
321 @pytest.mark.parametrize(
322 "reg,reg_type,unbalanced,unbalanced_type,alpha,loss",
323 itertools.product(
324 lst_reg,
325 lst_reg_type_gromov,
326 lst_unbalanced_gromov,
327 lst_unbalanced_type_gromov,
328 lst_alpha,
329 lst_gw_losses,
330 ),
331 )
332 def test_solve_gromov_grid(nx, reg, reg_type, unbalanced, unbalanced_type, alpha, loss):
333 np.random.seed(0)
334
335 n_samples_s = 3
336 n_samples_t = 5
337
338 Ca = np.random.rand(n_samples_s, n_samples_s)
339 Ca = (Ca + Ca.T) / 2
340
341 Cb = np.random.rand(n_samples_t, n_samples_t)
342 Cb = (Cb + Cb.T) / 2
343
344 a = ot.utils.unif(n_samples_s)
345 b = ot.utils.unif(n_samples_t)
346
347 M = np.random.rand(n_samples_s, n_samples_t)
348
349 try:
350 sol0 = ot.solve_gromov(
351 Ca,
352 Cb,
353 reg=reg,
354 reg_type=reg_type,
355 unbalanced=unbalanced,
356 unbalanced_type=unbalanced_type,
357 loss=loss,
358 ) # GW
359 sol0_fgw = ot.solve_gromov(
360 Ca,
361 Cb,
362 M,
363 reg=reg,
364 reg_type=reg_type,
365 unbalanced=unbalanced,
366 unbalanced_type=unbalanced_type,
367 alpha=alpha,
368 loss=loss,
369 ) # FGW
370
371 # solve in backend
372 ax, bx, Mx, Cax, Cbx = nx.from_numpy(a, b, M, Ca, Cb)
373
374 solx = ot.solve_gromov(
375 Cax,
376 Cbx,
377 reg=reg,
378 reg_type=reg_type,
379 unbalanced=unbalanced,
380 unbalanced_type=unbalanced_type,
381 loss=loss,
382 ) # GW
383 solx_fgw = ot.solve_gromov(
384 Cax,
385 Cbx,
386 Mx,
387 reg=reg,
388 reg_type=reg_type,
389 unbalanced=unbalanced,
390 unbalanced_type=unbalanced_type,
391 alpha=alpha,
392 loss=loss,
393 ) # FGW
394
395 solx.value_quad
396
397 assert_allclose_sol(sol0, solx)
398 assert_allclose_sol(sol0_fgw, solx_fgw)
399
400 except NotImplementedError:
401 pytest.skip("Not implemented")
402
403
404 def test_solve_gromov_not_implemented(nx):
405 np.random.seed(0)
406
407 n_samples_s = 3
408 n_samples_t = 5
409
410 Ca = np.random.rand(n_samples_s, n_samples_s)
411 Ca = (Ca + Ca.T) / 2
412
413 Cb = np.random.rand(n_samples_t, n_samples_t)
414 Cb = (Cb + Cb.T) / 2
415
416 a = ot.utils.unif(n_samples_s)
417 b = ot.utils.unif(n_samples_t)
418
419 M = np.random.rand(n_samples_s, n_samples_t)
420
421 Ca, Cb, M, a, b = nx.from_numpy(Ca, Cb, M, a, b)
422
423 # test not implemented and check raise
424 with pytest.raises(NotImplementedError):
425 ot.solve_gromov(Ca, Cb, loss="weird loss")
426 with pytest.raises(NotImplementedError):
427 ot.solve_gromov(Ca, Cb, unbalanced=1, unbalanced_type="cryptic divergence")
428 with pytest.raises(NotImplementedError):
429 ot.solve_gromov(Ca, Cb, reg=1, reg_type="cryptic divergence")
430
431 # detect partial not implemented and error detect in value
432 with pytest.raises(ValueError):
433 ot.solve_gromov(Ca, Cb, unbalanced_type="partial", unbalanced=1.5)
434 with pytest.raises(NotImplementedError):
435 ot.solve_gromov(Ca, Cb, M, unbalanced_type="partial", unbalanced=0.5)
436 with pytest.raises(ValueError):
437 ot.solve_gromov(Ca, Cb, reg=1, unbalanced_type="partial", unbalanced=1.5)
438
439
440 def test_solve_sample(nx):
441 # test solve_sample when is_Lazy = False
442 n = 20
443 X_s = np.reshape(1.0 * np.arange(n), (n, 1))
444 X_t = np.reshape(1.0 * np.arange(0, n), (n, 1))
445
446 a = ot.utils.unif(X_s.shape[0])
447 b = ot.utils.unif(X_t.shape[0])
448
449 M = ot.dist(X_s, X_t)
450
451 # solve with ot.solve
452 sol00 = ot.solve(M, a, b)
453
454 # solve unif weights
455 sol0 = ot.solve_sample(X_s, X_t)
456
457 # solve signe weights
458 sol = ot.solve_sample(X_s, X_t, a, b)
459
460 # check some attributes
461 sol.potentials
462 sol.sparse_plan
463 sol.marginals
464 sol.status
465
466 assert_allclose_sol(sol0, sol)
467 assert_allclose_sol(sol0, sol00)
468
469 # solve in backend
470 X_sb, X_tb, ab, bb = nx.from_numpy(X_s, X_t, a, b)
471 solb = ot.solve_sample(X_sb, X_tb, ab, bb)
472
473 assert_allclose_sol(sol, solb)
474
475 # test not implemented unbalanced and check raise
476 with pytest.raises(NotImplementedError):
477 sol0 = ot.solve_sample(
478 X_s, X_t, unbalanced=1, unbalanced_type="cryptic divergence"
479 )
480
481 # test not implemented reg_type and check raise
482 with pytest.raises(NotImplementedError):
483 sol0 = ot.solve_sample(X_s, X_t, reg=1, reg_type="cryptic divergence")
484
485
486 def test_solve_sample_lazy(nx):
487 # test solve_sample when is_Lazy = False
488 n = 20
489 X_s = np.reshape(1.0 * np.arange(n), (n, 1))
490 X_t = np.reshape(1.0 * np.arange(0, n), (n, 1))
491
492 a = ot.utils.unif(X_s.shape[0])
493 b = ot.utils.unif(X_t.shape[0])
494
495 X_s, X_t, a, b = nx.from_numpy(X_s, X_t, a, b)
496
497 M = ot.dist(X_s, X_t)
498
499 # solve with ot.solve
500 sol00 = ot.solve(M, a, b, reg=1)
501
502 sol0 = ot.solve_sample(X_s, X_t, a, b, reg=1)
503
504 # solve signe weights
505 sol = ot.solve_sample(X_s, X_t, a, b, reg=1, lazy=True)
506
507 assert_allclose_sol(sol0, sol00)
508
509 np.testing.assert_allclose(sol0.plan, sol.lazy_plan[:], rtol=1e-5, atol=1e-5)
510
511
512 @pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher")
513 @pytest.mark.skipif(not geomloss, reason="pytorch not installed")
514 @pytest.skip_backend("tf")
515 @pytest.skip_backend("cupy")
516 @pytest.skip_backend("jax")
517 @pytest.mark.parametrize("metric", ["sqeuclidean", "euclidean"])
518 def test_solve_sample_geomloss(nx, metric):
519 # test solve_sample when is_Lazy = False
520 n_samples_s = 13
521 n_samples_t = 7
522 n_features = 2
523 rng = np.random.RandomState(0)
524
525 x = rng.randn(n_samples_s, n_features)
526 y = rng.randn(n_samples_t, n_features)
527 a = ot.utils.unif(n_samples_s)
528 b = ot.utils.unif(n_samples_t)
529
530 xb, yb, ab, bb = nx.from_numpy(x, y, a, b)
531
532 sol0 = ot.solve_sample(xb, yb, ab, bb, reg=1)
533
534 # solve signe weights
535 sol = ot.solve_sample(xb, yb, ab, bb, reg=1, method="geomloss")
536 assert_allclose_sol(sol0, sol)
537
538 sol1 = ot.solve_sample(xb, yb, ab, bb, reg=1, lazy=False, method="geomloss")
539 assert_allclose_sol(sol0, sol)
540
541 sol1 = ot.solve_sample(
542 xb, yb, ab, bb, reg=1, lazy=True, method="geomloss_tensorized"
543 )
544 np.testing.assert_allclose(
545 nx.to_numpy(sol1.lazy_plan[:]),
546 nx.to_numpy(sol.lazy_plan[:]),
547 rtol=1e-5,
548 atol=1e-5,
549 )
550
551 sol1 = ot.solve_sample(xb, yb, ab, bb, reg=1, lazy=True, method="geomloss_online")
552 np.testing.assert_allclose(
553 nx.to_numpy(sol1.lazy_plan[:]),
554 nx.to_numpy(sol.lazy_plan[:]),
555 rtol=1e-5,
556 atol=1e-5,
557 )
558
559 sol1 = ot.solve_sample(
560 xb, yb, ab, bb, reg=1, lazy=True, method="geomloss_multiscale"
561 )
562 np.testing.assert_allclose(
563 nx.to_numpy(sol1.lazy_plan[:]),
564 nx.to_numpy(sol.lazy_plan[:]),
565 rtol=1e-5,
566 atol=1e-5,
567 )
568
569 sol1 = ot.solve_sample(xb, yb, ab, bb, reg=1, lazy=True, method="geomloss")
570 np.testing.assert_allclose(
571 nx.to_numpy(sol1.lazy_plan[:]),
572 nx.to_numpy(sol.lazy_plan[:]),
573 rtol=1e-5,
574 atol=1e-5,
575 )
576
577
578 @pytest.mark.parametrize("method_params", lst_method_params_solve_sample)
579 def test_solve_sample_methods(nx, method_params):
580 n_samples_s = 20
581 n_samples_t = 7
582 n_features = 2
583 rng = np.random.RandomState(0)
584
585 x = rng.randn(n_samples_s, n_features)
586 y = rng.randn(n_samples_t, n_features)
587 a = ot.utils.unif(n_samples_s)
588 b = ot.utils.unif(n_samples_t)
589
590 xb, yb, ab, bb = nx.from_numpy(x, y, a, b)
591
592 sol = ot.solve_sample(x, y, **method_params)
593 solb = ot.solve_sample(xb, yb, ab, bb, **method_params)
594
595 # check some attributes (no need )
596 assert_allclose_sol(sol, solb)
597
598 sol2 = ot.solve_sample(x, x, **method_params)
599 if method_params["method"] not in ["factored", "lowrank"]:
600 np.testing.assert_allclose(sol2.value, 0)
601
602
603 @pytest.mark.parametrize("method_params", lst_parameters_solve_sample_NotImplemented)
604 def test_solve_sample_NotImplemented(nx, method_params):
605 n_samples_s = 20
606 n_samples_t = 7
607 n_features = 2
608 rng = np.random.RandomState(0)
609
610 x = rng.randn(n_samples_s, n_features)
611 y = rng.randn(n_samples_t, n_features)
612 a = ot.utils.unif(n_samples_s)
613 b = ot.utils.unif(n_samples_t)
614
615 xb, yb, ab, bb = nx.from_numpy(x, y, a, b)
616
617 with pytest.raises(NotImplementedError):
618 ot.solve_sample(xb, yb, ab, bb, **method_params)