-
Notifications
You must be signed in to change notification settings - Fork 1
/
5_tetinductionmycn.R
4751 lines (3604 loc) · 206 KB
/
5_tetinductionmycn.R
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
###############################################################################################################
#
# Filippos Klironomos, Department of Pediatric Hematology, Oncology and SCT Charité University Hospital Berlin
#
###############################################################################################################
# BATCH_202004
#{{{
#################################################################################
#
#
# define the metadata
# create a preprocessed/ folder with cleaned up raw reads of at least 51nts long
# create sample subfolders with symbolic links to raw FASTQ files
# create Makefile and run the pipeline
# add FASTQC and featureCount metrics to metadata
#
#{{{
rm(list=ls())
library(RColorBrewer)
library(data.table)
# load metadata and process
meta<-fread('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/info/metadata.csv', header=F, sep=',', select=c(1:2, 4,6), col.names=c('bid', 'ids', 'library_prep', 'treatment'))[, cell_model:='MYCN']
meta[ grep('Tet', bid), treatment:='+Tet 120h']
meta[ grep('ETOH', bid), treatment:='ETOH 120h']
# identify the sequencing ids from the Projektbericht PDF:
#
# S2105Nr1 CD007
# S2105Nr2 CD008
# S2105Nr3 CD009
# S2105Nr4 CD010
# S2105Nr5 CD011
# S2105Nr6 CD012
#
# add the sequencing ids to the metadata
stopifnot( all.equal( meta$ids, sprintf('CD0%02.0f', 7:12) ) )
meta[, sid:=paste0('S2105Nr', 1:6)]
setcolorder(meta, c('bid', 'sid', 'ids', 'library_prep', 'cell_model', 'treatment'))
meta[ treatment %in% '+Tet 120h', col:='orangered3']
meta[ treatment %in% 'ETOH 120h', col:='seagreen4']
# provisional saving without FASTQC metrics and MultiQC metrics
#save(meta, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/metadata.RData')
# locate the first mates
r1<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/fastq -maxdepth 1 -type f -wholename "*\\1\\.fastq.gz"', stdout=T)
# identify the sequencing ids
names(r1)<-sub('(S2105Nr[0-9]*).*$', '\\1', basename(r1))
# create the subfolders and place symbolic links to the two mates in them
root<-'/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/'
for(n in seq_along(r1)){
d<-paste0(root, meta[ sid %in% names(r1)[n], bid])
system2('mkdir', args=c('-p', d), stdout=T)
system2('ln', args=c('-sf', r1[n], paste0(d, '/r1.fastq.gz')), stdout=T)
system2('ln', args=c('-sf', sub('\\.1\\.fastq', '.2.fastq', r1[n]), paste0(d, '/r2.fastq.gz')), stdout=T)
}
# copy the Makefile configuration from the parent directory and update all LIBS:= entries:
#
# sed '/# raw read libraries/q' ../totalrna.conf > totalrna.conf
# echo -ne 'LIBS:=' >> totalrna.conf
# find /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/CB* -maxdepth 0 -type d -printf " %p" >> totalrna.conf
# ln -s ../../lib/qsub.mf .
#
# run the pipeline at the cluster:
#
# make -f qsub.mf CONF=totalrna.conf qc optitype kallisto rrna star bwa
# make -f qsub.mf CONF=totalrna.conf counts ciri lin_vs_circ
#
# run MultiQC:
#
# multiqc --interactive -o multiqc --ignore '*dcc*' --ignore '*ciri*' --ignore '*hg19*' --ignore '*lin_vs_circ*' -v -f -d -s ./
# load FASTQC metrics from MultiQC report
# identify bid
# summarize %GC and total number of raw reads across read mates
# add to metadata
fgc<-fread('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/multiqc/multiqc_data/multiqc_fastqc.txt')[, c('Sample', 'Filename', '%GC', 'Total Sequences')]
colnames(fgc)<-c('sample', 'filename', 'gc', 'nreads')
fgc[, bid:=sub('^.*(C[HB][^ ]+).*$', '\\1', sample) ]
fgc<-fgc[, .(gc=mean(gc), nreads=mean(nreads)), by=.(bid)]
meta<-fgc[meta, on='bid']
rm(fgc)
# process featureCounts statistics and add to metadata
logs<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/ -maxdepth 3 -wholename \'*/counts/genes.tsv.summary\' -print', stdout=T)
names(logs)<-sub('^.*BATCH_202004/(C[HB][^/]+)/counts/.*$', '\\1', logs)
fc<-setNames(vector('list', length(logs)), names(logs))
for(l in logs){
bid<-names(logs[ logs==l ])
fc[[bid]]<-setNames(fread(l, header=T, sep='\t', data.table=F)[ c(1, 4:6), 2 ], c('features', 'no_features', 'unassigned_unmapped', 'unassigned_unmapped_mapq'))
}
fc<-as.data.frame(do.call(rbind, fc))
fc$bid<-rownames(fc)
rownames(fc)<-NULL
fc<-fc[, c(5, 1:4)]
fc$unmapped<-rowSums(fc[, 4:5]) # add unmapped fields together and drop them (unmapped mates + alignments not passing MAPQ threshold asked)
fc<-data.table(fc[, c(1:3, 6)])
meta<-fc[meta, on='bid']
rm(fc, l, logs, bid)
# add percentage of the total number of alignments+reads that were dropped
# mark failed samples with at least 50% of dropouts in alignments+reads and number of reads covering features below the median
meta[, p_unmapped:=100*unmapped/(features+no_features+unmapped)]
meta[, failed:=ifelse(p_unmapped>=50 & features<median(features, na.rm=T), T, F)]
setcolorder(meta, c('bid', 'sid', 'ids', 'library_prep', 'cell_model', 'treatment', 'failed', 'gc', 'nreads', 'features', 'no_features', 'unmapped', 'p_unmapped', 'col'))
# save
save(meta, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/metadata.RData')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/metadata.RData
#
#
#################################################################################
############################################################
#
#
# collect results and do some basic statistics and plotting
#
#
############################################################
# [featureCounts] collect results for genes and exons
# unannotated but called exons are removed including exons on unplaced contigs
#{{{
rm(list=ls())
library(GenomicFeatures)
library(rtracklayer)
library(data.table)
# functions
#{{{
parse_gene_counts<-function(B=''){
require(data.table)
# load counts skipping first row which is a comment
cn<-fread(B, sep='\t', skip=1, col.names=c('gene_id', 'chr', 'start', 'end', 'strand', 'length', 'counts'))[, c('chr', 'start', 'end', 'strand'):=list(NULL, NULL, NULL, NULL)]
return(as.data.frame(cn))
}
parse_exon_counts<-function(B=''){
require(data.table)
# load counts skipping first row which is a comment
cn<-fread(B, sep='\t', skip=1, col.names=c('gene_id', 'chr', 'start', 'end', 'strand', 'length', 'counts'))
# remove identical exon entries
cn<-cn[, .(counts=counts[1]), by=.(gene_id, chr, start, end, strand, length)]
# load junction counts
jn<-fread(sub('$', '.jcounts', B), sep='\t', skip=0, header=T, col.names=c('gene_id_d', 'gene_id_a', 'chr_d', 'start_d', 'strand_d', 'chr_a', 'start_a', 'strand_a', 'count'))
# remove exons on unannotated features or exons on unplaced contigs
jn<-jn[ !is.na(gene_id_d) ]
# convert the acceptors gene_id column to list
jn[, gene_id_a:=strsplit(gene_id_a, ',')]
return(list(exons=cn, junctions=jn))
}
#}}}
# locate the gene counts
cnts<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/ -maxdepth 3 -type f -wholename \'*/counts/genes.tsv\' -print', stdout=T)
# add ids
names(cnts)<-sub('^.*BATCH_202004/(C[BH][^/]+)/counts/.*$', '\\1', cnts)
# order them
cnts<-cnts[ order(names(cnts)) ]
# collect the gene counts
totalrna<-List()
for (n in seq_along(cnts)){
cat('\nprocessing: ', cnts[n], '\n')
totalrna[[ names(cnts)[n] ]]<-parse_gene_counts(cnts[n])
}
rm(n)
# save
save(totalrna, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/featureCounts.RData')
# collect the exon counts including the exon junctions
cnts<-sub('genes\\.tsv$', 'exons.tsv', cnts)
exns<-List()
for (n in seq_along(cnts)){
cat('\nprocessing: ', cnts[n], '\n')
exns[[ names(cnts)[n] ]]<-parse_exon_counts(cnts[n])
}
rm(n)
# save
save(exns, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/featureCounts_exons.RData')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/featureCounts.RData
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/featureCounts_exons.RData
# [kallisto] collect results
#{{{
rm(list=ls())
library(GenomicAlignments)
library(rtracklayer)
library(data.table)
# functions
#{{{
parse_results<-function(B=''){
require(data.table)
# load counts
gn<-fread(B, sep='\t', header=T, col.names=c('transcript_id', 'length', 'effective_length', 'counts', 'tpm'))
return(as.data.frame(gn))
}
#}}}
# locate the counts
cnts<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/ -maxdepth 3 -type f -wholename \'*/kallisto/abundance.tsv\' -print', stdout=T)
# add ids
names(cnts)<-sub('^.*BATCH_202004/(C[HB][^/]+)/kallisto/.*$', '\\1', cnts)
# order them
cnts<-cnts[ order(names(cnts)) ]
# append results
totalrna<-List()
for (n in seq_along(cnts)){
cat('\nprocessing: ', cnts[n], '\n')
totalrna[[ names(cnts)[n] ]]<-parse_results(cnts[n])
}
rm(n)
# save
save(totalrna, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/kallisto.RData')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/kallisto.RData
# [CIRI2] collect results
# transgenic circRNAs are split to a separate list
# circRNAs on alternative contigs, chrM, and chrY are removed
# define circ_name
#{{{
rm(list=ls())
library(GenomicFeatures)
library(rtracklayer)
library(data.table)
library(openxlsx)
# functions
#{{{
parse_results<-function(B=''){
require(data.table)
n<-tryCatch({
cr<-fread(B, sep='\t', select=c(2:5, 7:11), col.names=c('seqnames', 'start', 'end', 'jc_count', 'non_jc_count', 'ratio', 'region', 'gene_id', 'strand'))
# remove last useless comma from gene_id
cr$gene_id<-sub(',$', '', cr$gene_id)
# convert 'n/a' to empty string
cr$gene_id<-sub('n/a', '', cr$gene_id)
# convert whole column to list
cr[, gene_id:=strsplit(gene_id, ',', fixed=T)]
# convert all character(0) that strsplit() returns when no comma is found to NA
cr[ lengths(gene_id)==0, gene_id:=lapply(gene_id, function(g){ NA }) ]
# add gene_name column
cr[, gene_name:=relist(hsa$gene_name[ match(unlist(cr$gene_id), hsa$gene_id) ], cr$gene_id)]
# convert to GRanges()
cr<-GRanges(as.data.frame(cr))
# remove circRNAs on alternative contigs
seqlevels(cr, pruning.mode='coarse')<-seqlevels(cr)[ grep('chr', seqlevels(cr)) ]
# remove circRNAs on chrM, chrY
seqlevels(cr, pruning.mode='coarse')<-seqlevels(cr)[ grep('chrM|chrY', seqlevels(cr), invert=T) ]
# split transgenic circRNAs to a seprate list
tr<-cr[ lengths(cr$gene_id)>1 ]
cr<-cr[ lengths(cr$gene_id)==1 ]
cr$gene_id<-unlist(cr$gene_id)
cr$gene_name<-unlist(cr$gene_name)
# return GRanges object
return(GRangesList(circs=cr, trans=tr))
}, error=function(e){
warning(e)
return(GRangesList(circs=GRanges(), trans=GRanges()))
})
}
#}}}
# load the reference to add gene_name to gene_id
hsa<-import('/fast/groups/ag_schulte/work/reference/annotation/GRCh38/GRCh38.gencode.v30.gtf')
hsa<-hsa[ hsa$type %in% 'gene' ]
hsa<-mcols(hsa)[, c('gene_name', 'gene_id')]
# locate the CIRI2 results from the non-failed samples
cir<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/ -maxdepth 3 -type f -wholename \'*/ciri/circRNAs.tsv\' -print', stdout=T)
# add ids
names(cir)<-sub('^.*BATCH_202004/(C[HB][^/]+)/ciri/.*$', '\\1', cir)
# order them
cir<-cir[ order(names(cir)) ]
# append results
circ<-List()
trans<-List()
for (n in seq_along(cir)){
cat('\nprocessing: ', cir[n], '\n')
x<-parse_results(cir[n])
circ[[ names(cir)[n] ]]<-x$circ
trans[[ names(cir)[n] ]]<-x$trans
}
rm(n,x)
# convert from List to GRanges and add bid to metadata
circ<-unlist(GRangesList(lapply(circ,c)))
circ$bid<-names(circ)
names(circ)<-NULL
trans<-unlist(GRangesList(lapply(trans,c)))
trans$bid<-names(trans)
names(trans)<-NULL
# keep circRNAs with at least 5 reads covering the junction in at least one sample
#circ<-data.table(as.data.frame(circ))
#circ[, pass:=any(jc_count>=5), by=.(seqnames, start, end, strand)]
#circ<-circ[ pass %in% TRUE, ][, pass:=NULL]
#circ<-GRanges(seqnames=circ$seqnames, strand=circ$strand, ranges=IRanges(start=circ$start, end=circ$end), data.frame(circ[, -c(1:5)]))
stopifnot( all(lengths(circ$gene_id)==1) )
stopifnot( all(lengths(circ$gene_name)==1) )
circ$gene_id<-unlist(circ$gene_id)
circ$gene_name<-unlist(circ$gene_name)
#trans<-data.table(as.data.frame(trans))
#trans[, pass:=any(jc_count>=5), by=.(seqnames, start, end, strand)]
#trans<-trans[ pass %in% TRUE, ][, pass:=NULL]
#trans<-GRanges(seqnames=trans$seqnames, strand=trans$strand, ranges=IRanges(start=trans$start, end=trans$end), data.frame(trans[, -c(1:5)]))
# name them (we do not remove anything since the unified cohort has already been defined)
circ$circ_name<-paste0(circ$gene_id, '|', circ$gene_name,'_', as.character(seqnames(circ)),as.character(strand(circ)), start(circ), '-', end(circ))
# save
save(circ, trans, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/circRNAs_CIRI2.RData')
x<-data.frame(circ)[, -c(1:3,5)][, c(9, 1:8)]
x<-x[ order(x$jc_count, decreasing=T), ]
write.xlsx(x, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/circRNAs_CIRI2.xlsx', col.names=T, row.names=F, sheetName='circRNAs', append=F)
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/circRNAs_CIRI2.{RData,xlsx}
# [linear vs circular junction quantification] collect and process the quantification results
#{{{
rm(list=ls())
library(GenomicFeatures)
library(rtracklayer)
library(data.table)
# functions
#{{{
parse_results<-function(B='', SSID=''){
require(data.table)
# try to load the counts
n<-tryCatch({
cn<-fread(B, header=F, sep='\t', col.names=c('tx_name', 'count'))
total<-cn[, sum(count)]
# separate circular from linear junctions
ci<-cn[ grep('\\|jn_', tx_name, invert=T) ]
colnames(ci)<-c('circ_name', 'c.count')
li<-cn[ grep('\\|jn_', tx_name, invert=F) ]
colnames(li)<-c('junction_name', 'l.count')
rm(cn)
# add gene_id, gene_name, the linear junctions within the circRNA associated with the circular junction
# and count==NA if the junction is not covered in this sample
CI<-data.table(data.frame(mcols(CIRCS)[, c('circ_name', 'gene_id', 'gene_name', 'linear_junctions_within')]))
ci<-ci[ CI, on='circ_name' ]
# add gene_id for the linear junction and collect all counts and junction names under the same gene_id
li<-li[ LINEAR, on='junction_name' ][, .(l.counts=list(l.count), l.junct=list(junction_name)), by=.(gene_id)]
# add linear junction counts and junction names to the circular junctions
ci<-ci[ li, on='gene_id']
# go over each circular junction and compute the mean/max counts across all linear junctions and across all linear junctions outside
# of the corresponding circRNA range
ci<-ci[, .(c.count=c.count, gene_id=gene_id, gene_name=gene_name, l.count=mean(unlist(l.counts), na.rm=T),
l.count.max=as.numeric(max(unlist(l.counts), na.rm=T)),
l.count.out=mean(unlist(l.counts)[ unlist(l.junct) %in% setdiff(unlist(l.junct), unlist(linear_junctions_within)) ], na.rm=T),
l.count.out.max=as.numeric(max(unlist(l.counts)[ unlist(l.junct) %in% setdiff(unlist(l.junct), unlist(linear_junctions_within)) ], na.rm=T))
), by=.(circ_name)] # warnings about "returning -Inf" are expected for unexpressed genes
# replace -Inf with NA for fully unexpressed genes or for genes with no outter linear junctions found expressed
ci[ l.count.max %in% -Inf, l.count.max:=NA]
ci[ l.count.out.max %in% -Inf, l.count.out.max:=NA]
# add total number of counts
ci$total<-total
# add the bid for easy processing afterwards
ci$bid<-SSID
return(ci)
}, error=function(e){
warning(e)
return(data.table())
})
}
#}}}
# locate the results
lin_cir<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/ -maxdepth 3 -type f -wholename \'*/lin_vs_circ/counts.tsv\' -print', stdout=T)
# add sequencing-sample-id (bid)
names(lin_cir)<-sub('^.*/(C[HB][^/]+)/.*$', '\\1', lin_cir)
# order them
lin_cir<-lin_cir[ order(names(lin_cir)) ]
# load circular and linear junctions
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_linear_vs_circular.RData')
# collect results
lin.cir<-List()
for (n in seq_along(lin_cir)){
cat('\nprocessing: ', lin_cir[n], '\n')
lin.cir[[ names(lin_cir)[n] ]]<-parse_results(lin_cir[n], names(lin_cir)[n]) # "returning -Inf" warnings expected for unexpressed junctions
}
rm(n,lin_cir)
# save
save(lin.cir, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/circRNAs_linear_vs_circular_collected_results.RData')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/circRNAs_linear_vs_circular_collected_results.RData
# [STAR] collect mapping statistics for all samples
#{{{
rm(list=ls())
library(data.table)
# locate STAR Log.final.out files
logs<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/ -maxdepth 3 -wholename \'*/star/Log.final.out\' -print', stdout=T)
# populate mapping summary data.frame
map.s<-data.frame(logs=logs, dir='', bid='', raw_reads=0, unimapped=0, multimapped=0, unmapped=0, alignments=0)
for (l in seq_along(logs)){
r<-readLines(logs[l])
map.s$dir[l]<-dirname(dirname(logs[l]))
map.s$bid[l]<-sub('^.*/(C[HB][^/]+)/.*$', '\\1',logs[l])
map.s$raw_reads[l]<-as.integer(strsplit(r[ grep('Number of input reads', r) ], '\\t')[[1]][2])
map.s$unimapped[l]<-as.integer(strsplit(r[ grep('Uniquely mapped', r) ], '\\t')[[1]][2])
map.s$multimapped[l]<-as.integer(strsplit(r[ grep('Number of reads mapped to multiple loci', r) ], '\\t')[[1]][2])
map.s$unmapped[l]<-map.s$raw_reads[l]-map.s$unimapped[l]-map.s$multimapped[l]
map.s$alignments[l]<-as.integer(readLines(sub('Log.final.out', 'Aligned.sortedByCoord.out.bam.alignments', logs[l])))
}
rm(l,r,logs)
# order them
setorder(map.s, bid)
map.s<-map.s[, c('dir', 'bid', 'raw_reads', 'unmapped', 'unimapped', 'multimapped', 'alignments')]
rownames(map.s)<-NULL
# save
save(map.s, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/mapping_summary.RData')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/mapping_summary.RData
# [STAR] barplots
#{{{
rm(list=ls())
library(data.table)
library(RColorBrewer)
library(extrafont) # first time used need to run: font_import() , to load all for PDF device run: loadfonts(device='pdf')
loadfonts()
source('~/bio/lib/trim_text.R')
# load mapping summary and metadata
# order libraries according to metadata order
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/mapping_summary.RData')
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/metadata.RData')
stopifnot( length(setdiff( map.s$bid , meta$bid ))==0 ) # all sequenced libraries show up in the metadata
meta<-meta[ bid %in% map.s$bid ]
map.s<-map.s[ match(meta$bid, map.s$bid), ]
# colors related to alignments and samples
cl.l<-data.frame(symbol=c('unimapped', 'multimapped','unmapped'),
color=c('#228B22', # forestgreen
'#1874CD', # dodgerblue3
'#B22222')) # firebrick
cl.s<-setNames( unique(meta[, treatment]), unique(meta[, col]) )
# CLICK on it once to make sure it does not redraw, or options(scipen=-20) might be IGNORED
x11(width=18, height=16, title='', bg='white', type='cairo', pointsize=20, antialias='subpixel', family='Arial')
# stacked bars
par(mar=c(9.0, 12.0, 2.0, 0.0), mgp=c(3,1,0), oma=c(0,0,0,0), las=1, xpd=NA, bty='n', cex.lab=2.4, cex.axis=2.4)
x<-map.s[, c('unimapped', 'multimapped', 'unmapped')]
rownames(x)<-sub('-11-R01$', '', map.s$bid)
YMAX<-max( rowSums(x) - rowSums(x)%%1e5 + 1e5 )
YTICK<-pretty(c(0, YMAX), 5)
YMAX<-tail(YTICK, 1)
bp<-barplot(t(x), plot=F)
plot(0:1, 0:1, type='n', ylim=c(0, YMAX), xlim=range(bp)+c(-1, +1), axes=F, ann=F, xaxs='i', yaxs='i')
bp<-barplot(t(x), border='white', col=cl.l[match(colnames(x), cl.l$symbol), 2], axisnames=F, beside=F, xlab='', ylab='', las=1, yaxt='n', ylim=c(0, YMAX), add=T)
options(scipen=-20)
axis(2, at=YTICK, line=-1, cex.axis=2.4)
mtext(text=sub('CB-SKNAS-TR-MYCN-', '', rownames(x)), side=1, line=0, at=bp, col=meta$col, las=2, adj=1, cex=1.8)
mtext('Number of raw reads', side=2, line=9, padj=+0.1, las=0, cex=2.4)
legend(x=par('usr')[2]*0.50, y=1.05*par('usr')[4], legend=cl.l$symbol[match(colnames(x), cl.l$symbol)] , col=cl.l$color[match(colnames(x), cl.l$symbol)], bty='n', lty=1, lwd=15, cex=2.0, y.intersp=0.40, x.intersp=0.15, seg.len=0.5)
legend(x=par('usr')[1]*0.50, y=1.05*par('usr')[4], legend=cl.s , col=names(cl.s), bty='n', lty=1, lwd=15, cex=2.0, y.intersp=0.40, x.intersp=0.15, seg.len=0.5)
#mtext(paste0('Number of samples = ', nrow(x)), side=3, line=-1, padj=-0.6, las=0, cex=2.4)
dev.print(device=svg, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/figures/barplot_mapping_statistics_alignments.svg', width=18, height=16, bg='white', antialias='subpixel', pointsize=20, family='Arial')
options(scipen=0)
# clean up
dev.off()
#}}}
# [HLA typing] collect results
#{{{
rm(list=ls())
library(GenomicAlignments)
library(rtracklayer)
library(data.table)
# functions
#{{{
parse_results<-function(B=''){
require(data.table)
# load results
hl<-as.data.frame(fread(B, sep='\t'))
rownames(hl)<-hl[, 1]
hl<-hl[, -1]
return(hl)
}
#}}}
# locate the gene estimated TPMs and counts, the transcripts will be looked for later on
hla<-system2('find', args='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/ -maxdepth 4 -type f -wholename \'*/optitype/*/*result.tsv\' -print', stdout=T)
# add ids
names(hla)<-sub('^.*/(CB[^/]+)/optitype/.*$', '\\1', hla)
# order them
hla<-hla[ order(names(hla)) ]
# append results
hla.t<-List()
for (n in seq_along(hla)){
cat('\nprocessing: ', hla[n], '\n')
hla.t[[ names(hla)[n] ]]<-parse_results(hla[n])
}
hla<-hla.t
rm(n,hla.t)
# save
save(hla, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/hla_typing.RData')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/hla_typing.RData
# [HLA typing] by eye informatics comparing with previous SKNAS samples
#{{{
rm(list=ls())
library(GenomicAlignments)
library(rtracklayer)
library(data.table)
library(RColorBrewer)
library(extrafont) # first time used need to run: font_import() , to load all for PDF device run: loadfonts(device='pdf')
loadfonts()
# functions
#{{{
scatterplots<-function(s1='', s2='', figs.dir=NULL, trim.name.root=''){
# scatterplot based on counts and TPMs of commonly expressed genes between sample (s1) and (s2)
S1<-s1
S2<-s2
if(trim.name.root!=''){
S1<-sub(trim.name.root, '', S1)
S2<-sub(trim.name.root, '', S2)
}
# isolate the samples of interest
X<-totalrna[[ s1 ]]
Y<-totalrna[[ s2 ]]
# remove mutually unexpressed genes
keep<- X$counts!=0 & Y$counts!=0
cat('\nTotal number of genes = ', nrow(X), ' of which ', sum(!keep), ' (', round(100*sum(!keep)/nrow(X), 1), '%) are mutually non-expressed and will be removed.\n\n', sep='')
X<-X[keep, ]
Y<-Y[keep, ]
rm(keep)
# add FPKM and TPM columns
X$fpkm<-1e9*X$counts/X$length/sum(X$counts)
Y$fpkm<-1e9*Y$counts/Y$length/sum(Y$counts)
X$tpm<-1e6*X$fpkm/sum(X$fpkm)
Y$tpm<-1e6*Y$fpkm/sum(Y$fpkm)
# isolate log10(1+counts)
X.c<-setNames(X$counts, X$gene_id)
Y.c<-setNames(Y$counts, Y$gene_id)
X.c<-log10(1+X.c)
Y.c<-log10(1+Y.c)
# isolate log10(1+TPMs)
X.t<-setNames(X$tpm, X$gene_id)
Y.t<-setNames(Y$tpm, Y$gene_id)
X.t<-log10(1+X.t)
Y.t<-log10(1+Y.t)
# linear regression
l.c<-lm( Y.c ~ X.c )
l.t<-lm( Y.t ~ X.t )
# [counts] scatterplot
x11(width=11, height=11, title='', bg='white', type='cairo', pointsize=20, antialias='subpixel')
MAX<-ceiling(max(X.c, Y.c))
par(mar=c(4.5,5.0,1.0,1.0), mgp=c(3,1,0), oma=c(0,0,0,0), las=1, xpd=F, bty='n', cex.lab=1.8, cex.axis=1.8)
den<-col2rgb(densCols(X.c, Y.c, colramp=colorRampPalette(c('black', 'white'))))[1, ]+1L
cls<-colorRampPalette(c('#000099', '#00FEFF', '#45FE4F','#FCFF00', '#FF9400', '#FF3100'))(256)[den]
plot(X.c[ order(den) ], Y.c[order(den)], type='p', pch=20, col=cls[order(den)], main='', xlab='', ylab='', cex=1.2, xlim=c(0, MAX), ylim=c(0, MAX))
abline(l.c, lty=1, lwd=4, xpd=F)
mtext(bquote(R^2 == .(format(summary(l.c)$r.squared, digits=2))), side=3, line=-1, padj=+0.5, cex=1.4, xpd=NA)
mtext(bquote(log[10](1+counts) ~ group("[", .(S1), "]")), side=1, line=2, padj=+0.8, cex=1.8)
mtext(bquote(log[10](1+counts) ~ group("[", .(S2), "]")), side=2, line=3, padj=+0.2, cex=1.8, las=0)
if (!is.null(figs.dir)){
dev.print(device=svg, file=paste0(figs.dir, '/scatterplot_counts_', s1, '_', s2, '.svg'), width=16, height=16, bg='white', antialias='subpixel', pointsize=20, family='Arial')
}
# [TPMs] scatterplot
x11(width=11, height=11, title='', bg='white', type='cairo', pointsize=20, antialias='subpixel')
MAX<-ceiling(max(X.t, Y.t))
par(mar=c(4.5,5.0,1.0,1.0), mgp=c(3,1,0), oma=c(0,0,0,0), las=1, xpd=F, bty='n', cex.lab=1.8, cex.axis=1.8)
den<-col2rgb(densCols(X.t, Y.t, colramp=colorRampPalette(c('black', 'white'))))[1, ]+1L
cls<-colorRampPalette(c('#000099', '#00FEFF', '#45FE4F','#FCFF00', '#FF9400', '#FF3100'))(256)[den]
plot(X.t[ order(den) ], Y.t[order(den)], type='p', pch=20, col=cls[order(den)], main='', xlab='', ylab='', cex=1.2, xlim=c(0, MAX), ylim=c(0, MAX))
abline(l.t, lty=1, lwd=4, xpd=F)
mtext(bquote(R^2 == .(format(summary(l.t)$r.squared, digits=2))), side=3, line=-1, padj=+0.5, cex=1.4, xpd=NA)
mtext(bquote(log[10](1+TPM) ~ group("[", .(S1), "]")), side=1, line=2, padj=+0.8, cex=1.8)
mtext(bquote(log[10](1+TPM) ~ group("[", .(S2), "]")), side=2, line=3, padj=+0.2, cex=1.8, las=0)
if (!is.null(figs.dir)){
dev.print(device=svg, file=paste0(figs.dir, '/scatterplot_tpms_', s1, '_', s2, '.svg'), width=16, height=16, bg='white', antialias='subpixel', pointsize=20, family='Arial')
}
}
#}}}
# load collected HLA typing results and keep best solution
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/hla_typing.RData')
h<-do.call(rbind, lapply(hla, function(x){ x[1, ] }))[, 1:6]
h$bid<-rownames(h)
h<-data.table(h)[ order(A1, A2, B1, B2, C1, C2) ]
h[, hla:=paste(A1, A2, B1, B2, C1, C2, sep='_')]
# load sample metadata
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/metadata.RData')
# load count data
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/featureCounts.RData')
# indicate the identical HLA types
h[hla %in% names(table(hla)[ table(hla)>1]), ]
# scatterplot of identical HLA types
scatterplots('CB-SKNAS-TR-MYCN-120h-ETOH3', 'CB-SKNAS-TR-MYCN-120h-Tet1', figs.dir='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/figures/', trim.name.root='CB-SKNAS-TR-MYCN-120h-')
meta[ bid %in% c('CB2019-11-R01', 'CB3037-11-R01') ]
# check HLA types with the other SKNAS samples
h.this<-h
m.this<-meta
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/hla_typing.RData')
h<-do.call(rbind, lapply(hla, function(x){ x[1, ] }))[, 1:6]
h$bid<-rownames(h)
h<-data.table(h)[ order(A1, A2, B1, B2, C1, C2) ]
h[, hla:=paste(A1, A2, B1, B2, C1, C2, sep='_')]
h.prev<-h[ grep('CB-SKNAS-TR', bid) ]
rm(h, hla)
#}}}
# [neuroblastoma-specific genes expression] MYCN, PHOX2B, ALK, BIRC5, CCND1, NTRK1, NRAS
#{{{
rm(list=ls())
library(GenomicAlignments)
library(rtracklayer)
library(data.table)
library(gplots)
library(RColorBrewer)
library(extrafont) # first time used need to run: font_import() , to load all for PDF device run: loadfonts(device='pdf')
loadfonts()
# functions
#{{{
genes_barplot<-function(G=c(''), names.trim='', plot.dir='', order.genes=T){
source('~/bio/lib/trim_text.R')
# identify gene_id for given gene_name
gid<-data.frame(mcols(hsa[ hsa$gene_name %in% G])[, c('gene_id', 'gene_name')])
# isolate genes of interest
# add gene_name
# sort by gene_name and bid
# compute log10(1+TPM)
x<-fe[ gene_id %in% hsa$gene_id[ hsa$gene_name %in% G ] ]
x$gene_name<-gid$gene_name[ match(x$gene_id, gid$gene_id) ]
x<-x[, c('bid', 'gene_name', 'tpm')][ order(gene_name, bid) ]
x$tpm<-log10(1+x$tpm)
# trim patient bids
#x[, bid:=sub('-11-R01$', '', bid)]
# convert from:
#
# BID , GENE_NAME , TPM
#
# to:
#
# BID , GENE_NAME_TPM
#
# for any number of genes provided!
x<-dcast(x, bid ~ gene_name, value.var='tpm')
y<-as.matrix(x[, -1])
rownames(y)<-x$bid
x<-y
rm(y)
if(order.genes){
x<-x[, order(colMeans(x), decreasing=T), drop=F]
}
# define a color for each gene
cl<-setNames(colorRampPalette(brewer.pal(8,'Dark2'))(ncol(x)), colnames(x))
if(names.trim!=''){
original.names<-rownames(x)
rownames(x)<-sub(names.trim, '', rownames(x))
}
# barplot
YTICK<-pretty(c(0, max(x)), 5)
YMAX<-tail(YTICK, 1)
par(mar=c(2.5, 8.0, 4.0, 0.0), mgp=c(3,1,0), oma=c(0,0,0,0), las=1, xpd=NA, bty='n', cex.lab=2.4, cex.axis=2.4)
bp<-barplot(t(x), beside=T, plot=F)
plot(0:1, 0:1, type='n', ylim=c(0, YMAX), xlim=range(bp)+c(-1,2), axes=F, ann=F, xaxs='i', yaxs='i')
bp<-barplot(t(x), beside=T, border='white', col=cl[colnames(x)], axisnames=F, xlab='', ylab='', las=1, yaxt='n', ylim=range(YTICK), add=T)
axis(2, at=YTICK, line=0, cex.axis=2.4)
mtext(text=trim_text(rownames(x), 12), side=1, line=1, at=colMeans(bp), las=0, adj=0.5, cex=1.8)
mtext(expression(log[10](1+TPM)), side=2, line=5, padj=+0.1, las=0, cex=2.4)
legend(x=par('usr')[2]*0.05, y=par('usr')[4]*1.15, legend=names(cl) , col=cl, bty='n', lty=1, lwd=18, cex=2.0, y.intersp=0.60, x.intersp=0.1, seg.len=0.1)
# save only if directory is given
if(nchar(plot.dir)>0){
dev.print(device=svg, file=paste0(plot.dir, '/barplot_', paste0(G, collapse='_'), '.svg'), width=20, height=14, bg='white', antialias='subpixel', pointsize=20, family='Arial')
}
# replace original names
if(names.trim!=''){
rownames(x)<-original.names
}
return(x)
}
#}}}
# load annotation to identify gene_id from transcript_id
hsa<-import('/fast/groups/ag_schulte/work/reference/annotation/GRCh38/GRCh38.gencode.v30.gtf')
hsa<-hsa[ hsa$type %in% 'gene' ]
mcols(hsa)<-mcols(hsa)[, c('gene_id', 'gene_name', 'gene_type', 'level')]
# load featureCount data
# unlist them to data.table
# add TPMs
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/featureCounts.RData')
fe<-unlist(totalrna)
fe$bid<-sub('\\.[0-9]*$', '', rownames(fe))
rownames(fe)<-NULL
fe<-data.table(fe[, c('bid', 'gene_id', 'length', 'counts')])
fe<-fe[, tpm:=1e6*counts/length/sum(counts/length), by=.(bid)]
# stacked barplot
x11(width=20, height=14, title='', bg='white', type='cairo', pointsize=20, antialias='subpixel', family='Arial')
GENES<-c('MYCN', 'PHOX2B', 'ALK', 'BIRC5', 'CCND1', 'NTRK1', 'NRAS')
s<-genes_barplot(GENES, names.trim='CB-SKNAS-TR-MYCN-120h-', plot.dir='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/BATCH_202004/figures')
#}}}
###################################
#
#
# differential expression analysis
# enrichment analysis
#
#
###################################
# [run once] Prepare circRNAs and genes for the analysis. We compute:
#
# gene TPMs, raw counts and variance-stabilized log2-transformed counts
# circRNA raw counts and variance-stabilized log2-transformed counts based on size factors computed from gene counts
#
# PCA for genes and circRNAs is done THROUGHOUT THE SAMPLES using centered but not scaled variance-stabilized
# (and log2-transformed) counts
#
#{{{
rm(list=ls())
library(GenomicAlignments)
library(rtracklayer)
library(data.table)
library(DESeq2)