-
Notifications
You must be signed in to change notification settings - Fork 3
/
sceptre.py
1847 lines (1682 loc) · 57.8 KB
/
sceptre.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Tuple, Sequence, Mapping, Optional, Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from anndata import AnnData
from copy import copy
import pandas as pd
import ntpath
import numpy as np
import matplotlib.pyplot as plt
import scanpy as sc
import logging
import seaborn as sns
import warnings
# output scanpy logs
logging.basicConfig(level=logging.INFO)
sc.settings.verbosity = 3
# don´t show this numpy warning
warnings.filterwarnings("ignore", message="All-NaN slice encountered")
# basic plotting settings
plt.rcParams["xtick.labelsize"] = 8
plt.rcParams["ytick.labelsize"] = 8
plt.rcParams["font.size"] = 8
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["font.sans-serif"] = "Arial"
plt.rcParams["figure.figsize"] = 7.2, 4.45
plt.rcParams["figure.titlesize"] = 9
plt.rcParams["figure.dpi"] = 120
plt.rcParams["axes.titlesize"] = 9
plt.rcParams["axes.labelsize"] = 8
plt.rcParams["axes.axisbelow"] = True
plt.rcParams["axes.linewidth"] = 0.5
plt.rcParams["lines.linewidth"] = 0.7
plt.rcParams["lines.markersize"] = 2
plt.rcParams["legend.fontsize"] = 8
plt.rcParams["boxplot.flierprops.marker"] = "."
plt.rcParams["boxplot.flierprops.markerfacecolor"] = "k"
plt.rcParams["boxplot.flierprops.markersize"] = 2
plt.rcParams["pdf.fonttype"] = 42 # to make pdf text available for illustrator
plt.rcParams["ps.fonttype"] = 42 # to make pdf text available for illustrator
figwd = 7.2 # standard figure width
cellsize = 20 # size to plot cells
wspace = 1 # space between scanpy plots to make room for legends
hspace = 0.5 # space between scanpy plots to make room for legends
def create_meta_data(input_dir: str, output_dir: str):
"""Create a meta data table from PD output and mapping tables.
Requires the following tables in the `input_dir`:
* PD Protein
* PD InputFiles
* file_sample_mapping
* plate_layout_mapping
* sort_layout
* sample_layout
* facs_data
See the example files to understand the structure of these tables.
Alternatively, create meta data on you own and use :func:`~sceptre.load_dataset`
Parameters
----------
input_dir
The path to the input directory.
output_dir
The path to the output directory.
Returns
-------
:obj:`None`
Saves the meta table in `output_dir`.
"""
import os
# PD tables
for file in os.listdir(input_dir):
if "_Proteins.txt" in file:
prot = pd.read_table(input_dir + file, low_memory=False)
if "_InputFiles.txt" in file:
files = pd.read_table(input_dir + file)
files["File Name"] = files["File Name"].apply(lambda x: ntpath.basename(x))
# mapping tables
file_sample_mapping = pd.read_table("{}file_sample_mapping.txt".format(input_dir))
plate_layout_mapping = pd.read_table(
"{}plate_layout_mapping.txt".format(input_dir)
).set_index("Plate")
# plate data tables
plate_data = {k: {} for k in plate_layout_mapping.index.unique()}
for plate in plate_data.keys():
plate_data[plate]["sort_layout"] = pd.read_table(
"{}{}".format(input_dir, plate_layout_mapping.loc[plate, "Sort Layout"]),
index_col=0,
)
plate_data[plate]["label_layout"] = pd.read_table(
"{}{}".format(input_dir, plate_layout_mapping.loc[plate, "Label Layout"]),
index_col=0,
).fillna("")
plate_data[plate]["sample_layout"] = pd.read_table(
"{}{}".format(input_dir, plate_layout_mapping.loc[plate, "Sample Layout"]),
index_col=0,
)
plate_data[plate]["facs_data"] = pd.read_table(
"{}{}".format(input_dir, plate_layout_mapping.loc[plate, "Facs Data"])
)
plate_data[plate]["facs_data"] = plate_data[plate]["facs_data"].drop(
["Row", "Column"], axis=1
)
plate_data[plate]["facs_data"] = plate_data[plate]["facs_data"].set_index(
"Well"
)
# create cell metadata
# add each channel from each file to the rows
meta = pd.DataFrame(
[
x.split(" ")[2:]
for x in prot.columns[prot.columns.str.contains("Abundance")]
],
columns=["File ID", "Channel"],
)
# add the file name
meta = meta.merge(
files.set_index("File ID")["File Name"],
left_on="File ID",
right_index=True,
validate="many_to_one",
)
# add the plate and sample
_ = len(meta)
meta = meta.merge(file_sample_mapping, on="File Name", validate="many_to_one")
if len(meta) < _:
raise ValueError("Error in file_sample_mapping.txt")
# add the well information via the sample_layout and label_layout for each plate
for i in meta.index:
p, s, c = meta.loc[i, ["Plate", "Sample", "Channel"]]
p_d = plate_data[p]
well = (
p_d["sample_layout"][
(p_d["sample_layout"] == s) & (p_d["label_layout"] == c)
]
.stack()
.index.tolist()
)
if len(well) > 1:
raise ValueError(
"Error in plate layout data: Plate {}, Sample {}, Channel {}".format(
p, s, c
)
)
elif len(well) == 0:
row, col, well = pd.NA, pd.NA, pd.NA
else:
row = well[0][0]
col = well[0][1]
well = "".join(well[0])
meta.loc[i, ["Row", "Column", "Well"]] = row, col, well
# use the sort layout to map the sorted population and add the facs data
if not pd.isna(well):
meta.loc[i, "Sorted Population"] = plate_data[p]["sort_layout"].loc[
row, col
]
# add the facs data
# meta.loc[i] = meta.loc[i].append(plate_data[p]['facs_data'].loc[well, :])
else:
meta.loc[i, "Sorted Population"] = pd.NA
# add the facs data for each plate
_ = []
for p in meta["Plate"].unique():
_.append(
meta.loc[meta["Plate"] == p].merge(
plate_data[p]["facs_data"],
left_on="Well",
right_index=True,
how="left",
)
)
meta = pd.concat(_)
meta = meta.rename(columns={"Population": "Gated Population"})
meta.to_csv(output_dir + "meta.txt", sep="\t", index=False)
def load_dataset(proteins: str, psms: str, msms: str, files: str, meta: str):
"""Load the dataset from specified paths.
Parameters
----------
proteins
The path to the PD protein table.
psms
The path to the PD PSMs table.
msms
The path to the PD MSMS table.
files
The path to the PD InputFiles table.
meta
The path to the Meta table.
Returns
-------
A dict containing all required tables.
"""
prot = pd.read_table(proteins, low_memory=False)
# To use the Gene Symbol as index:
# Set nan Gene Symbol to protein accession
# and if Gene Symbol is not unique, add the protein accession to make duplicates unique.
nans = prot["Gene Symbol"].isna()
for i in nans.index:
if nans[i]:
prot.loc[i, "Gene Symbol"] = prot.loc[i, "Accession"]
duplicates = prot["Gene Symbol"].duplicated(keep=False)
for i in duplicates.index:
if duplicates[i]:
prot.loc[i, "Gene Symbol"] = (
prot.loc[i, "Gene Symbol"] + "_" + prot.loc[i, "Accession"]
)
psms = pd.read_table(psms, low_memory=False)
msms = pd.read_table(msms, low_memory=False)
files = pd.read_table(files, low_memory=False)
files["File Name"] = files["File Name"].apply(lambda x: ntpath.basename(x))
meta = pd.read_table(meta, low_memory=False)
return {"proteins": prot, "psms": psms, "msms": msms, "files": files, "meta": meta}
def plot_psms_msms(dataset: Mapping, figsize: Tuple[float, float] = (figwd, 3.5)):
"""Plot the number of MSMS spectra and PSMs per file.
Parameters
----------
dataset
Dict containing PD tables and meta information.
figsize
Size of the plotted figure.
Returns
-------
:obj:`None`
"""
ms_perf = pd.concat(
[
dataset["msms"].groupby("File ID").size(),
dataset["psms"].groupby("File ID").size(),
],
axis=1,
)
ms_perf.columns = ["MSMS", "PSMs"]
ordered_file_id = sorted(
ms_perf.index.tolist(), key=lambda x: int(x.split("F")[-1])
)
fig, ax = plt.subplots(figsize=figsize)
ms_perf.loc[ordered_file_id, :].plot.barh(
title="Number of MSMS spectra and PSMs per File", grid=True, ax=ax
)
# legend:
# shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
# put a legend below current axis
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.05), ncol=2)
fig.tight_layout()
def plot_avg_sn(dataset: Mapping, figsize: Tuple[float, float] = (figwd, 3)):
"""Boxplot of the average S/N of each PSM for each file.
Parameters
----------
dataset
Dict containing PD tables and meta information.
figsize
Size of the plotted figure.
Returns
-------
:obj:`None`
"""
ms_perf = pd.concat(
[
dataset["msms"].groupby("File ID").size(),
dataset["psms"].groupby("File ID").size(),
],
axis=1,
)
ms_perf.columns = ["MSMS", "PSMs"]
ordered_file_id = sorted(
ms_perf.index.tolist(), key=lambda x: int(x.split("F")[-1])
)
# set the File ID column to a ordered categorical
cat_dtype = pd.api.types.CategoricalDtype(categories=ordered_file_id, ordered=True)
dataset["psms"]["File ID"] = dataset["psms"]["File ID"].astype(cat_dtype)
fig, ax = plt.subplots(figsize=figsize)
dataset["psms"].boxplot(
"Average Reporter SN", by="File ID", vert=False, grid=True, ax=ax
)
ax.xaxis.label.set_visible(False)
ax.set_ylabel("File ID")
plt.title("Average Reporter S/N of PSMs per File")
plt.suptitle("")
fig.tight_layout()
def plot_set_overview(dataset: Mapping, figsize: Tuple[float, float] = (figwd, 10)):
"""Barplot of the median log10(S/N) of each quantification channel in each file.
Parameters
----------
dataset
Dict containing PD tables and meta information.
figsize
Size of the plotted figure.
Returns
-------
:obj:`None`
"""
grouped = dataset["psms"].groupby("File ID")
group_data = (
grouped[
dataset["psms"].columns[dataset["psms"].columns.str.contains("Abundance")]
]
.median()
.apply(np.log10)
)
group_data.columns = [x.split(" ")[1] for x in group_data.columns]
rowlength = int(grouped.ngroups / 3)
fig, axs = plt.subplots(
nrows=rowlength,
ncols=3,
gridspec_kw=dict(hspace=0.35, wspace=0.1),
sharex=True,
sharey=True,
figsize=figsize,
)
targets = zip(grouped.groups.keys(), axs.flatten())
for i, (key, ax) in enumerate(targets):
group_data.loc[key, :].plot.bar(ax=ax, grid=True, title=key)
def print_ms_stats(dataset: Mapping, s_c_channels: Sequence[str]):
"""Print statistics about the dataset.
Parameters
----------
dataset
Dict containing PD tables and meta information.
s_c_channels
The channels containing single-cells.
Returns
-------
:obj:`None`
"""
print("Protein IDs: {}".format(len(dataset["proteins"])))
print("Peptide IDs: {}".format(len(dataset["psms"]["Annotated Sequence"].unique())))
print("PSMs: {}".format(len(dataset["psms"])))
print("PSM rate: {}".format(round(len(dataset["psms"]) / len(dataset["msms"]), 3)))
print(
"Median of median S/N in single-cell channels: {}".format(
round(
dataset["psms"][
dataset["psms"].columns[
dataset["psms"].columns.str.contains("Abundance")
& dataset["psms"].columns.str.contains("|".join(s_c_channels))
]
]
.median()
.median(),
3,
)
)
)
print(
"Median of mean S/N in single-cell channels: {}".format(
round(
dataset["psms"][
dataset["psms"].columns[
dataset["psms"].columns.str.contains("Abundance")
& dataset["psms"].columns.str.contains("|".join(s_c_channels))
]
]
.mean()
.median(),
3,
)
)
)
print(
"Median S/N of booster channel: {}".format(
round(dataset["psms"]["Abundance 126"].median(), 3)
)
)
nums = []
for f in dataset["psms"]["File ID"].unique():
df = dataset["proteins"][
dataset["proteins"].columns[
dataset["proteins"].columns.str.contains("Found in Sample")
& dataset["proteins"].columns.str.contains(f)
]
]
nums.append((df != "Not Found").apply(any, axis=1).sum())
print("Mean protein IDs per file: {}".format(round(np.mean(nums), 3)))
def plot_interference(dataset: Mapping):
"""Violin plot of the isolation interference of all PSMs.
Parameters
----------
dataset
Dict containing PD tables and meta information.
Returns
-------
:obj:`None`
"""
import matplotlib.ticker as ticker
fig, ax = plt.subplots(figsize=(2, 2.5))
sns.violinplot(
y="Isolation Interference in Percent",
data=dataset["psms"],
inner="quartile",
bw=0.1,
cut=0,
ax=ax,
)
ax.yaxis.set_major_locator(ticker.MultipleLocator(10))
# linestyles = [':', '-', ':']
plt.title("Interference of all PSMs")
plt.grid()
fig.tight_layout()
def dataset_to_scanpy(dataset: Mapping, temp_dir: str = "../results/tmp"):
"""Load the dataset dict into a scanpy AnnData object.
Parameters
----------
dataset
Dict containing PD tables and meta information.
temp_dir
A directory to save temporary data in.
Returns
-------
:class:`~anndata.AnnData`
"""
quant = dataset["proteins"].set_index("Gene Symbol").copy()
if not quant.index.is_unique:
raise IndexError("Protein index not unique")
quant = quant[
quant.columns[quant.columns.str.contains("Abundance")]
] # only quantification columns
file_id = [x.split(" ")[-2] for x in quant.columns]
channel = [x.split(" ")[-1] for x in quant.columns]
quant.columns = pd.MultiIndex.from_tuples(
zip(file_id, channel), names=["File ID", "Channel"]
)
# quant[quant < 1.1] = pd.NA # set S/N values below 1.1 to NA
quant = quant.dropna(how="all").fillna(
0
) # remove all NA proteins and fill remaining NA with 0
quant_meta = (
dataset["meta"]
.set_index(["File ID", "Channel"])
.loc[quant.columns, :]
.copy()
.reset_index()
)
# save to file and load it in scanpy
quant.to_csv(
"{}/scanpy_data.txt".format(temp_dir), sep="\t", header=False, index=True
)
adata = sc.read_text(
"{}/scanpy_data.txt".format(temp_dir), delimiter="\t", first_column_names=False
).T
adata.obs = quant_meta
prots = dataset["proteins"].copy()
prot_anno = prots[
[
"Accession",
"Gene Symbol",
"Description",
"Biological Process",
"Cellular Component",
"Molecular Function",
"KEGG Pathways",
"Reactome Pathways",
"WikiPathways",
]
]
# object columns to category for .var
prot_anno = pd.concat(
[
prot_anno.select_dtypes([], ["object"]),
prot_anno.select_dtypes(["object"]).apply(
pd.Series.astype, dtype="category"
),
],
axis=1,
).reindex(prot_anno.columns, axis=1)
adata.var = adata.var.merge(
prot_anno,
how="left",
left_index=True,
right_on="Gene Symbol",
).set_index("Gene Symbol")
return adata
def normalize(
adata: AnnData,
method: Literal["file_channel", "file", "channel"] = "file_channel",
iter_thresh: float = 1.1,
na_thresh: Optional[float] = 1.1,
drop_na: bool = True,
):
"""Normalize expression values in AnnData object.
The median expression of each protein is equalized across files/channels
by applying correction factors.
If 'file_channel' is selected, the factors are applied iteratively for
file and channel until the highest change in values compared to the
previous iteration is below 'iter_thresh'.
Parameters
----------
adata
The annotated data matrix.
method : {``'file_channel'``, ``'file'``, ``'channel'``}
The normalization method. Options are:
* 'file_channel': Equalize medians across files and channels.
* 'file': Equalize medians across files.
* 'channel': Equalize medians across channels.
iter_thresh
Only for 'file_channel'. Stop iterating when the highest
change in the expression matrix is below this value.
na_thresh
If not None, replace expression values below this value with 0.
drop_na
Drop proteins with no expression values (i.e. 0)
Returns
-------
:obj:`None`
Updates `adata` with the normalized expression values.
"""
# get a df from adata
quant = pd.DataFrame(
adata.X.T.copy(),
columns=adata.obs[["File ID", "Channel"]]
.set_index(["File ID", "Channel"])
.index,
).replace(0, np.nan)
if method == "file_channel":
for i in range(100): # iterate to converge to normalized channel and file
quant_0 = quant.copy()
# file bias normalization
# calculate median for each protein in each sample
med = quant.T.reset_index().groupby("File ID").median().T
# calculate the factors needed for a median shift
med_tot = med.median(axis=1)
factors = med.divide(med_tot, axis=0)
quant = quant.groupby(axis=1, level=0).apply(
lambda x: x.divide(factors.loc[:, x.name], axis=0)
)
# channel bias normalization
# calculate median for each protein in each channel
med = quant.T.reset_index().groupby("Channel").median().T
# calculate the factors needed for a median shift
med_tot = med.median(axis=1)
factors = med.divide(med_tot, axis=0)
quant = quant.groupby(axis=1, level=1).apply(
lambda x: x.divide(factors.loc[:, x.name], axis=0)
)
# stop iterating when the change in quant to the previous iteration is below iter_thresh
if (abs(quant - quant_0).max().max()) <= iter_thresh:
break
print("performed {} iterations".format(i + 1))
elif method == "file":
# file bias normalization
# calculate median for each protein in each sample
med = quant.T.reset_index().groupby("File ID").median().T
# calculate the factors needed for a median shift
med_tot = med.median(axis=1)
factors = med.divide(med_tot, axis=0)
quant = quant.groupby(axis=1, level=0).apply(
lambda x: x.divide(factors.loc[:, x.name], axis=0)
)
elif method == "channel":
# channel bias normalization
# calculate median for each protein in each channel
med = quant.T.reset_index().groupby("Channel").median().T
# calculate the factors needed for a median shift
med_tot = med.median(axis=1)
factors = med.divide(med_tot, axis=0)
quant = quant.groupby(axis=1, level=1).apply(
lambda x: x.divide(factors.loc[:, x.name], axis=0)
)
# apply na_thresh and remove all NA proteins
if na_thresh:
print(
"{} values below {} were set to 0".format(
(quant < na_thresh).sum().sum(), na_thresh
)
)
quant[quant < na_thresh] = pd.NA
adata.X = quant.fillna(0).values.T
if drop_na:
sc.pp.filter_genes(adata, min_cells=1)
def calculate_cell_filter(
adata: AnnData,
min_proteins: int = 500,
thresh_sum: float = 3,
scatter_labels: Tuple[str, str] = ("Channel", "Sorted Population"),
figsizes: Tuple[Tuple[float, float], Tuple[float, float]] = (
(figwd, 4.5),
(figwd, 3),
),
):
"""Calculate the cell filtering based on defined thresholds.
Thresholds control MAD-based outlier detection.
Shows diagnostic plots.
Parameters
----------
adata
The annotated data matrix.
min_proteins
The minimum number of proteins per cell
thresh_sum
The threshold for the Log2 Sum S/N per cell
scatter_labels
The labels to use for the two scatterplots.
figsizes
Figure sizes for both figures
Returns
-------
A list of two :class:`~matplotlib.figure` objects.
Updates `adata` with the following fields.
Num Proteins : :class:`~pandas.Series` (``adata.obs``, dtype ``int``)
Array of dim (number of samples) that stores the number of proteins
identified in each cell.
Log2 Sum S/N : :class:`~pandas.Series` (``adata.obs``, dtype ``float``)
Array of dim (number of samples) that stores the Log2 Sum S/N of each cell.
Pass Cell Filter : :class:`~pandas.Series` (``adata.obs``, dtype ``bool``)
Array of dim (number of samples) that stores if the cell passed the filter.
"""
def mad_based_outlier(points, thresh):
if len(points.shape) == 1:
points = points.to_numpy()[:, None]
median = np.median(points, axis=0)
diff = np.sum((points - median) ** 2, axis=-1)
diff = np.sqrt(diff)
med_abs_deviation = np.median(diff)
modified_z_score = 0.6745 * diff / med_abs_deviation
df = pd.DataFrame(
{"points": points.flatten(), "modified_z_score": modified_z_score.flatten()}
)
outlier_up = df[
(df["modified_z_score"] <= thresh) & (df["points"] > median[0])
]["points"].max()
outlier_down = df[
(df["modified_z_score"] <= thresh) & (df["points"] < median[0])
]["points"].min()
return outlier_up, outlier_down
# annotate cells with qc parameters
adata.obs["Num Proteins"] = (adata.X > 0).sum(axis=1)
adata.obs["Log2 Sum S/N"] = np.log2((adata.X).sum(axis=1))
sum_sn_max, sum_sn_min = mad_based_outlier(
adata.obs["Log2 Sum S/N"], thresh=thresh_sum
)
# annotate cells with filter pass
adata.obs["Pass Cell Filter"] = (
(adata.obs["Log2 Sum S/N"] >= sum_sn_min)
& (adata.obs["Log2 Sum S/N"] <= sum_sn_max)
& (adata.obs["Num Proteins"] >= min_proteins)
)
print(
"{} of {} cells do not pass filter".format(
(len(adata.obs) - adata.obs["Pass Cell Filter"].sum()), len(adata.obs)
)
)
fig_objects = []
# plot qc params for each cell
gridspec = dict(
hspace=0.0, height_ratios=[1, 1, 0.5, 1, 1]
) # invisible axis for title between axes
fig, axs = plt.subplots(nrows=5, ncols=1, figsize=figsizes[0], gridspec_kw=gridspec)
labels = ["Log2 Sum S/N", "Num Proteins"]
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
for i, l in enumerate(labels):
ax = axs[i]
adata.obs[l].plot(ax=ax, grid=True, color=colors[i])
ax.set_ylabel(l)
ax.legend().remove()
if i == 0:
ax.set_title("Cells before filtering")
ax.axhline(sum_sn_max, color="black", linestyle="--")
ax.axhline(sum_sn_min, color="black", linestyle="--")
ax.xaxis.set_ticklabels([])
if i == 1:
ax.axhline(min_proteins, color="black", linestyle="--")
axs[2].set_visible(False)
# plot after filter
for i, l in enumerate(labels):
ax = axs[i + 3]
adata.obs.loc[adata.obs["Pass Cell Filter"], l].plot(
ax=ax, grid=True, color=colors[i]
)
if i == 0:
ax.set_title("Cells after filtering")
ax.xaxis.set_ticklabels([])
ax.set_ylabel(labels[i])
ax.legend().remove()
ax.set_xlabel("Cell index")
fig.tight_layout()
fig_objects.append(fig)
# scatterplots
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=figsizes[1])
sc.pl.scatter(
adata,
x="Log2 Sum S/N",
y="Num Proteins",
color=scatter_labels[0],
size=cellsize,
show=False,
title="Cell filter by Channel",
ax=axs[0],
)
axs[0].axvline(sum_sn_max, color="black", linestyle="--")
axs[0].axvline(sum_sn_min, color="black", linestyle="--")
axs[0].axhline(min_proteins, color="black", linestyle="--")
sc.pl.scatter(
adata,
x="Log2 Sum S/N",
y="Num Proteins",
color=scatter_labels[1],
size=cellsize,
show=False,
title="Cell filter by Population",
ax=axs[1],
)
axs[1].axvline(sum_sn_max, color="black", linestyle="--")
axs[1].axvline(sum_sn_min, color="black", linestyle="--")
axs[1].axhline(min_proteins, color="black", linestyle="--")
fig.tight_layout()
fig_objects.append(fig)
return fig_objects
def apply_cell_filter(adata: AnnData, min_cells: int = 3):
"""Remove cells that do not pass cell filter from `adata`.
Also removes Proteins that are detected in less than `min_cells`.
Requires having ran :func:`~sceptre.calculate_cell_filter` first.
Parameters
----------
adata
The annotated data matrix.
min_cells
Minimum number of cells a protein needs to be detected to
be retained.
Returns
-------
:obj:`None`
Filters and updates `adata`.
"""
# apply the filter
print(
"removed {} cells".format(int((adata.obs["Pass Cell Filter"] == False).sum()))
)
adata._inplace_subset_obs(adata.obs[adata.obs["Pass Cell Filter"]].index)
sc.pp.filter_genes(adata, min_cells=min_cells)
# recalculate cell stats after some genes were removed
adata.obs["Num Proteins"] = (adata.X > 0).sum(axis=1)
adata.obs["Log2 Sum S/N"] = np.log2(adata.X.sum(axis=1))
def plot_batch_qc(
adata: AnnData,
labels: Sequence[str] = ("Log2 Sum S/N", "Num Proteins"),
groupby: Sequence[str] = (
"File ID",
"Channel",
"Row",
"Column",
"Sorted Population",
"Gated Population",
"Plate",
),
figsize: Tuple[float, float] = (8, 15),
):
"""Plot QC parameters grouped by possible sources of batch effects.
Parameters
----------
adata
The annotated data matrix.
labels
QC parameters to plot.
groupby
Batch variables to group by.
figsize
Size of the plotted figure.
Returns
-------
:obj:`None`
"""
fig, axs = plt.subplots(len(groupby), len(labels), figsize=figsize)
for r in range(len(groupby)):
for c in range(len(labels)):
ax = axs[r, c]
sc.pl.violin(
adata,
labels[c],
jitter=1,
size=2,
groupby=groupby[r],
show=False,
rotation=45,
ax=ax,
)
ax.set_ylabel(labels[c])
ax.set_xlabel(groupby[r])
ax.grid(alpha=0.5)
fig.tight_layout()
def plot_plate_qc(
adata: AnnData,
labels: Sequence[str] = ("Log2 Sum S/N", "Num Proteins"),
figsize: Tuple[float, float] = (10, 3),
):
"""Plot QC parameters for each cell on the plate layout.
Parameters
----------
adata
The annotated data matrix.
labels
QC parameters to plot.
figsize
Size of the plotted figure.
Returns
-------
:obj:`None`
"""
rows = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
]
columns = range(1, 25)
plate = pd.DataFrame(
index=pd.MultiIndex.from_tuples(
[x for subl in [[(r, c) for c in columns] for r in rows] for x in subl],
names=("Row", "Column"),
)
)
plates = adata.obs["Plate"].unique()
color_map = copy(plt.get_cmap("copper"))
color_map.set_bad("lightgray")
fig, axs = plt.subplots(len(plates), len(labels), figsize=figsize)
for i, p in enumerate(plates):
for c in range(len(labels)):
if len(plates) == 1:
ax = axs[c]
else:
ax = axs[i, c]
df = adata.obs[adata.obs["Plate"] == p].copy()
df["Column"] = df["Column"].astype(int)
df = plate.merge(
df.set_index(["Row", "Column"])[labels[c]],
left_index=True,
right_index=True,
how="left",
)[labels[c]].unstack()
sns.heatmap(df, ax=ax, linewidths=0.3, square=True, cmap=color_map)
ax.set_yticklabels(ax.get_yticklabels(), rotation=0)
ax.xaxis.label.set_visible(False)
ax.set_ylabel("")
ax.xaxis.tick_top()
# ax.set_facecolor("lightgrey")
if len(plates) == 1:
for ax, col in zip(axs, labels):
ax.set_title(col)
for ax, row in zip(axs, plates):
ax.set_ylabel(row, rotation=90)
else:
for ax, col in zip(axs[0], labels):
ax.set_title(col)
for ax, row in zip(axs[:, 0], plates):
ax.set_ylabel(row, rotation=90)
fig.tight_layout()
def plot_data_completeness(adata: AnnData, figsize: Tuple[float, float] = (2.9, 2)):
"""Plot the data completeness of the expression matrix.
Parameters
----------
adata
The annotated data matrix.
figsize
Size of the plotted figure.
Returns
-------
:obj:`None`
"""
print(
"mean protein IDs per cell: {}".format(
round((~pd.DataFrame(adata.X.T).replace(0, pd.NA).isna()).sum().mean(), 1)
)
)
print(
"median protein IDs per cell: {}".format(
round((~pd.DataFrame(adata.X.T).replace(0, pd.NA).isna()).sum().median(), 1)
)
)
print(
"percent missing values: {}".format(
round(
100
* (pd.DataFrame(adata.X.T).replace(0, pd.NA).isna()).sum().sum()
/ (adata.X.shape[0] * adata.X.shape[1]),
2,
)
)
)
res = {}
frac_missing = (
(adata.X.shape[0] - np.count_nonzero(adata.X, axis=0)) / adata.X.shape[0] * 100
)
for i in [0, 20, 40, 60, 80, 99]:
res[i] = sum(frac_missing <= i)
fig, ax = plt.subplots(figsize=figsize)
plt.bar(res.keys(), res.values(), width=5)
plt.axhline(adata.X.shape[1], color="black", linestyle="--")
plt.xticks(list(res.keys()), [100, 80, 60, 40, 20, 1])
plt.text(