forked from theislab/cellrank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_lineage.py
1057 lines (809 loc) · 33.4 KB
/
test_lineage.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
import pickle
import pytest
from io import BytesIO
from unittest import mock
from collections import defaultdict
from html.parser import HTMLParser
from cellrank._utils import Lineage
from cellrank._utils._colors import _compute_mean_color, _create_categorical_colors
from cellrank._utils._lineage import _HT_CELLS, LineageView, PrimingDegree
import numpy as np
from pandas import DataFrame
import matplotlib.colors as colors
class SimpleHTMLValidator(HTMLParser):
_expected_tags = {"table", "div", "tr", "th", "td", "p"}
def __init__(self, n_expected_rows: int, n_expected_cells: int, *args, **kwargs):
super().__init__(*args, **kwargs)
self._cnt = defaultdict(int)
self._n_rows = 0
self._n_cells = 0
self._n_expected_rows = n_expected_rows
self._n_expected_cells = n_expected_cells
def handle_starttag(self, tag, attrs):
self._cnt[tag] += 1
self._n_rows += tag == "tr"
self._n_cells += tag == "td"
def handle_endtag(self, tag):
self._cnt[tag] -= 1
def validate(self):
assert self._n_cells == self._n_expected_cells
assert set(self._cnt.keys()) == self._expected_tags
assert set(self._cnt.values()) == {0}
class TestLineageCreation:
def test_creation(self):
x = np.random.random((10, 3))
names = ["foo", "bar", "baz"]
colors = ["#000000", "#ababab", "#ffffff"]
l = Lineage(x, names=names, colors=colors)
np.testing.assert_array_equal(l, x)
np.testing.assert_array_equal(l.names, np.array(names))
np.testing.assert_array_equal(l.colors, np.array(colors))
def test_zero_cells(self):
with pytest.raises(ValueError):
Lineage(np.zeros((0, 2)), names=["foo", "bar"])
def test_zero_lineages(self):
with pytest.raises(ValueError):
Lineage(np.zeros((10, 0)), names=[])
def test_non_null_1d(self):
l = Lineage(np.zeros((10,)), names=["foo"])
assert isinstance(l, Lineage)
assert l.shape == (10, 1)
np.testing.assert_array_equal(l, 0)
def test_from_lineage(self, lineage: Lineage):
y = Lineage(lineage, names=lineage.names)
assert not np.shares_memory(y.X, lineage.X)
np.testing.assert_array_equal(y, lineage)
np.testing.assert_array_equal(y.names, lineage.names)
np.testing.assert_array_equal(y.colors, lineage.colors)
def test_wrong_number_of_dimensions(self):
with pytest.raises(ValueError):
_ = Lineage(
np.random.random((10, 3, 1)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), "#ffffff", "#ff00FF"],
)
def test_names_length_mismatch(self):
with pytest.raises(ValueError):
_ = Lineage(
np.random.random((10, 3)),
names=["foo", "bar"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), "foobar"],
)
def test_colors_length_mismatch(self):
with pytest.raises(ValueError):
_ = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5)],
)
def test_wrong_colors(self):
with pytest.raises(ValueError):
_ = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), "foobar"],
)
def test_colors_setter(self):
l = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
colors = ["#ffffff", "#ffffff", "#ffffff"]
l.colors = colors
np.testing.assert_array_equal(l.colors, np.array(colors))
def test_color_setter_wrong_colors(self):
l = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
with pytest.raises(ValueError):
l.colors = ["#ffffff", "#ffffff", "foo"]
def test_names_setter(self):
l = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
names = ["foo1", "bar1", "baz1"]
l.names = names
np.testing.assert_array_equal(l.names, np.array(names))
def test_names_setter_wrong_type(self):
l = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
l.names = ["foo1", "bar1", 3]
np.testing.assert_array_equal(l.names, np.array(["foo1", "bar1", "3"]))
def test_names_setter_wrong_size(self):
l = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
with pytest.raises(ValueError):
l.names = ["foo1", "bar1"]
def test_names_setter_non_unique(self):
l = Lineage(
np.random.random((10, 3)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
with pytest.raises(ValueError):
l.names = ["foo1", "bar1", "bar1"]
def test_non_unique_names(self):
with pytest.raises(ValueError):
_ = Lineage(
np.random.random((10, 3, 1)),
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), "#ffffff", "#ff00FF"],
)
def test_non_unique_names_conversion(self):
with pytest.raises(ValueError):
_ = Lineage(
np.random.random((10, 3, 1)),
names=["foo", "1", 1],
colors=[(0, 0, 0), "#ffffff", "#ff00FF"],
)
class TestLineageAccessor:
def test_too_large_tuple(self, lineage: Lineage):
with pytest.raises(ValueError):
_ = lineage[0, 0, 0]
def test_none(self, lineage: Lineage):
y = lineage[None, None]
np.testing.assert_array_equal(y, lineage)
def test_ellipsis(self, lineage: Lineage):
y = lineage[..., ...]
np.testing.assert_array_equal(y, lineage)
def test_subset_same_instance(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[0, 0]
assert isinstance(y, Lineage)
def test_singleton_column(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[:, 0]
np.testing.assert_array_equal(x[:, 0], np.array(y)[:, 0])
def test_singleton_column_name(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[:, "foo"]
np.testing.assert_array_equal(x[:, 0], np.array(y)[:, 0])
def test_singleton_column_first_index_assignment(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l["baz"]
np.testing.assert_array_equal(x[:, 2], np.array(y)[:, 0])
np.testing.assert_array_equal(y.names, ["baz"])
def test_singleton_row_and_column(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[0, "foo"]
assert isinstance(l, Lineage)
assert y.shape == (1, 1)
assert x[0, 0] == y[0, 0]
def test_mixed_columns(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[0, ["foo", 2, "bar"]]
np.testing.assert_array_equal(x[[[0]], [0, 2, 1]], np.array(y))
def test_remove_duplicates(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[0, ["foo", 2, "bar", 0, 0, "foo"]]
np.testing.assert_array_equal(x[[[0]], [0, 2, 1]], np.array(y))
def test_column_invalid_name(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
with pytest.raises(KeyError):
_ = l["quux"]
def test_row_subset_with_ints(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[[1, 2, 3], :]
np.testing.assert_array_equal(x[[1, 2, 3], :], np.array(y))
def test_column_subset_boolean(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[:, [False, False, True]]
np.testing.assert_array_equal(x[:, -1], y.X.squeeze())
def test_column_subset_boolean_invalid_dim(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
with pytest.raises(IndexError):
_ = l[:, [True]]
def test_row_subset_with_mask(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
mask = np.ones((x.shape[0]), dtype=bool)
mask[:5] = False
y = l[mask, :]
np.testing.assert_array_equal(x[mask, :], np.array(y))
def test_column_subset_with_ints(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[:, [2, 0]]
np.testing.assert_array_equal(x[:, [2, 0]], np.array(y))
def test_column_subset_with_mask(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
mask = np.ones((x.shape[1]), dtype=bool)
mask[0] = False
y = l[:, mask]
np.testing.assert_array_equal(x[:, mask], np.array(y))
def test_column_subset_with_names(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[:, ["foo", "bar"]]
np.testing.assert_array_equal(x[:, [0, 1]], np.array(y))
def test_comb_row_int_col_int(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[[0, 1], [1, 2]]
np.testing.assert_array_equal(x[[0, 1], :][:, [1, 2]], np.array(y))
def test_comb_row_int_col_mask(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
mask = np.ones((x.shape[1]), dtype=bool)
mask[0] = False
y = l[[0, 1], mask]
np.testing.assert_array_equal(x[[0, 1], :][:, mask], np.array(y))
def test_comb_row_int_col_names(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
y = l[[0, 1], "baz"]
np.testing.assert_array_equal(x[[0, 1], :][:, [2]], np.array(y))
def test_comb_row_mask_col_int(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
mask = np.ones((x.shape[0]), dtype=bool)
mask[5:] = False
y = l[mask, 0]
np.testing.assert_array_equal(x[mask, :][:, [0]], np.array(y))
def test_comb_row_mask_col_mask(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
row_mask = np.ones((x.shape[0]), dtype=bool)
row_mask[5:] = False
col_mask = np.ones((x.shape[1]), dtype=bool)
y = l[row_mask, col_mask]
np.testing.assert_array_equal(x[row_mask, :][:, col_mask], np.array(y))
def test_comb_row_mask_col_names(self):
x = np.random.random((10, 3))
l = Lineage(
x,
names=["foo", "bar", "baz"],
colors=[(0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1)],
)
mask = np.ones((x.shape[0]), dtype=bool)
mask[5:] = False
y = l[mask, ["baz", "bar"]]
np.testing.assert_array_equal(x[mask, :][:, [2, 1]], np.array(y))
def test_reordering(self):
x = np.random.random((10, 3))
l = Lineage(
x, names=["foo", "bar", "baz"], colors=["#ff0000", "#00ff00", "#0000ff"]
)
y = l[["baz", "bar", "foo"]]
np.testing.assert_array_equal(y.names, ["baz", "bar", "foo"])
np.testing.assert_array_equal(y.colors, ["#0000ff", "#00ff00", "#ff0000"])
def test_non_trivial_subset(self):
x = np.random.random((10, 3))
l = Lineage(
x, names=["foo", "bar", "baz"], colors=["#ff0000", "#00ff00", "#0000ff"]
)
mask = np.ones((x.shape[0]), dtype=bool)
mask[5:] = False
y = l[mask, :][:, ["baz", "bar", "foo"]]
np.testing.assert_array_equal(y, x[mask, :][:, ::-1])
np.testing.assert_array_equal(y.names, ["baz", "bar", "foo"])
np.testing.assert_array_equal(y.colors, ["#0000ff", "#00ff00", "#ff0000"])
def test_non_trivial_subset_2(self):
x = np.random.random((10, 3))
l = Lineage(
x, names=["foo", "bar", "baz"], colors=["#ff0000", "#00ff00", "#0000ff"]
)
mask = np.ones((x.shape[0]), dtype=bool)
mask[5:] = False
y = l[mask, ["baz", "bar", "foo"]]
z = l[mask, :][:, ["baz", "bar", "foo"]]
np.testing.assert_array_equal(y, z)
np.testing.assert_array_equal(y, x[mask, :][:, [2, 1, 0]])
np.testing.assert_array_equal(y.names, z.names)
np.testing.assert_array_equal(y.colors, z.colors)
def test_col_order(self):
x = np.random.random((10, 5))
l = Lineage(
x,
names=["foo", "bar", "baz", "quux", "wex"],
colors=["#ff0000", "#00ff00", "#0000ff", "#aaaaaa", "#bbbbbb"],
)
y = l[["wex", "quux"]]
np.testing.assert_array_equal(x[:, [4, 3]], y)
np.testing.assert_array_equal(y.names, ["wex", "quux"])
np.testing.assert_array_equal(y.colors, ["#bbbbbb", "#aaaaaa"])
def test_automatic_color_assignment(self):
x = np.random.random((10, 3))
l = Lineage(x, names=["foo", "bar", "baz"])
gt_colors = [colors.to_hex(c) for c in _create_categorical_colors(3)]
np.testing.assert_array_equal(l.colors, gt_colors)
def test_correct_names_to_ixs(self):
x = np.random.random((10, 3))
l = Lineage(x, names=["foo", "bar", "baz"])
y = l[["baz", "bar"]]
assert y._names_to_ixs == {"baz": 0, "bar": 1}
def test_correct_order(self):
x = np.random.random((10, 3))
l = Lineage(x, names=["foo", "bar", "baz"])
np.testing.assert_array_equal(l[["foo", "baz"]].X, l[["baz", "foo"]].X[:, ::-1])
def test_mask_x_full_names_y(self):
x = np.random.random((10, 3))
l = Lineage(x, names=["Beta", "Epsilon", "Alpha"])
cmapper = dict(zip(l.names, l.colors))
mask = np.zeros(l.shape[0], dtype=bool)
mask[0] = True
mask[-1] = True
y = l[mask, ["Epsilon", "Alpha", "Beta"]]
assert y.shape == (2, 3)
np.testing.assert_array_equal(y.names, ["Epsilon", "Alpha", "Beta"])
np.testing.assert_array_equal(y.colors, [cmapper[n] for n in y.names])
np.testing.assert_array_equal(y.X, x[[0, -1], :][:, [1, 2, 0]])
def test_mask_and_names(self):
# see https://github.com/theislab/cellrank/issues/427
lin = Lineage(
np.random.normal(size=(100, 9)),
names=[
"Neuroendocrine",
"Ciliated activated_1",
"Basal",
"Goblet",
"Mki67+ proliferation",
"Ciliated activated_2",
"Krt8+ ADI",
"Ciliated",
"AT2 activated",
],
)
lineages = [
"Goblet",
"Ciliated",
"Ciliated activated_1",
"Ciliated activated_2",
]
mask = np.random.randint(2, size=(100,), dtype=bool)
res = lin[mask, lineages]
np.testing.assert_array_equal(res.names, lin.names[[3, 7, 1, 5]])
np.testing.assert_array_equal(res.colors, lin.colors[[3, 7, 1, 5]])
np.testing.assert_array_equal(res.X, lin[mask, :][:, [3, 7, 1, 5]])
def test_common_name(self):
l1 = Lineage(np.random.random((10, 2)), names=["EN", "Posterior EN"])
l2 = l1[["EN", "Posterior EN"]]
np.testing.assert_equal(l1.X, l2.X)
np.testing.assert_array_equal(l1.names, l2.names)
np.testing.assert_array_equal(l1.colors, l2.colors)
class TestLineageMixing:
def test_overlap(self):
x = Lineage(np.random.random((10, 4)), names=["foo", "bar", "baz", "quux"])
with pytest.raises(ValueError):
_ = x[["foo, bar", "foo"]]
def test_overlap_mix(self):
x = Lineage(np.random.random((10, 4)), names=["foo", "bar", "baz", "quux"])
with pytest.raises(ValueError):
_ = x[["foo, bar", 0]]
def test_no_rest_or_none(self):
x = Lineage(np.random.random((10, 4)), names=["foo", "bar", "baz", "quux"])
y = x[["foo, bar"]]
expected = np.sum(x.X[:, [0, 1]], axis=1)[..., np.newaxis]
assert y.shape == (10, 1)
np.testing.assert_array_equal(y.X, expected)
np.testing.assert_array_equal(y.names, ["bar, foo"])
np.testing.assert_array_equal(y.colors, [_compute_mean_color(x.colors[:2])])
def test_row_subset(self):
x = Lineage(np.random.random((10, 4)), names=["foo", "bar", "baz", "quux"])
y = x[:5, ["foo, bar"]]
expected = np.sum(x.X[:5, [0, 1]], axis=1)[..., np.newaxis]
assert y.shape == (5, 1)
np.testing.assert_array_equal(y.X, expected)
np.testing.assert_array_equal(y.names, ["bar, foo"])
np.testing.assert_array_equal(y.colors, [_compute_mean_color(x.colors[:2])])
class TestLineageNormalization:
def test_empty_keys(self, lineage: Lineage):
with pytest.raises(ValueError):
lineage.reduce()
def test_not_summing_to_1(self, lineage: Lineage):
lineage[0, 0] = 0
with pytest.raises(ValueError):
lineage.reduce("foo")
def test_invalid_key(self, lineage: Lineage):
with pytest.raises(KeyError):
lineage.reduce("non_existent")
def test_all_names(self, lineage: Lineage):
lin = lineage.reduce(*lineage.names)
np.testing.assert_array_equal(lin.X, lineage.X)
def test_invalid_mode(self, lineage: Lineage):
with pytest.raises(ValueError):
lineage.reduce("foo", "bar", mode="foo")
def test_invalid_dist_measure(self, lineage: Lineage):
with pytest.raises(ValueError):
lineage.reduce("foo", "bar", dist_measure="foo")
def test_invalid_weight_normalize(self, lineage: Lineage):
with pytest.raises(ValueError):
lineage.reduce("foo", "bar", normalize_weights="foo")
def test_return_weights_mode_scale(self, lineage: Lineage):
lin, weights = lineage.reduce("foo", "bar", mode="scale", return_weights=True)
assert isinstance(lin, Lineage)
assert weights is None
def test_return_weights_mode_dist(self, lineage: Lineage):
lin, weights = lineage.reduce("foo", "bar", mode="dist", return_weights=True)
assert isinstance(lin, Lineage)
assert isinstance(weights, DataFrame)
def test_normal_only_1(self, lineage: Lineage):
lin = lineage.reduce("foo")
assert lin.shape == (10, 1)
np.testing.assert_allclose(np.sum(lin, axis=1), 1.0)
np.testing.assert_array_equal(lin.names, ["foo"])
np.testing.assert_array_equal(lin.colors, lineage[["foo"]].colors)
def test_normal_run(self, lineage: Lineage):
lin = lineage.reduce("foo", "bar")
assert lin.shape == (10, 2)
np.testing.assert_allclose(np.sum(lin, axis=1), 1.0)
np.testing.assert_array_equal(lin.names, ["foo", "bar"])
np.testing.assert_array_equal(lin.colors, lineage[["foo", "bar"]].colors)
def test_normal_run_combination(self, lineage: Lineage):
lin = lineage.reduce("foo, bar", "baz")
assert lin.shape == (10, 2)
np.testing.assert_allclose(np.sum(lin, axis=1), 1.0)
np.testing.assert_array_equal(lin.names, ["bar, foo", "baz"])
np.testing.assert_array_equal(lin.colors, lineage[["foo, bar", "baz"]].colors)
def test_normal_run_combination_only_1(self, lineage: Lineage):
lin = lineage.reduce("foo, bar")
assert lin.shape == (10, 1)
np.testing.assert_allclose(np.sum(lin, axis=1), 1.0)
np.testing.assert_array_equal(lin.names, ["bar, foo"])
np.testing.assert_array_equal(lin.colors, lineage[["foo, bar"]].colors)
def test_normal_run_combination_all(self, lineage: Lineage):
assert lineage.shape == (10, 4)
lin = lineage.reduce("foo, bar", "baz, quux")
assert lin.shape == (10, 2)
np.testing.assert_allclose(np.sum(lin, axis=1), 1.0)
np.testing.assert_array_equal(lin.names, ["bar, foo", "baz, quux"])
np.testing.assert_array_equal(
lin.colors, lineage[["foo, bar", "baz, quux"]].colors
)
@mock.patch("cellrank._utils._lineage._cosine_sim")
def test_cosine(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce("foo", "bar", dist_measure="cosine_sim", mode="dist")
except ValueError:
pass
finally:
mocker.assert_called_once()
@mock.patch("cellrank._utils._lineage._wasserstein_dist")
def test_wasserstein(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce(
"foo", "bar", dist_measure="wasserstein_dist", mode="dist"
)
except ValueError:
pass
finally:
mocker.assert_called_once()
@mock.patch("cellrank._utils._lineage._kl_div")
def test_kl_div(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce("foo", "bar", dist_measure="kl_div", mode="dist")
except ValueError:
pass
finally:
mocker.assert_called_once()
@mock.patch("cellrank._utils._lineage._js_div")
def test_js_div(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce("foo", "bar", dist_measure="js_div", mode="dist")
except ValueError:
pass
finally:
mocker.assert_called_once()
@mock.patch("cellrank._utils._lineage._mutual_info")
def test_mutual_info(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce("foo", "bar", dist_measure="mutual_info", mode="dist")
except ValueError:
pass
finally:
mocker.assert_called_once()
@mock.patch("cellrank._utils._lineage._row_normalize")
def test_equal(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce("foo", "bar", dist_measure="equal", mode="dist")
except ValueError:
pass
finally:
# should be twice, but we have extra check inside and we're mocking that does nothing
mocker.assert_called_once()
@mock.patch("cellrank._utils._lineage._row_normalize")
def test_row_normalize(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce("foo", "bar", mode="scale")
except ValueError:
pass
finally:
mocker.assert_called_once()
@mock.patch("cellrank._utils._lineage._softmax")
def test_softmax(self, mocker, lineage: Lineage):
try:
_ = lineage.reduce("foo", "bar", normalize_weights="softmax", mode="dist")
except ValueError:
pass
finally:
mocker.assert_called_once()
class TestLineageSameLengthIndexing:
def test_same_names(self):
x = Lineage(np.random.random((10, 4)), names=["foo", "bar", "baz", "quux"])
y = x[np.arange(len(x)), ["foo"] * len(x)]
expected = x["foo"]
assert y.shape == (10, 1)
np.testing.assert_array_equal(y.X, expected.X)
np.testing.assert_array_equal(y.names, ["mixture"])
np.testing.assert_array_equal(y.colors, ["#000000"])
def test_same_indices(self):
x = Lineage(np.random.random((10, 4)), names=["foo", "bar", "baz", "quux"])
half = len(x) // 2
y = x[[0] * len(x), ["foo"] * half + ["bar"] * half]
expected = np.array([x[0, "foo"].X[0, 0]] * half + [x[0, "bar"].X[0, 0]] * half)
assert y.shape == (10, 1)
np.testing.assert_array_equal(y.X.squeeze(), expected)
np.testing.assert_array_equal(y.names, ["mixture"])
np.testing.assert_array_equal(y.colors, ["#000000"])
class TestTransposition:
def test_double_t(self, lineage: Lineage):
x = lineage.T.T
assert x.shape == lineage.shape
np.testing.assert_array_equal(x, lineage)
def test_copy(self, lineage: Lineage):
y = lineage.T.copy()
lineage[0, 0] = -100000
assert y is not lineage
assert y.shape == lineage.shape[::-1]
assert y[0, 0] != lineage[0, 0]
def test_simple_access(self, lineage: Lineage):
y = lineage.T["foo"]
with pytest.raises(TypeError):
_ = lineage.T[:, "foo"]
assert y.shape == (1, lineage.shape[0])
np.testing.assert_array_equal(y.T, lineage["foo"])
def test_combined_access(self, lineage: Lineage):
y = lineage.T["bar", 0]
assert y.shape == (1, 1)
np.testing.assert_array_equal(y, lineage[0, "bar"])
def test_double_string(self, lineage: Lineage):
x = lineage["baz", "foo"]
y = lineage.T["baz", "foo"]
np.testing.assert_array_equal(x, y.T[:, ::-1])
def test_boolean_accessor(self, lineage: Lineage):
mask = np.zeros(shape=lineage.shape[0], dtype=bool)
mask[[3, 5]] = True
y = lineage.T[["baz", "bar"], mask]
assert y.shape == (2, 2)
np.testing.assert_array_equal(y.names, ["baz", "bar"])
np.testing.assert_array_equal(y, lineage[[3, 5], ["baz", "bar"]].T)
class TestHTMLRepr:
def test_normal_run(self, lineage):
p = SimpleHTMLValidator(
n_expected_rows=lineage.shape[0] + 1,
n_expected_cells=int(np.prod(lineage.shape)),
)
p.feed(lineage._repr_html_())
p.validate()
def test_normal_run_transpose(self, lineage):
p = SimpleHTMLValidator(
n_expected_rows=lineage.shape[1],
n_expected_cells=int(np.prod(lineage.shape)),
)
p.feed(lineage.T._repr_html_())
p.validate()
def test_stripped(self):
lineage = Lineage(np.zeros((1000, 4)), names=["foo", "bar", "baz", "quux"])
# +2 for header and ...
p = SimpleHTMLValidator(
n_expected_rows=_HT_CELLS * 2 + 2,
n_expected_cells=(_HT_CELLS * 2 + 1) * lineage.shape[1],
)
p.feed(lineage._repr_html_())
p.validate()
def test_stripped_transpose(self):
lineage = Lineage(np.zeros((1000, 2)), names=["foo", "bar"])
p = SimpleHTMLValidator(
n_expected_rows=lineage.shape[1],
n_expected_cells=(_HT_CELLS * 2 + 1) * lineage.shape[1],
)
p.feed(lineage.T._repr_html_())
p.validate()
class TestUfuncs:
def test_shape_preserving(self, lineage: Lineage):
x = np.mean(lineage, axis=0)
y = np.mean(lineage, axis=1)
assert x.shape == (1, x.shape[1])
assert y.shape == (y.shape[0], 1)
np.testing.assert_array_equal(x.X[0, :], np.mean(x.X, axis=0))
np.testing.assert_array_equal(y.X[:, 0], np.mean(y.X, axis=1))
def test_shape_preserving_axis_none(self, lineage: Lineage):
y = np.max(lineage, axis=None)
assert y.shape == (1, 1)
assert y.X[0, 0] == np.max(lineage.X)
def test_expand_dims_not_implemented(self, lineage: Lineage):
with pytest.raises(TypeError):
np.expand_dims(lineage, -1)
def test_pretty_naming_axis_0(self, lineage: Lineage):
y = lineage.std(axis=0)
np.testing.assert_array_equal(
y.names, ["std of foo", "std of bar", "std of baz", "std of quux"]
)
def test_color_propagation_axis_0(self, lineage: Lineage):
lineage = lineage.copy()
lineage.colors = [
["red", "green", "blue"][i % 3] for i in range(lineage.shape[1])
]
y = lineage.mean(0)
np.testing.assert_array_equal(y.colors, lineage.colors)
def test_pretty_naming_axis_1(self, lineage: Lineage):
y = lineage.max(axis=1)
np.testing.assert_array_equal(y.names, ["max of foo, bar, baz, quux"])
def test_pretty_naming_axis_None(self, lineage: Lineage):
y = lineage.sum(axis=None)
np.testing.assert_array_equal(y.names, ["sum"])
class TestView:
def test_shares_memory(self, lineage: Lineage):
x = lineage.view()
assert x.owner is lineage
assert isinstance(x.T, LineageView)
assert np.shares_memory(x.X, lineage.X)
assert np.shares_memory(x.names, lineage.names)
assert np.shares_memory(x.colors, lineage.colors)
assert x._names_to_ixs is lineage._names_to_ixs
def test_unable_to_set_attributes(self, lineage: Lineage):
x = lineage.view()
with pytest.raises(RuntimeError):
x.names = lineage.names[::-1]
with pytest.raises(RuntimeError):
x.colors = lineage.colors[::-1]
def test_double_view_owner(self, lineage: Lineage):
x = lineage.view().view()
assert x.owner is lineage
class TestPickling:
def test_pickle_normal(self, lineage: Lineage):
handle = BytesIO()
pickle.dump(lineage, handle)
handle.flush()
handle.seek(0)
res = pickle.load(handle)
assert res.shape == lineage.shape
assert res.dtype == lineage.dtype
assert not np.shares_memory(res.X, lineage.X)