forked from scverse/scanpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_plotting.py
1702 lines (1467 loc) · 49.4 KB
/
test_plotting.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
from __future__ import annotations
from functools import partial
from itertools import chain, combinations, repeat
from pathlib import Path
from typing import TYPE_CHECKING
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pytest
import seaborn as sns
from anndata import AnnData
from matplotlib.testing.compare import compare_images
from packaging.version import Version
import scanpy as sc
from scanpy._compat import pkg_version
from testing.scanpy._helpers.data import (
krumsiek11,
pbmc3k,
pbmc3k_processed,
pbmc68k_reduced,
)
from testing.scanpy._pytest.marks import needs
if TYPE_CHECKING:
from collections.abc import Callable
HERE: Path = Path(__file__).parent
ROOT = HERE / "_images"
# Test images are saved in the directory ./_images/<test-name>/
# If test images need to be updated, simply copy actual.png to expected.png.
@needs.leidenalg
def test_heatmap(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
adata = krumsiek11()
sc.pl.heatmap(
adata, adata.var_names, "cell_type", use_raw=False, show=False, dendrogram=True
)
save_and_compare_images("heatmap")
# test swap axes
sc.pl.heatmap(
adata,
adata.var_names,
"cell_type",
use_raw=False,
show=False,
dendrogram=True,
swap_axes=True,
figsize=(10, 3),
cmap="YlGnBu",
)
save_and_compare_images("heatmap_swap_axes")
# test heatmap numeric column():
# set as numeric column the vales for the first gene on the matrix
adata.obs["numeric_value"] = adata.X[:, 0]
sc.pl.heatmap(
adata,
adata.var_names,
"numeric_value",
use_raw=False,
num_categories=4,
figsize=(4.5, 5),
show=False,
)
save_and_compare_images("heatmap2")
# test var/obs standardization and layer
adata.layers["test"] = -1 * adata.X.copy()
sc.pl.heatmap(
adata,
adata.var_names,
"cell_type",
use_raw=False,
dendrogram=True,
show=False,
standard_scale="var",
layer="test",
)
save_and_compare_images("heatmap_std_scale_var")
# test standard_scale_obs
sc.pl.heatmap(
adata,
adata.var_names,
"cell_type",
use_raw=False,
dendrogram=True,
show=False,
standard_scale="obs",
)
save_and_compare_images("heatmap_std_scale_obs")
# test var_names as dict
pbmc = pbmc68k_reduced()
sc.tl.leiden(
pbmc,
key_added="clusters",
resolution=0.5,
flavor="igraph",
n_iterations=2,
directed=False,
)
# call umap to trigger colors for the clusters
sc.pl.umap(pbmc, color="clusters")
marker_genes_dict = {
"3": ["GNLY", "NKG7"],
"1": ["FCER1A"],
"2": ["CD3D"],
"0": ["FCGR3A"],
"4": ["CD79A", "MS4A1"],
}
sc.pl.heatmap(
adata=pbmc,
var_names=marker_genes_dict,
groupby="clusters",
vmin=-2,
vmax=2,
cmap="RdBu_r",
dendrogram=True,
swap_axes=True,
)
save_and_compare_images("heatmap_var_as_dict")
# test that plot elements are well aligned
# small
a = AnnData(
np.array([[0, 0.3, 0.5], [1, 1.3, 1.5], [2, 2.3, 2.5]]),
obs={"foo": "a b c".split()},
var=pd.DataFrame({"genes": "g1 g2 g3".split()}).set_index("genes"),
)
a.obs["foo"] = a.obs["foo"].astype("category")
sc.pl.heatmap(
a, var_names=a.var_names, groupby="foo", swap_axes=True, figsize=(4, 4)
)
save_and_compare_images("heatmap_small_swap_alignment")
sc.pl.heatmap(
a, var_names=a.var_names, groupby="foo", swap_axes=False, figsize=(4, 4)
)
save_and_compare_images("heatmap_small_alignment")
@pytest.mark.skipif(
pkg_version("matplotlib") < Version("3.1"),
reason="https://github.com/mwaskom/seaborn/issues/1953",
)
@pytest.mark.parametrize(
"obs_keys,name",
[(None, "clustermap"), ("cell_type", "clustermap_withcolor")],
)
def test_clustermap(image_comparer, obs_keys, name):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
adata = krumsiek11()
sc.pl.clustermap(adata, obs_keys)
save_and_compare_images(name)
@pytest.mark.parametrize(
"id,fn",
[
(
"dotplot",
partial(
sc.pl.dotplot, groupby="cell_type", title="dotplot", dendrogram=True
),
),
(
"dotplot2",
partial(
sc.pl.dotplot,
groupby="numeric_column",
use_raw=False,
num_categories=7,
title="non categorical obs",
figsize=(7, 2.5),
),
),
(
"dotplot3",
partial(
sc.pl.dotplot,
groupby="cell_type",
dot_max=0.7,
dot_min=0.1,
cmap="hot_r",
title="dot_max=0.7 dot_min=0.1, var_groups",
var_group_positions=[(0, 1), (9, 10)],
var_group_labels=["A", "B"],
dendrogram=True,
),
),
(
"dotplot_std_scale_group",
partial(
sc.pl.dotplot,
groupby="cell_type",
use_raw=False,
dendrogram=True,
layer="test",
swap_axes=True,
title="swap_axes, layer=-1*X, scale=group\nsmallest_dot=10",
standard_scale="group",
smallest_dot=10,
),
),
(
"dotplot_dict",
partial(
sc.pl.dotplot,
groupby="cell_type",
dot_max=0.7,
dot_min=0.1,
color_map="winter",
title="var as dict",
dendrogram=True,
),
),
(
"matrixplot",
partial(
sc.pl.matrixplot,
groupby="cell_type",
use_raw=False,
title="matrixplot",
dendrogram=True,
),
),
(
"matrixplot_std_scale_var_dict",
partial(
sc.pl.matrixplot,
groupby="cell_type",
dendrogram=True,
standard_scale="var",
layer="test",
cmap="Blues_r",
title='scale var, custom colorbar_title, layer="test"',
colorbar_title="Scaled expression",
),
),
(
"matrixplot_std_scale_group",
partial(
sc.pl.matrixplot,
groupby="cell_type",
use_raw=False,
standard_scale="group",
title="scale_group, swap_axes",
swap_axes=True,
),
),
(
"matrixplot2",
partial(
sc.pl.matrixplot,
groupby="numeric_column",
use_raw=False,
num_categories=4,
title="non-categorical obs, custom figsize",
figsize=(8, 2.5),
cmap="RdBu_r",
),
),
(
"stacked_violin",
partial(
sc.pl.stacked_violin,
groupby="cell_type",
use_raw=False,
title="stacked_violin",
dendrogram=True,
),
),
(
"stacked_violin_std_scale_var_dict",
partial(
sc.pl.stacked_violin,
groupby="cell_type",
dendrogram=True,
standard_scale="var",
layer="test",
title='scale var, layer="test"',
),
),
(
"stacked_violin_std_scale_group",
partial(
sc.pl.stacked_violin,
groupby="cell_type",
use_raw=False,
standard_scale="group",
title="scale_group\nswap_axes",
swap_axes=True,
cmap="Blues",
),
),
(
"stacked_violin_no_cat_obs",
partial(
sc.pl.stacked_violin,
groupby="numeric_column",
use_raw=False,
num_categories=4,
title="non-categorical obs, custom figsize",
figsize=(8, 2.5),
),
),
],
)
def test_dotplot_matrixplot_stacked_violin(image_comparer, id, fn):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
adata = krumsiek11()
adata.obs["numeric_column"] = adata.X[:, 0]
adata.layers["test"] = -1 * adata.X.copy()
genes_dict = {
"group a": ["Gata2", "Gata1"],
"group b": ["Fog1", "EKLF", "Fli1", "SCL"],
"group c": ["Cebpa", "Pu.1", "cJun", "EgrNab", "Gfi1"],
}
if id.endswith("dict"):
fn(adata, genes_dict, show=False)
else:
fn(adata, adata.var_names, show=False)
save_and_compare_images(id)
def test_dotplot_obj(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
# test dotplot dot_min, dot_max, color_map, and var_groups
pbmc = pbmc68k_reduced()
genes = [
*["CD79A", "MS4A1", "CD8A", "CD8B", "LYZ", "LGALS3"],
*["S100A8", "GNLY", "NKG7", "KLRB1", "FCGR3A", "FCER1A", "CST3"],
]
# test layer, var standardization, smallest_dot,
# color title, size_title return_fig and dot_edge
pbmc.layers["test"] = pbmc.X * -1
plot = sc.pl.dotplot(
pbmc,
genes,
"bulk_labels",
layer="test",
dendrogram=True,
return_fig=True,
standard_scale="var",
smallest_dot=40,
colorbar_title="scaled column max",
size_title="Fraction of cells",
)
plot.style(dot_edge_color="black", dot_edge_lw=0.1, cmap="Reds").show()
save_and_compare_images("dotplot_std_scale_var")
def test_dotplot_add_totals(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=5)
pbmc = pbmc68k_reduced()
markers = {"T-cell": "CD3D", "B-cell": "CD79A", "myeloid": "CST3"}
sc.pl.dotplot(pbmc, markers, "bulk_labels", return_fig=True).add_totals().show()
save_and_compare_images("dotplot_totals")
def test_matrixplot_obj(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
adata = pbmc68k_reduced()
marker_genes_dict = {
"3": ["GNLY", "NKG7"],
"1": ["FCER1A"],
"2": ["CD3D"],
"0": ["FCGR3A"],
"4": ["CD79A", "MS4A1"],
}
plot = sc.pl.matrixplot(
adata,
marker_genes_dict,
"bulk_labels",
use_raw=False,
title="added totals",
return_fig=True,
)
plot.add_totals(sort="descending").style(edge_color="white", edge_lw=0.5).show()
save_and_compare_images("matrixplot_with_totals")
axes = plot.get_axes()
assert "mainplot_ax" in axes, "mainplot_ax not found in returned axes dict"
def test_stacked_violin_obj(image_comparer, plt):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
pbmc = pbmc68k_reduced()
markers = {
"T-cell": ["CD3D", "CD3E", "IL32"],
"B-cell": ["CD79A", "CD79B", "MS4A1"],
"myeloid": ["CST3", "LYZ"],
}
plot = sc.pl.stacked_violin(
pbmc,
markers,
"bulk_labels",
use_raw=False,
title="return_fig. add_totals",
return_fig=True,
)
plot.add_totals().style(row_palette="tab20").show()
save_and_compare_images("stacked_violin_return_fig")
def test_tracksplot(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
adata = krumsiek11()
sc.pl.tracksplot(
adata, adata.var_names, "cell_type", dendrogram=True, use_raw=False
)
save_and_compare_images("tracksplot")
def test_multiple_plots(image_comparer):
# only testing stacked_violin, matrixplot and dotplot
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
adata = pbmc68k_reduced()
markers = {
"T-cell": ["CD3D", "CD3E", "IL32"],
"B-cell": ["CD79A", "CD79B", "MS4A1"],
"myeloid": ["CST3", "LYZ"],
}
fig, (ax1, ax2, ax3) = plt.subplots(
1, 3, figsize=(20, 5), gridspec_kw={"wspace": 0.7}
)
_ = sc.pl.stacked_violin(
adata,
markers,
groupby="bulk_labels",
ax=ax1,
title="stacked_violin",
dendrogram=True,
show=False,
)
_ = sc.pl.dotplot(
adata,
markers,
groupby="bulk_labels",
ax=ax2,
title="dotplot",
dendrogram=True,
show=False,
)
_ = sc.pl.matrixplot(
adata,
markers,
groupby="bulk_labels",
ax=ax3,
title="matrixplot",
dendrogram=True,
show=False,
)
save_and_compare_images("multiple_plots")
def test_violin(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=40)
with plt.rc_context():
sc.pl.set_rcParams_defaults()
sc.set_figure_params(dpi=50, color_map="viridis")
pbmc = pbmc68k_reduced()
sc.pl.violin(
pbmc,
["n_genes", "percent_mito", "n_counts"],
stripplot=True,
multi_panel=True,
jitter=True,
show=False,
)
save_and_compare_images("violin_multi_panel")
sc.pl.violin(
pbmc,
["n_genes", "percent_mito", "n_counts"],
ylabel=["foo", "bar", "baz"],
groupby="bulk_labels",
stripplot=True,
multi_panel=True,
jitter=True,
show=False,
rotation=90,
)
save_and_compare_images("violin_multi_panel_with_groupby")
# test use of layer
pbmc.layers["negative"] = pbmc.X * -1
sc.pl.violin(
pbmc,
"CST3",
groupby="bulk_labels",
stripplot=True,
multi_panel=True,
jitter=True,
show=False,
layer="negative",
use_raw=False,
rotation=90,
)
save_and_compare_images("violin_multi_panel_with_layer")
# TODO: Generalize test to more plotting types
def test_violin_without_raw(tmp_path):
# https://github.com/scverse/scanpy/issues/1546
has_raw_pth = tmp_path / "has_raw.png"
no_raw_pth = tmp_path / "no_raw.png"
pbmc = pbmc68k_reduced()
pbmc_no_raw = pbmc.raw.to_adata().copy()
sc.pl.violin(pbmc, "CST3", groupby="bulk_labels", show=False, jitter=False)
plt.savefig(has_raw_pth)
plt.close()
sc.pl.violin(pbmc_no_raw, "CST3", groupby="bulk_labels", show=False, jitter=False)
plt.savefig(no_raw_pth)
plt.close()
assert compare_images(has_raw_pth, no_raw_pth, tol=5) is None
def test_dendrogram(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=10)
pbmc = pbmc68k_reduced()
sc.pl.dendrogram(pbmc, "bulk_labels")
save_and_compare_images("dendrogram")
def test_correlation(image_comparer):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
pbmc = pbmc68k_reduced()
sc.pl.correlation_matrix(pbmc, "bulk_labels")
save_and_compare_images("correlation")
@pytest.mark.parametrize(
"name,fn",
[
(
"ranked_genes_sharey",
partial(
sc.pl.rank_genes_groups, n_genes=12, n_panels_per_row=3, show=False
),
),
(
"ranked_genes",
partial(
sc.pl.rank_genes_groups,
n_genes=12,
n_panels_per_row=3,
sharey=False,
show=False,
),
),
(
"ranked_genes_heatmap",
partial(
sc.pl.rank_genes_groups_heatmap, n_genes=4, cmap="YlGnBu", show=False
),
),
(
"ranked_genes_heatmap_swap_axes",
partial(
sc.pl.rank_genes_groups_heatmap,
n_genes=20,
swap_axes=True,
use_raw=False,
show_gene_labels=False,
show=False,
vmin=-3,
vmax=3,
cmap="bwr",
),
),
(
"ranked_genes_heatmap_swap_axes_vcenter",
partial(
sc.pl.rank_genes_groups_heatmap,
n_genes=20,
swap_axes=True,
use_raw=False,
show_gene_labels=False,
show=False,
vmin=-3,
vcenter=1,
vmax=3,
cmap="RdBu_r",
),
),
(
"ranked_genes_stacked_violin",
partial(
sc.pl.rank_genes_groups_stacked_violin,
n_genes=3,
show=False,
groups=["3", "0", "5"],
),
),
(
"ranked_genes_dotplot",
partial(sc.pl.rank_genes_groups_dotplot, n_genes=4, show=False),
),
(
"ranked_genes_dotplot_gene_names",
partial(
sc.pl.rank_genes_groups_dotplot,
var_names={
"T-cell": ["CD3D", "CD3E", "IL32"],
"B-cell": ["CD79A", "CD79B", "MS4A1"],
"myeloid": ["CST3", "LYZ"],
},
values_to_plot="logfoldchanges",
cmap="bwr",
vmin=-3,
vmax=3,
show=False,
),
),
(
"ranked_genes_dotplot_logfoldchange",
partial(
sc.pl.rank_genes_groups_dotplot,
n_genes=4,
values_to_plot="logfoldchanges",
vmin=-5,
vmax=5,
min_logfoldchange=3,
cmap="RdBu_r",
swap_axes=True,
title="log fold changes swap_axes",
show=False,
),
),
(
"ranked_genes_dotplot_logfoldchange_vcenter",
partial(
sc.pl.rank_genes_groups_dotplot,
n_genes=4,
values_to_plot="logfoldchanges",
vmin=-5,
vcenter=1,
vmax=5,
min_logfoldchange=3,
cmap="RdBu_r",
swap_axes=True,
title="log fold changes swap_axes",
show=False,
),
),
(
"ranked_genes_matrixplot",
partial(
sc.pl.rank_genes_groups_matrixplot,
n_genes=5,
show=False,
title="matrixplot",
gene_symbols="symbol",
use_raw=False,
),
),
(
"ranked_genes_matrixplot_gene_names_symbol",
partial(
sc.pl.rank_genes_groups_matrixplot,
var_names={
"T-cell": ["CD3D__", "CD3E__", "IL32__"],
"B-cell": ["CD79A__", "CD79B__", "MS4A1__"],
"myeloid": ["CST3__", "LYZ__"],
},
values_to_plot="logfoldchanges",
cmap="bwr",
vmin=-3,
vmax=3,
gene_symbols="symbol",
use_raw=False,
show=False,
),
),
(
"ranked_genes_matrixplot_n_genes_negative",
partial(
sc.pl.rank_genes_groups_matrixplot,
n_genes=-5,
show=False,
title="matrixplot n_genes=-5",
),
),
(
"ranked_genes_matrixplot_swap_axes",
partial(
sc.pl.rank_genes_groups_matrixplot,
n_genes=5,
show=False,
swap_axes=True,
values_to_plot="logfoldchanges",
vmin=-6,
vmax=6,
cmap="bwr",
title="log fold changes swap_axes",
),
),
(
"ranked_genes_matrixplot_swap_axes_vcenter",
partial(
sc.pl.rank_genes_groups_matrixplot,
n_genes=5,
show=False,
swap_axes=True,
values_to_plot="logfoldchanges",
vmin=-6,
vcenter=1,
vmax=6,
cmap="bwr",
title="log fold changes swap_axes",
),
),
(
"ranked_genes_tracksplot",
partial(
sc.pl.rank_genes_groups_tracksplot,
n_genes=3,
show=False,
groups=["3", "2", "1"],
),
),
(
"ranked_genes_violin",
partial(
sc.pl.rank_genes_groups_violin,
groups="0",
n_genes=5,
use_raw=True,
jitter=False,
strip=False,
show=False,
),
),
(
"ranked_genes_violin_not_raw",
partial(
sc.pl.rank_genes_groups_violin,
groups="0",
n_genes=5,
use_raw=False,
jitter=False,
strip=False,
show=False,
),
),
],
)
def test_rank_genes_groups(image_comparer, name, fn):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
pbmc = pbmc68k_reduced()
sc.tl.rank_genes_groups(pbmc, "louvain", n_genes=pbmc.raw.shape[1])
# add gene symbol
pbmc.var["symbol"] = pbmc.var.index + "__"
with plt.rc_context({"axes.grid": True, "figure.figsize": (4, 4)}):
fn(pbmc)
save_and_compare_images(name)
plt.close()
@pytest.fixture(scope="session")
def _gene_symbols_adatas():
"""Create two anndata objects which are equivalent except for var_names
Both have ensembl ids and hgnc symbols as columns in var. The first has ensembl
ids as var_names, the second has symbols.
"""
pbmc = pbmc3k_processed().raw.to_adata()
pbmc_counts = pbmc3k()
pbmc.layers["counts"] = pbmc_counts[pbmc.obs_names, pbmc.var_names].X.copy()
pbmc.var["gene_symbol"] = pbmc.var_names
pbmc.var["ensembl_id"] = pbmc_counts.var["gene_ids"].loc[pbmc.var_names]
pbmc.var = pbmc.var.set_index("ensembl_id", drop=False)
# Cutting down on size for plotting, tracksplot and stacked_violin are slow
pbmc = pbmc[pbmc.obs["louvain"].isin(pbmc.obs["louvain"].cat.categories[:4])]
pbmc = pbmc[::3].copy()
# Creating variations
a = pbmc.copy()
b = pbmc.copy()
a.var = a.var.set_index("ensembl_id")
b.var = b.var.set_index("gene_symbol")
# Computing DE
sc.tl.rank_genes_groups(a, groupby="louvain")
sc.tl.rank_genes_groups(b, groupby="louvain")
return a, b
@pytest.fixture
def gene_symbols_adatas(_gene_symbols_adatas):
a, b = _gene_symbols_adatas
return a.copy(), b.copy()
@pytest.mark.parametrize(
"func",
(
sc.pl.rank_genes_groups_dotplot,
sc.pl.rank_genes_groups_heatmap,
sc.pl.rank_genes_groups_matrixplot,
sc.pl.rank_genes_groups_stacked_violin,
sc.pl.rank_genes_groups_tracksplot,
# TODO: add other rank_genes_groups plots here once they work
),
)
def test_plot_rank_genes_groups_gene_symbols(
gene_symbols_adatas, func, tmp_path, check_same_image
):
a, b = gene_symbols_adatas
pth_1_a = tmp_path / f"{func.__name__}_equivalent_gene_symbols_1_a.png"
pth_1_b = tmp_path / f"{func.__name__}_equivalent_gene_symbols_1_b.png"
func(a, gene_symbols="gene_symbol")
plt.savefig(pth_1_a)
plt.close()
func(b)
plt.savefig(pth_1_b)
pass
check_same_image(pth_1_a, pth_1_b, tol=1)
pth_2_a = tmp_path / f"{func.__name__}_equivalent_gene_symbols_2_a.png"
pth_2_b = tmp_path / f"{func.__name__}_equivalent_gene_symbols_2_b.png"
func(a)
plt.savefig(pth_2_a)
plt.close()
func(b, gene_symbols="ensembl_id")
plt.savefig(pth_2_b)
plt.close()
check_same_image(pth_2_a, pth_2_b, tol=1)
@pytest.mark.parametrize(
"func",
(
sc.pl.rank_genes_groups_dotplot,
sc.pl.rank_genes_groups_heatmap,
sc.pl.rank_genes_groups_matrixplot,
sc.pl.rank_genes_groups_stacked_violin,
sc.pl.rank_genes_groups_tracksplot,
# TODO: add other rank_genes_groups plots here once they work
),
)
def test_rank_genes_groups_plots_n_genes_vs_var_names(tmp_path, func, check_same_image):
"""\
Checks that passing a negative value for n_genes works, and that passing
var_names as a dict works.
"""
N = 3
pbmc = pbmc68k_reduced().raw.to_adata()
groups = pbmc.obs["louvain"].cat.categories[:3]
pbmc = pbmc[pbmc.obs["louvain"].isin(groups)][::3].copy()
sc.tl.rank_genes_groups(pbmc, groupby="louvain")
top_genes = {}
bottom_genes = {}
for g, subdf in sc.get.rank_genes_groups_df(pbmc, group=groups).groupby(
"group", observed=True
):
top_genes[g] = list(subdf["names"].head(N))
bottom_genes[g] = list(subdf["names"].tail(N))
positive_n_pth = tmp_path / f"{func.__name__}_positive_n.png"
top_genes_pth = tmp_path / f"{func.__name__}_top_genes.png"
negative_n_pth = tmp_path / f"{func.__name__}_negative_n.png"
bottom_genes_pth = tmp_path / f"{func.__name__}_bottom_genes.png"
def wrapped(pth, **kwargs):
func(pbmc, groupby="louvain", dendrogram=False, **kwargs)
plt.savefig(pth)
plt.close()
wrapped(positive_n_pth, n_genes=N)
wrapped(top_genes_pth, var_names=top_genes)
check_same_image(positive_n_pth, top_genes_pth, tol=1)
wrapped(negative_n_pth, n_genes=-N)
wrapped(bottom_genes_pth, var_names=bottom_genes)
check_same_image(negative_n_pth, bottom_genes_pth, tol=1)
# Shouldn't be able to pass these together
with pytest.raises(
ValueError, match="n_genes and var_names are mutually exclusive"
):
wrapped(tmp_path / "not_written.png", n_genes=N, var_names=top_genes)
@pytest.mark.parametrize(
"id,fn",
[
("heatmap", sc.pl.heatmap),
("dotplot", sc.pl.dotplot),
("matrixplot", sc.pl.matrixplot),
("stacked_violin", sc.pl.stacked_violin),
("tracksplot", sc.pl.tracksplot),
],
)
def test_genes_symbols(image_comparer, id, fn):
save_and_compare_images = partial(image_comparer, ROOT, tol=15)
adata = krumsiek11()
# add a 'symbols' column
adata.var["symbols"] = adata.var.index.map(lambda x: f"symbol_{x}")
symbols = [f"symbol_{x}" for x in adata.var_names]
fn(adata, symbols, "cell_type", dendrogram=True, gene_symbols="symbols", show=False)
save_and_compare_images(f"{id}_gene_symbols")
@pytest.fixture(scope="module")
def _pbmc_scatterplots_session():
# Wrapped in another fixture to avoid mutation
pbmc = pbmc68k_reduced()
pbmc.obs["mask"] = pbmc.obs["louvain"].isin(["0", "1", "3"])
pbmc.layers["sparse"] = pbmc.raw.X / 2
pbmc.layers["test"] = pbmc.X.copy() + 100
pbmc.var["numbers"] = [str(x) for x in range(pbmc.shape[1])]
sc.pp.neighbors(pbmc)
sc.tl.tsne(pbmc, random_state=0, n_pcs=30)
sc.tl.diffmap(pbmc)
return pbmc
@pytest.fixture
def pbmc_scatterplots(_pbmc_scatterplots_session):
return _pbmc_scatterplots_session.copy()
@pytest.mark.parametrize(
"id,fn",
[
("pca", partial(sc.pl.pca, color="bulk_labels")),
(
"pca_with_fonts",
partial(
sc.pl.pca,
color=["bulk_labels", "louvain"],
legend_loc="on data",
legend_fontoutline=2,
legend_fontweight="normal",
legend_fontsize=10,
),
),
pytest.param(
"3dprojection", partial(sc.pl.pca, color="bulk_labels", projection="3d")
),
(
"multipanel",
partial(
sc.pl.pca,
color=["CD3D", "CD79A"],
components=["1,2", "1,3"],