-
Notifications
You must be signed in to change notification settings - Fork 5
/
PipelineScRNASeq.py
1625 lines (1216 loc) · 54.5 KB
/
PipelineScRNASeq.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
'''
PipelineScRNASeq.py - Utility functions for pipeline_scRNASeq.py
==============================================================
:Author: Toms Smith
:Release: $Id$
:Date: |today|
:Tags: Python
Code
----
'''
import collections
import CGATPipelines.Pipeline as P
import CGAT.IOTools as IOTools
import CGAT.Counts as Counts
import pysam
import pandas as pd
import numpy as np
import glob
import regex
import re
from CGATPipelines.Pipeline import cluster_runnable
import os
import CGAT.Fastq as Fastq
from rpy2.robjects import r as R
from rpy2.robjects import pandas2ri
import pandas.rpy.common as com
import rpy2.robjects as robjects
@cluster_runnable
def extractUMIsAndFilterFastq(fastq_seq, fastq_UMI, barcodes):
'''
Paired end sequencing:
read 1 - cell barcode (6bp) then UMI (10bp)
read 2 - genomic sequence
Need to extract UMI, append to read 2 read name and write out
reads to single cell fastqs
1. check sequence quality of barcode and UMI
2. check barcode is an expected sequence (384 possible barcodes)
3. Extract UMI from read 1 and append to read name for read pair
4. write out to single cell fastq using barcode as identifier
Filtering performed here mirrors filtering used by Soumillon et al 2014
'''
# TS - expected location of UMI and barcode is hard-coded in here...
out_prefix = P.snip(fastq_UMI, "_1.fastq.gz")
out_prefix_base = os.path.basename(out_prefix)
fastq = IOTools.openFile(fastq_seq, "r")
UMI_fastq = IOTools.openFile(fastq_UMI, "r")
def FastqNext(infile):
''' get next fastq entry in file - without format checks'''
line1 = infile.readline()
if not line1:
return None
line2 = infile.readline()
line3 = infile.readline()
line4 = infile.readline()
return Fastq.Record(line1[1:-1], line2[:-1], line4[:-1])
record = FastqNext(fastq)
UMI_record = FastqNext(UMI_fastq)
def getReadName(record):
return record.identifier.split(" ")[0]
counts = collections.Counter()
outfs = set()
# use IOTools.FilePool class to open multiple file handles
fastq_outfiles = IOTools.FilePool(
output_pattern=out_prefix + "_UMI_%s.fastq.gz")
while record is not None:
# check both records are for the same fastq read
assert getReadName(record) == getReadName(record), (
"fastq read names do not match")
UMI_record.format = "illumina-1.8"
# check quality of barcode
if not min(UMI_record.toPhred()[0:6]) >= 10:
counts["barcode_quality_fail"] += 1
else:
# check quality of UMI
if not min(UMI_record.toPhred()[6:16]) >= 30:
counts["UMI_quality_fail"] += 1
else:
# check barcode matches supplied barcodes
if not any(UMI_record.seq[0:6] == barcode
for barcode in barcodes):
counts["barcode_match_fail"] += 1
else:
counts["keep"] += 1
cell = UMI_record.seq[0:6]
UMI = UMI_record.seq[6:16]
record.identifier = record.identifier.replace(" ", ":") + "_" + UMI
outfs.update((cell,))
fastq_outfiles.write(cell, "%s\n" % record)
record = FastqNext(fastq)
UMI_record = FastqNext(UMI_fastq)
@cluster_runnable
def countAlignmentsPerGene(infile, outfile, mapq_threshold=0):
''' count the number of reads aligning to each contig(gene) in bam '''
# bash one-liner using cut|uniq -c would be
# much quicker but the zero counts would be lost.
counts = collections.Counter()
insam = pysam.Samfile(infile, "rb")
references = insam.references
references_dict = {}
for n, reference in enumerate(references):
references_dict[n] = reference
counts[reference] = 0
inreads = insam.fetch()
for read in inreads:
if read.is_unmapped:
continue
if read.mapq < mapq_threshold:
continue
counts[references_dict[read.reference_id]] += 1
with IOTools.openFile(outfile, "w") as f:
for k, v in counts.most_common():
f.write("%s\t%s\n" % (k, v))
@cluster_runnable
def summariseEditDistances(infiles, outfile):
''' tally counts for edit distances '''
final_df = pd.DataFrame()
for infile in infiles:
temp_df = pd.read_table(infile, sep="\t", index_col="edit_distance")
final_df = final_df.add(temp_df, fill_value=0)
final_df = final_df.astype(int)
final_df.to_csv(outfile, sep="\t")
@cluster_runnable
def mergeAndPlotEditDistances(infiles, outfile, plot_out):
''' merge the edit distance stats for each duplication method
and plot cumulative sum'''
plot_out2 = P.snip(plot_out, ".png") + "_unique_only.png"
plot_out3 = P.snip(plot_out, ".png") + "_cluster_only.png"
plot_out4 = P.snip(plot_out, ".png") + "_dir_only.png"
final_df = pd.DataFrame()
pre_null_df = pd.DataFrame()
for infile in infiles:
dedup_method = infile.split("/")[-2].replace(
"dedup_", "").replace(".dir", "")
tmp_df = pd.read_table(infile)
tmp_df.columns = [x.replace("-", "_") for x in tmp_df.columns]
tmp_post_df = tmp_df[[dedup_method, "%s_null" % dedup_method,
"edit_distance"]]
tmp_post_df.columns = [x.replace(dedup_method, "post")
for x in tmp_post_df.columns]
pre_null_df[dedup_method] = tmp_df["unique_null"]
dedup_method = dedup_method.title()
tmp_post_df['method'] = dedup_method
final_df = final_df.append(tmp_post_df)
final_df.to_csv(outfile, sep="\t", index=True)
plot_edit_distances = R('''
function(df){
library(ggplot2)
library(reshape)
library(plyr)
library(grid)
df = df[df$edit_distance!="Single_UMI",]
df$edit_distance = as.numeric(as.character(df$edit_distance))
df_null = df[df$method=="Unique",]
df_null$method="Null"
df_null$post = df_null$post_null
df = rbind(df, df_null)
max_distance = max(df$edit_distance)
col_range = topo.colors(max_distance, alpha = 0.9)
df = df[df$edit_distance<max_distance,]
df = df[order(df$edit_distance),]
l_txt = element_text(size=20)
df$method = factor(df$method,
levels=c("Unique", "Percentile", "Cluster",
"Adjacency", "Directional",
"Null"))
a = aes(y=post, x=method)
b = geom_bar(aes(fill=as.factor(edit_distance), colour="NA"),
stat="identity",
position="fill")
x = xlab("")
y = ylab("Fraction")
s_f = scale_fill_manual(name="Edit distance", values=col_range)
s_c = scale_colour_manual(guide="none", values="grey80")
t= theme(axis.text.y=l_txt,
axis.title.x=l_txt, axis.title.y=l_txt,
legend.text=l_txt, strip.text=l_txt,
legend.title=l_txt,
panel.margin = unit(1, "lines"),
legend.position="right",
legend.key.size=unit(2, "line"),
aspect.ratio=1,
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
x_no_angle = theme(axis.text.x=element_text(size=20))
x_angle = theme(axis.text.x=element_text(size=20, angle=90,
hjust=1, vjust=0.5))
p = ggplot(df) + a + b + x + y + s_f + theme_bw() + t + x_angle + s_c
ggsave("%(plot_out)s", width=10, height=10)
p2 = ggplot(df[(df$method=="Unique") | (df$method=="Null"),]) +
a + b + x + y + theme_bw() + s_f + t + x_no_angle + s_c
ggsave("%(plot_out2)s", width=10, height=8)
p3 = ggplot(df[(df$method=="Cluster") | (df$method=="Null"),]) +
a + b + x + y + theme_bw() + s_f + t + x_no_angle + s_c
ggsave("%(plot_out3)s", width=10, height=8)
p4 = ggplot(df[(df$method=="Directional") | (df$method=="Null"),]) +
a + b + y + x + theme_bw() + s_f + t + x_no_angle + s_c
ggsave("%(plot_out4)s", width=10, height=8)
}
''' % locals())
final_df.index = range(0, len(final_df.index), 1)
r_df = com.convert_to_r_dataframe(final_df)
plot_edit_distances(r_df)
@cluster_runnable
def getGeneCounts(infiles, outfile):
df = pd.DataFrame()
for infile in infiles:
temp_df = pd.io.parsers.read_csv(
infile, sep="\t", index_col=0, names=["counts"])
cell = re.sub(".*_UMI_", "", infile).replace(
"_deduped", "").replace(
".trans.gene.counts.tsv", "")
temp_df.index = temp_df.index
temp_df.sort_index(inplace=True)
temp_df.index.names = ['gene']
df[cell] = temp_df["counts"]
df.to_csv(outfile, sep="\t", index=True)
@cluster_runnable
def makeHeatmapsAndPCA(infiles,
outfile,
min_counts_per_sample=1000,
max_counts_per_sample=100000,
top_genes_heatmap=100, top_genes_pca=2000):
'''
1. Concatenates the counts from day 0 and day 14 and subset to samples
with counts within set range.
2. Heatmaps plotted for each dedup method using these samples
and top 100 genes
3. PCA plotted for each dedup method using these samples and top 2000 genes
'''
def getDay(infile):
''' return the day from the infile sample id'''
if "SRR1058003" in infile:
return "_day0"
elif "SRR1058023" in infile:
return "_day14"
else:
return None
methods = set([re.sub("_SRR.*", "", os.path.basename(x).replace(
"dedup_", "")) for x in infiles])
uniq_final_df = pd.DataFrame()
with IOTools.openFile(outfile, "w") as outf:
# start with just the uniq
for infile in [x for x in infiles if "unique" in x]:
day = getDay(infile)
# ignore sample id SRR1058003 / 1058023
if not day:
continue
tmp_df = pd.io.parsers.read_csv(infile, sep="\t", index_col=0)
tmp_df.columns = [x + day for x in tmp_df.columns]
uniq_final_df = pd.concat([uniq_final_df, tmp_df], axis=1)
uniq_genes_only = uniq_final_df.drop(
[x for x in uniq_final_df.index if "ERCC" in str(x)])
uniq_genes_only = uniq_genes_only.drop("chrM")
# filter out low abundance and high abundance samples
size_factors = uniq_genes_only.sum(axis=0)
keep = [(float(x) > min_counts_per_sample and
float(x) < max_counts_per_sample) for x in size_factors]
uniq_filtered = uniq_genes_only.iloc[:, keep]
cells = uniq_filtered.columns
outf.write("number of cells: %i\n" % len(cells.tolist()))
# need to recalculate as some samples have been removed
size_factors = uniq_filtered.sum(axis=0)
r_size_factors = robjects.Vector(size_factors.tolist())
# normalise
uniq_normed = uniq_filtered * 1000000.0 / size_factors
# subset to option(**top_genes**) most highly expressed
sum_counts_per_row = uniq_normed.sum(1)
countsLog = Counts.Counts(uniq_normed)
countsLog.normalise(method="total-column")
countsLog.log()
log_df = countsLog.table
countsZ = Counts.Counts(uniq_normed)
countsZ.zNormalise()
z_df = countsZ.table
z_df['order'] = sum_counts_per_row
log_df['order'] = sum_counts_per_row
z_df = z_df.sort(columns="order", ascending=False)
log_df = log_df.sort(columns="order", ascending=False)
z_df_pca = z_df[0:top_genes_pca]
z_df_heatmap = z_df[0:top_genes_heatmap]
log_df_heatmap = log_df[0:top_genes_heatmap]
z_df_pca_filtered = z_df_pca.drop("order", 1)
z_df_heatmap_filtered = z_df_heatmap.drop("order", 1)
log_df_heatmap_filtered = log_df_heatmap.drop("order", 1)
genes_pca = z_df_pca_filtered.index
genes_heatmap = z_df_heatmap_filtered.index
genes_heatmap_log = z_df_heatmap_filtered.index
outf.write("number of pca genes: %i\n" % len(genes_pca.tolist()))
outf.write("number of heatmap genes: %i\n" % len(genes_heatmap.tolist()))
plot_heatmap = R('''
function(df, plot_outfile, table_outfile){
options(expressions = 10000)
library(Biobase)
library(RColorBrewer)
library(gplots)
hmcol <- colorRampPalette(brewer.pal(9, "GnBu"))(100)
col_cols = sapply(colnames(df),
FUN=function(x) ifelse(grepl(".*day0", x), "chartreuse4", "chocolate2"))
d = as.dendrogram(hclust(as.dist(1-cor(df,
method = "spearman")),
method = "ward.D2"))
# write out clusters
df_clusters = data.frame(
"cluster" = dendextend:::cutree.dendrogram(d, k=2))
df_clusters$sample_group = gsub("[A-Z]+_","", rownames(df_clusters))
df_clusters$sample_group <- gsub("day0", "mES Cells",
df_clusters$sample_group)
cluster_table = table(df_clusters$cluster, by=df_clusters$sample_group)
write.table(cluster_table, table_outfile,
quote=FALSE, sep="\t", row.names=FALSE)
png(plot_outfile, width=25, height=25, unit="cm", res=400)
heatmap.2(as.matrix(df),
col = hmcol, scale="none", trace="none",
margin=c(18, 10), keysize=1, cexCol=2,
dendrogram="column",
Colv = d,
ColSideColors=col_cols,
hclustfun = function(x) hclust(x, method = 'average'),
distfun = function(x) as.dist(1 - cor(t(x),
method="spearman")),
labRow=F, labCol=F, key=F)
legend(0, 1,
legend = unique(sapply(colnames(df),
FUN=function(x) ifelse(grepl(".*_day0", x),
"Day 0", "Day 14"))),
col = unique(col_cols),
lty=1, lwd=0, pch=15, cex=1, pt.cex = 3, bty="n")
dev.off()
}''')
plot_PCA = R('''
function(df,
r_size_factors,
plot_base){
library(ggplot2)
library(grid)
m_text = element_text(size=15)
s_text = element_text(size=10)
gene_pca <- prcomp(t(df), center = TRUE)
variance = gene_pca$sdev^2
variance_explained = round(variance/sum(variance), 5)
variance_df = data.frame("Variance_explained" = variance_explained,
"PC" = seq(1, length(variance)))
write.table(variance_df, paste0(plot_base, "_variance.tsv"),
sep="\t", quote=FALSE, row.names=FALSE)
p_variance = ggplot(variance_df, aes(x=PC, y=Variance_explained))+
geom_point()+
geom_line()+
theme_classic()+
ylab("Variance explained (%%)")+
theme_bw() +
theme(axis.text.x = m_text,
axis.title.y = m_text,
axis.title.x = m_text,
axis.text.y = m_text,
aspect.ratio=1)
ggsave(paste0(plot_base, "_pca_variance.png"), width=5, height=5)
PCs_df = data.frame(gene_pca$x)
PCs_df$id_1 = sapply(strsplit(rownames(PCs_df), "_"), "[", 1)
PCs_df$id_2 = sapply(strsplit(rownames(PCs_df), "_"), "[", 2)
PCs_df$id_expression = log(as.numeric(r_size_factors),10)
write.table(PCs_df, paste0(plot_base, "_eigenvectors.tsv"),
sep="\t", row.names=FALSE)
p = geom_point(size=2, aes(shape=id_2, colour=id_2))
s_c = scale_colour_discrete(name="")
s_s = scale_shape_discrete(name="")
t = theme(axis.text.x = s_text, axis.text.y = s_text,
title = m_text, legend.text = m_text,
legend.title = m_text, legend.key.size = unit(7, "mm"),
aspect.ratio=1)
p_pca = ggplot(PCs_df, aes(x=PC1, y=PC2)) +
xlab(paste0('PC1 (Variance explained = ' ,
round(100 * variance_explained[1], 1), '%)')) +
ylab(paste0('PC2 (Variance explained = ' ,
round(100 * variance_explained[2], 1), '%)')) +
p + theme_bw() + s_c + s_s + t
ggsave(paste0(plot_base, "_pc1_pc2.png"), width=5, height=5)
p_pca = ggplot(PCs_df, aes(x=PC3, y=PC4)) +
xlab(paste0('PC4 (Variance explained = ' ,
round(100 * variance_explained[3], 1), '%)')) +
ylab(paste0('PC4 (Variance explained = ' ,
round(100 * variance_explained[4], 1), '%)')) +
p + theme_bw() + s_c + s_s + t
ggsave(paste0(plot_base, "_pc3_pc4.png"), width=5, height=5)
p_pca = ggplot(PCs_df, aes(x=PC1, y=PC2)) +
geom_point(size=2, aes(shape=id_2, colour=id_expression)) +
scale_shape_manual(name=guide_legend(title='Sample'), values=c(8,20)) +
scale_colour_continuous(name=guide_legend(title='Counts')) +
xlab(paste0('PC1 (Variance explained = ' ,
round(100 * variance_explained[1], 1), '%)')) +
ylab(paste0('PC2 (Variance explained = ' ,
round(100 * variance_explained[2], 1), '%)')) +
theme_bw() + t
ggsave(paste0(plot_base, "_pc1_pc2_expression.png"), width=5, height=5)
p_pca = ggplot(PCs_df, aes(x=PC3, y=PC4)) +
geom_point(size=2, aes(shape=id_2, colour=id_expression)) +
scale_shape_manual(name=guide_legend(title='Sample'), values=c(8,20)) +
scale_colour_continuous(name=guide_legend(title='Counts')) +
xlab(paste0('PC3 (Variance explained = ' ,
round(100 * variance_explained[1], 1), '%)')) +
ylab(paste0('PC4 (Variance explained = ' ,
round(100 * variance_explained[2], 1), '%)')) +
theme_bw() + t
ggsave(paste0(plot_base, "_pc3_pc4_expression.png"), width=7, height=5)
}''')
plot_outfile = P.snip(outfile, ".log") + "_uniq.png"
cluster_table = P.snip(outfile, ".log") + "_clusters.tsv"
plot_base = os.path.join(os.path.dirname(outfile), "uniq")
outf.write("%s\n" % plot_base)
r_uniq_pca_df = com.convert_to_r_dataframe(z_df_pca_filtered)
r_uniq_heatmap_df = com.convert_to_r_dataframe(log_df_heatmap_filtered)
log_df_heatmap_filtered.to_csv(outfile+"4", sep="\t", index=True)
plot_heatmap(r_uniq_heatmap_df, plot_outfile, cluster_table)
plot_PCA(r_uniq_pca_df,
r_size_factors,
plot_base)
outf.write("plotting heatmap for uniq deduping\n")
outf.write("plotting PCAs for uniq deduping\n")
# now repeat the heatmap and pca plotting for the other methods
outf.write("methods:\n%s\n" % "\n".join(map(str, methods)))
methods.remove("unique")
methods.remove("transcriptome")
for method in methods:
final_df = pd.DataFrame()
for infile in infiles:
if method == "transcriptome":
pattern = method
else:
pattern = "dedup_%s" % method
if pattern in infile:
outf.write("%s\n" % infile)
day = getDay(infile)
# ignore other sample ids
if not day:
continue
tmp_df = pd.io.parsers.read_csv(infile, sep="\t", index_col=0)
tmp_df.columns = [x + day for x in tmp_df.columns]
final_df = pd.concat([final_df, tmp_df], axis=1)
outf.write("%s\n" % "\t".join(map(str, final_df.shape)))
outf.write("number of cells: %i\n" % len(final_df.index))
# subset to chosen cells from uniquq dedup and
# extract the size factors for the selected cells
filtered = final_df.loc[:, cells.tolist()]
outf.write("%s\n" % "\t".join(map(str, filtered.shape)))
size_factors = filtered.sum(axis=0)
r_size_factors = robjects.Vector(size_factors.tolist())
normed = filtered * 1000000.0 / size_factors
countsLog = Counts.Counts(normed)
countsLog.normalise(method="total-column")
countsLog.log(inplace=True)
countsZ = Counts.Counts(normed)
countsZ = countsZ.zNormalise(inplace=False)
z_df = countsZ.table
log_df = countsLog.table
# subset to genes from unique dedup
normed_pca_filtered = z_df.loc[genes_pca, :]
normed_heatmap_filtered = log_df.loc[genes_heatmap, :]
outf.write("%s\n" % "\t".join(map(str, normed_pca_filtered.shape)))
outf.write("%s\n" % "\t".join(map(str, normed_heatmap_filtered.shape)))
plot_outfile = P.snip(outfile, ".log") + "_%s.png" % method
cluster_table = P.snip(outfile, ".log") + "_clusters_%s.tsv" % method
plot_base = os.path.join(os.path.dirname(outfile), method)
normed_pca_filtered.to_csv(
outfile.replace(".log", "%s_pca_df.tsv" % method), sep="\t")
normed_heatmap_filtered.to_csv(
outfile.replace(".log", "%s_heatmap_df.tsv" % method), sep="\t")
r_df_pca = pandas2ri.py2ri(normed_pca_filtered)
r_df_heatmap = pandas2ri.py2ri(normed_heatmap_filtered)
outf.write("plotting heatmap for %s deduping\n" % method)
plot_heatmap(r_df_heatmap, plot_outfile, cluster_table)
outf.write("plotting PCAs for %s deduping\n" % method)
plot_PCA(r_df_pca,
r_size_factors,
plot_base)
@cluster_runnable
def extractUMIsAndFilterFastqGSE65525(fastq_UMI, fastq_seq,
barcodes1_infile, barcodes2_infile,
cell_barcode_count):
'''Paired end sequencing:
read 1 - 51bp: cell barcode1 (8-12bp) then adapter sequence (22bp),
cell barcode2 (8bp) then UMI (6bp), then Ts
read 2 - genomic sequence
Need to extract UMI, append to read 2 read name and write out
reads to single cell fastqs for each cell
1. Check barcode is an expected sequence (384^2 possible barcodes)
2. Extract UMI and cell barcode from read 1 and append to read
name for read pair2
3. Write out to temporary single end fastq and generate
frequency table of barcodes
4. Identify n most abundant barcodes where n is the the of cells
and re-parse single-end fastq to retain only these barcodes
5. Strip cell barcode from fastq identifier and write out to
single cell fastq using concatenated barcodes as fastq name
Filtering performed here mirrors filtering used by Klein et al
2015
Ideally, we would parse the pair of fastqs twice. First to
generate the frequency table and then again to identify all cell
barcodes within a hamming distance of 2 from the n most abundnant
barcodes. However, the identification of cell barcode near
mismatches is extremely time consuming and some barcodes cannot be
unambiguously resolved at a Hamming distance of 2. Hence, only
perfect cell barcode matches are retained.
Since we have already identified all the candidate perfect matches
on the first parse, we can save these out to a temporary single
end fastq and parse this to identify the perfect matches to the n
most abundant cell barcodes
'''
def reverseComp(seq):
comp = {"A": "T",
"T": "A",
"C": "G",
"G": "C",
"N": "N"}
return "".join([comp[x] for x in seq[::-1]])
barcode_set1 = set()
barcode_set2 = set()
with IOTools.openFile(barcodes1_infile) as inf:
for line in inf:
barcode_set1.update((reverseComp(line.strip()),))
with IOTools.openFile(barcodes2_infile) as inf:
for line in inf:
barcode_set2.update((reverseComp(line.strip()),))
out_prefix = P.snip(fastq_UMI, "_1.fastq.gz")
#out_prefix_base = os.path.basename(out_prefix)
fastq = IOTools.openFile(fastq_seq, "r")
UMI_fastq = IOTools.openFile(fastq_UMI, "r")
def FastqNext(infile):
''' get next fastq entry in file - without format checks'''
line1 = infile.readline()
if not line1:
return None
line2 = infile.readline()
line3 = infile.readline()
line4 = infile.readline()
return Fastq.Record(line1[1:-1], line2[:-1], line4[:-1])
def getReadName(record):
return record.identifier.split(" ")[0]
counts = collections.Counter()
outfs = collections.Counter()
outfile_tmp = out_prefix + "_tmp.fastq"
fastq_tmp_outfile = IOTools.openFile(outfile_tmp, "w")
n = 0
with IOTools.openFile(out_prefix + "_log.tsv", "w") as outf:
# should really add an assert here to check for empty files
record = 1
while record is not None:
record = FastqNext(fastq)
UMI_record = FastqNext(UMI_fastq)
# check for end of file
if record is None or UMI_record is None:
if UMI_record is None:
outf.write("reached end of UMI fastq\n")
if record is None:
outf.write("reached end of paired end fastq\n")
break
if n % 100000 == 0:
outf.write("read through %i fastq records. %i records retained"
"\n" % (n, counts["keep"]))
for reason, count in counts.most_common():
outf.write("%s\t%i\n" % (reason, count))
n += 1
# check both records are for the same fastq read
assert getReadName(UMI_record) == getReadName(record), (
"fastq read names do not match")
UMI_record.format = "illumina-1.8"
# match must start from at least 9 bp into fastq sequence
# allow two mismatches
pos = regex.search("(GAGTGATTGCTTGTGACGCCTT){s<=2}",
UMI_record.seq[8:])
#pos = re.search("GAGTGATTGCTTGTGACGCCTT", UMI_record.seq)
# Skip if:
# - no match
# - matched string is not the right length
# - match starts too far from 5' end
if not pos:
counts["no_adapter_sequence"] += 1
continue
if len(pos.captures()[0]) != 22:
counts["adapter_sequence_wrong_length"] += 1
continue
start = pos.start() + 8
if start > 12:
counts["no_adapter_sequence_match_in_correct_location"] += 1
continue
barcode1 = UMI_record.seq[0:start]
barcode2 = UMI_record.seq[start+22:start+30]
UMI = UMI_record.seq[start+30:start+36]
# check barcode and UMI lengths. This is mainly to exlude
# read lengths which are too short to encode the UMI but
# also a back up check for barcode 1
if len(barcode1) < 8:
counts["barcode1_too_short"] += 1
continue
if len(barcode1) > 12:
counts["barcode1_too_long"] += 1
continue
if len(barcode2) != 8:
counts["barcode2_wrong_length"] += 1
continue
if len(UMI) < 6:
counts["UMI_too_short"] += 1
continue
# check barcodes are found in lists
if str(barcode1) not in barcode_set1:
counts["barcode1_mismatch"] += 1
continue
if str(barcode2) not in barcode_set2:
counts["barcode2_mismatch"] += 1
continue
counts["kept"] += 1
cell = barcode1 + barcode2
# for now, just write out all the fastqs which pass filters
# we'll reparse through this fastq later and "correct" the cell barcode
record.identifier = "_".join((
record.identifier.replace(" ", ":"), UMI, cell))
outfs[cell] += 1
fastq_tmp_outfile.write("%s\n" % record)
for reason, count in counts.most_common():
outf.write("%s\t%i\n" % (reason, count))
fastq_tmp_outfile.close()
fastq.close()
UMI_fastq.close()
with IOTools.openFile(out_prefix + "_barcode_counts.tsv", "w") as outf:
for barcode, count in outfs.most_common():
outf.write("%s\t%i\n" % (barcode, count))
with IOTools.openFile(out_prefix + "_barcode1.tsv", "w") as outf:
outf.write("barcode set 1\n")
for x in barcode_set1:
outf.write("%s\n" % "\t".join((x, "length: ", str(len(x)))))
with IOTools.openFile(out_prefix + "_barcode2.tsv", "w") as outf:
outf.write("barcode set 2\n")
for x in barcode_set2:
outf.write("%s\n" % "\t".join((x, "length: ", str(len(x)))))
# find the first n cell barcodes these represent the selected cells
cell_barcode_set = set()
n = 1
for barcode, count in outfs.most_common():
if n <= cell_barcode_count:
n += 1
cell_barcode_set.update((barcode,))
else:
break
fastq = IOTools.openFile(outfile_tmp, "r")
# use IOTools.FilePool class to open multiple file handles
fastq_outfiles = IOTools.FilePool(
output_pattern=out_prefix + "_UMI_%s.fastq.gz")
# re-initate objects
counts = collections.Counter()
outfs = collections.Counter()
counts["total"] = 0
with IOTools.openFile(out_prefix + "_log2.tsv", "w") as outf:
# should really add an assert here to check for empty files
record = 1
while record is not None:
record = FastqNext(fastq)
# check for end of file
if record is None:
outf.write("reached end of fastq\n")
break
if counts["total"] % 100000 == 0:
outf.write("read through %i fastq records. %i records retained"
"\n" % (counts["total"], counts["kept"]))
for reason, count in counts.most_common():
outf.write("%s\t%i\n" % (reason, count))
counts["total"] += 1
record.format = "illumina-1.8"
cell = record.identifier.split("_")[-1]
# check if cell barcode is in set
if cell not in cell_barcode_set:
counts["cell_barcode_mismatch"] += 1
continue
else:
counts["kept"] += 1
# append the UMI onto read2 and write out
#record.identifier = "_".join((
# record.identifier.replace(" ", ":"), UMI))
record.identifier = "_".join((
record.identifier.split("_")[0:2]))
outfs[cell] += 1
fastq_outfiles.write(cell, "%s\n" % record)
for reason, count in counts.most_common():
outf.write("%s\t%i\n" % (reason, count))
with IOTools.openFile(out_prefix + "_barcode_counts2.tsv", "w") as outf:
for barcode, count in outfs.most_common():
outf.write("%s\t%i\n" % (barcode, count))
os.unlink(outfile_tmp)
@cluster_runnable
def mergeTimepointsGSE65525(infiles, outfile):
''' merge gene counts from different timepoints and write out '''
df = pd.DataFrame()
for infile in infiles:
if "SRR1784310" in infile:
day = 0
elif "SRR1784313" in infile:
day = 2
elif "SRR1784314" in infile:
day = 4
elif "SRR1784315" in infile:
day = 7
tmp_df = pd.read_csv(IOTools.openFile(infile, "r"),
sep="\t", index_col=0)
tmp_df.columns = ["%s_day%i" % (x, day) for x in tmp_df.columns]
df = pd.concat([df, tmp_df], axis=1)
df.to_csv(outfile, sep="\t", index=True)
@cluster_runnable
def plotCV(infiles, plotfile, normalise_method):
''' calculate CVs and plot, split by method'''
plotfile2 = plotfile.replace(".png", "_difference.png")
plotfile3 = plotfile.replace(".png", "_no_unique.png")
plotfile4 = plotfile.replace(".png", "_vs_mean.png")
plotfile5 = plotfile.replace(".png", "_difference_hist.png")
cv_df = pd.DataFrame()
for infile in infiles:
method = re.sub("_SRR.*", "", os.path.basename(infile)).replace(
"dedup_", "")
method = method.title()
if method == "Transcriptome":
method = "None"
tmp_df = Counts.Counts(pd.read_csv(IOTools.openFile(infile, "r"),
sep="\t", index_col=0))
tmp_df.removeObservationsFreq(1)
tmp_df.normalise(method=normalise_method)
tmp_cv_df = pd.DataFrame({
"Method": method,
"mean": tmp_df.table.apply(np.mean, axis=1),
"cv": tmp_df.table.apply(
func=lambda(x): np.std(x)/np.mean(x), axis=1)})
cv_df = pd.concat([cv_df, tmp_cv_df], axis=0)
# need to check all genes have CVs for all methods
# it's possible for some genes to have no CV value for network-based methods
# if all reads fail the mapq threshold --> all zero counts --> no CV!
# we can do this by operating on the index = gene names
n_methods = len(set(cv_df['Method']))
gene_counts = collections.Counter(cv_df.index)
retain_genes = [x for x in gene_counts.keys() if gene_counts[x] == n_methods]
cv_df = cv_df.ix[retain_genes]
table_outfile = plotfile.replace(".png", ".tsv")
cv_df.to_csv(table_outfile, sep="\t", index=True)
plotCV = R('''
function(){
library(ggplot2)
df = read.table("%(table_outfile)s", sep="\t", header=T)
m_txt = element_text(size=18)
min_x = log(min(df$mean), 10)
max_x = log(max(df$mean), 10)
min_y = log(min(df$cv), 10)
max_y = log(max(df$cv), 10)
df$Method = factor(df$Method, levels=c("None", "Unique", "Percentile",
"Cluster", "Adjacency",
"Directional"))
t = theme(axis.text.x = m_txt,
axis.text.y = m_txt,
axis.title.x = m_txt,
axis.title.y = m_txt,
legend.position = "none",