-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpypumatac.py
executable file
·2164 lines (1851 loc) · 70.7 KB
/
pypumatac.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
import os
import glob
import pprint as pp
import re
import gzip
import pycisTopic
from pycisTopic.qc import *
import pickle
import pybiomart as pbm
from scipy.optimize import curve_fit
import scipy
import numpy as np
import pandas as pd
import polars as pl
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.gridspec import GridSpec
import seaborn as sns
import palettable
import math
# dictionary of instrument id regex: [platform(s)]
InstrumentIDs = {
"HWI-M[0-9]{4}$": ["MiSeq"],
"HWUSI": ["Genome Analyzer IIx"],
"M[0-9]{5}$": ["MiSeq"],
"HWI-C[0-9]{5}$": ["HiSeq 1500"],
"C[0-9]{5}$": ["HiSeq 1500"],
"HWI-D[0-9]{5}$": ["HiSeq 2500"],
"D[0-9]{5}$": ["HiSeq 2500"],
"J[0-9]{5}$": ["HiSeq 3000"],
"K[0-9]{5}$": ["HiSeq 3000", "HiSeq 4000"],
"E[0-9]{5}$": ["HiSeq X"],
"NB[0-9]{6}$": ["NextSeq 500/550"],
"NS[0-9]{6}$": ["NextSeq 500/550"],
"MN[0-9]{5}$": ["MiniSeq"],
"N[0-9]{5}$": ["NextSeq 500/550"], # added since original was outdated
"A[0-9]{5}$": ["NovaSeq 6000"], # added since original was outdated
"V[0-9]{5}$": ["NextSeq 2000"], # added since original was outdated
"VH[0-9]{5}$": ["NextSeq 2000"], # added since original was outdated
}
# dictionary of flow cell id regex: ([platform(s)], flow cell version and yeild)
FCIDs = {
"C[A-Z,0-9]{4}ANXX$": (
["HiSeq 1500", "HiSeq 2000", "HiSeq 2500"],
"High Output (8-lane) v4 flow cell",
),
"C[A-Z,0-9]{4}ACXX$": (
["HiSeq 1000", "HiSeq 1500", "HiSeq 2000", "HiSeq 2500"],
"High Output (8-lane) v3 flow cell",
),
"H[A-Z,0-9]{4}ADXX$": (
["HiSeq 1500", "HiSeq 2500"],
"Rapid Run (2-lane) v1 flow cell",
),
"H[A-Z,0-9]{4}BCXX$": (
["HiSeq 1500", "HiSeq 2500"],
"Rapid Run (2-lane) v2 flow cell",
),
"H[A-Z,0-9]{4}BCXY$": (
["HiSeq 1500", "HiSeq 2500"],
"Rapid Run (2-lane) v2 flow cell",
),
"H[A-Z,0-9]{4}BBXX$": (["HiSeq 4000"], "(8-lane) v1 flow cell"),
"H[A-Z,0-9]{4}BBXY$": (["HiSeq 4000"], "(8-lane) v1 flow cell"),
"H[A-Z,0-9]{4}CCXX$": (["HiSeq X"], "(8-lane) flow cell"),
"H[A-Z,0-9]{4}CCXY$": (["HiSeq X"], "(8-lane) flow cell"),
"H[A-Z,0-9]{4}ALXX$": (["HiSeq X"], "(8-lane) flow cell"),
"H[A-Z,0-9]{4}BGXX$": (["NextSeq"], "High output flow cell"),
"H[A-Z,0-9]{4}BGXY$": (["NextSeq"], "High output flow cell"),
"H[A-Z,0-9]{4}BGX2$": (["NextSeq"], "High output flow cell"),
"H[A-Z,0-9]{4}AFXX$": (["NextSeq"], "Mid output flow cell"),
"A[A-Z,0-9]{4}$": (["MiSeq"], "MiSeq flow cell"),
"B[A-Z,0-9]{4}$": (["MiSeq"], "MiSeq flow cell"),
"D[A-Z,0-9]{4}$": (["MiSeq"], "MiSeq nano flow cell"),
"G[A-Z,0-9]{4}$": (["MiSeq"], "MiSeq micro flow cell"),
"H[A-Z,0-9]{4}DMXX$": (["NovaSeq"], "S2 flow cell"),
}
SUPERNOVA_PLATFORM_BLACKLIST = ["HiSeq 3000", "HiSeq 4000", "HiSeq 3000/4000"]
_upgrade_set1 = set(["HiSeq 2000", "HiSeq 2500"])
_upgrade_set2 = set(["HiSeq 1500", "HiSeq 2500"])
_upgrade_set3 = set(["HiSeq 3000", "HiSeq 4000"])
_upgrade_set4 = set(["HiSeq 1000", "HiSeq 1500"])
_upgrade_set5 = set(["HiSeq 1000", "HiSeq 2000"])
fail_msg = "Cannot determine sequencing platform"
success_msg_template = "(likelihood: {})"
null_template = "{}"
# do intersection of lists
def intersect(a, b):
return list(set(a) & set(b))
def union(a, b):
return list(set(a) | set(b))
# extract ids from reads
def parse_readhead(head):
fields = head.strip("\n").split(":")
# if ill-formatted/modified non-standard header, return cry-face
if len(fields) < 3:
return -1, -1
iid = fields[0][1:]
fcid = fields[2]
return iid, fcid
# infer sequencer from ids from single fastq
def infer_sequencer(iid, fcid):
seq_by_iid = []
for key in InstrumentIDs:
if re.search(key, iid):
seq_by_iid += InstrumentIDs[key]
seq_by_fcid = []
for key in FCIDs:
if re.search(key, fcid):
seq_by_fcid += FCIDs[key][0]
sequencers = []
# if both empty
if not seq_by_iid and not seq_by_fcid:
return sequencers, "fail"
# if one non-empty
if not seq_by_iid:
return seq_by_fcid, "likely"
if not seq_by_fcid:
return seq_by_iid, "likely"
# if neither empty
sequencers = intersect(seq_by_iid, seq_by_fcid)
if sequencers:
return sequencers, "high"
# this should not happen, but if both ids indicate different sequencers..
else:
sequencers = union(seq_by_iid, seq_by_fcid)
return sequencers, "uncertain"
# process the flag and detected sequencer(s) for single fastq
def infer_sequencer_with_message(iid, fcid):
sequencers, flag = infer_sequencer(iid, fcid)
if not sequencers:
return [""], fail_msg
if flag == "high":
msg_template = null_template
else:
msg_template = success_msg_template
if set(sequencers) <= _upgrade_set1:
return ["HiSeq2000/2500"], msg_template.format(flag)
if set(sequencers) <= _upgrade_set2:
return ["HiSeq1500/2500"], msg_template.format(flag)
if set(sequencers) <= _upgrade_set3:
return ["HiSeq3000/4000"], msg_template.format(flag)
return sequencers, msg_template.format(flag)
def test_sequencer_detection():
Samples = [
"@ST-E00314:132:HLCJTCCXX:6:2206:31213:47966 1:N:0",
"@D00209:258:CACDKANXX:6:2216:1260:1978 1:N:0:CGCAGTT",
"@D00209:258:CACDKANXX:6:2216:1586:1970 1:N:0:GAGCAAG",
"@A00311:74:HMLK5DMXX:1:1101:2013:1000 3:N:0:ACTCAGAC",
]
seqrs = set()
for head in Samples:
iid, fcid = parse_readhead(head)
seqr, msg = infer_sequencer_with_message(iid, fcid)
for sr in seqr:
signal = (sr, msg)
seqrs.add(signal)
print(seqrs)
def sequencer_detection_message(fastq_files):
seqrs = set()
# accumulate (sequencer, status) set
for fastq in fastq_files:
with gzip.open(fastq) as f:
head = str(f.readline())
# line = str(f.readline()
# if len(line) > 0:
# if line[0] == "@":
# head = line
# else:
# print("Incorrectly formatted first read in FASTQ file: %s" % fastq)
# print(line)
iid, fcid = parse_readhead(head)
seqr, msg = infer_sequencer_with_message(iid, fcid)
for sr in seqr:
signal = (sr, msg)
seqrs.add(signal)
# get a list of sequencing platforms
platforms = set()
for platform, _ in seqrs:
platforms.add(platform)
sequencers = list(platforms)
# if no sequencer detected at all
message = ""
fails = 0
for platform, status in seqrs:
if status == fail_msg:
fails += 1
if fails == len(seqrs):
message = "could not detect the sequencing platform(s) used to generate the input FASTQ files"
return message, sequencers
# if partial or no detection failures
if fails > 0:
message = "could not detect the sequencing platform used to generate some of the input FASTQ files, "
message += "detected the following sequencing platforms- "
for platform, status in seqrs:
if status != fail_msg:
message += platform + " " + status + ", "
message = message.strip(", ")
return message, sequencers
### make tree view of files
def list_files(startpath, maxlevel):
for root, dirs, files in os.walk(startpath, followlinks=True):
# Exclude hidden directories and files
dirs[:] = [d for d in dirs if not d[0] == "."]
files = [f for f in files if not f[0] == "."]
level = root.replace(startpath, "").count(os.sep)
if level <= maxlevel:
indent = " " * 4 * (level)
print("{}{}/".format(indent, os.path.basename(root)))
if level == maxlevel:
dirs[
:
] = (
[]
) # clear dir list at max level to prevent unnecessary directory traversal
### Download genome dict
pbm_genome_name_dict = {
"hg38": "hsapiens_gene_ensembl",
"hg37": "hsapiens_gene_ensembl",
"mm10": "mmusculus_gene_ensembl",
"dm6": "dmelanogaster_gene_ensembl",
}
pbm_host_dict = {
"hg38": "http://www.ensembl.org",
"hg37": "http://grch37.ensembl.org/",
"mm10": "http://nov2020.archive.ensembl.org/",
"dm6": "http://www.ensembl.org",
}
def download_genome_annotation(inverse_genome_dict):
annotation_dict = {}
for genome in inverse_genome_dict.keys():
filename = f"{genome}_annotation.tsv"
if os.path.exists(filename):
print(f"Loading cached genome annotation {filename}")
annotation = pd.read_csv(filename, sep="\t", header=0, index_col=0)
else:
dataset = pbm.Dataset(
name=pbm_genome_name_dict.get(genome, "default_value"),
host=pbm_host_dict.get(genome, "default_value"),
)
annotation = dataset.query(
attributes=[
"chromosome_name",
"transcription_start_site",
"strand",
"external_gene_name",
"transcript_biotype",
]
)
filter = annotation["Chromosome/scaffold name"].str.contains("CHR|GL|JH|MT")
annotation = annotation[~filter]
annotation["Chromosome/scaffold name"] = annotation[
"Chromosome/scaffold name"
].str.replace(r"(\b\S)", r"chr\1")
annotation["Chromosome/scaffold name"] = (
"chr" + annotation["Chromosome/scaffold name"]
)
annotation.columns = [
"Chromosome",
"Start",
"Strand",
"Gene",
"Transcript_type",
]
annotation = annotation[annotation.Transcript_type == "protein_coding"]
annotation.to_csv(filename, sep="\t")
annotation_dict[genome] = annotation
return annotation_dict
### Otsu filtering
def histogram(array, nbins=100):
"""
Draw histogram from distribution and identify centers.
Parameters
---------
array: `class::np.array`
Scores distribution
nbins: int
Number of bins to use in the histogram
Return
---------
float
Histogram values and bin centers.
"""
array = array.ravel().flatten()
hist, bin_edges = np.histogram(array, bins=nbins, range=None)
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2.0
return hist, bin_centers
def threshold_otsu(array, nbins=100, min_value=100):
"""
Apply Otsu threshold on topic-region distributions [Otsu, 1979].
Parameters
---------
array: `class::np.array`
Array containing the region values for the topic to be binarized.
nbins: int
Number of bins to use in the binarization histogram
Return
---------
float
Binarization threshold.
Reference
---------
Otsu, N., 1979. A threshold selection method from gray-level histograms. IEEE transactions on systems, man, and
cybernetics, 9(1), pp.62-66.
"""
array = array[(array >= min_value)]
hist, bin_centers = histogram(array, nbins)
hist = hist.astype(float)
# Class probabilities for all possible thresholds
weight1 = np.cumsum(hist)
weight2 = np.cumsum(hist[::-1])[::-1]
# Class means for all possible thresholds
mean1 = np.cumsum(hist * bin_centers) / weight1
mean2 = (np.cumsum((hist * bin_centers)[::-1]) / weight2[::-1])[::-1]
# Clip ends to align class 1 and class 2 variables:
# The last value of ``weight1``/``mean1`` should pair with zero values in
# ``weight2``/``mean2``, which do not exist.
variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2
idx = np.argmax(variance12)
threshold = bin_centers[:-1][idx]
return threshold
def plot_frag_qc(
x,
y,
z,
ax,
x_thr_min=None,
x_thr_max=None,
y_thr_min=None,
y_thr_max=None,
ylab=None,
xlab="Number of (unique) fragments in regions",
cmap="viridis",
s=10,
marker="+",
c="#343434",
xlim=None,
ylim=None,
**kwargs,
):
from scipy.stats import gaussian_kde
assert all(x.index == y.index)
barcodes = x.index.values
sp = ax.scatter(
x,
y,
c=z if z is not None else None,
s=s,
edgecolors=None,
marker=marker,
cmap=cmap,
**kwargs,
)
if ylim is not None:
ax.set_ylim(ylim[0], ylim[1])
if xlim is not None:
ax.set_xlim(xlim[0], xlim[1])
# Start with keeping all barcodes.
barcodes_to_keep = np.full(x.shape[0], True)
# Filter barcodes out if needed based on thresholds:
if x_thr_min is not None:
ax.axvline(x=x_thr_min, color="r", linestyle="--")
if x_thr_max is not None:
ax.axvline(x=x_thr_max, color="r", linestyle="--")
if y_thr_min is not None:
ax.axhline(y=y_thr_min, color="r", linestyle="--")
if y_thr_max is not None:
ax.axhline(y=y_thr_max, color="r", linestyle="--")
ax.set_xscale("log")
ax.set_xmargin(0.01)
ax.set_ymargin(0.01)
ax.set_xlabel(xlab, fontsize=10)
ax.set_ylabel(ylab, fontsize=10)
def plot_qc(
sample,
sample_alias,
metadata_bc_df,
bc_passing_filters=[],
x_thresh=None,
y_thresh=None,
include_kde=False,
detailed_title=True,
max_dict={},
min_dict={},
s=4,
):
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 4), dpi=150)
y_var_list = ["TSS_enrichment", "FRIP", "Dupl_rate"]
y_labels = ["TSS Enrichment", "FRIP", "Duplicate rate per cell"]
# plot everything
axes = [ax1, ax2, ax3]
for i, (y_var, ax, y_label) in enumerate(zip(y_var_list, axes, y_labels)):
z_col_name = f"kde__log_Unique_nr_frag_in_regions__{y_var}"
# print(metadata_bc_df.columns)
if include_kde:
print("plotting with KDE")
if not z_col_name in metadata_bc_df.columns:
print(f"{z_col_name} is not present, calculating")
x_log = np.log(metadata_bc_df["Unique_nr_frag_in_regions"] + 1)
xy = np.vstack([x_log, metadata_bc_df[y_var]])
# print(xy)
z = gaussian_kde(xy)(xy)
# print(z)
# now order x and y in the same way that z was ordered, otherwise random z value is assigned to barcode:
idx = (
z.argsort()
) # order based on z value so that highest value is plotted on top, and not hidden by lower values
df_sub = pd.DataFrame(index=metadata_bc_df.index[idx])
df_sub[z_col_name] = z[idx]
metadata_bc_df[z_col_name] = df_sub[z_col_name]
else:
print(f"{z_col_name} is present, not calculating")
else:
print("plotting without KDE")
if include_kde:
metadata_bc_df = metadata_bc_df.sort_values(by=z_col_name, ascending=True)
plot_frag_qc(
x=metadata_bc_df["Unique_nr_frag_in_regions"],
y=metadata_bc_df[y_var],
z=metadata_bc_df[z_col_name] if include_kde else None,
ylab=y_label,
s=s,
x_thr_min=x_thresh,
y_thr_min=y_thresh,
xlim=[10, max_dict["Unique_nr_frag_in_regions"]],
ylim=[0, max_dict[y_var]] if y_var == "TSS_enrichment" else [0, 1],
ax=ax,
)
if detailed_title:
med_nf = round(
metadata_bc_df.loc[
bc_passing_filters, "Unique_nr_frag_in_regions"
].median(),
2,
)
med_tss = round(
metadata_bc_df.loc[bc_passing_filters, "TSS_enrichment"].median(), 2
)
med_frip = round(metadata_bc_df.loc[bc_passing_filters, "FRIP"].median(), 2)
title = f"{sample_alias}: Kept {len(bc_passing_filters)} cells using Otsu filtering. Median Unique Fragments: {med_nf:.0f}. Median TSS Enrichment: {med_tss:.2f}. Median FRIP: {med_frip:.2f}\nUsed a minimum of {x_thresh:.2f} fragments and TSS enrichment of {y_thresh:.2f})"
else:
title = sample
fig.suptitle(title, x=0.5, y=0.95, fontsize=10)
return fig
### Saturation analysis
def read_bc_and_counts_from_fragments_file(fragments_bed_filename: str) -> pl.DataFrame:
"""
Read cell barcode (column 4) and counts per fragment (column 5) from fragments BED file.
Cell barcodes will appear more than once as they have counts per fragment, but as
the fragment locations are not needed, they are not returned.
Parameters
----------
fragments_bed_filename: Fragments BED filename.
Returns
-------
Polars dataframe with cell barcode and count per fragment (column 4 and 5 of BED file).
"""
# Set the correct open function depending if the fragments BED file is gzip compressed or not.
open_fn = gzip.open if fragments_bed_filename.endswith(".gz") else open
skip_rows = 0
nbr_columns = 0
with open_fn(fragments_bed_filename, "rt") as fragments_bed_fh:
for line in fragments_bed_fh:
# Remove newlines and spaces.
line = line.strip()
if not line or line.startswith("#"):
# Count number of empty lines and lines which start with a comment before the actual data.
skip_rows += 1
else:
# Get number of columns from the first real BED entry.
nbr_columns = len(line.split("\t"))
# Stop reading the BED file.
break
if nbr_columns < 5:
raise ValueError(
f'Fragments BED file needs to have at least 5 columns. "{fragments_bed_filename}" contains only '
f"{nbr_columns} columns."
)
# Read cell barcode (column 4) and counts (column 5) per fragment from fragments BED file.
fragments_df = pl.read_csv(
fragments_bed_filename,
has_header=False,
skip_rows=skip_rows,
separator="\t",
use_pyarrow=False,
n_threads=6,
columns=["column_1", "column_2", "column_3", "column_4", "column_5"],
new_columns=["Chromosome", "Start", "End", "CellBarcode", "FragmentCount"],
dtypes=[pl.Categorical, pl.UInt32, pl.UInt32, pl.Categorical, pl.UInt32],
)
return fragments_df
sampling_fractions_default = [
0.0,
0.1,
0.2,
0.3,
0.4,
0.5,
0.55,
0.6,
0.65,
0.7,
0.75,
0.8,
0.85,
0.9,
0.92,
0.94,
0.96,
0.98,
1.0,
]
def sub_sample_fragments(
fragments_df,
n_reads,
min_uniq_frag=200,
selected_barcodes=[],
sampling_fractions=sampling_fractions_default,
stats_tsv_filename="sampling_stats.tsv",
):
sampling_fractions_length = len(sampling_fractions)
# Initialize dataframe for storing all statistics results.
stats_df = pd.DataFrame(
{
"mean_frag_per_bc": np.zeros(sampling_fractions_length, np.float64),
"median_uniq_frag_per_bc": np.zeros(sampling_fractions_length, np.float64),
"total_unique_frag_count": np.zeros(sampling_fractions_length, np.uint32),
"total_frag_count": np.zeros(sampling_fractions_length, np.uint32),
"cell_barcode_count": np.zeros(sampling_fractions_length, np.uint32),
},
index=pd.Index(data=np.array(sampling_fractions), name="sampling_fraction"),
)
# Get all cell barcodes which have more than min_uniq_frag fragments.
if not selected_barcodes:
selected_barcodes = (
fragments_df.groupby("CellBarcode")
.agg(pl.col("FragmentCount").count().alias("nbr_frags_per_CBs"))
.filter(pl.col("nbr_frags_per_CBs") > min_uniq_frag)
)
else:
selected_barcodes = pl.DataFrame(
[
pl.Series("CellBarcode", selected_barcodes, dtype=pl.Categorical),
]
)
# Count all good cell barcodes.
nbr_selected_barcodes = selected_barcodes.height
if 1.0 in sampling_fractions:
# As there is no need to sample when sampling fraction is 100%,
# the median number of unique fragments per barcode can be
# calculated much more efficiently on the original fragments
# file dataframe with counts than the expanded one, which is
# needed when sampling is required.
print("Calculate statistics for sampling fraction 100.0%.")
print(f"Keep fragments with good barcodes.")
fragments_for_good_bc_df = selected_barcodes.join(
fragments_df, left_on="CellBarcode", right_on="CellBarcode", how="left"
)
print("Calculate total number of fragments.")
stats_df.loc[1.0, "total_unique_frag_count"] = (
fragments_for_good_bc_df.groupby(
["CellBarcode", "Chromosome", "Start", "End"]
)
.agg([pl.first("Start").alias("Start_tmp")])
.select(pl.count())
.item()
)
stats_df.loc[1.0, "total_frag_count"] = fragments_for_good_bc_df.select(
pl.col("FragmentCount").sum()
).item()
print(
"Calculate mean number of fragments per barcode and median number of unique"
" fragments per barcode."
)
stats_df_pl = (
fragments_for_good_bc_df.groupby("CellBarcode")
.agg(
[
pl.col("FragmentCount").sum().alias("MeanFragmentsPerCB"),
pl.count().alias("UniqueFragmentsPerCB"),
]
)
.select(
[
pl.col("MeanFragmentsPerCB").mean(),
pl.col("UniqueFragmentsPerCB").median(),
]
)
)
stats_df.loc[1.0, "mean_frag_per_bc"] = stats_df_pl["MeanFragmentsPerCB"][0]
stats_df.loc[1.0, "median_uniq_frag_per_bc"] = stats_df_pl[
"UniqueFragmentsPerCB"
][0]
stats_df.loc[1.0, "cell_barcode_count"] = nbr_selected_barcodes
# Delete dataframe to free memory.
del fragments_for_good_bc_df
# Create dataframe where each row contains one fragment:
# - Original dataframe has a count per fragment with the same cell barcode.
# - Create a row for each count, so we can sample fairly afterwards.
print("Create dataframe with all fragments (for sampling).")
fragments_all_df = fragments_df.with_columns(
pl.col("FragmentCount").repeat_by(pl.col("FragmentCount"))
).explode("FragmentCount")
# Delete input dataframe to free memory.
del fragments_df
for sampling_fraction in sampling_fractions:
if sampling_fraction == 0.0:
# All statistics are zero and already set when the stats_df dataframe is created.
continue
elif sampling_fraction == 1.0:
# Statistics for 100% sampling are already calculated as there is no need
# to have the fragments_all_df dataframe as no sampling is needed.
# This avoids the need to use the expensive groupby operations for the
# calculations of the median number of unique fragments per barcode.
continue
print(
"Calculate statistics for sampling fraction"
f" {round(sampling_fraction * 100, 1)}%."
)
# Sample x% from all fragments (with duplicates) and keep fragments which have good barcodes.
print(
f"Sample {round(sampling_fraction * 100, 1)}% from all fragments and keep"
" fragments with good barcodes."
)
fragments_sampled_for_good_bc_df = selected_barcodes.join(
fragments_all_df.sample(fraction=sampling_fraction),
left_on="CellBarcode",
right_on="CellBarcode",
how="left",
)
# Get number of sampled fragments (with possible duplicate fragments) which have good barcodes.
stats_df.loc[sampling_fraction, "total_unique_frag_count"] = (
fragments_sampled_for_good_bc_df.groupby(
["CellBarcode", "Chromosome", "Start", "End"]
)
.agg([pl.first("Start").alias("Start_tmp")])
.select(pl.count())
.item()
)
stats_df.loc[
sampling_fraction, "total_frag_count"
] = fragments_sampled_for_good_bc_df.select(pl.count()).item()
print("Calculate mean number of fragments per barcode.")
stats_df.loc[sampling_fraction, "mean_frag_per_bc"] = (
fragments_sampled_for_good_bc_df.select(
[pl.col("CellBarcode"), pl.col("FragmentCount")]
)
.groupby("CellBarcode")
.agg([pl.count("FragmentCount").alias("FragmentsPerCB")])
.select([pl.col("FragmentsPerCB").mean().alias("MeanFragmentsPerCB")])[
"MeanFragmentsPerCB"
][0]
)
print("Calculate median number of unique fragments per barcode.")
stats_df.loc[sampling_fraction, "median_uniq_frag_per_bc"] = (
fragments_sampled_for_good_bc_df.groupby(
["CellBarcode", "Chromosome", "Start", "End"]
)
.agg([pl.col("FragmentCount").first().alias("FragmentCount")])
.select([pl.col("CellBarcode"), pl.col("FragmentCount")])
.groupby("CellBarcode")
.agg(pl.col("FragmentCount").count().alias("UniqueFragmentsPerCB"))
.select(pl.col("UniqueFragmentsPerCB").median())["UniqueFragmentsPerCB"][0]
)
stats_df.loc[sampling_fraction, "cell_barcode_count"] = nbr_selected_barcodes
# Delete dataframe to free memory.
del fragments_sampled_for_good_bc_df
# then add some extra stats
stats_df["total_reads"] = n_reads * stats_df.index
stats_df["mean_reads_per_barcode"] = (
stats_df["total_reads"] / stats_df["cell_barcode_count"]
)
stats_df["mean_reads_per_barcode"].fillna(0, inplace=True)
stats_df["duplication_rate"] = (
stats_df["total_frag_count"] - stats_df["total_unique_frag_count"]
) / stats_df["total_frag_count"]
stats_df["duplication_rate"] = stats_df["duplication_rate"].fillna(0)
print(f'Saving statistics in "{stats_tsv_filename}".')
stats_df.to_csv(stats_tsv_filename, sep="\t")
return stats_df
# subsample a fragments file and return the subsampled fragments file
def sub_sample_fragments_single(
fragments_df,
sampling_fraction=None,
out_file_path=None,
):
if sampling_fraction > 1:
print("sampling fraction > 1, impossible, returning none")
elif sampling_fraction == 1:
print("sampling fraction = 1, returning full fragments file.")
if out_file_path:
fragments_df.write_csv(out_file_path, separator="\t", has_header=False)
else:
return fragments_df
elif sampling_fraction == 0.0:
print("sampling fraction = 0, returning none")
return None
else:
fragments_all_df = fragments_df.with_columns(
pl.col("FragmentCount").repeat_by(pl.col("FragmentCount"))
).explode("FragmentCount")
# downsample
fragments_sampled_df = fragments_all_df.sample(fraction=sampling_fraction)
# re-group
fragments_sampled_df_contracted = fragments_sampled_df.groupby(
["Chromosome", "Start", "End", "CellBarcode"]
).agg([pl.count("FragmentCount").alias("FragmentCount")])
if out_file_path:
fragments_sampled_df_contracted.write_csv(
out_file_path, separator="\t", has_header=False
)
else:
return fragments_sampled_df_contracted
### Plot duplication
def MM(x, Vmax, Km):
"""
Define the Michaelis-Menten Kinetics model that will be used for the model fitting.
"""
if Vmax > 0 and Km > 0:
y = (Vmax * x) / (Km + x)
else:
y = 1e10
return y
def plot_saturation_fragments(
filepath,
sample,
n_reads,
n_cells,
percentage_toplot,
svg_output_path,
png_output_path,
plot_current_saturation=True,
x_axis="mean_reads_per_barcode",
y_axis="median_uniq_frag_per_bc",
function=MM,
):
fig, ax = plt.subplots(figsize=(6, 4))
stats_df = pd.read_csv(filepath, sep="\t", index_col=0)
if x_axis == "mean_reads_per_barcode":
x_data = np.array(stats_df.loc[0:, x_axis]) / 10**3
else:
x_data = np.array(stats_df.loc[0:, x_axis])
y_data = np.array(stats_df.loc[0:, y_axis])
# fit to MM function
best_fit_ab, covar = curve_fit(function, x_data, y_data, bounds=(0, +np.inf))
# expand fit space
x_fit = np.linspace(0, int(np.max(x_data) * 1000), num=100000)
y_fit = function(x_fit, *(best_fit_ab))
# impute maximum saturation to plot as 95% of y_max
y_val = best_fit_ab[0] * 0.95
# subset x_fit space if bigger then y_val
if y_val < max(y_fit):
x_coef = np.where(y_fit >= y_val)[0][0]
x_fit = x_fit[0:x_coef]
y_fit = y_fit[0:x_coef]
# plot model
ax.plot(
x_fit, function(x_fit, *best_fit_ab), label="fitted", c="black", linewidth=1
)
# plot raw data
ax.scatter(x=x_data, y=y_data, c="red", s=10)
# mark curent saturation
curr_x_coef = max(x_data)
curr_y_coef = max(y_data)
if plot_current_saturation == True:
ax.plot([curr_x_coef, curr_x_coef], [0, 9999999], linestyle="--", c="red")
ax.plot([0, curr_x_coef], [curr_y_coef, curr_y_coef], linestyle="--", c="red")
ax.text(
x=curr_x_coef * 1.1,
y=curr_y_coef * 0.9,
s=str(round(curr_y_coef, 1))
+ " fragments, {:.2f}".format(curr_x_coef)
+ " kRPC",
c="red",
ha="left",
va="bottom",
)
# Find read count for percent saturation
y_val = best_fit_ab[0] * 0.9 * percentage_toplot
# Find closest match in fit
if max(y_fit) > y_val:
x_idx = np.where(y_fit >= y_val)[0][0]
x_coef = x_fit[x_idx]
y_coef = y_fit[x_idx]
# Draw vline
ax.plot([x_coef, x_coef], [0, 9999999], linestyle="--", c="blue")
# Draw hline
ax.plot([0, x_coef], [y_coef, y_coef], linestyle="--", c="blue")
# Plot imputed read count
ax.text(
x=x_coef * 1.1,
y=y_coef * 0.9,
s=str(round(y_coef, 1)) + " fragments, {:.2f}".format(x_coef) + " kRPC",
c="blue",
ha="left",
va="bottom",
)
# get xlim value
y_max = y_fit[-1] * 0.95
x_idx = np.where(y_fit >= y_max)[0][0]
x_max = x_fit[x_idx]
ax.set_xlim([0, x_max])
ax.set_ylim([0, y_max])
# add second axis
ax2 = ax.twiny()
ax2.set_xticks(ax.get_xticks())
upper_xticklabels = [str(int(x)) for x in ax.get_xticks() * n_cells / 1000]
ax2.set_xticklabels(upper_xticklabels)
ax2.set_xlabel("Total reads (millions)")
ax2.set_xlim([0, x_max])
# save figure
ax.set_xlabel("Reads per cell (thousands)")
# plt.yscale("log")
# ax.set_xscale("log")
ax.set_ylabel(y_axis)
title_str = f"{sample}\n{n_cells} cells, {round(n_reads/1000000)}M reads\nCurrently at {int(curr_y_coef)} {y_axis} with {int(curr_x_coef)} kRPC\nFor {int(percentage_toplot*100)}% saturation: {int(x_coef*n_cells/1000)}M reads needed\n"
ax.set_title(title_str)
plt.savefig(png_output_path, dpi=300, bbox_inches="tight")
plt.savefig(svg_output_path, dpi=300, bbox_inches="tight")
plt.show()
plt.close()
print(title_str)
def MM_duplication(x, Km):
"""
Define the Michaelis-Menten Kinetics model that will be used for the model fitting.
"""
if Km > 0:
y = x / (Km + x)
else:
y = 1e10
return y
def plot_saturation_duplication(
filepath,
sample,
n_reads,
n_cells,
percentage_toplot,
png_output_path,
svg_output_path,
function=MM_duplication,
plot_current_saturation=True,
x_axis="mean_reads_per_barcode",
y_axis="median_uniq_frag_per_bc",
):
fig, ax = plt.subplots(figsize=(6, 4))
stats_df = pd.read_csv(filepath, sep="\t", index_col=0)
if x_axis == "mean_reads_per_barcode":
x_data = np.array(stats_df.loc[0:, x_axis]) / 10**3
else:
x_data = np.array(stats_df.loc[0:, x_axis])
y_data = np.array(stats_df.loc[0:, y_axis])
# fit to MM function