-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathclasses.py
More file actions
1286 lines (1092 loc) · 42.6 KB
/
classes.py
File metadata and controls
1286 lines (1092 loc) · 42.6 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
"""
Title: SpatialBasePlot for all spatial coordinates and image plot
Author: Duy Pham
Date: 20 Feb 2021
"""
from lib2to3.pgen2.token import OP
from typing import Optional, Union, Mapping, List # Special
from typing import Sequence, Iterable # ABCs
from typing import Tuple # Classes
import numbers
import numpy as np
import pandas as pd
from anndata import AnnData
from matplotlib import rcParams, ticker, gridspec, axes
import matplotlib.pyplot as plt
import matplotlib
from scipy.interpolate import griddata
import networkx as nx
from ..classes import Spatial
from ..utils import _AxesSubplot, Axes, _read_graph
from .utils import centroidpython, get_cluster, get_node, check_sublist, get_cmap
################################################################
# #
# Spatial base plot class #
# #
################################################################
class SpatialBasePlot(Spatial):
def __init__(
self,
# plotting param
adata: AnnData,
title: Optional["str"] = None,
figsize: Optional[Tuple[float, float]] = None,
cmap: Optional[str] = "Spectral_r",
use_label: Optional[str] = None,
list_clusters: Optional[list] = None,
ax: Optional[matplotlib.axes._subplots.Axes] = None,
fig: Optional[matplotlib.figure.Figure] = None,
show_plot: Optional[bool] = True,
show_axis: Optional[bool] = False,
show_image: Optional[bool] = True,
show_color_bar: Optional[bool] = True,
color_bar_label: Optional[str] = "",
zoom_coord: Optional[float] = None,
crop: Optional[bool] = True,
margin: Optional[bool] = 100,
size: Optional[float] = 7,
image_alpha: Optional[float] = 1.0,
cell_alpha: Optional[float] = 0.7,
use_raw: Optional[bool] = False,
fname: Optional[str] = None,
dpi: Optional[int] = 120,
**kwds,
):
super().__init__(
adata,
)
self.title = title
self.figsize = figsize
self.image_alpha = image_alpha
self.cell_alpha = cell_alpha
self.size = size
self.query_adata = self.adata[0].copy()
self.list_clusters = list_clusters
self.fname = fname
self.dpi = dpi
if use_raw:
self.query_adata = self.adata[0].raw.to_adata().copy()
if self.list_clusters != None:
assert use_label != None, "Please specify `use_label` parameter!"
if use_label != None:
assert (
use_label in self.adata[0].obs.columns
), "Please choose the right label in `adata.obs.columns`!"
self.use_label = use_label
if self.list_clusters is None:
self.list_clusters = np.array(
self.adata[0].obs[use_label].cat.categories
)
else:
if type(self.list_clusters) != list:
self.list_clusters = [self.list_clusters]
clusters_indexes = [
np.where(adata.obs[use_label].cat.categories == i)[0][0]
for i in self.list_clusters
]
self.list_clusters = np.array(self.list_clusters)[
np.argsort(clusters_indexes)
]
self.query_indexes = self._get_query_clusters_index()
self._select_clusters()
# Initialize cmap
scanpy_cmap = ["vega_10_scanpy", "vega_20_scanpy", "default_102", "default_28"]
stlearn_cmap = ["jana_40", "default"]
cmap_available = plt.colormaps() + scanpy_cmap + stlearn_cmap
error_msg = (
"cmap must be a matplotlib.colors.LinearSegmentedColormap OR"
"one of these: " + str(cmap_available)
)
if type(cmap) == str:
assert cmap in cmap_available, error_msg
elif type(cmap) != matplotlib.colors.LinearSegmentedColormap:
raise Exception(error_msg)
self.cmap = cmap
if type(fig) == type(None) and type(ax) == type(None):
self.fig, self.ax = self._generate_frame()
else:
self.fig, self.ax = fig, ax
if show_axis == False:
self._remove_axis(self.ax)
if show_image:
self._add_image(self.ax)
if zoom_coord is not None:
self._zoom_image(self.ax, zoom_coord)
crop = False
if crop:
self._crop_image(self.ax, margin)
def _select_clusters(self):
def create_query(list_cl, use_label):
ini = ""
for sub in list_cl:
ini = ini + self.use_label + ' == "' + str(sub) + '" | '
return ini[:-2]
if self.list_clusters is not None:
# IF not all clusters specified, subset, otherwise just copy.
if len(self.list_clusters) != len(
self.adata[0].obs[self.use_label].cat.categories
):
self.query_adata = self.query_adata[
self.query_adata.obs.query(
create_query(self.list_clusters, self.use_label)
).index
].copy()
else:
self.query_adata = self.query_adata.copy()
else:
self.query_adata = self.query_adata.copy()
def _generate_frame(self):
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=self.figsize)
return [fig, ax]
def _add_image(self, main_ax: Axes):
image = self.query_adata.uns["spatial"][self.library_id]["images"][self.img_key]
main_ax.imshow(
image,
alpha=self.image_alpha,
zorder=-1,
)
def _plot_colorbar(self, plot_ax: Axes, color_bar_label: str = ""):
cb = plt.colorbar(
plot_ax, aspect=10, shrink=0.5, cmap=self.cmap, label=color_bar_label
)
cb.outline.set_visible(False)
def _remove_axis(self, main_ax: Axes):
main_ax.axis("off")
def _crop_image(self, main_ax: _AxesSubplot, margin: float):
main_ax.set_xlim(self.imagecol.min() - margin, self.imagecol.max() + margin)
main_ax.set_ylim(self.imagerow.min() - margin, self.imagerow.max() + margin)
main_ax.set_ylim(main_ax.get_ylim()[::-1])
def _zoom_image(self, main_ax: _AxesSubplot, zoom_coord: Optional[float]):
main_ax.set_xlim(zoom_coord[0], zoom_coord[1])
main_ax.set_ylim(zoom_coord[2], zoom_coord[3])
def _add_color_bar(self, plot, color_bar_label: str = ""):
cb = plt.colorbar(
plot,
aspect=10,
shrink=0.5,
cmap=self.cmap,
label=color_bar_label,
)
cb.outline.set_visible(False)
def _add_title(self):
plt.title(self.title)
def _get_query_clusters_index(self):
index_query = []
full_labels = self.adata[0].obs[self.use_label].cat.categories
for query in self.list_clusters:
index_query.append(np.where(np.array(full_labels) == query)[0][0])
return index_query
def _save_output(self):
self.fig.savefig(
fname=self.fname, bbox_inches="tight", pad_inches=0, dpi=self.dpi
)
################################################################
# #
# Gene plot class #
# #
################################################################
import warnings
class GenePlot(SpatialBasePlot):
def __init__(
self,
adata: AnnData,
# plotting param
title: Optional["str"] = None,
figsize: Optional[Tuple[float, float]] = None,
cmap: Optional[str] = "Spectral_r",
use_label: Optional[str] = None,
list_clusters: Optional[list] = None,
ax: Optional[matplotlib.axes._subplots.Axes] = None,
fig: Optional[matplotlib.figure.Figure] = None,
show_plot: Optional[bool] = True,
show_axis: Optional[bool] = False,
show_image: Optional[bool] = True,
show_color_bar: Optional[bool] = True,
color_bar_label: Optional[str] = "",
crop: Optional[bool] = True,
zoom_coord: Optional[float] = None,
margin: Optional[bool] = 100,
size: Optional[float] = 7,
image_alpha: Optional[float] = 1.0,
cell_alpha: Optional[float] = 1.0,
use_raw: Optional[bool] = False,
fname: Optional[str] = None,
dpi: Optional[int] = 120,
# gene plot param
gene_symbols: Union[str, list] = None,
threshold: Optional[float] = None,
method: str = "CumSum",
contour: bool = False,
step_size: Optional[int] = None,
vmin: float = None,
vmax: float = None,
**kwargs,
):
super().__init__(
adata=adata,
title=title,
figsize=figsize,
cmap=cmap,
use_label=use_label,
list_clusters=list_clusters,
ax=ax,
fig=fig,
show_plot=show_plot,
show_axis=show_axis,
show_image=show_image,
show_color_bar=show_color_bar,
zoom_coord=zoom_coord,
crop=crop,
margin=margin,
size=size,
image_alpha=image_alpha,
cell_alpha=cell_alpha,
use_raw=use_raw,
fname=fname,
dpi=dpi,
)
method_available = ["CumSum", "NaiveMean"]
assert method in method_available, "Please choose available method in: " + str(
method_available
)
self.method = method
self.step_size = step_size
if self.title == None:
if type(gene_symbols) == str:
self.title = str(gene_symbols)
gene_symbols = [gene_symbols]
else:
self.title = ", ".join(gene_symbols)
self._add_title()
self.gene_symbols = gene_symbols
gene_values = self._get_gene_expression()
self.available_ids = self._add_threshold(gene_values, threshold)
self.vmin, self.vmax = vmin, vmax
if contour:
plot = self._plot_contour(gene_values[self.available_ids])
else:
plot = self._plot_genes(gene_values[self.available_ids])
if show_color_bar:
self._add_color_bar(plot, color_bar_label=color_bar_label)
if fname != None:
self._save_output()
def _get_gene_expression(self):
# Gene plot option
if len(self.gene_symbols) == 0:
raise ValueError("Genes should be provided, please input genes")
elif len(self.gene_symbols) == 1:
if self.gene_symbols[0] not in self.query_adata.var_names:
raise ValueError(
self.gene_symbols[0]
+ " is not exist in the data, please try another gene"
)
colors = self.query_adata[:, self.gene_symbols].to_df().iloc[:, -1]
return colors
else:
for gene in self.gene_symbols:
if gene not in self.query_adata.var.index:
self.gene_symbols.remove(gene)
warnings.warn(
"We removed " + gene + " because they not exist in the data"
)
if len(self.gene_symbols) == 0:
raise ValueError("All provided genes are not exist in the data")
count_gene = self.query_adata[:, self.gene_symbols].to_df()
if self.method is None:
raise ValueError(
"Please provide method to combine genes by NaiveMean/CumSum"
)
if self.method == "NaiveMean":
present_genes = (count_gene > 0).sum(axis=1) / len(self.gene_symbols)
count_gene = (count_gene.mean(axis=1)) * present_genes
elif self.method == "CumSum":
count_gene = count_gene.cumsum(axis=1).iloc[:, -1]
colors = count_gene
return colors
def _plot_genes(self, gene_values: pd.Series):
if type(self.vmin) == type(None) and type(self.vmax) == type(None):
vmin = min(gene_values)
vmax = max(gene_values)
else:
vmin, vmax = self.vmin, self.vmax
# Plot scatter plot based on pixel of spots
imgcol_new = self.query_adata.obsm["spatial"][:, 0] * self.scale_factor
imgrow_new = self.query_adata.obsm["spatial"][:, 1] * self.scale_factor
plot = self.ax.scatter(
imgcol_new,
imgrow_new,
edgecolor="none",
alpha=self.cell_alpha,
s=self.size,
marker="o",
vmin=vmin,
vmax=vmax,
cmap=plt.get_cmap(self.cmap) if type(self.cmap) == str else self.cmap,
c=gene_values,
)
return plot
def _plot_contour(self, gene_values: pd.Series):
imgcol_new = self.query_adata.obsm["spatial"][:, 0] * self.scale_factor
imgrow_new = self.query_adata.obsm["spatial"][:, 1] * self.scale_factor
# Extracting x,y and values (z)
z = gene_values
y = imgrow_new
x = imgcol_new
# Interpolating values to get better coverage
xi = np.linspace(x.min(), x.max(), 100)
yi = np.linspace(y.min(), y.max(), 100)
zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method="linear")
if self.step_size == None:
self.step_size = int(np.max(z) / 50)
if self.step_size < 1:
self.step_size = 1
# Creating contour plot with a step size of 1
cs = plt.contourf(
xi,
yi,
zi,
range(0, int(np.nanmax(zi)) + self.step_size, self.step_size),
cmap=plt.get_cmap(self.cmap) if type(self.cmap) == str else self.cmap,
alpha=self.cell_alpha,
)
return cs
def _add_threshold(self, gene_values, threshold):
if threshold == None:
return np.repeat(True, len(gene_values))
else:
return gene_values > threshold
################################################################
# #
# Feature plot class #
# #
################################################################
class FeaturePlot(SpatialBasePlot):
def __init__(
self,
adata: AnnData,
# plotting param
title: Optional["str"] = None,
figsize: Optional[Tuple[float, float]] = None,
cmap: Optional[str] = "Spectral_r",
use_label: Optional[str] = None,
list_clusters: Optional[list] = None,
ax: Optional[matplotlib.axes._subplots.Axes] = None,
fig: Optional[matplotlib.figure.Figure] = None,
show_plot: Optional[bool] = True,
show_axis: Optional[bool] = False,
show_image: Optional[bool] = True,
show_color_bar: Optional[bool] = True,
color_bar_label: Optional[str] = "",
crop: Optional[bool] = True,
zoom_coord: Optional[float] = None,
margin: Optional[bool] = 100,
size: Optional[float] = 7,
image_alpha: Optional[float] = 1.0,
cell_alpha: Optional[float] = 1.0,
use_raw: Optional[bool] = False,
fname: Optional[str] = None,
dpi: Optional[int] = 120,
# gene plot param
feature: str = None,
threshold: Optional[float] = None,
contour: bool = False,
step_size: Optional[int] = None,
vmin: float = None,
vmax: float = None,
**kwargs,
):
super().__init__(
adata=adata,
title=title,
figsize=figsize,
cmap=cmap,
use_label=use_label,
list_clusters=list_clusters,
ax=ax,
fig=fig,
show_plot=show_plot,
show_axis=show_axis,
show_image=show_image,
show_color_bar=show_color_bar,
zoom_coord=zoom_coord,
crop=crop,
margin=margin,
size=size,
image_alpha=image_alpha,
cell_alpha=cell_alpha,
use_raw=use_raw,
fname=fname,
dpi=dpi,
)
self.step_size = step_size
self.title = feature
self._add_title()
self.feature = feature
feature_values = self._get_feature_values()
self.available_ids = self._add_threshold(feature_values, threshold)
self.vmin, self.vmax = vmin, vmax
if contour:
plot = self._plot_contour(feature_values[self.available_ids])
else:
plot = self._plot_feature(feature_values[self.available_ids])
if show_color_bar:
self._add_color_bar(plot, color_bar_label=color_bar_label)
if fname != None:
self._save_output()
def _get_feature_values(self):
if self.feature not in self.query_adata.obs:
raise ValueError(
self.feature + " is not in data.obs, please try another feature"
)
elif not isinstance(
self.query_adata.obs[self.feature].values[0], numbers.Number
):
raise ValueError(
self.feature
+ " in data.obs is not continuous, please try another feature"
)
colors = self.query_adata.obs[self.feature]
return colors
def _plot_feature(self, feature_values: pd.Series):
if type(self.vmin) == type(None) and type(self.vmax) == type(None):
vmin = min(feature_values)
vmax = max(feature_values)
else:
vmin, vmax = self.vmin, self.vmax
# Plot scatter plot based on pixel of spots
imgcol_new = self.query_adata.obsm["spatial"][:, 0] * self.scale_factor
imgrow_new = self.query_adata.obsm["spatial"][:, 1] * self.scale_factor
plot = self.ax.scatter(
imgcol_new,
imgrow_new,
edgecolor="none",
alpha=self.cell_alpha,
s=self.size,
marker="o",
vmin=vmin,
vmax=vmax,
cmap=plt.get_cmap(self.cmap) if type(self.cmap) == str else self.cmap,
c=feature_values,
)
return plot
def _plot_contour(self, feature_values: pd.Series):
imgcol_new = self.query_adata.obsm["spatial"][:, 0] * self.scale_factor
imgrow_new = self.query_adata.obsm["spatial"][:, 1] * self.scale_factor
# Extracting x,y and values (z)
z = feature_values
y = imgrow_new
x = imgcol_new
# Interpolating values to get better coverage
xi = np.linspace(x.min(), x.max(), 100)
yi = np.linspace(y.min(), y.max(), 100)
zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method="linear")
if self.step_size == None:
self.step_size = int(np.max(z) / 50)
if self.step_size < 1:
self.step_size = 1
# Creating contour plot with a step size of 1
cs = plt.contourf(
xi,
yi,
zi,
range(0, int(np.nanmax(zi)) + self.step_size, self.step_size),
cmap=plt.get_cmap(self.cmap) if type(self.cmap) == str else self.cmap,
alpha=self.cell_alpha,
)
return cs
def _add_threshold(self, feature_values, threshold):
if threshold == None:
return np.repeat(True, len(feature_values))
else:
return feature_values > threshold
################################################################
# #
# Cluster plot class #
# #
################################################################
class ClusterPlot(SpatialBasePlot):
def __init__(
self,
adata: AnnData,
# plotting param
title: Optional["str"] = None,
figsize: Optional[Tuple[float, float]] = None,
cmap: Optional[str] = "default",
use_label: Optional[str] = None,
list_clusters: Optional[list] = None,
ax: Optional[matplotlib.axes._subplots.Axes] = None,
fig: Optional[matplotlib.figure.Figure] = None,
show_plot: Optional[bool] = True,
show_axis: Optional[bool] = False,
show_image: Optional[bool] = True,
show_color_bar: Optional[bool] = True,
crop: Optional[bool] = True,
zoom_coord: Optional[float] = None,
margin: Optional[bool] = 100,
size: Optional[float] = 5,
image_alpha: Optional[float] = 1.0,
cell_alpha: Optional[float] = 1.0,
fname: Optional[str] = None,
dpi: Optional[int] = 120,
# cluster plot param
show_subcluster: Optional[bool] = False,
show_cluster_labels: Optional[bool] = False,
show_trajectories: Optional[bool] = False,
reverse: Optional[bool] = False,
show_node: Optional[bool] = False,
threshold_spots: Optional[int] = 5,
text_box_size: Optional[float] = 5,
color_bar_size: Optional[float] = 10,
bbox_to_anchor: Optional[Tuple[float, float]] = (1, 1),
# trajectory
trajectory_node_size: Optional[int] = 10,
trajectory_alpha: Optional[float] = 1.0,
trajectory_width: Optional[float] = 2.5,
trajectory_edge_color: Optional[str] = "#f4efd3",
trajectory_arrowsize: Optional[int] = 17,
):
super().__init__(
adata=adata,
title=title,
figsize=figsize,
cmap=cmap,
use_label=use_label,
list_clusters=list_clusters,
ax=ax,
fig=fig,
show_plot=show_plot,
show_axis=show_axis,
show_image=show_image,
show_color_bar=show_color_bar,
zoom_coord=zoom_coord,
crop=crop,
margin=margin,
size=size,
image_alpha=image_alpha,
cell_alpha=cell_alpha,
fname=fname,
dpi=dpi,
)
self.cmap_ = self._get_cmap(self.cmap)
self._add_cluster_colors()
self._plot_clusters()
self.threshold_spots = threshold_spots
self.text_box_size = text_box_size
self.color_bar_size = color_bar_size
self.reverse = reverse
self.show_node = show_node
if show_color_bar:
self._add_cluster_bar(bbox_to_anchor)
if show_cluster_labels:
self._add_cluster_labels()
if show_subcluster:
self._add_sub_clusters()
if show_trajectories:
self.trajectory_node_size = trajectory_node_size
self.trajectory_alpha = trajectory_alpha
self.trajectory_width = trajectory_width
self.trajectory_edge_color = trajectory_edge_color
self.trajectory_arrowsize = trajectory_arrowsize
self._add_trajectories()
if fname != None:
self._save_output()
def _add_cluster_colors(self):
if self.use_label + "_colors" not in self.adata[0].uns:
# self.adata[0].uns[self.use_label + "_set"] = []
self.adata[0].uns[self.use_label + "_colors"] = []
for i, cluster in enumerate(self.adata[0].obs.groupby(self.use_label)):
self.adata[0].uns[self.use_label + "_colors"].append(
matplotlib.colors.to_hex(self.cmap_(i / (self.cmap_n - 1)))
)
# self.adata[0].uns[self.use_label + "_set"].append( cluster[0] )
def _plot_clusters(self):
# Plot scatter plot based on pixel of spots
# for i, cluster in enumerate(self.query_adata.obs[self.use_label].cat.categories):
for i, cluster in enumerate(self.query_adata.obs.groupby(self.use_label)):
# Plot scatter plot based on pixel of spots
subset_spatial = self.query_adata.obsm["spatial"][
check_sublist(list(self.query_adata.obs.index), list(cluster[1].index))
]
if self.use_label + "_colors" in self.adata[0].uns:
# label_set = self.adata[0].uns[self.use_label+'_set']
label_set = (
self.adata[0].obs[self.use_label].cat.categories.values.astype(str)
)
col_index = np.where(label_set == cluster[0])[0][0]
color = self.adata[0].uns[self.use_label + "_colors"][col_index]
else:
color = self.cmap_(self.query_indexes[i] / (self.cmap_n - 1))
imgcol_new = subset_spatial[:, 0] * self.scale_factor
imgrow_new = subset_spatial[:, 1] * self.scale_factor
_ = self.ax.scatter(
imgcol_new,
imgrow_new,
c=[color],
label=cluster[0],
edgecolor="none",
alpha=self.cell_alpha,
s=self.size,
marker="o",
)
def _get_cmap(self, cmap):
cmap_, cmap_n = get_cmap(cmap)
self.cmap_n = cmap_n
return cmap_
def _add_cluster_bar(self, bbox_to_anchor):
lgnd = self.ax.legend(
bbox_to_anchor=bbox_to_anchor,
labelspacing=0.05,
fontsize=self.color_bar_size,
handleheight=1.0,
edgecolor="white",
)
for handle in lgnd.legendHandles:
handle.set_sizes([20.0])
def _add_cluster_labels(self):
for i, label in enumerate(self.list_clusters):
label_index = list(
self.query_adata.obs[
self.query_adata.obs[self.use_label] == str(label)
].index
)
subset_spatial = self.query_adata.obsm["spatial"][
check_sublist(list(self.query_adata.obs.index), label_index)
]
imgcol_new = subset_spatial[:, 0] * self.scale_factor
imgrow_new = subset_spatial[:, 1] * self.scale_factor
centroids = [centroidpython(imgcol_new, imgrow_new)]
if centroids[0][0] < 1500:
x = -100
y = 50
else:
x = 100
y = -50
colors = self.adata[0].uns[self.use_label + "_colors"]
index = self.query_indexes[i]
self.ax.text(
centroids[0][0] + x,
centroids[0][1] + y,
label,
color="black",
fontsize=self.text_box_size,
zorder=3,
bbox=dict(
facecolor=colors[index],
boxstyle="round",
alpha=1.0,
),
)
def _add_sub_clusters(self):
if "sub_cluster_labels" not in self.query_adata.obs.columns:
raise ValueError("Please run stlearn.spatial.cluster.localization")
for i, label in enumerate(self.list_clusters):
label_index = list(
self.query_adata.obs[
self.query_adata.obs[self.use_label] == str(label)
].index
)
subset_spatial = self.query_adata.obsm["spatial"][
check_sublist(list(self.query_adata.obs.index), label_index)
]
imgcol_new = subset_spatial[:, 0] * self.scale_factor
imgrow_new = subset_spatial[:, 1] * self.scale_factor
if (
len(
self.query_adata.obs[
self.query_adata.obs[self.use_label] == str(label)
]["sub_cluster_labels"].unique()
)
< 2
):
centroids = [centroidpython(imgcol_new, imgrow_new)]
classes = np.array(
self.query_adata.obs[
self.query_adata.obs[self.use_label] == str(label)
]["sub_cluster_labels"].unique()
)
else:
from sklearn.neighbors import NearestCentroid
clf = NearestCentroid()
clf.fit(
np.column_stack((imgcol_new, imgrow_new)),
self.query_adata.obs[
self.query_adata.obs[self.use_label] == str(label)
]["sub_cluster_labels"],
)
centroids = clf.centroids_
classes = clf.classes_
for j, label in enumerate(classes):
if (
len(
self.query_adata.obs[
self.query_adata.obs["sub_cluster_labels"] == label
]
)
> self.threshold_spots
):
if centroids[j][0] < 1500:
x = -100
y = 50
else:
x = 100
y = -50
colors = self.adata[0].uns[self.use_label + "_colors"]
index = self.query_indexes[i]
self.ax.text(
centroids[j][0] + x,
centroids[j][1] + y,
label,
color="black",
fontsize=5,
zorder=3,
bbox=dict(
facecolor=colors[index],
boxstyle="round",
alpha=1.0,
),
clip_on=True,
)
def _add_trajectories(self):
used_colors = self.adata[0].uns[self.use_label + "_colors"]
cmaps = matplotlib.colors.LinearSegmentedColormap.from_list("", used_colors)
cmap = plt.get_cmap(cmaps)
if "PTS_graph" not in self.adata[0].uns:
raise ValueError("Please run stlearn.spatial.trajectory.pseudotimespace!")
tmp = _read_graph(self.adata[0], "PTS_graph")
G = tmp.copy()
remove = [edge for edge in G.edges if 9999 in edge]
G.remove_edges_from(remove)
G.remove_node(9999)
centroid_dict = self.adata[0].uns["centroid_dict"]
centroid_dict = {int(key): centroid_dict[key] for key in centroid_dict}
if self.reverse:
nx.draw_networkx_edges(
G,
pos=centroid_dict,
node_size=self.trajectory_node_size,
alpha=self.trajectory_alpha,
width=self.trajectory_width,
edge_color=self.trajectory_edge_color,
arrowsize=self.trajectory_arrowsize,
arrowstyle="<|-",
connectionstyle="arc3,rad=0.2",
)
else:
nx.draw_networkx_edges(
G,
pos=centroid_dict,
node_size=self.trajectory_node_size,
alpha=self.trajectory_alpha,
width=self.trajectory_width,
edge_color=self.trajectory_edge_color,
arrowsize=self.trajectory_arrowsize,
arrowstyle="-|>",
connectionstyle="arc3,rad=0.2",
)
if self.show_node:
for x, y in centroid_dict.items():
if x in get_node(self.list_clusters, self.adata[0].uns["split_node"]):
self.ax.text(
y[0],
y[1],
get_cluster(str(x), self.adata[0].uns["split_node"]),
color="black",
fontsize=8,
zorder=100,
bbox=dict(
facecolor=cmap(
int(
get_cluster(str(x), self.adata[0].uns["split_node"])
)
/ (len(used_colors) - 1)
),
boxstyle="circle",
alpha=1,
),
)
################################################################
# #
# SubCluster plot class #
# #
################################################################
class SubClusterPlot(SpatialBasePlot):
def __init__(
self,
adata: AnnData,
# plotting param
title: Optional["str"] = None,
figsize: Optional[Tuple[float, float]] = None,
cmap: Optional[str] = "jet",
use_label: Optional[str] = None,
list_clusters: Optional[list] = None,
ax: Optional[matplotlib.axes._subplots.Axes] = None,
fig: Optional[matplotlib.figure.Figure] = None,
show_plot: Optional[bool] = True,
show_axis: Optional[bool] = False,
show_image: Optional[bool] = True,
show_color_bar: Optional[bool] = True,
crop: Optional[bool] = True,
zoom_coord: Optional[float] = None,
margin: Optional[bool] = 100,
size: Optional[float] = 5,
image_alpha: Optional[float] = 1.0,
cell_alpha: Optional[float] = 1.0,
fname: Optional[str] = None,
dpi: Optional[int] = 120,
# subcluster plot param
cluster: Optional[int] = 0,
threshold_spots: Optional[int] = 5,