-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
test_hierarchy.py
1341 lines (1152 loc) · 49.7 KB
/
test_hierarchy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Author: Damian Eads
# Date: April 17, 2008
#
# Copyright (C) 2008 Damian Eads
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# 3. The name of the author may not be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
from numpy.testing import assert_allclose, assert_equal, assert_, assert_warns
import pytest
from pytest import raises as assert_raises
import scipy.cluster.hierarchy
from scipy.cluster.hierarchy import (
ClusterWarning, linkage, from_mlab_linkage, to_mlab_linkage,
num_obs_linkage, inconsistent, cophenet, fclusterdata, fcluster,
is_isomorphic, single, leaders,
correspond, is_monotonic, maxdists, maxinconsts, maxRstat,
is_valid_linkage, is_valid_im, to_tree, leaves_list, dendrogram,
set_link_color_palette, cut_tree, optimal_leaf_ordering,
_order_cluster_tree, _hierarchy, _LINKAGE_METHODS)
from scipy.spatial.distance import pdist
from scipy.cluster._hierarchy import Heap
from scipy.conftest import (
array_api_compatible,
skip_if_array_api,
skip_if_array_api_gpu,
skip_if_array_api_backend,
)
from scipy._lib._array_api import xp_assert_close
from . import hierarchy_test_data
# Matplotlib is not a scipy dependency but is optionally used in dendrogram, so
# check if it's available
try:
import matplotlib
# and set the backend to be Agg (no gui)
matplotlib.use('Agg')
# before importing pyplot
import matplotlib.pyplot as plt
have_matplotlib = True
except Exception:
have_matplotlib = False
class TestLinkage:
@skip_if_array_api_gpu
@array_api_compatible
def test_linkage_non_finite_elements_in_distance_matrix(self, xp):
# Tests linkage(Y) where Y contains a non-finite element (e.g. NaN or Inf).
# Exception expected.
y = xp.zeros((6,))
y[0] = xp.nan
assert_raises(ValueError, linkage, y)
def test_linkage_empty_distance_matrix(self):
# Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected.
y = np.zeros((0,))
assert_raises(ValueError, linkage, y)
@skip_if_array_api_gpu
@array_api_compatible
def test_linkage_tdist(self, xp):
for method in ['single', 'complete', 'average', 'weighted']:
self.check_linkage_tdist(method, xp)
def check_linkage_tdist(self, method, xp):
# Tests linkage(Y, method) on the tdist data set.
Z = linkage(xp.asarray(hierarchy_test_data.ytdist), method)
expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_' + method)
xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
@skip_if_array_api_gpu
@array_api_compatible
def test_linkage_X(self, xp):
for method in ['centroid', 'median', 'ward']:
self.check_linkage_q(method, xp)
def check_linkage_q(self, method, xp):
# Tests linkage(Y, method) on the Q data set.
Z = linkage(xp.asarray(hierarchy_test_data.X), method)
expectedZ = getattr(hierarchy_test_data, 'linkage_X_' + method)
xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
y = scipy.spatial.distance.pdist(hierarchy_test_data.X,
metric="euclidean")
Z = linkage(xp.asarray(y), method)
xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
@skip_if_array_api_gpu
@array_api_compatible
def test_compare_with_trivial(self, xp):
rng = np.random.RandomState(0)
n = 20
X = rng.rand(n, 2)
d = pdist(X)
for method, code in _LINKAGE_METHODS.items():
Z_trivial = _hierarchy.linkage(d, n, code)
Z = linkage(xp.asarray(d), method)
xp_assert_close(Z, xp.asarray(Z_trivial), rtol=1e-14, atol=1e-15)
@skip_if_array_api_gpu
@array_api_compatible
def test_optimal_leaf_ordering(self, xp):
Z = linkage(xp.asarray(hierarchy_test_data.ytdist), optimal_ordering=True)
expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_single_olo')
xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
class TestLinkageTies:
_expectations = {
'single': np.array([[0, 1, 1.41421356, 2],
[2, 3, 1.41421356, 3]]),
'complete': np.array([[0, 1, 1.41421356, 2],
[2, 3, 2.82842712, 3]]),
'average': np.array([[0, 1, 1.41421356, 2],
[2, 3, 2.12132034, 3]]),
'weighted': np.array([[0, 1, 1.41421356, 2],
[2, 3, 2.12132034, 3]]),
'centroid': np.array([[0, 1, 1.41421356, 2],
[2, 3, 2.12132034, 3]]),
'median': np.array([[0, 1, 1.41421356, 2],
[2, 3, 2.12132034, 3]]),
'ward': np.array([[0, 1, 1.41421356, 2],
[2, 3, 2.44948974, 3]]),
}
@skip_if_array_api_gpu
@array_api_compatible
def test_linkage_ties(self, xp):
for method in ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward']:
self.check_linkage_ties(method, xp)
def check_linkage_ties(self, method, xp):
X = xp.asarray([[-1, -1], [0, 0], [1, 1]])
Z = linkage(X, method=method)
expectedZ = self._expectations[method]
xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
class TestInconsistent:
@skip_if_array_api_gpu
@array_api_compatible
def test_inconsistent_tdist(self, xp):
for depth in hierarchy_test_data.inconsistent_ytdist:
self.check_inconsistent_tdist(depth, xp)
def check_inconsistent_tdist(self, depth, xp):
Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
xp_assert_close(inconsistent(Z, depth),
xp.asarray(hierarchy_test_data.inconsistent_ytdist[depth]))
class TestCopheneticDistance:
@skip_if_array_api_gpu
@array_api_compatible
def test_linkage_cophenet_tdist_Z(self, xp):
# Tests cophenet(Z) on tdist data set.
expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
295, 138, 219, 295, 295])
Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
M = cophenet(Z)
xp_assert_close(M, expectedM, atol=1e-10, check_dtype=False)
@skip_if_array_api_gpu
@array_api_compatible
def test_linkage_cophenet_tdist_Z_Y(self, xp):
# Tests cophenet(Z, Y) on tdist data set.
Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
(c, M) = cophenet(Z, xp.asarray(hierarchy_test_data.ytdist))
expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
295, 138, 219, 295, 295])
expectedc = xp.asarray(0.639931296433393415057366837573)[()]
xp_assert_close(c, expectedc, atol=1e-10, check_dtype=False)
xp_assert_close(M, expectedM, atol=1e-10, check_dtype=False)
class TestMLabLinkageConversion:
@skip_if_array_api
def test_mlab_linkage_conversion_empty(self):
# Tests from/to_mlab_linkage on empty linkage array.
X = np.asarray([])
assert_equal(from_mlab_linkage([]), X)
assert_equal(to_mlab_linkage([]), X)
@skip_if_array_api_gpu
@array_api_compatible
def test_mlab_linkage_conversion_single_row(self, xp):
# Tests from/to_mlab_linkage on linkage array with single row.
Z = xp.asarray([[0., 1., 3., 2.]])
Zm = xp.asarray([[1, 2, 3]])
xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15, check_dtype=False)
xp_assert_close(to_mlab_linkage(Z), Zm, rtol=1e-15, check_dtype=False)
@skip_if_array_api_gpu
@array_api_compatible
def test_mlab_linkage_conversion_multiple_rows(self, xp):
# Tests from/to_mlab_linkage on linkage array with multiple rows.
Zm = xp.asarray([[3, 6, 138], [4, 5, 219],
[1, 8, 255], [2, 9, 268], [7, 10, 295]])
Z = xp.asarray([[2., 5., 138., 2.],
[3., 4., 219., 2.],
[0., 7., 255., 3.],
[1., 8., 268., 4.],
[6., 9., 295., 6.]],
dtype=xp.float64)
xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15)
xp_assert_close(to_mlab_linkage(Z), Zm, rtol=1e-15, check_dtype=False)
class TestFcluster:
@skip_if_array_api_gpu
@array_api_compatible
def test_fclusterdata(self, xp):
for t in hierarchy_test_data.fcluster_inconsistent:
self.check_fclusterdata(t, 'inconsistent', xp)
for t in hierarchy_test_data.fcluster_distance:
self.check_fclusterdata(t, 'distance', xp)
for t in hierarchy_test_data.fcluster_maxclust:
self.check_fclusterdata(t, 'maxclust', xp)
def check_fclusterdata(self, t, criterion, xp):
# Tests fclusterdata(X, criterion=criterion, t=t) on a random 3-cluster data set.
expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
X = xp.asarray(hierarchy_test_data.Q_X)
T = fclusterdata(X, criterion=criterion, t=t)
assert_(is_isomorphic(T, expectedT))
@skip_if_array_api_gpu
@array_api_compatible
def test_fcluster(self, xp):
for t in hierarchy_test_data.fcluster_inconsistent:
self.check_fcluster(t, 'inconsistent', xp)
for t in hierarchy_test_data.fcluster_distance:
self.check_fcluster(t, 'distance', xp)
for t in hierarchy_test_data.fcluster_maxclust:
self.check_fcluster(t, 'maxclust', xp)
def check_fcluster(self, t, criterion, xp):
# Tests fcluster(Z, criterion=criterion, t=t) on a random 3-cluster data set.
expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
Z = single(xp.asarray(hierarchy_test_data.Q_X))
T = fcluster(Z, criterion=criterion, t=t)
assert_(is_isomorphic(T, expectedT))
@skip_if_array_api_gpu
@array_api_compatible
def test_fcluster_monocrit(self, xp):
for t in hierarchy_test_data.fcluster_distance:
self.check_fcluster_monocrit(t, xp)
for t in hierarchy_test_data.fcluster_maxclust:
self.check_fcluster_maxclust_monocrit(t, xp)
def check_fcluster_monocrit(self, t, xp):
expectedT = xp.asarray(hierarchy_test_data.fcluster_distance[t])
Z = single(xp.asarray(hierarchy_test_data.Q_X))
T = fcluster(Z, t, criterion='monocrit', monocrit=maxdists(Z))
assert_(is_isomorphic(T, expectedT))
def check_fcluster_maxclust_monocrit(self, t, xp):
expectedT = xp.asarray(hierarchy_test_data.fcluster_maxclust[t])
Z = single(xp.asarray(hierarchy_test_data.Q_X))
T = fcluster(Z, t, criterion='maxclust_monocrit', monocrit=maxdists(Z))
assert_(is_isomorphic(T, expectedT))
class TestLeaders:
@skip_if_array_api_gpu
@array_api_compatible
def test_leaders_single(self, xp):
# Tests leaders using a flat clustering generated by single linkage.
X = hierarchy_test_data.Q_X
Y = pdist(X)
Y = xp.asarray(Y)
Z = linkage(Y)
T = fcluster(Z, criterion='maxclust', t=3)
Lright = (xp.asarray([53, 55, 56]), xp.asarray([2, 3, 1]))
T = xp.asarray(T, dtype=xp.int32)
L = leaders(Z, T)
assert_allclose(np.concatenate(L), np.concatenate(Lright), rtol=1e-15)
class TestIsIsomorphic:
@skip_if_array_api
def test_is_isomorphic_1(self):
# Tests is_isomorphic on test case #1 (one flat cluster, different labellings)
a = [1, 1, 1]
b = [2, 2, 2]
assert_(is_isomorphic(a, b))
assert_(is_isomorphic(b, a))
@skip_if_array_api
def test_is_isomorphic_2(self):
# Tests is_isomorphic on test case #2 (two flat clusters, different labelings)
a = np.asarray([1, 7, 1])
b = np.asarray([2, 3, 2])
assert_(is_isomorphic(a, b))
assert_(is_isomorphic(b, a))
@skip_if_array_api
def test_is_isomorphic_3(self):
# Tests is_isomorphic on test case #3 (no flat clusters)
a = np.asarray([])
b = np.asarray([])
assert_(is_isomorphic(a, b))
@skip_if_array_api
def test_is_isomorphic_4A(self):
# Tests is_isomorphic on test case #4A (3 flat clusters, different labelings, isomorphic)
a = np.asarray([1, 2, 3])
b = np.asarray([1, 3, 2])
assert_(is_isomorphic(a, b))
assert_(is_isomorphic(b, a))
@skip_if_array_api
def test_is_isomorphic_4B(self):
# Tests is_isomorphic on test case #4B (3 flat clusters, different labelings, nonisomorphic)
a = np.asarray([1, 2, 3, 3])
b = np.asarray([1, 3, 2, 3])
assert_(is_isomorphic(a, b) is False)
assert_(is_isomorphic(b, a) is False)
@skip_if_array_api
def test_is_isomorphic_4C(self):
# Tests is_isomorphic on test case #4C (3 flat clusters, different labelings, isomorphic)
a = np.asarray([7, 2, 3])
b = np.asarray([6, 3, 2])
assert_(is_isomorphic(a, b))
assert_(is_isomorphic(b, a))
@skip_if_array_api
def test_is_isomorphic_5(self):
# Tests is_isomorphic on test case #5 (1000 observations, 2/3/5 random
# clusters, random permutation of the labeling).
for nc in [2, 3, 5]:
self.help_is_isomorphic_randperm(1000, nc)
@skip_if_array_api
def test_is_isomorphic_6(self):
# Tests is_isomorphic on test case #5A (1000 observations, 2/3/5 random
# clusters, random permutation of the labeling, slightly
# nonisomorphic.)
for nc in [2, 3, 5]:
self.help_is_isomorphic_randperm(1000, nc, True, 5)
@skip_if_array_api
def test_is_isomorphic_7(self):
# Regression test for gh-6271
a = np.asarray([1, 2, 3])
b = np.asarray([1, 1, 1])
assert_(not is_isomorphic(a, b))
def help_is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0):
for k in range(3):
a = np.int_(np.random.rand(nobs) * nclusters)
b = np.zeros(a.size, dtype=np.int_)
P = np.random.permutation(nclusters)
for i in range(0, a.shape[0]):
b[i] = P[a[i]]
if noniso:
Q = np.random.permutation(nobs)
b[Q[0:nerrors]] += 1
b[Q[0:nerrors]] %= nclusters
assert_(is_isomorphic(a, b) == (not noniso))
assert_(is_isomorphic(b, a) == (not noniso))
class TestIsValidLinkage:
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_various_size(self, xp):
for nrow, ncol, valid in [(2, 5, False), (2, 3, False),
(1, 4, True), (2, 4, True)]:
self.check_is_valid_linkage_various_size(nrow, ncol, valid, xp)
def check_is_valid_linkage_various_size(self, nrow, ncol, valid, xp):
# Tests is_valid_linkage(Z) with linkage matrics of various sizes
Z = xp.asarray([[0, 1, 3.0, 2, 5],
[3, 2, 4.0, 3, 3]], dtype=xp.float64)
Z = Z[:nrow, :ncol]
assert_(is_valid_linkage(Z) == valid)
if not valid:
assert_raises(ValueError, is_valid_linkage, Z, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_int_type(self, xp):
# Tests is_valid_linkage(Z) with integer type.
Z = xp.asarray([[0, 1, 3.0, 2],
[3, 2, 4.0, 3]], dtype=xp.int64)
assert_(is_valid_linkage(Z) is False)
assert_raises(TypeError, is_valid_linkage, Z, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_empty(self, xp):
# Tests is_valid_linkage(Z) with empty linkage.
Z = xp.zeros((0, 4), dtype=xp.float64)
assert_(is_valid_linkage(Z) is False)
assert_raises(ValueError, is_valid_linkage, Z, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_4_and_up(self, xp):
# Tests is_valid_linkage(Z) on linkage on observation sets between
# sizes 4 and 15 (step size 3).
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
assert_(is_valid_linkage(Z) is True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_4_and_up_neg_index_left(self, xp):
# Tests is_valid_linkage(Z) on linkage on observation sets between
# sizes 4 and 15 (step size 3) with negative indices (left).
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
Z[i//2,0] = -2
assert_(is_valid_linkage(Z) is False)
assert_raises(ValueError, is_valid_linkage, Z, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_4_and_up_neg_index_right(self, xp):
# Tests is_valid_linkage(Z) on linkage on observation sets between
# sizes 4 and 15 (step size 3) with negative indices (right).
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
Z[i//2,1] = -2
assert_(is_valid_linkage(Z) is False)
assert_raises(ValueError, is_valid_linkage, Z, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_4_and_up_neg_dist(self, xp):
# Tests is_valid_linkage(Z) on linkage on observation sets between
# sizes 4 and 15 (step size 3) with negative distances.
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
Z[i//2,2] = -0.5
assert_(is_valid_linkage(Z) is False)
assert_raises(ValueError, is_valid_linkage, Z, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_linkage_4_and_up_neg_counts(self, xp):
# Tests is_valid_linkage(Z) on linkage on observation sets between
# sizes 4 and 15 (step size 3) with negative counts.
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
Z[i//2,3] = -2
assert_(is_valid_linkage(Z) is False)
assert_raises(ValueError, is_valid_linkage, Z, throw=True)
class TestIsValidInconsistent:
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_im_int_type(self, xp):
# Tests is_valid_im(R) with integer type.
R = xp.asarray([[0, 1, 3.0, 2],
[3, 2, 4.0, 3]], dtype=xp.int64)
assert_(is_valid_im(R) is False)
assert_raises(TypeError, is_valid_im, R, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_im_various_size(self, xp):
for nrow, ncol, valid in [(2, 5, False), (2, 3, False),
(1, 4, True), (2, 4, True)]:
self.check_is_valid_im_various_size(nrow, ncol, valid, xp)
def check_is_valid_im_various_size(self, nrow, ncol, valid, xp):
# Tests is_valid_im(R) with linkage matrics of various sizes
R = xp.asarray([[0, 1, 3.0, 2, 5],
[3, 2, 4.0, 3, 3]], dtype=xp.float64)
R = R[:nrow, :ncol]
assert_(is_valid_im(R) == valid)
if not valid:
assert_raises(ValueError, is_valid_im, R, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_im_empty(self, xp):
# Tests is_valid_im(R) with empty inconsistency matrix.
R = xp.zeros((0, 4), dtype=xp.float64)
assert_(is_valid_im(R) is False)
assert_raises(ValueError, is_valid_im, R, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_im_4_and_up(self, xp):
# Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
# (step size 3).
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
R = inconsistent(Z)
assert_(is_valid_im(R) is True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_im_4_and_up_neg_index_left(self, xp):
# Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
# (step size 3) with negative link height means.
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
R = inconsistent(Z)
R[i//2,0] = -2.0
assert_(is_valid_im(R) is False)
assert_raises(ValueError, is_valid_im, R, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_im_4_and_up_neg_index_right(self, xp):
# Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
# (step size 3) with negative link height standard deviations.
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
R = inconsistent(Z)
R[i//2,1] = -2.0
assert_(is_valid_im(R) is False)
assert_raises(ValueError, is_valid_im, R, throw=True)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_valid_im_4_and_up_neg_dist(self, xp):
# Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
# (step size 3) with negative link counts.
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
R = inconsistent(Z)
R[i//2,2] = -0.5
assert_(is_valid_im(R) is False)
assert_raises(ValueError, is_valid_im, R, throw=True)
class TestNumObsLinkage:
@skip_if_array_api_gpu
@array_api_compatible
def test_num_obs_linkage_empty(self, xp):
# Tests num_obs_linkage(Z) with empty linkage.
Z = xp.zeros((0, 4), dtype=xp.float64)
assert_raises(ValueError, num_obs_linkage, Z)
@array_api_compatible
def test_num_obs_linkage_1x4(self, xp):
# Tests num_obs_linkage(Z) on linkage over 2 observations.
Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
assert_equal(num_obs_linkage(Z), 2)
@array_api_compatible
def test_num_obs_linkage_2x4(self, xp):
# Tests num_obs_linkage(Z) on linkage over 3 observations.
Z = xp.asarray([[0, 1, 3.0, 2],
[3, 2, 4.0, 3]], dtype=xp.float64)
assert_equal(num_obs_linkage(Z), 3)
@skip_if_array_api_gpu
@array_api_compatible
def test_num_obs_linkage_4_and_up(self, xp):
# Tests num_obs_linkage(Z) on linkage on observation sets between sizes
# 4 and 15 (step size 3).
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
assert_equal(num_obs_linkage(Z), i)
class TestLeavesList:
@skip_if_array_api_gpu
@array_api_compatible
def test_leaves_list_1x4(self, xp):
# Tests leaves_list(Z) on a 1x4 linkage.
Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
to_tree(Z)
assert_allclose(leaves_list(Z), [0, 1], rtol=1e-15)
@skip_if_array_api_gpu
@array_api_compatible
def test_leaves_list_2x4(self, xp):
# Tests leaves_list(Z) on a 2x4 linkage.
Z = xp.asarray([[0, 1, 3.0, 2],
[3, 2, 4.0, 3]], dtype=xp.float64)
to_tree(Z)
assert_allclose(leaves_list(Z), [0, 1, 2], rtol=1e-15)
@skip_if_array_api_gpu
@array_api_compatible
def test_leaves_list_Q(self, xp):
for method in ['single', 'complete', 'average', 'weighted', 'centroid',
'median', 'ward']:
self.check_leaves_list_Q(method, xp)
def check_leaves_list_Q(self, method, xp):
# Tests leaves_list(Z) on the Q data set
X = xp.asarray(hierarchy_test_data.Q_X)
Z = linkage(X, method)
node = to_tree(Z)
assert_allclose(node.pre_order(), leaves_list(Z), rtol=1e-15)
@skip_if_array_api_gpu
@array_api_compatible
def test_Q_subtree_pre_order(self, xp):
# Tests that pre_order() works when called on sub-trees.
X = xp.asarray(hierarchy_test_data.Q_X)
Z = linkage(X, 'single')
node = to_tree(Z)
assert_allclose(node.pre_order(), (node.get_left().pre_order()
+ node.get_right().pre_order()),
rtol=1e-15)
class TestCorrespond:
@skip_if_array_api_gpu
@array_api_compatible
def test_correspond_empty(self, xp):
# Tests correspond(Z, y) with empty linkage and condensed distance matrix.
y = xp.zeros((0,), dtype=xp.float64)
Z = xp.zeros((0,4), dtype=xp.float64)
assert_raises(ValueError, correspond, Z, y)
@skip_if_array_api_gpu
@array_api_compatible
def test_correspond_2_and_up(self, xp):
# Tests correspond(Z, y) on linkage and CDMs over observation sets of
# different sizes.
for i in range(2, 4):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
assert_(correspond(Z, y))
for i in range(4, 15, 3):
y = np.random.rand(i*(i-1)//2)
y = xp.asarray(y)
Z = linkage(y)
assert_(correspond(Z, y))
@skip_if_array_api_gpu
@array_api_compatible
def test_correspond_4_and_up(self, xp):
# Tests correspond(Z, y) on linkage and CDMs over observation sets of
# different sizes. Correspondence should be false.
for (i, j) in (list(zip(list(range(2, 4)), list(range(3, 5)))) +
list(zip(list(range(3, 5)), list(range(2, 4))))):
y = np.random.rand(i*(i-1)//2)
y2 = np.random.rand(j*(j-1)//2)
y = xp.asarray(y)
y2 = xp.asarray(y2)
Z = linkage(y)
Z2 = linkage(y2)
assert not correspond(Z, y2)
assert not correspond(Z2, y)
@skip_if_array_api_gpu
@array_api_compatible
def test_correspond_4_and_up_2(self, xp):
# Tests correspond(Z, y) on linkage and CDMs over observation sets of
# different sizes. Correspondence should be false.
for (i, j) in (list(zip(list(range(2, 7)), list(range(16, 21)))) +
list(zip(list(range(2, 7)), list(range(16, 21))))):
y = np.random.rand(i*(i-1)//2)
y2 = np.random.rand(j*(j-1)//2)
y = xp.asarray(y)
y2 = xp.asarray(y2)
Z = linkage(y)
Z2 = linkage(y2)
assert not correspond(Z, y2)
assert not correspond(Z2, y)
@skip_if_array_api_gpu
@array_api_compatible
def test_num_obs_linkage_multi_matrix(self, xp):
# Tests num_obs_linkage with observation matrices of multiple sizes.
for n in range(2, 10):
X = np.random.rand(n, 4)
Y = pdist(X)
Y = xp.asarray(Y)
Z = linkage(Y)
assert_equal(num_obs_linkage(Z), n)
class TestIsMonotonic:
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_empty(self, xp):
# Tests is_monotonic(Z) on an empty linkage.
Z = xp.zeros((0, 4), dtype=xp.float64)
assert_raises(ValueError, is_monotonic, Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_1x4(self, xp):
# Tests is_monotonic(Z) on 1x4 linkage. Expecting True.
Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64)
assert is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_2x4_T(self, xp):
# Tests is_monotonic(Z) on 2x4 linkage. Expecting True.
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.4, 3]], dtype=xp.float64)
assert is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_2x4_F(self, xp):
# Tests is_monotonic(Z) on 2x4 linkage. Expecting False.
Z = xp.asarray([[0, 1, 0.4, 2],
[2, 3, 0.3, 3]], dtype=xp.float64)
assert not is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_3x4_T(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage. Expecting True.
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.4, 2],
[4, 5, 0.6, 4]], dtype=xp.float64)
assert is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_3x4_F1(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False.
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.2, 2],
[4, 5, 0.6, 4]], dtype=xp.float64)
assert not is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_3x4_F2(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False.
Z = xp.asarray([[0, 1, 0.8, 2],
[2, 3, 0.4, 2],
[4, 5, 0.6, 4]], dtype=xp.float64)
assert not is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_3x4_F3(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.4, 2],
[4, 5, 0.2, 4]], dtype=xp.float64)
assert not is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_tdist_linkage1(self, xp):
# Tests is_monotonic(Z) on clustering generated by single linkage on
# tdist data set. Expecting True.
Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
assert is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_tdist_linkage2(self, xp):
# Tests is_monotonic(Z) on clustering generated by single linkage on
# tdist data set. Perturbing. Expecting False.
Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
Z[2,2] = 0.0
assert not is_monotonic(Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_is_monotonic_Q_linkage(self, xp):
# Tests is_monotonic(Z) on clustering generated by single linkage on
# Q data set. Expecting True.
X = xp.asarray(hierarchy_test_data.Q_X)
Z = linkage(X, 'single')
assert is_monotonic(Z)
class TestMaxDists:
@skip_if_array_api_gpu
@array_api_compatible
def test_maxdists_empty_linkage(self, xp):
# Tests maxdists(Z) on empty linkage. Expecting exception.
Z = xp.zeros((0, 4), dtype=xp.float64)
assert_raises(ValueError, maxdists, Z)
@skip_if_array_api_gpu
@array_api_compatible
def test_maxdists_one_cluster_linkage(self, xp):
# Tests maxdists(Z) on linkage with one cluster.
Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
MD = maxdists(Z)
expectedMD = calculate_maximum_distances(Z, xp)
xp_assert_close(MD, expectedMD, atol=1e-15)
@skip_if_array_api_gpu
@array_api_compatible
def test_maxdists_Q_linkage(self, xp):
for method in ['single', 'complete', 'ward', 'centroid', 'median']:
self.check_maxdists_Q_linkage(method, xp)
def check_maxdists_Q_linkage(self, method, xp):
# Tests maxdists(Z) on the Q data set
X = xp.asarray(hierarchy_test_data.Q_X)
Z = linkage(X, method)
MD = maxdists(Z)
expectedMD = calculate_maximum_distances(Z, xp)
xp_assert_close(MD, expectedMD, atol=1e-15)
class TestMaxInconsts:
@skip_if_array_api_gpu
@array_api_compatible
def test_maxinconsts_empty_linkage(self, xp):
# Tests maxinconsts(Z, R) on empty linkage. Expecting exception.
Z = xp.zeros((0, 4), dtype=xp.float64)
R = xp.zeros((0, 4), dtype=xp.float64)
assert_raises(ValueError, maxinconsts, Z, R)
@array_api_compatible
def test_maxinconsts_difrow_linkage(self, xp):
# Tests maxinconsts(Z, R) on linkage and inconsistency matrices with
# different numbers of clusters. Expecting exception.
Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
R = np.random.rand(2, 4)
R = xp.asarray(R)
assert_raises(ValueError, maxinconsts, Z, R)
@skip_if_array_api_gpu
@array_api_compatible
def test_maxinconsts_one_cluster_linkage(self, xp):
# Tests maxinconsts(Z, R) on linkage with one cluster.
Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
MD = maxinconsts(Z, R)
expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
xp_assert_close(MD, expectedMD, atol=1e-15)
@skip_if_array_api_gpu
@array_api_compatible
def test_maxinconsts_Q_linkage(self, xp):
for method in ['single', 'complete', 'ward', 'centroid', 'median']:
self.check_maxinconsts_Q_linkage(method, xp)
def check_maxinconsts_Q_linkage(self, method, xp):
# Tests maxinconsts(Z, R) on the Q data set
X = xp.asarray(hierarchy_test_data.Q_X)
Z = linkage(X, method)
R = inconsistent(Z)
MD = maxinconsts(Z, R)
expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
xp_assert_close(MD, expectedMD, atol=1e-15)
class TestMaxRStat:
@array_api_compatible
def test_maxRstat_invalid_index(self, xp):
for i in [3.3, -1, 4]:
self.check_maxRstat_invalid_index(i, xp)
def check_maxRstat_invalid_index(self, i, xp):
# Tests maxRstat(Z, R, i). Expecting exception.
Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
if isinstance(i, int):
assert_raises(ValueError, maxRstat, Z, R, i)
else:
assert_raises(TypeError, maxRstat, Z, R, i)
@skip_if_array_api_gpu
@array_api_compatible
def test_maxRstat_empty_linkage(self, xp):
for i in range(4):
self.check_maxRstat_empty_linkage(i, xp)
def check_maxRstat_empty_linkage(self, i, xp):
# Tests maxRstat(Z, R, i) on empty linkage. Expecting exception.
Z = xp.zeros((0, 4), dtype=xp.float64)
R = xp.zeros((0, 4), dtype=xp.float64)
assert_raises(ValueError, maxRstat, Z, R, i)
@array_api_compatible
def test_maxRstat_difrow_linkage(self, xp):
for i in range(4):
self.check_maxRstat_difrow_linkage(i, xp)
def check_maxRstat_difrow_linkage(self, i, xp):
# Tests maxRstat(Z, R, i) on linkage and inconsistency matrices with
# different numbers of clusters. Expecting exception.
Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
R = np.random.rand(2, 4)
R = xp.asarray(R)
assert_raises(ValueError, maxRstat, Z, R, i)
@skip_if_array_api_gpu
@array_api_compatible
def test_maxRstat_one_cluster_linkage(self, xp):
for i in range(4):
self.check_maxRstat_one_cluster_linkage(i, xp)
def check_maxRstat_one_cluster_linkage(self, i, xp):
# Tests maxRstat(Z, R, i) on linkage with one cluster.
Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
MD = maxRstat(Z, R, 1)
expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
xp_assert_close(MD, expectedMD, atol=1e-15)
@skip_if_array_api_gpu
@array_api_compatible
def test_maxRstat_Q_linkage(self, xp):
for method in ['single', 'complete', 'ward', 'centroid', 'median']:
for i in range(4):
self.check_maxRstat_Q_linkage(method, i, xp)
def check_maxRstat_Q_linkage(self, method, i, xp):
# Tests maxRstat(Z, R, i) on the Q data set
X = xp.asarray(hierarchy_test_data.Q_X)
Z = linkage(X, method)
R = inconsistent(Z)
MD = maxRstat(Z, R, 1)
expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
xp_assert_close(MD, expectedMD, atol=1e-15)
class TestDendrogram:
@skip_if_array_api_gpu
@array_api_compatible
def test_dendrogram_single_linkage_tdist(self, xp):
# Tests dendrogram calculation on single linkage of the tdist data set.
Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
R = dendrogram(Z, no_plot=True)
leaves = R["leaves"]
assert_equal(leaves, [2, 5, 1, 0, 3, 4])
@skip_if_array_api_gpu
@array_api_compatible