Debian Codegraph @

test/test_utils.py

raw symbols SCIP
1 """Tests for module utils for timing and parallel computation"""
2
3 # Author: Remi Flamary <[email protected]>
4 #
5 # License: MIT License
6
7 import ot
8 import numpy as np
9 import sys
10 import pytest
11
12
13 def get_LazyTensor(nx):
14 n1 = 100
15 n2 = 200
16
17 rng = np.random.RandomState(42)
18 a = rng.rand(n1)
19 a /= a.sum()
20 b = rng.rand(n2)
21 b /= b.sum()
22
23 a, b = nx.from_numpy(a, b)
24
25 def getitem(i, j, a, b):
26 return a[i, None] * b[None, j]
27
28 # create a lazy tensor
29 T = ot.utils.LazyTensor((n1, n2), getitem, a=a, b=b)
30
31 return T, a, b
32
33
34 def test_proj_simplex(nx):
35 n = 10
36 rng = np.random.RandomState(0)
37
38 # test on matrix when projection is done on axis 0
39 x = rng.randn(n, 2)
40 x1 = nx.from_numpy(x)
41
42 # all projections should sum to 1
43 proj = ot.utils.proj_simplex(x1)
44 l1 = np.sum(nx.to_numpy(proj), axis=0)
45 l2 = np.ones(2)
46 np.testing.assert_allclose(l1, l2, atol=1e-5)
47
48 # all projections should sum to 3
49 proj = ot.utils.proj_simplex(x1, 3)
50 l1 = np.sum(nx.to_numpy(proj), axis=0)
51 l2 = 3 * np.ones(2)
52 np.testing.assert_allclose(l1, l2, atol=1e-5)
53
54 # tets on vector
55 x = rng.randn(n)
56 x1 = nx.from_numpy(x)
57
58 # all projections should sum to 1
59 proj = ot.utils.proj_simplex(x1)
60 l1 = np.sum(nx.to_numpy(proj), axis=0)
61 l2 = np.ones(2)
62 np.testing.assert_allclose(l1, l2, atol=1e-5)
63
64
65 def test_projection_sparse_simplex():
66 def double_sort_projection_sparse_simplex(X, max_nz, z=1, axis=None):
67 r"""This is an equivalent but less efficient version
68 of ot.utils.projection_sparse_simplex, as it uses two
69 sorts instead of one.
70 """
71
72 if axis == 0:
73 # For each column of X, find top max_nz values and
74 # their corresponding indices. This incurs a sort.
75 max_nz_indices = np.argpartition(X, kth=-max_nz, axis=0)[-max_nz:]
76
77 max_nz_values = X[max_nz_indices, np.arange(X.shape[1])]
78
79 # Project the top max_nz values onto the simplex.
80 # This incurs a second sort.
81 G_nz_values = ot.smooth.projection_simplex(max_nz_values, z=z, axis=0)
82
83 # Put the projection of max_nz_values to their original indices
84 # and set all other values zero.
85 G = np.zeros_like(X)
86 G[max_nz_indices, np.arange(X.shape[1])] = G_nz_values
87 return G
88 elif axis == 1:
89 return double_sort_projection_sparse_simplex(X.T, max_nz, z, axis=0).T
90
91 else:
92 X = X.ravel().reshape(-1, 1)
93 return double_sort_projection_sparse_simplex(X, max_nz, z, axis=0).ravel()
94
95 m, n = 5, 10
96 rng = np.random.RandomState(0)
97 X = rng.uniform(size=(m, n))
98 max_nz = 3
99
100 for axis in [0, 1, None]:
101 slow_sparse_proj = double_sort_projection_sparse_simplex(X, max_nz, axis=axis)
102 fast_sparse_proj = ot.utils.projection_sparse_simplex(X, max_nz, axis=axis)
103
104 # check that two versions produce consistent results
105 np.testing.assert_allclose(slow_sparse_proj, fast_sparse_proj)
106
107
108 def test_parmap():
109 n = 10
110
111 def f(i):
112 return 1.0 * i * i
113
114 a = np.arange(n)
115
116 l1 = list(map(f, a))
117
118 l2 = list(ot.utils.parmap(f, a))
119
120 np.testing.assert_allclose(l1, l2)
121
122
123 def test_tic_toc():
124 import time
125
126 ot.tic()
127 time.sleep(0.1)
128 t = ot.toc()
129 t2 = ot.toq()
130
131 # test timing
132 # np.testing.assert_allclose(0.1, t, rtol=1e-1, atol=1e-1)
133 # very slow macos github action equality not possible
134 assert t > 0.09
135
136 # test toc vs toq
137 np.testing.assert_allclose(t, t2, rtol=1e-1, atol=1e-1)
138
139
140 def test_kernel():
141 n = 100
142 rng = np.random.RandomState(0)
143 x = rng.randn(n, 2)
144
145 K = ot.utils.kernel(x, x)
146
147 # gaussian kernel has ones on the diagonal
148 np.testing.assert_allclose(np.diag(K), np.ones(n))
149
150
151 def test_unif():
152 n = 100
153
154 u = ot.unif(n)
155
156 np.testing.assert_allclose(1, np.sum(u))
157
158
159 def test_unif_backend(nx):
160 n = 100
161
162 for tp in nx.__type_list__:
163 print(nx.dtype_device(tp))
164
165 u = ot.unif(n, type_as=tp)
166
167 np.testing.assert_allclose(1, np.sum(nx.to_numpy(u)), atol=1e-6)
168
169
170 def test_dist():
171 n = 10
172
173 rng = np.random.RandomState(0)
174 x = rng.randn(n, 2)
175
176 D = np.zeros((n, n))
177 for i in range(n):
178 for j in range(n):
179 D[i, j] = np.sum(np.square(x[i, :] - x[j, :]))
180
181 D2 = ot.dist(x, x)
182 D3 = ot.dist(x)
183
184 D4 = ot.dist(x, x, metric="minkowski", p=2)
185
186 assert D4[0, 1] == D4[1, 0]
187
188 # dist shoul return squared euclidean
189 np.testing.assert_allclose(D, D2, atol=1e-14)
190 np.testing.assert_allclose(D, D3, atol=1e-14)
191
192 # tests that every metric runs correctly
193 metrics_w = [
194 "braycurtis",
195 "canberra",
196 "chebyshev",
197 "cityblock",
198 "correlation",
199 "cosine",
200 "dice",
201 "euclidean",
202 "hamming",
203 "jaccard",
204 "matching",
205 "minkowski",
206 "rogerstanimoto",
207 "russellrao",
208 "sokalmichener",
209 "sokalsneath",
210 "sqeuclidean",
211 "yule",
212 ] # those that support weights
213 metrics = [
214 "mahalanobis",
215 "seuclidean",
216 ] # do not support weights depending on scipy's version
217
218 for metric in metrics_w:
219 print(metric)
220 ot.dist(x, x, metric=metric, p=3, w=rng.random((2,)))
221 ot.dist(
222 x, x, metric=metric, p=3, w=None
223 ) # check that not having any weight does not cause issues
224 for metric in metrics:
225 print(metric)
226 ot.dist(x, x, metric=metric, p=3)
227
228 # weighted minkowski but with no weights
229 with pytest.raises(ValueError):
230 ot.dist(x, x, metric="wminkowski")
231
232
233 def test_dist_backends(nx):
234 n = 100
235 rng = np.random.RandomState(0)
236 x = rng.randn(n, 2)
237 x1 = nx.from_numpy(x)
238
239 lst_metric = ["euclidean", "sqeuclidean"]
240
241 for metric in lst_metric:
242 D = ot.dist(x, x, metric=metric)
243 D1 = ot.dist(x1, x1, metric=metric)
244
245 # low atol because jax forces float32
246 np.testing.assert_allclose(D, nx.to_numpy(D1), atol=1e-5)
247
248
249 def test_dist0():
250 n = 100
251 M = ot.utils.dist0(n, method="lin_square")
252
253 # dist0 default to linear sampling with quadratic loss
254 np.testing.assert_allclose(M[0, -1], (n - 1) * (n - 1))
255
256
257 def test_dots():
258 n1, n2, n3, n4 = 100, 50, 200, 100
259
260 rng = np.random.RandomState(0)
261
262 A = rng.randn(n1, n2)
263 B = rng.randn(n2, n3)
264 C = rng.randn(n3, n4)
265
266 X1 = ot.utils.dots(A, B, C)
267
268 X2 = A.dot(B.dot(C))
269
270 np.testing.assert_allclose(X1, X2)
271
272
273 def test_clean_zeros():
274 n = 100
275 nz = 50
276 nz2 = 20
277 u1 = ot.unif(n)
278 u1[:nz] = 0
279 u1 = u1 / u1.sum()
280 u2 = ot.unif(n)
281 u2[:nz2] = 0
282 u2 = u2 / u2.sum()
283
284 M = ot.utils.dist0(n)
285
286 a, b, M2 = ot.utils.clean_zeros(u1, u2, M)
287
288 assert len(a) == n - nz
289 assert len(b) == n - nz2
290
291
292 def test_cost_normalization(nx):
293 rng = np.random.RandomState(0)
294
295 C = rng.rand(10, 10)
296 C1 = nx.from_numpy(C)
297
298 # does nothing
299 M0 = ot.utils.cost_normalization(C1)
300 M1 = nx.to_numpy(M0)
301 np.testing.assert_allclose(C, M1)
302
303 M = ot.utils.cost_normalization(C1, "median")
304 M1 = nx.to_numpy(M)
305 np.testing.assert_allclose(np.median(M1), 1)
306
307 M = ot.utils.cost_normalization(C1, "max")
308 M1 = nx.to_numpy(M)
309 np.testing.assert_allclose(M1.max(), 1)
310
311 M = ot.utils.cost_normalization(C1, "log")
312 M1 = nx.to_numpy(M)
313 np.testing.assert_allclose(M1.max(), np.log(1 + C).max())
314
315 M = ot.utils.cost_normalization(C1, "loglog")
316 M1 = nx.to_numpy(M)
317 np.testing.assert_allclose(M1.max(), np.log(1 + np.log(1 + C)).max())
318
319 with pytest.raises(ValueError):
320 ot.utils.cost_normalization(C1, "error")
321
322
323 def test_list_to_array(nx):
324 lst = [np.array([1, 2, 3]), np.array([4, 5, 6])]
325
326 a1, a2 = ot.utils.list_to_array(*lst)
327
328 assert a1.shape == (3,)
329 assert a2.shape == (3,)
330
331 a, b, M = ot.utils.list_to_array([], [], [[1.0, 2.0], [3.0, 4.0]])
332
333
334 def test_check_params():
335 res1 = ot.utils.check_params(first="OK", second=20)
336 assert res1 is True
337
338 res0 = ot.utils.check_params(first="OK", second=None)
339 assert res0 is False
340
341
342 def test_check_random_state_error():
343 with pytest.raises(ValueError):
344 ot.utils.check_random_state("error")
345
346
347 def test_get_parameter_pair_error():
348 with pytest.raises(ValueError):
349 ot.utils.get_parameter_pair((1, 2, 3)) # not pair ;)
350
351
352 def test_deprecated_func():
353 @ot.utils.deprecated("deprecated text for fun")
354 def fun():
355 pass
356
357 def fun2():
358 pass
359
360 @ot.utils.deprecated("deprecated text for class")
361 class Class:
362 pass
363
364 with pytest.warns(DeprecationWarning):
365 fun()
366
367 with pytest.warns(DeprecationWarning):
368 cl = Class()
369 print(cl)
370
371 if sys.version_info < (3, 5):
372 print("Not tested")
373 else:
374 assert ot.utils._is_deprecated(fun) is True
375
376 assert ot.utils._is_deprecated(fun2) is False
377
378
379 def test_BaseEstimator():
380 class Class(ot.utils.BaseEstimator):
381 def __init__(self, first="spam", second="eggs"):
382 self.first = first
383 self.second = second
384
385 cl = Class()
386
387 names = cl._get_param_names()
388 assert "first" in names
389 assert "second" in names
390
391 params = cl.get_params()
392 assert "first" in params
393 assert "second" in params
394
395 params["first"] = "spam again"
396 cl.set_params(**params)
397
398 with pytest.raises(ValueError):
399 cl.set_params(bibi=10)
400
401 assert cl.first == "spam again"
402
403
404 def test_OTResult():
405 res = ot.utils.OTResult()
406
407 # test print
408 print(res)
409
410 # tets get citation
411 print(res.citation)
412
413 lst_attributes = [
414 "lazy_plan",
415 "marginal_a",
416 "marginal_b",
417 "marginals",
418 "plan",
419 "potential_a",
420 "potential_b",
421 "potentials",
422 "sparse_plan",
423 "status",
424 "value",
425 "value_linear",
426 "value_quad",
427 "log",
428 ]
429 for at in lst_attributes:
430 print(at)
431 assert getattr(res, at) is None
432
433 list_not_implemented = ["a_to_b", "b_to_a"]
434 for at in list_not_implemented:
435 print(at)
436 with pytest.raises(NotImplementedError):
437 getattr(res, at)
438
439
440 def test_get_coordinate_circle():
441 rng = np.random.RandomState(42)
442 u = rng.rand(1, 100)
443 x1, y1 = np.cos(u * (2 * np.pi)), np.sin(u * (2 * np.pi))
444 x = np.concatenate([x1, y1]).T
445 x_p = ot.utils.get_coordinate_circle(x)
446
447 np.testing.assert_allclose(u[0], x_p)
448
449
450 def test_LazyTensor(nx):
451 n1 = 100
452 n2 = 200
453 shape = (n1, n2)
454
455 rng = np.random.RandomState(42)
456 x1 = rng.randn(n1, 2)
457 x2 = rng.randn(n2, 2)
458
459 x1, x2 = nx.from_numpy(x1, x2)
460
461 # i,j can be integers or slices, x1,x2 have to be passed as keyword arguments
462 def getitem(i, j, x1, x2):
463 return nx.dot(x1[i], x2[j].T)
464
465 # create a lazy tensor
466 T = ot.utils.LazyTensor((n1, n2), getitem, x1=x1, x2=x2)
467
468 assert T.shape == (n1, n2)
469 assert str(T) == "LazyTensor(shape=(100, 200),attributes=(x1,x2))"
470
471 assert T.x1 is x1
472 assert T.x2 is x2
473
474 # get the full tensor (not lazy)
475 assert T[:].shape == shape
476
477 # get one component
478 assert T[1, 1] == nx.dot(x1[1], x2[1].T)
479
480 # get one row
481 assert T[1].shape == (n2,)
482
483 # get one column with slices
484 assert T[::10, 5].shape == (10,)
485
486 with pytest.raises(NotImplementedError):
487 T["error"]
488
489
490 def test_OTResult_LazyTensor(nx):
491 T, a, b = get_LazyTensor(nx)
492
493 res = ot.utils.OTResult(lazy_plan=T, batch_size=9, backend=nx)
494
495 np.testing.assert_allclose(nx.to_numpy(a), nx.to_numpy(res.marginal_a))
496 np.testing.assert_allclose(nx.to_numpy(b), nx.to_numpy(res.marginal_b))
497
498
499 def test_LazyTensor_reduce(nx):
500 T, a, b = get_LazyTensor(nx)
501
502 T0 = T[:]
503 s0 = nx.sum(T0)
504
505 # total sum
506 s = ot.utils.reduce_lazytensor(T, nx.sum, nx=nx)
507 np.testing.assert_allclose(nx.to_numpy(s), 1)
508 np.testing.assert_allclose(nx.to_numpy(s), nx.to_numpy(s0))
509
510 s2 = ot.utils.reduce_lazytensor(T, nx.sum)
511 np.testing.assert_allclose(nx.to_numpy(s), nx.to_numpy(s2))
512
513 s2 = ot.utils.reduce_lazytensor(T, nx.sum, batch_size=500)
514 np.testing.assert_allclose(nx.to_numpy(s), nx.to_numpy(s2))
515
516 s2 = ot.utils.reduce_lazytensor(T, nx.sum, batch_size=11)
517 np.testing.assert_allclose(nx.to_numpy(s), nx.to_numpy(s2))
518
519 # sum over axis 0
520 s = ot.utils.reduce_lazytensor(T, nx.sum, axis=0, nx=nx)
521 np.testing.assert_allclose(nx.to_numpy(s), nx.to_numpy(b))
522
523 # sum over axis 1
524 s = ot.utils.reduce_lazytensor(T, nx.sum, axis=1, nx=nx)
525 np.testing.assert_allclose(nx.to_numpy(s), nx.to_numpy(a))
526
527 # test otehr reduction function
528 s = ot.utils.reduce_lazytensor(T, nx.logsumexp, axis=1, nx=nx)
529 s2 = nx.logsumexp(T[:], axis=1)
530 np.testing.assert_allclose(nx.to_numpy(s), nx.to_numpy(s2))
531
532 # test 3D tensors
533 def getitem(i, j, k, a, b, c):
534 return a[i, None, None] * b[None, j, None] * c[None, None, k]
535
536 # create a lazy tensor
537 n = a.shape[0]
538 T = ot.utils.LazyTensor((n, n, n), getitem, a=a, b=a, c=a)
539
540 # total sum
541 s1 = ot.utils.reduce_lazytensor(T, nx.sum, axis=0, nx=nx)
542 s2 = ot.utils.reduce_lazytensor(T, nx.sum, axis=1, nx=nx)
543
544 np.testing.assert_allclose(nx.to_numpy(s1), nx.to_numpy(s2))
545
546 with pytest.raises(NotImplementedError):
547 ot.utils.reduce_lazytensor(T, nx.sum, axis=2, nx=nx, batch_size=10)
548
549
550 def test_lowrank_LazyTensor(nx):
551 p = 5
552 n1 = 100
553 n2 = 200
554
555 shape = (n1, n2)
556
557 rng = np.random.RandomState(42)
558 X1 = rng.randn(n1, p)
559 X2 = rng.randn(n2, p)
560 diag_d = rng.rand(p)
561
562 X1, X2, diag_d = nx.from_numpy(X1, X2, diag_d)
563
564 T0 = nx.dot(X1, X2.T)
565
566 T = ot.utils.get_lowrank_lazytensor(X1, X2)
567
568 np.testing.assert_allclose(nx.to_numpy(T[:]), nx.to_numpy(T0))
569
570 assert T.Q is X1
571 assert T.R is X2
572
573 # get the full tensor (not lazy)
574 assert T[:].shape == shape
575
576 # get one component
577 assert T[1, 1] == nx.dot(X1[1], X2[1].T)
578
579 # get one row
580 assert T[1].shape == (n2,)
581
582 # get one column with slices
583 assert T[::10, 5].shape == (10,)
584
585 T0 = nx.dot(X1 * diag_d[None, :], X2.T)
586
587 T = ot.utils.get_lowrank_lazytensor(X1, X2, diag_d, nx=nx)
588
589 np.testing.assert_allclose(nx.to_numpy(T[:]), nx.to_numpy(T0))
590
591
592 def test_labels_to_mask_helper(nx):
593 y = np.array([1, 0, 2, 2, 1])
594 out = np.array(
595 [
596 [0, 1, 0],
597 [1, 0, 0],
598 [0, 0, 1],
599 [0, 0, 1],
600 [0, 1, 0],
601 ]
602 )
603 y = nx.from_numpy(y)
604 masks = ot.utils.labels_to_masks(y)
605 np.testing.assert_array_equal(out, masks)
606
607
608 def test_label_normalization(nx):
609 y = nx.from_numpy(np.arange(5) + 1)
610 out = np.arange(5)
611 # labels are shifted
612 y_normalized = ot.utils.label_normalization(y)
613 np.testing.assert_array_equal(out, y_normalized)
614 # labels are shifted but the shift if expected
615 y_normalized_start = ot.utils.label_normalization(y, start=1)
616 np.testing.assert_array_equal(y, y_normalized_start)
617
618
619 def test_proj_SDP(nx):
620 t = np.pi / 8
621 U = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])
622 w = np.array([1.0, -1.0])
623 S = np.stack([U @ np.diag(w) @ U.T] * 2, axis=0)
624 S_nx = nx.from_numpy(S)
625 R = ot.utils.proj_SDP(S_nx)
626
627 w_expected = np.array([1.0, 0.0])
628 S_expected = np.stack([U @ np.diag(w_expected) @ U.T] * 2, axis=0)
629 assert np.allclose(nx.to_numpy(R), S_expected)
630
631 R0 = ot.utils.proj_SDP(S_nx[0])
632 assert np.allclose(nx.to_numpy(R0), S_expected[0])
633
634
635 def test_laplacian():
636 n = 100
637 rng = np.random.RandomState(0)
638 x = rng.randn(n, 2)
639 M = ot.dist(x, x)
640 L = ot.utils.laplacian(M)
641 assert L.shape == (n, n)
642
643
644 def test_kl_div(nx):
645 n = 10
646 rng = np.random.RandomState(0)
647 # test on non-negative tensors
648 x = rng.randn(n)
649 x = x - x.min() + 1e-5
650 y = rng.randn(n)
651 y = y - y.min() + 1e-5
652 xb = nx.from_numpy(x)
653 yb = nx.from_numpy(y)
654 kl = nx.kl_div(xb, yb)
655 kl_mass = nx.kl_div(xb, yb, True)
656 recovered_kl = kl_mass - nx.sum(yb - xb)
657 np.testing.assert_allclose(kl, recovered_kl)