-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathtest_render_shapes.py
More file actions
1001 lines (815 loc) · 49.1 KB
/
test_render_shapes.py
File metadata and controls
1001 lines (815 loc) · 49.1 KB
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 math
import anndata
import geopandas as gpd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pytest
import scanpy as sc
from anndata import AnnData
from matplotlib.colors import Normalize
from shapely.geometry import MultiPolygon, Point, Polygon
from spatialdata import SpatialData, deepcopy
from spatialdata.models import ShapesModel, TableModel
from spatialdata.transformations import Affine, Identity, MapAxis, Scale, Sequence, Translation
from spatialdata.transformations._utils import _set_transformations
import spatialdata_plot # noqa: F401
from spatialdata_plot._logging import logger, logger_warns
from tests.conftest import DPI, PlotTester, PlotTesterMeta, _viridis_with_under_over, get_standard_RNG
sc.pl.set_rcParams_defaults()
sc.set_figure_params(dpi=DPI, color_map="viridis")
matplotlib.use("agg") # same as GitHub action runner
_ = spatialdata_plot
# WARNING:
# 1. all classes must both subclass PlotTester and use metaclass=PlotTesterMeta
# 2. tests which produce a plot must be prefixed with `test_plot_`
# 3. if the tolerance needs to be changed, don't prefix the function with `test_plot_`, but with something else
# the comp. function can be accessed as `self.compare(<your_filename>, tolerance=<your_tolerance>)`
# ".png" is appended to <your_filename>, no need to set it
class TestShapes(PlotTester, metaclass=PlotTesterMeta):
def test_plot_can_render_circles(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles").pl.show()
def test_plot_can_render_circles_with_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", outline_alpha=1).pl.show()
def test_plot_can_render_circles_with_colored_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", outline_alpha=1, outline_color="red").pl.show()
def test_plot_can_render_polygons(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons").pl.show()
def test_plot_can_render_polygons_with_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", outline_alpha=1).pl.show()
def test_plot_can_render_polygons_with_str_colored_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", outline_alpha=1, outline_color="red").pl.show()
def test_plot_can_render_polygons_with_rgb_colored_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
element="blobs_polygons", outline_alpha=1, outline_color=(0.0, 0.0, 1.0, 1.0)
).pl.show()
def test_plot_can_render_polygons_with_rgba_colored_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
element="blobs_polygons", outline_alpha=1, outline_color=(0.0, 1.0, 0.0, 1.0)
).pl.show()
def test_plot_can_render_empty_geometry(self, sdata_blobs: SpatialData):
sdata_blobs.shapes["blobs_circles"].at[0, "geometry"] = gpd.points_from_xy([None], [None])[0]
sdata_blobs.pl.render_shapes().pl.show()
def test_plot_can_render_circles_with_default_outline_width(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", outline_alpha=1).pl.show()
def test_plot_can_render_circles_with_specified_outline_width(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", outline_alpha=1, outline_width=3.0).pl.show()
def test_plot_can_render_multipolygons(self):
def _make_multi():
hole = MultiPolygon(
[(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), [((0.2, 0.2), (0.2, 0.8), (0.8, 0.8), (0.8, 0.2))])]
)
overlap = MultiPolygon(
[
Polygon([(2.0, 0.0), (2.0, 0.8), (2.8, 0.8), (2.8, 0.0)]),
Polygon([(2.2, 0.2), (2.2, 1.0), (3.0, 1.0), (3.0, 0.2)]),
]
)
poly = Polygon([(4.0, 0.0), (4.0, 1.0), (5.0, 1.0), (5.0, 0.0)])
circ = Point(6.0, 0.5)
polygon_series = gpd.GeoSeries([hole, overlap, poly, circ])
cell_polygon_table = gpd.GeoDataFrame(geometry=polygon_series)
sd_polygons = ShapesModel.parse(cell_polygon_table)
sd_polygons.loc[:, "radius"] = [None, None, None, 0.3]
return sd_polygons
sdata = SpatialData(shapes={"p": _make_multi()})
adata = anndata.AnnData(pd.DataFrame({"p": ["hole", "overlap", "square", "circle"]}))
adata.obs.loc[:, "region"] = "p"
adata.obs.loc[:, "val"] = [0, 1, 2, 3]
table = TableModel.parse(adata, region="p", region_key="region", instance_key="val")
sdata["table"] = table
sdata.pl.render_shapes(color="val", fill_alpha=0.3).pl.show()
def test_plot_can_render_multipolygons_with_multiple_holes(self):
square = [(0.0, 0.0), (5.0, 0.0), (5.0, 5.0), (0.0, 5.0), (0.0, 0.0)]
first_hole = [(1.0, 1.0), (2.0, 1.0), (2.0, 2.0), (1.0, 2.0), (1.0, 1.0)]
second_hole = [(3.0, 3.0), (4.0, 3.0), (4.0, 4.0), (3.0, 3.0), (3.0, 3.0)]
multipoly = MultiPolygon([Polygon(square, holes=[first_hole, second_hole])])
cell_polygon_table = gpd.GeoDataFrame(geometry=gpd.GeoSeries([multipoly]))
sd_polygons = ShapesModel.parse(cell_polygon_table)
sdata = SpatialData(shapes={"two_holes": sd_polygons})
fig, ax = plt.subplots()
sdata.pl.render_shapes(element="two_holes").pl.show(ax=ax)
ax.set_xlim(-1, 6)
ax.set_ylim(-1, 6)
fig.tight_layout()
def test_plot_can_render_multipolygons_that_say_they_are_polygons(self):
exterior = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
interior = [(0.1, 0.1), (0.1, 0.9), (0.9, 0.9), (0.9, 0.1), (0.1, 0.1)]
polygon = Polygon(exterior, [interior])
geo_df = gpd.GeoDataFrame(geometry=[polygon])
sdata = SpatialData(shapes={"test": ShapesModel.parse(geo_df)})
fig, ax = plt.subplots()
sdata.pl.render_shapes(element="test").pl.show(ax=ax)
ax.set_xlim(-1, 2)
ax.set_ylim(-1, 2)
fig.tight_layout()
def test_plot_can_render_polygon_with_inverted_inner_ring(self):
ext = [
(7.866043666934409, 32.80184055229537),
(19.016191271980425, 203.48380872801957),
(75.90086964475744, 236.02570144190528),
(229.48380872801957, 235.98380872801957),
(235.98380872801957, 5.516191271980426),
(197.42585593903195, 6.144892860751103),
(116.5, 96.4575926540027),
(55.65582863082729, 12.531294107459374),
(7.866043666934409, 32.80184055229537),
]
interior = [
(160.12353079731844, 173.21221665537414),
(181.80184055229537, 159.13395633306558),
(198.86604366693442, 179.80184055229537),
(178.19815944770465, 198.86604366693442),
(160.12353079731844, 173.21221665537414),
]
polygon = Polygon(ext, [interior])
geo_df = gpd.GeoDataFrame(geometry=[polygon])
sdata = SpatialData(shapes={"inverted_ring": ShapesModel.parse(geo_df)})
fig, ax = plt.subplots()
sdata.pl.render_shapes(element="inverted_ring").pl.show(ax=ax)
ax.set_xlim(0, 250)
ax.set_ylim(0, 250)
fig.tight_layout()
def test_plot_can_render_multipolygon_with_inverted_inner_ring_and_disjoint_part(self):
ext = [
(7.866043666934409, 32.80184055229537),
(19.016191271980425, 203.48380872801957),
(75.90086964475744, 236.02570144190528),
(229.48380872801957, 235.98380872801957),
(235.98380872801957, 5.516191271980426),
(197.42585593903195, 6.144892860751103),
(116.5, 96.4575926540027),
(55.65582863082729, 12.531294107459374),
(7.866043666934409, 32.80184055229537),
]
interior = [
(160.12353079731844, 173.21221665537414),
(181.80184055229537, 159.13395633306558),
(198.86604366693442, 179.80184055229537),
(178.19815944770465, 198.86604366693442),
(160.12353079731844, 173.21221665537414),
]
# Part with a hole and non-standard orientation, plus a disjoint simple part
poly_with_hole = Polygon(ext, [interior])
disjoint_poly = Polygon(
[
(300.0, 300.0),
(320.0, 300.0),
(320.0, 320.0),
(300.0, 320.0),
(300.0, 300.0),
]
)
multipoly = MultiPolygon([poly_with_hole, disjoint_poly])
geo_df = gpd.GeoDataFrame(geometry=[multipoly])
sdata = SpatialData(shapes={"inverted_ring_multipoly": ShapesModel.parse(geo_df)})
fig, ax = plt.subplots()
sdata.pl.render_shapes(element="inverted_ring_multipoly").pl.show(ax=ax)
ax.set_xlim(0, 350)
ax.set_ylim(0, 350)
fig.tight_layout()
def test_plot_can_color_multipolygons_with_multiple_holes(self):
square = [(0.0, 0.0), (5.0, 0.0), (5.0, 5.0), (0.0, 5.0), (0.0, 0.0)]
first_hole = [(1.0, 1.0), (2.0, 1.0), (2.0, 2.0), (1.0, 2.0), (1.0, 1.0)]
second_hole = [(3.0, 3.0), (4.0, 3.0), (4.0, 4.0), (3.0, 4.0), (3.0, 3.0)]
multipoly = MultiPolygon([Polygon(square, holes=[first_hole, second_hole])])
cell_polygon_table = gpd.GeoDataFrame(geometry=gpd.GeoSeries([multipoly]))
cell_polygon_table["instance_id"] = [0]
sd_polygons = ShapesModel.parse(cell_polygon_table)
adata = anndata.AnnData(pd.DataFrame({"value": [1]}))
adata.obs["region"] = pd.Categorical(["two_holes"] * adata.n_obs)
adata.obs["instance_id"] = [0]
adata.obs["category"] = ["holey"]
table = TableModel.parse(adata, region="two_holes", region_key="region", instance_key="instance_id")
sdata = SpatialData(shapes={"two_holes": sd_polygons}, tables={"table": table})
fig, ax = plt.subplots()
sdata.pl.render_shapes(element="two_holes", color="category", table_name="table").pl.show(ax=ax)
ax.set_xlim(-1, 6)
ax.set_ylim(-1, 6)
fig.tight_layout()
def test_plot_can_color_from_geodataframe(self, sdata_blobs: SpatialData):
blob = deepcopy(sdata_blobs)
blob["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * blob["table"].n_obs)
blob["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
blob.shapes["blobs_polygons"]["value"] = [1, 10, 1, 20, 1]
blob.pl.render_shapes(
element="blobs_polygons",
color="value",
).pl.show()
def test_plot_can_scale_shapes(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", scale=0.5).pl.show()
def test_plot_can_filter_with_groups(self, sdata_blobs: SpatialData):
_, axs = plt.subplots(nrows=1, ncols=2, layout="tight")
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["cluster"] = "c1"
sdata_blobs.shapes["blobs_polygons"].iloc[3:5, 1] = "c2"
sdata_blobs.shapes["blobs_polygons"]["cluster"] = sdata_blobs.shapes["blobs_polygons"]["cluster"].astype(
"category"
)
sdata_blobs.pl.render_shapes("blobs_polygons", color="cluster").pl.show(ax=axs[0], legend_fontsize=6)
sdata_blobs.pl.render_shapes("blobs_polygons", color="cluster", groups="c1").pl.show(
ax=axs[1], legend_fontsize=6
)
def test_plot_coloring_with_palette(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["cluster"] = "c1"
sdata_blobs.shapes["blobs_polygons"].iloc[3:5, 1] = "c2"
sdata_blobs.shapes["blobs_polygons"]["cluster"] = sdata_blobs.shapes["blobs_polygons"]["cluster"].astype(
"category"
)
sdata_blobs.pl.render_shapes(
"blobs_polygons", color="cluster", groups=["c2", "c1"], palette=["green", "yellow"]
).pl.show()
def test_plot_colorbar_respects_input_limits(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["cluster"] = [1, 2, 3, 5, 20]
sdata_blobs.pl.render_shapes("blobs_polygons", color="cluster").pl.show()
def test_plot_colorbar_can_be_normalised(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["cluster"] = [1, 2, 3, 5, 20]
norm = Normalize(vmin=0, vmax=5, clip=True)
sdata_blobs.pl.render_shapes("blobs_polygons", color="cluster", groups=["c1"], norm=norm).pl.show()
def test_render_shapes_duplicate_shape_indices_error(self, sdata_blobs: SpatialData):
element = "blobs_polygons"
shapes = sdata_blobs.shapes[element].copy()
n_shapes = len(shapes)
rng = get_standard_RNG()
adata = AnnData(rng.normal(size=(n_shapes, 3)))
adata.obs["annotation"] = rng.choice(["a", "b"], size=n_shapes)
adata.obs["instance_id"] = [f"id_{i}" for i in range(n_shapes)]
adata.obs["region"] = pd.Categorical([element] * n_shapes)
table = TableModel.parse(adata=adata, region=element, region_key="region", instance_key="instance_id")
sdata_blobs["table"] = table
instance_key = table.uns["spatialdata_attrs"]["instance_key"]
shapes.index = table.obs[instance_key].tolist()
duplicated_index = shapes.index.to_list()
duplicated_index[1] = duplicated_index[0]
shapes.index = duplicated_index
sdata_blobs.shapes[element] = shapes
with pytest.raises(ValueError, match="duplicate index values"):
sdata_blobs.pl.render_shapes(
element=element,
color="annotation",
table_name="table",
).pl.show()
def test_render_shapes_duplicate_table_rows_error(self, sdata_blobs: SpatialData):
element = "blobs_polygons"
shapes = sdata_blobs.shapes[element]
n_shapes = len(shapes)
rng = get_standard_RNG()
shape_ids = [f"shape_{i}" for i in range(n_shapes)]
shapes.index = shape_ids
sdata_blobs.shapes[element] = shapes
adata = AnnData(rng.normal(size=(n_shapes, 3)))
adata.obs["annotation"] = rng.choice(["a", "b"], size=n_shapes)
adata.obs["instance_id"] = shape_ids
adata.obs["region"] = pd.Categorical([element] * n_shapes)
table = TableModel.parse(adata=adata, region=element, region_key="region", instance_key="instance_id")
instance_key = table.uns["spatialdata_attrs"]["instance_key"]
table.obs.at[table.obs.index[1], instance_key] = table.obs.at[table.obs.index[0], instance_key]
sdata_blobs["table"] = table
with pytest.raises(ValueError, match="duplicate 'instance"):
sdata_blobs.pl.render_shapes(
element=element,
color="annotation",
table_name="table",
).pl.show()
def test_render_shapes_raises_when_color_key_missing(self, sdata_blobs_shapes_annotated: SpatialData):
missing_col = "__non_existent_column__"
with pytest.raises(KeyError, match=f"Unable to locate color key '{missing_col}'"):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons",
color=missing_col,
).pl.show()
def test_render_shapes_raises_for_invalid_table_name(self, sdata_blobs_shapes_annotated: SpatialData):
table = sdata_blobs_shapes_annotated["table"]
table.obs["region"] = pd.Categorical(["blobs_polygons"] * table.n_obs)
table.uns["spatialdata_attrs"]["region"] = "blobs_polygons"
table.obs["valid_col"] = np.arange(table.n_obs)
with pytest.raises(KeyError, match="Table 'not_a_table' does not annotate element 'blobs_polygons'"):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons", color="valid_col", table_name="not_a_table"
)
def test_render_shapes_raises_for_missing_column_in_table(self, sdata_blobs_shapes_annotated: SpatialData):
table = sdata_blobs_shapes_annotated["table"]
table.obs["region"] = pd.Categorical(["blobs_polygons"] * table.n_obs)
table.uns["spatialdata_attrs"]["region"] = "blobs_polygons"
with pytest.raises(
KeyError, match="Column 'not_a_column' not found in obs/var of table 'table' for element 'blobs_polygons'"
):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons", color="not_a_column", table_name="table"
)
def test_plot_can_plot_shapes_after_spatial_query(self, sdata_blobs: SpatialData):
# subset to only shapes, should be unnecessary after rasterizeation of multiscale images is included
blob = SpatialData.init_from_elements(
{
"blobs_circles": sdata_blobs.shapes["blobs_circles"],
"blobs_multipolygons": sdata_blobs.shapes["blobs_multipolygons"],
"blobs_polygons": sdata_blobs.shapes["blobs_polygons"],
}
)
cropped_blob = blob.query.bounding_box(
axes=["x", "y"], min_coordinate=[100, 100], max_coordinate=[300, 300], target_coordinate_system="global"
)
cropped_blob.pl.render_shapes().pl.show()
def test_plot_can_plot_with_annotation_despite_random_shuffling(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_circles"] * sdata_blobs["table"].n_obs)
new_table = sdata_blobs["table"][:5]
new_table.uns["spatialdata_attrs"]["region"] = "blobs_circles"
new_table.obs["instance_id"] = np.array(range(5))
new_table.obs["annotation"] = ["a", "b", "c", "d", "e"]
new_table.obs["annotation"] = new_table.obs["annotation"].astype("category")
sdata_blobs["table"] = new_table
# random permutation of table and shapes
sdata_blobs["table"].obs = sdata_blobs["table"].obs.sample(frac=1, random_state=83)
temp = sdata_blobs["blobs_circles"].sample(frac=1, random_state=47)
del sdata_blobs.shapes["blobs_circles"]
sdata_blobs["blobs_circles"] = temp
sdata_blobs.pl.render_shapes("blobs_circles", color="annotation").pl.show()
def test_plot_can_plot_queried_with_annotation_despite_random_shuffling(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_circles"] * sdata_blobs["table"].n_obs)
new_table = sdata_blobs["table"][:5].copy()
new_table.uns["spatialdata_attrs"]["region"] = "blobs_circles"
new_table.obs["instance_id"] = np.array(range(5))
new_table.obs["annotation"] = ["a", "b", "c", "d", "e"]
new_table.obs["annotation"] = new_table.obs["annotation"].astype("category")
sdata_blobs["table"] = new_table
# random permutation of table and shapes
sdata_blobs["table"].obs = sdata_blobs["table"].obs.sample(frac=1, random_state=83)
temp = sdata_blobs["blobs_circles"].sample(frac=1, random_state=47)
del sdata_blobs.shapes["blobs_circles"]
sdata_blobs["blobs_circles"] = temp
# subsetting the data
sdata_cropped = sdata_blobs.query.bounding_box(
axes=("x", "y"),
min_coordinate=[100, 150],
max_coordinate=[400, 250],
target_coordinate_system="global",
filter_table=True,
)
sdata_cropped.pl.render_shapes("blobs_circles", color="annotation").pl.show()
def test_plot_can_color_two_shapes_elements_by_annotation(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_circles"] * sdata_blobs["table"].n_obs)
new_table = sdata_blobs["table"][:10].copy()
new_table.uns["spatialdata_attrs"]["region"] = ["blobs_circles", "blobs_polygons"]
new_table.obs["instance_id"] = np.concatenate((np.array(range(5)), np.array(range(5))))
new_table.obs["region"] = new_table.obs["region"].cat.add_categories(["blobs_polygons"])
new_table.obs.loc[5 * [False] + 5 * [True], "region"] = "blobs_polygons"
new_table.obs["annotation"] = ["a", "b", "c", "d", "e", "v", "w", "x", "y", "z"]
new_table.obs["annotation"] = new_table.obs["annotation"].astype("category")
sdata_blobs["table"] = new_table
sdata_blobs.pl.render_shapes("blobs_circles", color="annotation").pl.render_shapes(
"blobs_polygons", color="annotation"
).pl.show()
def test_plot_can_color_two_queried_shapes_elements_by_annotation(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_circles"] * sdata_blobs["table"].n_obs)
new_table = sdata_blobs["table"][:10].copy()
new_table.uns["spatialdata_attrs"]["region"] = ["blobs_circles", "blobs_polygons"]
new_table.obs["instance_id"] = np.concatenate((np.array(range(5)), np.array(range(5))))
new_table.obs["region"] = new_table.obs["region"].cat.add_categories(["blobs_polygons"])
new_table.obs.loc[5 * [False] + 5 * [True], "region"] = "blobs_polygons"
new_table.obs["annotation"] = ["a", "b", "c", "d", "e", "v", "w", "x", "y", "z"]
new_table.obs["annotation"] = new_table.obs["annotation"].astype("category")
sdata_blobs["table"] = new_table
sdata_blobs["table"].obs = sdata_blobs["table"].obs.sample(frac=1, random_state=83)
temp = sdata_blobs["blobs_circles"].sample(frac=1, random_state=47)
sdata_blobs["blobs_circles"] = temp
temp = sdata_blobs["blobs_polygons"].sample(frac=1, random_state=71)
sdata_blobs["blobs_polygons"] = temp
# subsetting the data
sdata_cropped = sdata_blobs.query.bounding_box(
axes=("x", "y"),
min_coordinate=[100, 150],
max_coordinate=[350, 300],
target_coordinate_system="global",
filter_table=True,
)
sdata_cropped.pl.render_shapes("blobs_circles", color="annotation").pl.render_shapes(
"blobs_polygons", color="annotation"
).pl.show()
def test_plot_can_stack_render_shapes(self, sdata_blobs: SpatialData):
(
sdata_blobs.pl.render_shapes(element="blobs_circles", na_color="red", fill_alpha=0.5)
.pl.render_shapes(element="blobs_polygons", na_color="blue", fill_alpha=0.5)
.pl.show()
)
def test_plot_can_color_by_color_name(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", color="red").pl.show()
def test_plot_can_color_by_rgb_array(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", color=[0.5, 0.5, 1.0]).pl.show()
def test_plot_can_color_by_rgba_array(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", color=[0.5, 0.5, 1.0, 0.5]).pl.show()
def test_plot_can_color_by_hex(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", color="#88a136").pl.show()
def test_plot_can_color_by_hex_with_alpha(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", color="#88a13688").pl.show()
def test_plot_alpha_overwrites_opacity_from_color(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", color=[0.5, 0.5, 1.0, 0.5], fill_alpha=1.0).pl.show()
def test_plot_shapes_coercable_categorical_color(self, sdata_blobs: SpatialData):
n_obs = len(sdata_blobs["blobs_polygons"])
adata = AnnData(get_standard_RNG().normal(size=(n_obs, 10)))
adata.obs = pd.DataFrame(get_standard_RNG().normal(size=(n_obs, 3)), columns=["a", "b", "c"])
adata.obs["instance_id"] = np.arange(adata.n_obs)
adata.obs["category"] = get_standard_RNG().choice(["a", "b", "c"], size=adata.n_obs)
adata.obs["instance_id"] = list(range(adata.n_obs))
adata.obs["region"] = "blobs_polygons"
table = TableModel.parse(adata=adata, region_key="region", instance_key="instance_id", region="blobs_polygons")
sdata_blobs["table"] = table
sdata_blobs.pl.render_shapes("blobs_polygons", color="category").pl.show()
def test_plot_shapes_categorical_color(self, sdata_blobs: SpatialData):
n_obs = len(sdata_blobs["blobs_polygons"])
adata = AnnData(get_standard_RNG().normal(size=(n_obs, 10)))
adata.obs = pd.DataFrame(get_standard_RNG().normal(size=(n_obs, 3)), columns=["a", "b", "c"])
adata.obs["instance_id"] = np.arange(adata.n_obs)
adata.obs["category"] = get_standard_RNG().choice(["a", "b", "c"], size=adata.n_obs)
adata.obs["instance_id"] = list(range(adata.n_obs))
adata.obs["region"] = "blobs_polygons"
table = TableModel.parse(adata=adata, region_key="region", instance_key="instance_id", region="blobs_polygons")
sdata_blobs["table"] = table
sdata_blobs["table"].obs["category"] = sdata_blobs["table"].obs["category"].astype("category")
sdata_blobs.pl.render_shapes("blobs_polygons", color="category").pl.show()
def test_plot_datashader_can_render_shapes(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(method="datashader").pl.show()
def test_plot_datashader_can_render_colored_shapes(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(method="datashader", color="red").pl.show()
def test_plot_datashader_can_render_with_different_alpha(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(method="datashader", fill_alpha=0.7).pl.show()
def test_plot_datashader_can_color_by_category(self, sdata_blobs: SpatialData):
n_obs = len(sdata_blobs["blobs_polygons"])
adata = AnnData(get_standard_RNG().normal(size=(n_obs, 10)))
adata.obs = pd.DataFrame(get_standard_RNG().normal(size=(n_obs, 3)), columns=["a", "b", "c"])
adata.obs["category"] = get_standard_RNG().choice(["a", "b", "c"], size=adata.n_obs)
adata.obs["instance_id"] = list(range(adata.n_obs))
adata.obs["region"] = "blobs_polygons"
table = TableModel.parse(
adata=adata,
region_key="region",
instance_key="instance_id",
region="blobs_polygons",
)
sdata_blobs["table"] = table
sdata_blobs.pl.render_shapes(element="blobs_polygons", color="category", method="datashader").pl.show()
def test_plot_datashader_can_color_by_category_with_cmap(self, sdata_blobs: SpatialData):
n_obs = len(sdata_blobs["blobs_polygons"])
adata = AnnData(get_standard_RNG().normal(size=(n_obs, 10)))
adata.obs = pd.DataFrame(get_standard_RNG().normal(size=(n_obs, 3)), columns=["a", "b", "c"])
adata.obs["category"] = get_standard_RNG().choice(["a", "b", "c"], size=adata.n_obs)
adata.obs["instance_id"] = list(range(adata.n_obs))
adata.obs["region"] = "blobs_polygons"
table = TableModel.parse(
adata=adata,
region_key="region",
instance_key="instance_id",
region="blobs_polygons",
)
sdata_blobs["table"] = table
sdata_blobs.pl.render_shapes(
element="blobs_polygons", color="category", method="datashader", cmap="cool"
).pl.show()
def test_plot_can_color_by_category_with_cmap(self, sdata_blobs: SpatialData):
n_obs = len(sdata_blobs["blobs_polygons"])
adata = AnnData(get_standard_RNG().normal(size=(n_obs, 10)))
adata.obs = pd.DataFrame(get_standard_RNG().normal(size=(n_obs, 3)), columns=["a", "b", "c"])
adata.obs["category"] = get_standard_RNG().choice(["a", "b", "c"], size=adata.n_obs)
adata.obs["instance_id"] = list(range(adata.n_obs))
adata.obs["region"] = "blobs_polygons"
table = TableModel.parse(
adata=adata,
region_key="region",
instance_key="instance_id",
region="blobs_polygons",
)
sdata_blobs["table"] = table
sdata_blobs.pl.render_shapes(element="blobs_polygons", color="category", cmap="cool").pl.show()
def test_plot_datashader_can_color_by_value(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["value"] = [1, 10, 1, 20, 1]
sdata_blobs.pl.render_shapes(element="blobs_polygons", color="value", method="datashader").pl.show()
def test_plot_datashader_can_color_by_identical_value(self, sdata_blobs: SpatialData):
"""
We test this, because datashader internally scales the values, so when all shapes have the same value,
the scaling would lead to all of them being assigned an alpha of 0, so we wouldn't see anything
"""
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["value"] = [1, 1, 1, 1, 1]
sdata_blobs.pl.render_shapes(element="blobs_polygons", color="value", method="datashader").pl.show()
def test_plot_datashader_shades_with_linear_cmap(self, sdata_blobs: SpatialData):
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["value"] = [1, 2, 1, 20, 1]
sdata_blobs.pl.render_shapes(element="blobs_polygons", color="value", method="datashader").pl.show()
def test_plot_datashader_can_render_with_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(method="datashader", element="blobs_polygons", outline_alpha=1).pl.show()
def test_plot_datashader_can_render_with_diff_alpha_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(method="datashader", element="blobs_polygons", outline_alpha=0.5).pl.show()
def test_plot_datashader_can_render_with_diff_width_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
method="datashader", element="blobs_polygons", outline_alpha=1.0, outline_width=5.0
).pl.show()
def test_plot_datashader_can_render_with_colored_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
method="datashader", element="blobs_polygons", outline_alpha=1, outline_color="red"
).pl.show()
def test_plot_datashader_can_render_with_rgb_colored_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
method="datashader", element="blobs_polygons", outline_alpha=1, outline_color=(0.0, 0.0, 1.0)
).pl.show()
def test_plot_datashader_can_render_with_rgba_colored_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
method="datashader", element="blobs_polygons", outline_alpha=1, outline_color=(0.0, 1.0, 0.0, 1.0)
).pl.show()
def test_plot_can_set_clims_clip(self, sdata_blobs: SpatialData):
table_shapes = sdata_blobs["table"][:5].copy()
table_shapes.obs.instance_id = list(range(5))
table_shapes.obs["region"] = pd.Categorical(["blobs_circles"] * table_shapes.n_obs)
table_shapes.obs["dummy_gene_expression"] = [i * 10 for i in range(5)]
table_shapes.uns["spatialdata_attrs"]["region"] = "blobs_circles"
sdata_blobs["new_table"] = table_shapes
norm = Normalize(vmin=20, vmax=40, clip=True)
sdata_blobs.pl.render_shapes(
"blobs_circles", color="dummy_gene_expression", norm=norm, table_name="new_table"
).pl.show()
def test_plot_datashader_can_transform_polygons(self, sdata_blobs: SpatialData):
theta = math.pi / 1.7
rotation = Affine(
[
[math.cos(theta), -math.sin(theta), 0],
[math.sin(theta), math.cos(theta), 0],
[0, 0, 1],
],
input_axes=("x", "y"),
output_axes=("x", "y"),
)
scale = Scale([-1.3, 1.8], axes=("x", "y"))
identity = Identity()
mapaxis = MapAxis({"x": "y", "y": "x"})
translation = Translation([20, -65], ("x", "y"))
seq = Sequence([mapaxis, scale, identity, translation, rotation])
_set_transformations(sdata_blobs["blobs_polygons"], {"global": seq})
sdata_blobs.pl.render_shapes("blobs_polygons", method="datashader", outline_alpha=1.0).pl.show()
def test_plot_datashader_can_transform_multipolygons(self, sdata_blobs: SpatialData):
theta = math.pi / 1.7
rotation = Affine(
[
[math.cos(theta), -math.sin(theta), 0],
[math.sin(theta), math.cos(theta), 0],
[0, 0, 1],
],
input_axes=("x", "y"),
output_axes=("x", "y"),
)
scale = Scale([-1.3, 1.8], axes=("x", "y"))
identity = Identity()
mapaxis = MapAxis({"x": "y", "y": "x"})
translation = Translation([20, -65], ("x", "y"))
seq = Sequence([mapaxis, scale, identity, translation, rotation])
_set_transformations(sdata_blobs["blobs_multipolygons"], {"global": seq})
sdata_blobs.pl.render_shapes("blobs_multipolygons", method="datashader", outline_alpha=1.0).pl.show()
def test_plot_datashader_can_transform_circles(self, sdata_blobs: SpatialData):
theta = math.pi / 1.7
rotation = Affine(
[
[math.cos(theta), -math.sin(theta), 0],
[math.sin(theta), math.cos(theta), 0],
[0, 0, 1],
],
input_axes=("x", "y"),
output_axes=("x", "y"),
)
scale = Scale([-1.3, 1.8], axes=("x", "y"))
identity = Identity()
mapaxis = MapAxis({"x": "y", "y": "x"})
translation = Translation([20, -65], ("x", "y"))
seq = Sequence([mapaxis, scale, identity, translation, rotation])
_set_transformations(sdata_blobs["blobs_circles"], {"global": seq})
sdata_blobs.pl.render_shapes("blobs_circles", method="datashader", outline_alpha=1.0).pl.show()
def test_plot_can_do_non_matching_table(self, sdata_blobs: SpatialData):
table_shapes = sdata_blobs["table"][:3].copy()
table_shapes.obs.instance_id = list(range(3))
table_shapes.obs["region"] = pd.Categorical(["blobs_circles"] * table_shapes.n_obs)
table_shapes.uns["spatialdata_attrs"]["region"] = "blobs_circles"
sdata_blobs["new_table"] = table_shapes
sdata_blobs.pl.render_shapes("blobs_circles", color="instance_id").pl.show()
def test_plot_can_color_with_norm_no_clipping(self, sdata_blobs_shapes_annotated: SpatialData):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons", color="value", norm=Normalize(2, 4, clip=False), cmap=_viridis_with_under_over()
).pl.show()
def test_plot_datashader_can_color_with_norm_and_clipping(self, sdata_blobs_shapes_annotated: SpatialData):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons",
color="value",
norm=Normalize(2, 4, clip=True),
cmap=_viridis_with_under_over(),
method="datashader",
datashader_reduction="max",
).pl.show()
def test_plot_datashader_can_color_with_norm_no_clipping(self, sdata_blobs_shapes_annotated: SpatialData):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons",
color="value",
norm=Normalize(2, 4, clip=False),
cmap=_viridis_with_under_over(),
method="datashader",
datashader_reduction="max",
).pl.show()
def test_plot_datashader_norm_vmin_eq_vmax_without_clip(self, sdata_blobs_shapes_annotated: SpatialData):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons",
color="value",
norm=Normalize(3, 3, clip=False),
cmap=_viridis_with_under_over(),
method="datashader",
datashader_reduction="max",
).pl.show()
def test_plot_datashader_norm_vmin_eq_vmax_with_clip(self, sdata_blobs_shapes_annotated: SpatialData):
sdata_blobs_shapes_annotated.pl.render_shapes(
element="blobs_polygons",
color="value",
norm=Normalize(3, 3, clip=True),
cmap=_viridis_with_under_over(),
method="datashader",
datashader_reduction="max",
).pl.show()
def test_plot_can_annotate_shapes_with_table_layer(self, sdata_blobs: SpatialData):
nrows, ncols = 5, 3
feature_matrix = get_standard_RNG().random((nrows, ncols))
var_names = [f"feature{i}" for i in range(ncols)]
obs_indices = sdata_blobs["blobs_circles"].index
obs = pd.DataFrame()
obs["instance_id"] = obs_indices
obs["region"] = "blobs_circles"
obs["region"].astype("category")
table = AnnData(X=feature_matrix, var=pd.DataFrame(index=var_names), obs=obs)
table = TableModel.parse(table, region="blobs_circles", region_key="region", instance_key="instance_id")
sdata_blobs["circle_table"] = table
sdata_blobs["circle_table"].layers["normalized"] = get_standard_RNG().random((nrows, ncols))
sdata_blobs.pl.render_shapes("blobs_circles", color="feature0", table_layer="normalized").pl.show()
def test_plot_respects_custom_colors_from_uns(self, sdata_blobs: SpatialData):
shapes_name = "blobs_polygons"
# Ensure that the table annotations point to the shapes element
sdata_blobs["table"].obs["region"] = pd.Categorical([shapes_name] * sdata_blobs["table"].n_obs)
sdata_blobs.set_table_annotates_spatialelement("table", region=shapes_name)
categories = get_standard_RNG().choice(["a", "b", "c"], size=sdata_blobs["table"].n_obs)
categories[:3] = ["a", "b", "c"]
categories = pd.Categorical(categories, categories=["a", "b", "c"])
sdata_blobs["table"].obs["category"] = categories
sdata_blobs["table"].uns["category_colors"] = ["red", "green", "blue"]
sdata_blobs.pl.render_shapes(shapes_name, color="category", table_name="table").pl.show()
def test_plot_can_render_circles_to_hex(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", shape="hex").pl.show()
def test_plot_can_render_circles_to_square(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", shape="square").pl.show()
def test_plot_can_render_polygons_to_hex(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", shape="hex").pl.show()
def test_plot_can_render_polygons_to_square(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", shape="square").pl.show()
def test_plot_can_render_polygons_to_circle(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", shape="circle").pl.show()
def test_plot_can_render_multipolygons_to_hex(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_multipolygons", shape="hex").pl.show()
def test_plot_can_render_multipolygons_to_square(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_multipolygons", shape="square").pl.show()
def test_plot_can_render_multipolygons_to_circle(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_multipolygons", shape="circle").pl.show()
def test_plot_visium_hex_hexagonal_grid(self, sdata_hexagonal_grid_spots: SpatialData):
_, axs = plt.subplots(nrows=1, ncols=2, layout="tight")
sdata_hexagonal_grid_spots.pl.render_shapes(element="spots", shape="circle").pl.show(ax=axs[0])
sdata_hexagonal_grid_spots.pl.render_shapes(element="spots", shape="visium_hex").pl.show(ax=axs[1])
def test_plot_datashader_can_render_circles_to_hex(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", shape="hex", method="datashader").pl.show()
def test_plot_datashader_can_render_circles_to_square(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_circles", shape="square", method="datashader").pl.show()
def test_plot_datashader_can_render_polygons_to_hex(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", shape="hex", method="datashader").pl.show()
def test_plot_datashader_can_render_polygons_to_square(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", shape="square", method="datashader").pl.show()
def test_plot_datashader_can_render_polygons_to_circle(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_polygons", shape="circle", method="datashader").pl.show()
def test_plot_datashader_can_render_multipolygons_to_hex(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_multipolygons", shape="hex", method="datashader").pl.show()
def test_plot_datashader_can_render_multipolygons_to_square(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_multipolygons", shape="square", method="datashader").pl.show()
def test_plot_datashader_can_render_multipolygons_to_circle(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(element="blobs_multipolygons", shape="circle", method="datashader").pl.show()
def test_plot_can_render_shapes_with_double_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes("blobs_circles", outline_width=(10.0, 5.0)).pl.show()
def test_plot_can_render_shapes_with_colored_double_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
"blobs_polygons", outline_width=(10.0, 5.0), outline_color=("purple", "orange")
).pl.show()
def test_plot_can_render_double_outline_with_diff_alpha(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
element="blobs_circles", outline_color=("red", "blue"), outline_alpha=(0.7, 0.3), outline_width=(20, 10)
).pl.show()
def test_plot_outline_alpha_takes_precedence(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
element="blobs_circles",
outline_color=("#ff660033", "#33aa0066"),
outline_width=(20, 10),
outline_alpha=(1.0, 1.0),
).pl.show()
def test_plot_datashader_can_render_shapes_with_double_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes("blobs_circles", outline_width=(10.0, 5.0), method="datashader").pl.show()
def test_plot_datashader_can_render_shapes_with_colored_double_outline(self, sdata_blobs: SpatialData):
sdata_blobs.pl.render_shapes(
"blobs_polygons",
outline_width=(10.0, 5.0),
outline_color=("purple", "orange"),
method="datashader",
).pl.show()
def test_raises_when_table_does_not_annotate_element(self, sdata_blobs: SpatialData):
# Work on an independent copy since we mutate tables
sdata_blobs_local = deepcopy(sdata_blobs)
# Create a table that annotates a DIFFERENT element than the one we will render
other_table = sdata_blobs_local["table"].copy()
other_table.obs["region"] = pd.Categorical(["blobs_points"] * other_table.n_obs) # Different region
other_table.uns["spatialdata_attrs"]["region"] = "blobs_points"
sdata_blobs_local["other_table"] = other_table
# Rendering "blobs_circles" with a table that annotates "blobs_points"
# should now raise to alert the user about the mismatch.
with pytest.raises(
KeyError,
match="Table 'other_table' does not annotate element 'blobs_circles'",
):
sdata_blobs_local.pl.render_shapes(
"blobs_circles",
color="channel_0_sum",
table_name="other_table",
).pl.show()
def test_raises_when_element_has_no_annotating_tables(self, sdata_blobs: SpatialData):
"""Test that rendering an element with no annotating tables raises a clear error."""
# Work on an independent copy since we mutate tables
sdata_blobs_local = deepcopy(sdata_blobs)
# Change the region to something else so it no longer annotates "blobs_circles"
table = sdata_blobs_local["table"].copy()
table.obs["region"] = pd.Categorical(["blobs_points"] * table.n_obs)
table.uns["spatialdata_attrs"]["region"] = "blobs_points"
sdata_blobs_local["table"] = table
# Now "blobs_circles" should have no annotating tables
# Trying to render it with a color column should raise an error
with pytest.raises(
KeyError,
match="Element 'blobs_circles' has no annotating tables",
):
sdata_blobs_local.pl.render_shapes(
"blobs_circles",
color="channel_0_sum",
).pl.show()
def test_plot_can_handle_nan_values_in_color_data(sdata_blobs: SpatialData, caplog):
"""Test that NaN values in color data are handled gracefully and logged."""
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_circles"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_circles"
# Add color column with NaN values
sdata_blobs.shapes["blobs_circles"]["color_with_nan"] = [1.0, 2.0, np.nan, 4.0, 5.0]
# Expect a logger warning about NaN values
with logger_warns(caplog, logger, match="Found 1 NaN values in color data"):
sdata_blobs.pl.render_shapes(element="blobs_circles", color="color_with_nan", na_color="red").pl.show()
def test_plot_colorbar_normalization_with_nan_values(sdata_blobs: SpatialData):
"""Test that colorbar normalization works correctly with NaN values."""
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_polygons"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_polygons"
sdata_blobs.shapes["blobs_polygons"]["color_with_nan"] = [1.0, 2.0, np.nan, 4.0, 5.0]
# Test colorbar with NaN values - should use nanmin/nanmax under the hood and not crash
sdata_blobs.pl.render_shapes(element="blobs_polygons", color="color_with_nan", na_color="gray").pl.show()
def test_plot_can_handle_non_numeric_radius_values(sdata_blobs: SpatialData):
"""Test that non-numeric radius values are handled gracefully."""
sdata_blobs.shapes["blobs_circles"]["radius_mixed"] = [1.0, "invalid", 3.0, np.nan, 5.0]
sdata_blobs.pl.render_shapes(element="blobs_circles", color="red").pl.show()
def test_plot_can_handle_mixed_numeric_and_color_data(sdata_blobs: SpatialData):
"""Test that mixed numeric and color-like data raises a clear error."""
sdata_blobs["table"].obs["region"] = pd.Categorical(["blobs_circles"] * sdata_blobs["table"].n_obs)
sdata_blobs["table"].uns["spatialdata_attrs"]["region"] = "blobs_circles"
sdata_blobs.shapes["blobs_circles"]["mixed_data"] = [1.0, 2.0, np.nan, "red", 5.0]
# Mixed numeric / non-numeric values should raise a TypeError
with pytest.raises(TypeError, match="contains both numeric and non-numeric values"):
sdata_blobs.pl.render_shapes(element="blobs_circles", color="mixed_data", na_color="gray").pl.show()
def test_plot_datashader_single_category(sdata_blobs: SpatialData):
"""Datashader with a single-category Categorical must not raise.
Regression test for https://github.com/scverse/spatialdata-plot/issues/483.
Before the fix, color_key was None when there was only 1 category, but ds.by()
still produced a 3D DataArray, causing datashader to raise:
ValueError: Color key must be provided, with at least as many colors as
there are categorical fields
"""
n_obs = len(sdata_blobs["blobs_polygons"])
adata = AnnData(get_standard_RNG().normal(size=(n_obs, 10)))
adata.obs = pd.DataFrame(get_standard_RNG().normal(size=(n_obs, 3)), columns=["a", "b", "c"])
adata.obs["category"] = pd.Categorical(["only_cat"] * n_obs)
adata.obs["instance_id"] = list(range(n_obs))
adata.obs["region"] = "blobs_polygons"
table = TableModel.parse(
adata=adata,
region_key="region",
instance_key="instance_id",
region="blobs_polygons",
)
sdata_blobs["table"] = table