This repository has been archived by the owner on Nov 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathplotting.py
1456 lines (1289 loc) · 44.4 KB
/
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
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from collections import defaultdict
import matplotlib.font_manager
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from adjustText import adjust_text
from sklearn.decomposition import KernelPCA
from sklearn.metrics import r2_score
from sklearn.metrics.pairwise import cosine_similarity
FONT_SIZE = 10
font = {"size": FONT_SIZE}
matplotlib.rc("font", **font)
matplotlib.rc("ytick", labelsize=FONT_SIZE)
matplotlib.rc("xtick", labelsize=FONT_SIZE)
class CPAVisuals:
"""
A wrapper for automatic plotting CompPert latent embeddings and dose-response
curve. Sets up prefix for all files and default dictionaries for atomic
perturbations and cell types.
"""
def __init__(
self,
cpa,
fileprefix=None,
perts_palette=None,
covars_palette=None,
plot_params={"fontsize": None},
):
"""
Parameters
----------
cpa : CompPertAPI
Variable from API class.
fileprefix : str, optional (default: None)
Prefix (with path) to the filename to save all embeddings in a
standartized manner. If None, embeddings are not saved to file.
perts_palette : dict (default: None)
Dictionary of colors for the embeddings of perturbations. Keys
correspond to perturbations and values to their colors. If None,
default dicitonary will be set up.
covars_palette : dict (default: None)
Dictionary of colors for the embeddings of covariates. Keys
correspond to covariates and values to their colors. If None,
default dicitonary will be set up.
"""
self.fileprefix = fileprefix
self.perturbation_key = cpa.perturbation_key
self.dose_key = cpa.dose_key
self.covariate_keys = cpa.covariate_keys
self.measured_points = cpa.measured_points
self.unique_perts = cpa.unique_perts
self.unique_covars = cpa.unique_covars
if perts_palette is None:
self.perts_palette = dict(
zip(self.unique_perts, get_palette(len(self.unique_perts)))
)
else:
self.perts_palette = perts_palette
if covars_palette is None:
self.covars_palette = {}
for cov in self.unique_covars:
self.covars_palette[cov] = dict(
zip(
self.unique_covars[cov],
get_palette(len(self.unique_covars[cov]), palette_name="tab10"),
)
)
else:
self.covars_palette = covars_palette
if plot_params["fontsize"] is None:
self.fontsize = FONT_SIZE
else:
self.fontsize = plot_params["fontsize"]
def plot_latent_embeddings(
self,
emb,
titlename="Example",
kind="perturbations",
palette=None,
labels=None,
dimred="KernelPCA",
filename=None,
show_text=True,
):
"""
Parameters
----------
emb : np.array
Multi-dimensional embedding of perturbations or covariates.
titlename : str, optional (default: 'Example')
Title.
kind : int, optional, optional (default: 'perturbations')
Specify if this is embedding of perturbations, covariates or some
other. If it is perturbations or covariates, it will use default
saved dictionaries for colors.
palette : dict, optional (default: None)
If embedding of kind not perturbations or covariates, the user can
specify color dictionary for the embedding.
labels : list, optional (default: None)
Labels for the embeddings.
dimred : str, optional (default: 'KernelPCA')
Dimensionality reduction method for plotting low dimensional
representations. Options: 'KernelPCA', 'UMAPpre', 'UMAPcos', None.
If None, uses first 2 dimensions of the embedding.
filename : str (default: None)
Name of the file to save the plot. If None, will automatically
generate name from prefix file.
"""
if filename is None:
if self.fileprefix is None:
filename = None
file_name_similarity = None
else:
filename = f"{self.fileprefix}_emebdding.png"
file_name_similarity = f"{self.fileprefix}_emebdding_similarity.png"
else:
file_name_similarity = filename.split(".")[0] + "_similarity.png"
if labels is None:
if kind == "perturbations":
palette = self.perts_palette
labels = self.unique_perts
elif kind in self.unique_covars:
palette = self.covars_palette[kind]
labels = self.unique_covars[kind]
if len(emb) < 2:
print(f"Embedding contains only {len(emb)} vectors. Not enough to plot.")
else:
plot_embedding(
fast_dimred(emb, method=dimred),
labels,
show_lines=True,
show_text=show_text,
col_dict=palette,
title=titlename,
file_name=filename,
fontsize=self.fontsize,
)
plot_similarity(
emb,
labels,
col_dict=palette,
fontsize=self.fontsize,
file_name=file_name_similarity,
)
def plot_contvar_response2D(
self,
df_response2D,
df_ref=None,
levels=15,
figsize=(4, 4),
xlims=(0, 1.03),
ylims=(0, 1.03),
palette="coolwarm",
response_name="response",
title_name=None,
fontsize=None,
postfix="",
filename=None,
alpha=0.4,
sizes=(40, 160),
logdose=False,
):
"""
Parameters
----------
df_response2D : pd.DataFrame
Data frame with responses of combinations with columns=(dose1, dose2,
response).
levels: int, optional (default: 15)
Number of levels for contour plot.
response_name : str (default: 'response')
Name of column in df_response to plot as response.
alpha: float (default: 0.4)
Transparency of the background contour.
figsize: tuple (default: (4,4))
Size of the figure in inches.
palette : dict, optional (default: None)
Colors dictionary for perturbations to plot.
title_name : str, optional (default: None)
Title for the plot.
postfix : str, optional (defualt: '')
Postfix to add to the output file name to save the model.
filename : str, optional (defualt: None)
Name of the file to save the plot. If None, will automatically
generate name from prefix file.
logdose: bool (default: False)
If True, dose values will be log10. 0 values will be mapped to
minumum value -1,e.g.
if smallest non-zero dose was 0.001, 0 will be mapped to -4.
"""
sns.set_style("white")
if (filename is None) and not (self.fileprefix is None):
filename = f"{self.fileprefix}_{postfix}response2D.png"
if fontsize is None:
fontsize = self.fontsize
x_name, y_name = df_response2D.columns[:2]
x = df_response2D[x_name].values
y = df_response2D[y_name].values
if logdose:
x = log10_with0(x)
y = log10_with0(y)
z = df_response2D[response_name].values
n = int(np.sqrt(len(x)))
X = x.reshape(n, n)
Y = y.reshape(n, n)
Z = z.reshape(n, n)
fig, ax = plt.subplots(figsize=figsize)
CS = ax.contourf(X, Y, Z, cmap=palette, levels=levels, alpha=alpha)
CS = ax.contour(X, Y, Z, levels=15, cmap=palette)
ax.clabel(CS, inline=1, fontsize=fontsize)
ax.set(xlim=(0, 1), ylim=(0, 1))
ax.axis("equal")
ax.axis("square")
ax.yaxis.set_tick_params(labelsize=fontsize)
ax.xaxis.set_tick_params(labelsize=fontsize)
ax.set_xlabel(x_name, fontsize=fontsize, fontweight="bold")
ax.set_ylabel(y_name, fontsize=fontsize, fontweight="bold")
ax.set_xlim(xlims)
ax.set_ylim(ylims)
# sns.despine(left=False, bottom=False, right=True)
sns.despine()
if not (df_ref is None):
sns.scatterplot(
x=x_name,
y=y_name,
hue="split",
size="num_cells",
sizes=sizes,
alpha=1.0,
palette={"train": "#000000", "training": "#000000", "ood": "#e41a1c"},
data=df_ref,
ax=ax,
)
ax.legend_.remove()
ax.set_title(title_name, fontweight="bold", fontsize=fontsize)
plt.tight_layout()
if filename:
save_to_file(fig, filename)
def plot_contvar_response(
self,
df_response,
response_name="response",
var_name=None,
df_ref=None,
palette=None,
title_name=None,
postfix="",
xlabelname=None,
filename=None,
logdose=False,
fontsize=None,
measured_points=None,
bbox=(1.35, 1.0),
figsize=(7.0, 4.0),
):
"""
Parameters
----------
df_response : pd.DataFrame
Data frame of responses.
response_name : str (default: 'response')
Name of column in df_response to plot as response.
var_name : str, optional (default: None)
Name of conditioning variable, e.g. could correspond to covariates.
df_ref : pd.DataFrame, optional (default: None)
Reference values. Fields for plotting should correspond to
df_response.
palette : dict, optional (default: None)
Colors dictionary for perturbations to plot.
title_name : str, optional (default: None)
Title for the plot.
postfix : str, optional (defualt: '')
Postfix to add to the output file name to save the model.
filename : str, optional (defualt: None)
Name of the file to save the plot. If None, will automatically
generate name from prefix file.
logdose: bool (default: False)
If True, dose values will be log10. 0 values will be mapped to
minumum value -1,e.g.
if smallest non-zero dose was 0.001, 0 will be mapped to -4.
figsize: tuple (default: (7., 4.))
Size of output figure
"""
if (filename is None) and not (self.fileprefix is None):
filename = f"{self.fileprefix}_{postfix}response.png"
if fontsize is None:
fontsize = self.fontsize
if logdose:
dose_name = f"log10-{self.dose_key}"
df_response[dose_name] = log10_with0(df_response[self.dose_key].values)
if not (df_ref is None):
df_ref[dose_name] = log10_with0(df_ref[self.dose_key].values)
else:
dose_name = self.dose_key
if var_name is None:
if len(self.unique_covars) > 1:
var_name = self.covars_key
else:
var_name = self.perturbation_key
if palette is None:
if var_name == self.perturbation_key:
palette = self.perts_palette
elif var_name in self.covariate_keys:
palette = self.covars_palette[var_name]
plot_dose_response(
df_response,
dose_name,
var_name,
xlabelname=xlabelname,
df_ref=df_ref,
response_name=response_name,
title_name=title_name,
use_ref_response=(not (df_ref is None)),
col_dict=palette,
plot_vertical=False,
f1=figsize[0],
f2=figsize[1],
fname=filename,
logscale=measured_points,
measured_points=measured_points,
bbox=bbox,
fontsize=fontsize,
figformat="png",
)
def plot_scatter(
self,
df,
x_axis,
y_axis,
hue=None,
size=None,
style=None,
figsize=(4.5, 4.5),
title=None,
palette=None,
filename=None,
alpha=0.75,
sizes=(30, 90),
text_dict=None,
postfix="",
fontsize=14,
):
sns.set_style("white")
if (filename is None) and not (self.fileprefix is None):
filename = f"{self.fileprefix}_scatter{postfix}.png"
if fontsize is None:
fontsize = self.fontsize
fig = plt.figure(figsize=figsize)
ax = plt.gca()
sns.scatterplot(
x=x_axis,
y=y_axis,
hue=hue,
style=style,
size=size,
sizes=sizes,
alpha=alpha,
palette=palette,
data=df,
)
ax.legend_.remove()
ax.set_xlabel(x_axis, fontsize=fontsize)
ax.set_ylabel(y_axis, fontsize=fontsize)
ax.xaxis.set_tick_params(labelsize=fontsize)
ax.yaxis.set_tick_params(labelsize=fontsize)
ax.set_title(title)
if not (text_dict is None):
texts = []
for label in text_dict.keys():
texts.append(
ax.text(
text_dict[label][0],
text_dict[label][1],
label,
fontsize=fontsize,
)
)
adjust_text(
texts, arrowprops=dict(arrowstyle="-", color="black", lw=0.1), ax=ax
)
plt.tight_layout()
if filename:
save_to_file(fig, filename)
def log10_with0(x):
mx = np.min(x[x > 0])
x[x == 0] = mx / 10
return np.log10(x)
def get_palette(n_colors, palette_name="Set1"):
try:
palette = sns.color_palette(palette_name)
except:
print("Palette not found. Using default palette tab10")
palette = sns.color_palette()
while len(palette) < n_colors:
palette += palette
return palette
def fast_dimred(emb, method="KernelPCA"):
"""
Takes high dimensional embeddings and produces a 2-dimensional representation
for plotting.
emb: np.array
Embeddings matrix.
method: str (default: 'KernelPCA')
Method for dimensionality reduction: KernelPCA, UMAPpre, UMAPcos, tSNE.
If None return first 2 dimensions of the embedding vector.
"""
if method is None:
return emb[:, :2]
elif method == "KernelPCA":
similarity_matrix = cosine_similarity(emb)
np.fill_diagonal(similarity_matrix, 1.0)
X = KernelPCA(n_components=2, kernel="precomputed").fit_transform(
similarity_matrix
)
else:
raise NotImplementedError
return X
def plot_dose_response(
df,
contvar_key,
perturbation_key,
df_ref=None,
response_name="response",
use_ref_response=False,
palette=None,
col_dict=None,
fontsize=8,
measured_points=None,
interpolate=True,
f1=7,
f2=3.0,
bbox=(1.35, 1.0),
ref_name="origin",
title_name="None",
plot_vertical=True,
fname=None,
logscale=None,
xlabelname=None,
figformat="png",
):
"""Plotting decoding of the response with respect to dose.
Params
------
df : `DataFrame`
Table with columns=[perturbation_key, contvar_key, response_name].
The last column is always "response".
contvar_key : str
Name of the column in df for values to use for x axis.
perturbation_key : str
Name of the column in df for the perturbation or covariate to plot.
response_name: str (default: response)
Name of the column in df for values to use for y axis.
df_ref : `DataFrame` (default: None)
Table with the same columns as in df to plot ground_truth or another
condition for comparison. Could
also be used to just extract reference values for x-axis.
use_ref_response : bool (default: False)
A flag indicating if to use values for y axis from df_ref (True) or j
ust to extract reference values for x-axis.
col_dict : dictionary (default: None)
Dictionary with colors for each value in perturbation_key.
bbox : tuple (default: (1.35, 1.))
Coordinates to adjust the legend.
plot_vertical : boolean (default: False)
Flag if to plot reference values for x axis from df_ref dataframe.
f1 : float (default: 7.0))
Width in inches for the plot.
f2 : float (default: 3.0))
Hight in inches for the plot.
fname : str (default: None)
Name of the file to export the plot. The name comes without format
extension.
format : str (default: png)
Format for the file to export the plot.
"""
sns.set_style("white")
if use_ref_response and not (df_ref is None):
df[ref_name] = "predictions"
df_ref[ref_name] = "observations"
if interpolate:
df_plt = pd.concat([df, df_ref])
else:
df_plt = df
else:
df_plt = df
df_plt = df_plt.reset_index()
atomic_drugs = np.unique(df[perturbation_key].values)
if palette is None:
current_palette = get_palette(len(list(atomic_drugs)))
if col_dict is None:
col_dict = dict(zip(list(atomic_drugs), current_palette))
fig = plt.figure(figsize=(f1, f2))
ax = plt.gca()
if use_ref_response:
sns.lineplot(
x=contvar_key,
y=response_name,
palette=col_dict,
hue=perturbation_key,
style=ref_name,
dashes=[(1, 0), (2, 1)],
legend="full",
style_order=["predictions", "observations"],
data=df_plt,
ax=ax,
)
df_ref = df_ref.replace("training_treated", "train")
sns.scatterplot(
x=contvar_key,
y=response_name,
hue="split",
size="num_cells",
sizes=(10, 100),
alpha=1.0,
palette={"train": "#000000", "training": "#000000", "ood": "#e41a1c"},
data=df_ref,
ax=ax,
)
sns.despine()
ax.legend_.remove()
else:
sns.lineplot(
x=contvar_key,
y=response_name,
palette=col_dict,
hue=perturbation_key,
data=df_plt,
ax=ax,
)
ax.legend(loc="upper right", bbox_to_anchor=bbox, fontsize=fontsize)
sns.despine()
if not (title_name is None):
ax.set_title(title_name, fontsize=fontsize, fontweight="bold")
ax.grid("off")
if xlabelname is None:
ax.set_xlabel(contvar_key, fontsize=fontsize)
else:
ax.set_xlabel(xlabelname, fontsize=fontsize)
ax.set_ylabel(f"{response_name}", fontsize=fontsize)
ax.xaxis.set_tick_params(labelsize=fontsize)
ax.yaxis.set_tick_params(labelsize=fontsize)
if not (logscale is None):
ax.set_xticks(np.log10(logscale))
ax.set_xticklabels(logscale, rotation=90)
if not (df_ref is None):
atomic_drugs = np.unique(df_ref[perturbation_key].values)
for drug in atomic_drugs:
x = df_ref[df_ref[perturbation_key] == drug][contvar_key].values
m1 = np.min(df[df[perturbation_key] == drug][response_name].values)
m2 = np.max(df[df[perturbation_key] == drug][response_name].values)
if plot_vertical:
for x_dot in x:
ax.plot(
[x_dot, x_dot],
[m1, m2],
":",
color="black",
linewidth=0.5,
alpha=0.5,
)
fig.tight_layout()
if fname:
plt.savefig(f"{fname}.{figformat}", format=figformat, dpi=600)
return fig
def plot_uncertainty_comb_dose(
cpa_api,
cov,
pert,
N=11,
metric="cosine",
measured_points=None,
cond_key="condition",
figsize=(4, 4),
vmin=None,
vmax=None,
sizes=(40, 160),
df_ref=None,
xlims=(0, 1.03),
ylims=(0, 1.03),
fixed_drugs="",
fixed_doses="",
title="",
filename=None,
):
"""Plotting uncertainty for a single perturbation at a dose range for a
particular covariate.
Params
------
cpa_api
Api object for the model class.
cov : dict
Name of covariate.
pert : str
Name of the perturbation.
N : int
Number of dose values.
metric: str (default: 'cosine')
Metric to evaluate uncertainty.
measured_points : dict (default: None)
A dicitionary of dictionaries. Per each covariate a dictionary with
observed doses per perturbation, e.g. {'covar1': {'pert1':
[0.1, 0.5, 1.0], 'pert2': [0.3]}
cond_key : str (default: 'condition')
Name of the variable to use for plotting.
filename : str (default: None)
Full path to the file to export the plot. File extension should be
included.
Returns
-------
pd.DataFrame of uncertainty estimations.
"""
cov_name = "_".join([cov[cov_key] for cov_key in cpa_api.covariate_keys])
df_list = []
for i in np.round(np.linspace(0, 1, N), decimals=2):
for j in np.round(np.linspace(0, 1, N), decimals=2):
df_list.append(
{
"covariates": cov_name,
"condition": pert + fixed_drugs,
"dose_val": str(i) + "+" + str(j) + fixed_doses,
}
)
df_pred = pd.DataFrame(df_list)
uncert_cos = []
uncert_eucl = []
closest_cond_cos = []
closest_cond_eucl = []
for i in range(df_pred.shape[0]):
(
uncert_cos_,
uncert_eucl_,
closest_cond_cos_,
closest_cond_eucl_,
) = cpa_api.compute_uncertainty(
cov=cov, pert=df_pred.iloc[i]["condition"], dose=df_pred.iloc[i]["dose_val"]
)
uncert_cos.append(uncert_cos_)
uncert_eucl.append(uncert_eucl_)
closest_cond_cos.append(closest_cond_cos_)
closest_cond_eucl.append(closest_cond_eucl_)
df_pred["uncertainty_cosine"] = uncert_cos
df_pred["uncertainty_eucl"] = uncert_eucl
df_pred["closest_cond_cos"] = closest_cond_cos
df_pred["closest_cond_eucl"] = closest_cond_eucl
doses = df_pred.dose_val.apply(lambda x: x.split("+"))
X = np.array(doses.apply(lambda x: x[0]).astype(float)).reshape(N, N)
Y = np.array(doses.apply(lambda x: x[1]).astype(float)).reshape(N, N)
Z = np.array(df_pred[f"uncertainty_{metric}"].values.astype(float)).reshape(N, N)
fig, ax = plt.subplots(1, 1, figsize=figsize)
CS = ax.contourf(X, Y, Z, cmap="coolwarm", levels=20, alpha=1, vmin=vmin, vmax=vmax)
ax.set_xlabel(pert.split("+")[0], fontweight="bold")
ax.set_ylabel(pert.split("+")[1], fontweight="bold")
if not (df_ref is None):
sns.scatterplot(
x=pert.split("+")[0],
y=pert.split("+")[1],
hue="split",
size="num_cells",
sizes=sizes,
alpha=1.0,
palette={"train": "#000000", "training": "#000000", "ood": "#e41a1c"},
data=df_ref,
ax=ax,
)
ax.legend_.remove()
if measured_points:
ticks = measured_points[cov_name][pert]
xticks = [float(x.split("+")[0]) for x in ticks]
yticks = [float(x.split("+")[1]) for x in ticks]
ax.set_xticks(xticks)
ax.set_xticklabels(xticks, rotation=90)
ax.set_yticks(yticks)
fig.colorbar(CS)
sns.despine()
ax.axis("equal")
ax.axis("square")
ax.set_xlim(xlims)
ax.set_ylim(ylims)
ax.set_title(title, fontsize=10, fontweight='bold')
plt.tight_layout()
if filename:
plt.savefig(filename, dpi=600)
return df_pred
def plot_uncertainty_dose(
cpa_api,
cov,
pert,
N=11,
metric="cosine",
measured_points=None,
cond_key="condition",
log=False,
min_dose=None,
filename=None,
):
"""Plotting uncertainty for a single perturbation at a dose range for a
particular covariate.
Params
------
cpa_api
Api object for the model class.
cov : str
Name of covariate.
pert : str
Name of the perturbation.
N : int
Number of dose values.
metric: str (default: 'cosine')
Metric to evaluate uncertainty.
measured_points : dict (default: None)
A dicitionary of dictionaries. Per each covariate a dictionary with
observed doses per perturbation, e.g. {'covar1': {'pert1':
[0.1, 0.5, 1.0], 'pert2': [0.3]}
cond_key : str (default: 'condition')
Name of the variable to use for plotting.
log : boolean (default: False)
A flag if to plot on a log scale.
min_dose : float (default: None)
Minimum dose for the uncertainty estimate.
filename : str (default: None)
Full path to the file to export the plot. File extension should be included.
Returns
-------
pd.DataFrame of uncertainty estimations.
"""
df_list = []
if log:
if min_dose is None:
min_dose = 1e-3
N_val = np.round(np.logspace(np.log10(min_dose), np.log10(1), N), decimals=10)
else:
if min_dose is None:
min_dose = 0
N_val = np.round(np.linspace(min_dose, 1.0, N), decimals=3)
cov_name = "_".join([cov[cov_key] for cov_key in cpa_api.covariate_keys])
for i in N_val:
df_list.append({"covariates": cov_name, "condition": pert, "dose_val": repr(i)})
df_pred = pd.DataFrame(df_list)
uncert_cos = []
uncert_eucl = []
closest_cond_cos = []
closest_cond_eucl = []
for i in range(df_pred.shape[0]):
(
uncert_cos_,
uncert_eucl_,
closest_cond_cos_,
closest_cond_eucl_,
) = cpa_api.compute_uncertainty(
cov=cov, pert=df_pred.iloc[i]["condition"], dose=df_pred.iloc[i]["dose_val"]
)
uncert_cos.append(uncert_cos_)
uncert_eucl.append(uncert_eucl_)
closest_cond_cos.append(closest_cond_cos_)
closest_cond_eucl.append(closest_cond_eucl_)
df_pred["uncertainty_cosine"] = uncert_cos
df_pred["uncertainty_eucl"] = uncert_eucl
df_pred["closest_cond_cos"] = closest_cond_cos
df_pred["closest_cond_eucl"] = closest_cond_eucl
x = df_pred.dose_val.values.astype(float)
y = df_pred[f"uncertainty_{metric}"].values.astype(float)
fig, ax = plt.subplots(1, 1)
ax.plot(x, y)
ax.set_xlabel(pert)
ax.set_ylabel("Uncertainty")
ax.set_title(cov_name)
if log:
ax.set_xscale("log")
if measured_points:
ticks = measured_points[cov_name][pert]
ax.set_xticks(ticks)
ax.set_xticklabels(ticks, rotation=90)
else:
plt.draw()
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
sns.despine()
plt.tight_layout()
if filename:
plt.savefig(filename)
return df_pred
def save_to_file(fig, file_name, file_format=None):
if file_format is None:
if file_name.split(".")[-1] in ["png", "pdf"]:
file_format = file_name.split(".")[-1]
savename = file_name
else:
file_format = "pdf"
savename = f"{file_name}.{file_format}"
else:
savename = file_name
fig.savefig(savename, format=file_format, dpi=600)
print(f"Saved file to: {savename}")
def plot_embedding(
emb,
labels=None,
col_dict=None,
title=None,
show_lines=False,
show_text=False,
show_legend=True,
axis_equal=True,
circle_size=40,
circe_transparency=1.0,
line_transparency=0.8,
line_width=1.0,
fontsize=9,
fig_width=4,
fig_height=4,
file_name=None,
file_format=None,
labels_name=None,
width_ratios=[7, 1],
bbox=(1.3, 0.7),
):
sns.set_style("white")
# create data structure suitable for embedding
df = pd.DataFrame(emb, columns=["dim1", "dim2"])
if not (labels is None):
if labels_name is None:
labels_name = "labels"
df[labels_name] = labels
fig = plt.figure(figsize=(fig_width, fig_height))
ax = plt.gca()
sns.despine(left=False, bottom=False, right=True)
if (col_dict is None) and not (labels is None):
col_dict = get_colors(labels)
sns.scatterplot(
x="dim1",
y="dim2",
hue=labels_name,
palette=col_dict,
alpha=circe_transparency,
edgecolor="none",
s=circle_size,
data=df,
ax=ax,
)
try:
ax.legend_.remove()
except:
pass
if show_lines:
for i in range(len(emb)):
if col_dict is None:
ax.plot(
[0, emb[i, 0]],
[0, emb[i, 1]],
alpha=line_transparency,
linewidth=line_width,
c=None,
)
else:
ax.plot(
[0, emb[i, 0]],
[0, emb[i, 1]],
alpha=line_transparency,
linewidth=line_width,
c=col_dict[labels[i]],
)
if show_text and not (labels is None):
texts = []
labels = np.array(labels)
unique_labels = np.unique(labels)
for label in unique_labels:
idx_label = np.where(labels == label)[0]
texts.append(
ax.text(
np.mean(emb[idx_label, 0]),
np.mean(emb[idx_label, 1]),
label,
#fontsize=fontsize,
)
)
adjust_text(
texts, arrowprops=dict(arrowstyle="-", color="black", lw=0.1), ax=ax
)
if axis_equal:
ax.axis("equal")
ax.axis("square")
if title:
ax.set_title(title, fontweight="bold")
ax.set_xlabel("dim1"),# fontsize=fontsize)
ax.set_ylabel("dim2"),# fontsize=fontsize)
#ax.xaxis.set_tick_params(labelsize=fontsize)