-
Notifications
You must be signed in to change notification settings - Fork 1
/
1_circRNA.R
3272 lines (2539 loc) · 156 KB
/
1_circRNA.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
#
###############################################################################################################
################################################################################
#
#
# define the neuroblastoma specific circRNA cohort and everything related to it
#
#
################################################################################
# [run once] define the circRNA cohort that will be used throughout the analysis:
#
# remove failed samples and keep only neuroblastoma tumors
# keep only exon-exon circRNAs (trans-gene + chrM + chrY circRNAs have been removed already)
# allow +-1nt corresponding exon boundary discrepancies for the exons with the donor and acceptor sites provided the gene_id matches
# keep only circRNAs supported by at least 25% of samples OR have backspliced junction coverage > 20 in at least three samples
#
# we query the circRNA and corresponding gene expression across neuroblastoma tumors, human brain tissue and various tumors
#
# N.B. circRNA CPMs are based on the total counts on gene features
#
# For the different cell models we identify the same unified cohort of circRNAs
#
#{{{
rm(list=ls())
library(GenomicFeatures)
library(rtracklayer)
library(data.table)
library(extrafont) # first time used need to run: font_import() , to load all for PDF device run: loadfonts(device='pdf')
loadfonts()
source('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/lib/load_circ_gene_expression.R')
# load circRNAs
# remove failed samples and keep only tumors (Pilot samples are removed as well)
# keep only the exon-exon circRNAs
# add circ_name
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/circRNAs_CIRI2.RData')
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/metadata.RData')
meta<-meta.tum[ !(failed) ]
CIRCS<-circ[ circ$bid %in% meta$bid & circ$region %in% 'exon' ]
META<-meta[ bid %in% CIRCS$bid ]
CIRCS$circ_name<-paste0(CIRCS$gene_id, '|', CIRCS$gene_name,'_', as.character(seqnames(CIRCS)),as.character(strand(CIRCS)), start(CIRCS), '-', end(CIRCS))
CIRCS.all<-CIRCS
CIRCS<-unique(CIRCS)
mcols(CIRCS)<-mcols(CIRCS)[, c('gene_name', 'gene_id', 'circ_name')]
rm(circ, meta.tum, meta.cel, meta.prefailed, trans)
# load the annotated exons
# enforce the seqlevels of circRNAs (remove chrM)
txdb<-loadDb('/fast/groups/ag_schulte/work/reference/annotation/GRCh38/TxDb_GRCh38.gencode.v30.RData')
EXONS<-exons(txdb, columns=c('EXONNAME', 'GENEID'))
colnames(mcols(EXONS))<-c('exon_name', 'gene_id')
seqlevels(EXONS, pruning.mode='coarse')<-seqlevels(CIRCS)
stopifnot( all(lengths(EXONS$gene_id)==1) )
EXONS$gene_id<-unlist(EXONS$gene_id)
rm(txdb)
# allow for +-1nt discrepancies with the exon boundaries provided circRNA and donor/acceptor exon gene_ids match!
#{{{
# allow +-1nt discrepancy at the donor site
ov<-findOverlaps(EXONS, resize(CIRCS, 2, fix='start'), type='any')
ex<-EXONS[ queryHits(ov) ]
ci<-CIRCS[ subjectHits(ov) ]
ov<-ov[ ex$gene_id==ci$gene_id & ( ( as.logical( strand(ci) %in% '+') & abs(start(ex)-start(ci))<=1 ) |
( as.logical( strand(ci) %in% '-') & abs(end(ex)-end(ci))<=1 ) ) ]
f<-CIRCS[ setdiff(seq_along(CIRCS), subjectHits(ov)) ] # inspect those dropping out
CIRCS<-CIRCS[ unique(subjectHits(ov)) ]
rm(f,ov,ex,ci)
# allow +-1nt discrepancy at the acceptor site
ov<-findOverlaps(EXONS, resize(CIRCS, 2, fix='end'), type='any')
ex<-EXONS[ queryHits(ov) ]
ci<-CIRCS[ subjectHits(ov) ]
ov<-ov[ ex$gene_id==ci$gene_id & ( ( as.logical( strand(ci) %in% '+') & abs(end(ex)-end(ci))<=1 ) |
( as.logical( strand(ci) %in% '-') & abs(start(ex)-start(ci))<=1 ) ) ]
f<-CIRCS[ setdiff(seq_along(CIRCS), subjectHits(ov)) ] # inspect those dropping out
CIRCS<-CIRCS[ unique(subjectHits(ov)) ]
rm(f,ov,ex,ci,EXONS)
#}}}
# keep only the circRNAs supported by at least 25% of samples OR have counts > 20 in at least three of the samples
x<-data.table(circ_name=CIRCS.all$circ_name, bid=CIRCS.all$bid, jc_count=CIRCS.all$jc_count)[ circ_name %in% CIRCS$circ_name ]
x<-dcast(x, bid ~ circ_name, value.var='jc_count')[, bid:=NULL]
keep<-unlist(c(as.data.frame(x[, lapply(.SD, function(x){ sum(is.na(x))/.N<0.75 | sum(x>20, na.rm=T)>=3 })])))
nf<-CIRCS.all[ CIRCS.all$circ_name %in% names(keep[ keep ]) ]
nf<-nf[ order(nf$jc_count, decreasing=T) ]
nf[ nf$gene_name %in% 'ARID1A' ] # chr1:26729651-26732792
nf[ nf$gene_name %in% 'SETD3' ] # chr14:99458279-99465813
nf[ nf$gene_name %in% 'EYA1' ] # chr8:71299047-71334174
nf[ nf$gene_name %in% 'TET2' ] # chr4:105233897-105237351
nf[ nf$gene_name %in% 'SMARCA5' ] # chr4:143543509-143543972
nf[ nf$gene_name %in% 'LINC00632' ] # CDR1as == LINC00632 chrX:140783175-140784659
nf[ nf$gene_name %in% 'HIPK3' ] # chr11:33286413-33287511
nf[ nf$gene_name %in% 'ATRX' ] # chrX:77652114-77656653
nf[ nf$gene_name %in% 'HUWE1' ] # chrX:53614534-53615835, chrX:53645311-53654131
nf[ nf$gene_name %in% 'EZH2' ] # chr7:148846470-148847305
nf[ nf$gene_name %in% 'VRK1' ] # chr14:96833467-96860735
nf[ nf$gene_name %in% 'CHD7' ] # chr8:60794986-60801593, chr8:60741259-60743097
nf[ nf$gene_name %in% 'KDM1A' ] # chr1:23030469-23059167, chr1:23030469-23050520
CIRCS.all<-nf
rm(nf,keep,x)
# unique calls (removing bid, count information since it is irrelevant)
CIRCS<-unique(CIRCS.all)
mcols(CIRCS)<-mcols(CIRCS)[, c('gene_id', 'gene_name', 'circ_name')]
# keep the unique genes also making sure to include Clara's housekeeping gene as well
GENES<-unique(mcols(CIRCS)[, c('gene_id', 'gene_name')])
if(nrow( GENES[ GENES$gene_id %in% 'ENSG00000073578.17' ,] )==0){
GENES<-rbind(GENES, DataFrame(gene_id=c('ENSG00000073578.17'), gene_name=c('SDHA')))
}
# import circRNA and gene expression in CPMs
l<-load_circ_gene_expression(CIRCS, GENES, META, nb.tumors.only=T, vt.tumors.only=T, gene.tpm=F)
# inflate
nb.circs<-l$nb$circs
nb.genes<-l$nb$genes
nb.meta<-l$nb$meta
hb.circs<-l$hb$circs
hb.genes<-l$hb$genes
hb.meta<-l$hb$meta
vt.circs<-l$vt$circs
vt.genes<-l$vt$genes
vt.meta<-l$vt$meta
rm(l)
# save
save(CIRCS.all, CIRCS, GENES, hb.circs, hb.genes, hb.meta, nb.circs, nb.genes, nb.meta, vt.circs, vt.genes, vt.meta, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues.RData')
# summarize circRNAs into an HTML table and Excel sheet
#{{{
rm(list=ls())
library(GenomicFeatures)
library(rtracklayer)
library(data.table)
library(openxlsx)
# functions
#{{{
granges2kable<-function(gr){
circ_pos<-paste0('[', as.character(seqnames(gr)), '(', as.character(strand(gr)),'):', start(gr), '-', end(gr),
'](http://www.ensembl.org/Homo_sapiens/Location/View?r=',
sub('^chr', '', as.character(seqnames(gr))), ':', start(gr), '-', end(gr),
')')
gene_name<-paste0('[', gr$gene_name, '](http://www.genecards.org/cgi-bin/carddisp.pl?gene=', gr$gene_name, '&keywords=', gr$gene_name, ')')
gene_name[ grep('\\[NA\\]', gene_name) ]<-'not_annotated'
gr.table<-data.table(
locus=circ_pos,
#strand=paste0('\\', as.character(strand(gr))),
width=width(gr),
gene_name=gene_name,
jc_count=gr$jc_count,
non_jc_count=gr$non_jc_count,
ratio=gr$ratio,
region=gr$region,
bid=gr$bid
)
# unlist all lists and convert to comma-separated strings, make sure to add space so kable and line-break them
gr.table[, ':='(locus=locus,
width=width,
gene_name=gene_name,
jc_count=sapply(jc_count, paste, sep='', collapse=', '),
non_jc_count=sapply(non_jc_count, paste, sep='', collapse=', '),
ratio=sapply(ratio, paste, sep='', collapse=', '),
region=region,
bid=sapply(bid, paste, sep='', collapse=', '))]
return(as.data.frame(gr.table))
}
#}}}
# load circRNAs
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues.RData')
# summarize duplicate calls across samples
l<-CIRCS.all
l<-data.table(as.data.frame(l))[, .(jc_count=list(jc_count), non_jc_count=list(non_jc_count), ratio=list(ratio), bid=list(bid)), by=.(seqnames, start, end, strand, gene_name, gene_id, region, circ_name)]
l<-GRanges(as.data.frame(l))
l$jc_count<-as(l$jc_count, 'CompressedList')
l$non_jc_count<-as(l$non_jc_count, 'CompressedList')
l$ratio<-as(l$ratio, 'CompressedList')
l$bid<-as(l$bid, 'CompressedList')
# create HTML table with proper links
l.table<-granges2kable(l)
# save as R object
save(l, l.table, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues_summarized.RData')
# save as Excel sheet after converting list columns to character vectors
x<-data.table(cbind(data.frame(position=paste0(as.character(seqnames(l)), '(', as.character(strand(l)),'):', start(l), '-', end(l))), as.data.frame(l)[, -c(1:3,5)]))
x[, ':='(jc_count=sapply(jc_count, paste, sep='', collapse=','),
non_jc_count=sapply(non_jc_count, paste, sep='', collapse=','),
ratio=sapply(ratio, paste, sep='', collapse=','),
bid=sapply(bid, paste, sep='', collapse=','))]
write.xlsx(as.data.frame(x), file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues_summarized.xlsx', col.names=T, row.names=F, sheetName='summarized circRNAs', append=F)
#}}}
# identify the same circRNA cohort in cell models
#{{{
rm(list=ls())
library(GenomicFeatures)
library(rtracklayer)
library(data.table)
library(extrafont) # first time used need to run: font_import() , to load all for PDF device run: loadfonts(device='pdf')
loadfonts()
# identify cell models
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/metadata.RData')
meta<-meta.cel[ ! (failed) & !is.na(cell_model) ]
rm(meta.tum, meta.cel, meta.prefailed)
# load unified circRNAs based on the neuroblastoma tumors and keep their names
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues.RData')
circ_name<-CIRCS$circ_name
rm(list=ls(pattern='\\.meta|\\.circs|\\.genes|GENES|CIRCS'))
# load all CIRI2 circRNAs
# keep those defined by the tumor cohort found in the cell models
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/circRNAs_CIRI2.RData')
CIRCS.all<-circ[ circ$bid %in% meta$bid & circ$region %in% 'exon' ]
CIRCS.all$circ_name<-paste0(CIRCS.all$gene_id, '|', CIRCS.all$gene_name,'_', as.character(seqnames(CIRCS.all)),as.character(strand(CIRCS.all)), start(CIRCS.all), '-', end(CIRCS.all))
CIRCS.all<-CIRCS.all[ CIRCS.all$circ_name %in% circ_name ]
rm(circ,circ_name)
# save
save(CIRCS.all, meta, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues_cell_models.RData')
#}}}
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues.RData
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues_summarized.{RData,xlsx}
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues_cell_models.RData
# [run once] construct circRNA sequences and controls:
#
# circRNA sequences:
#
# we identify all exons within a given circRNA of identical gene_id as the circRNA and among overlapping exons we take the longest
# we set the first/last exon boundaries to be identical to the circRNA boundaries, irrespective of possible +-1nt discrepancies
#
# controls:
#
# identify all exons downstream of the last circRNA exon and upstream of the first circRNA exon
# take the longest among overlapping ones in both lists
# take the upstream or downstream list that produces the longest spliced sequence
# when possible trim the spliced sequence to identical length as the circRNA sequence by fixing the center (symmetrical trimming)
# discard empty lists when there is no upstream or downstream exon
#
#{{{
rm(list=ls())
library(data.table)
library(GenomicFeatures)
library(rtracklayer)
library(BSgenome.Hsapiens.UCSC.hg38)
# load circRNAs
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues.RData')
rm(list=c(ls(pattern='[nhv][tb]\\.*'), 'GENES', 'CIRCS.all'))
# extract all annotated exons
# take unique exon entries per gene
txdb<-loadDb('/fast/groups/ag_schulte/work/reference/annotation/GRCh38/TxDb_GRCh38.gencode.v30.RData')
EXONS<-unlist(exonsBy(txdb, 'gene'))
EXONS$gene_id<-names(EXONS)
names(EXONS)<-NULL
x<-data.table( seqnames=as.character(seqnames(EXONS)), strand=as.character(strand(EXONS)), start=start(EXONS), end=end(EXONS), exon_name=EXONS$exon_name, gene_id=EXONS$gene_id)[, ex:=paste(seqnames, strand, start, end, sep='_')][, .(exon_name=exon_name[ !duplicated(ex) ], ex=ex[ !duplicated(ex) ]), by=.(gene_id)]
EXONS<-EXONS[ EXONS$exon_name %in% x$exon_name ]
mcols(EXONS)<-mcols(EXONS)[, 'gene_id', drop=F]
rm(x)
# [~10min] circRNA sequences
#{{{
# At this point the group of circRNAs has +-1nt agreement with the donor/acceptor exon boundaries,
# so we identify now all exons in between making sure again that the gene_ids match
ov<-findOverlaps(EXONS, resize(CIRCS, width(CIRCS)+2, fix='center'), select='all', type='within')
ov<-ov[ EXONS$gene_id[ queryHits(ov) ]==CIRCS$gene_id[ subjectHits(ov) ] ]
print(CIRCS[ setdiff(seq_along(CIRCS), subjectHits(ov)) ]) # there should not be any circRNAs rejected at this point
# [<7min] group exons by circRNA
# reverse the ordering for minus strand exons in order for extractTranscriptSeqs() to work properly
# keep all non-overlapping and the longest among overlapping
EX<-split(EXONS[queryHits(ov)], subjectHits(ov))
CIRCS.exons<-GRangesList()
for(n in seq_along(EX)){
X<-EX[[n]]
R<-CIRCS[ as.integer(names(EX)[n]) ]
M<-as.logical(strand(X)[1]=='-') # minus strand?
# reverse the order if on minus strand
if(M){
X<-X[ order(start(X), decreasing=T) ]
}
# find out if there are overlapping exons and take the longest
o<-findOverlaps(X, X, type='any', select='all')
if(!all(queryHits(o)==subjectHits(o))){
o<-data.frame(o[ queryHits(o)<subjectHits(o) ])
w<-width(X)
# pairwise comparison of indices, if one exon overlaps many then sequentially the shortest is always discarded, so the same
# index might appear multiple times in the list to discard but this is fine
X<-X[-apply(o, 1, function(x){ x[ which.min(w[x]) ] })]
}
# if on plus (minus) strand make sure the start (end) of the first (last) exon and the end (start) of the last (first) exon are identical
# to those of the corresponding circRNA
if(!M){
start(X[1])<-start(R)
end(X[length(X)])<-end(R)
} else {
end(X[1])<-end(R)
start(X[length(X)])<-start(R)
}
CIRCS.exons[[n]]<-X
}
names(CIRCS.exons)<-names(EX)
stopifnot( length(CIRCS.exons)==length(CIRCS) ) # split() has re-ordered them by ascending order of queryHits(), i.e. CIRCS order
rm(ov,n,EX)
# check number of gene_ids per circRNA group of exons
g<-lapply(CIRCS.exons, function(x){ unique(x$gene_id) })
table(lengths(g))
stopifnot( all(lengths(g)==1) )
stopifnot( all.equal( CIRCS$gene_id, unname(unlist(g)) ) )
rm(g)
# get the circRNA sequences
#
# ----->!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<-----
# ----->!!!!! !!!!!<-----
# ----->!!!!! extractTranscriptSeqs() pastes together exons sequences IN THE ORDER THEY APPEAR !!!!!<-----
# ----->!!!!! exonsBy(TxDb, 'tx') orders exons by rank which for minus-strand transcripts is !!!!!<-----
# ----->!!!!! from right to left so the pasting would result in the correct transcript sequence !!!!!<-----
# ----->!!!!! !!!!!<-----
# ----->!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<-----
#
names(CIRCS.exons)<-CIRCS$circ_name
CIRCS.exons.seqs<-extractTranscriptSeqs(BSgenome.Hsapiens.UCSC.hg38, CIRCS.exons)
#}}}
# [~10min] control sequences
#{{{
CIRCS.controls<-endoapply(CIRCS.exons, function(X){
ex<-EXONS[ EXONS$gene_id %in% X$gene_id[1] ];
L<-length(ex);
if (as.logical(strand(ex)[1]=='-')){
ex<-ex[ order(start(ex), decreasing=T) ]
};
# first and last circRNA exons are enough to identify the boundaries
# this will work for one-exon circRNAs as well, since first and last will be identical in this case
o<-findOverlaps(X[c(1, length(X))], ex, select='all', type='any' )
up<-subjectHits(o)[1]-1
down<-subjectHits(o)[2]+1
ex.up<-ex.down<-GRanges()
if(up>0){
ex.up<-ex[1:up]
w<-width(ex.up);
# keep longest exons among overlapping exons
o<-findOverlaps(ex.up, ex.up, type='any', select='all');
if(!all(queryHits(o)==subjectHits(o))){
o<-data.frame(o[ queryHits(o)<subjectHits(o) ]);
ex.up<-ex.up[-apply(o, 1, function(x){ x[ which.min(w[x]) ] })]
}
};
if(down<=L){
ex.down<-ex[down:L]
w<-width(ex.down);
# keep longest exons among overlapping exons
o<-findOverlaps(ex.down, ex.down, type='any', select='all');
if(!all(queryHits(o)==subjectHits(o))){
o<-data.frame(o[ queryHits(o)<subjectHits(o) ]);
ex.down<-ex.down[-apply(o, 1, function(x){ x[ which.min(w[x]) ] })]
}
};
if(sum(width(ex.up))>=sum(width(ex.down))){
return(ex.up)
} else {
return(ex.down)
};
})
# only ENSG00000281508.1|CDR1_chrX+140783176-140784660 drops out as expected there are no upstream/downsteam exons available
names(CIRCS.controls[ lengths(CIRCS.controls)==0 ])
CIRCS.controls<-CIRCS.controls[ lengths(CIRCS.controls)>0 ]
# get the control sequences
#
# ----->!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<-----
# ----->!!!!! !!!!!<-----
# ----->!!!!! extractTranscriptSeqs() pastes together exons sequences IN THE ORDER THEY APPEAR !!!!!<-----
# ----->!!!!! exonsBy(TxDb, 'tx') orders exons by rank which for minus-strand transcripts is !!!!!<-----
# ----->!!!!! from right to left so the pasting would result in the correct transcript sequence !!!!!<-----
# ----->!!!!! !!!!!<-----
# ----->!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<-----
#
CIRCS.controls.seqs<-extractTranscriptSeqs(BSgenome.Hsapiens.UCSC.hg38, CIRCS.controls)
#}}}
# statistics of circRNA sequence lengths vs control sequence lengths
x<-CIRCS.exons.seqs[ names(CIRCS.controls.seqs) ]
y<-CIRCS.controls.seqs
d<-width(x) - width(y)
summary(d)
#
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# -75782.000 -7728.500 -4941.000 -5816.729 -2927.000 8654.000
hist( d, breaks=100, xlim=c(-4e4, 2e4)) # most of control sequences are much larger than the circRNA sequences
# resize control sequences to circRNA length if possible
i<-IRanges(start=1, end=width(CIRCS.controls.seqs))
ir<-resize(i, fix='center', width=width(CIRCS.exons.seqs[ names(CIRCS.controls.seqs) ]))
wrong<-start(ir)<=0 | end(ir)>width(i) # out of bound resizing either at the left or at the right
ir[ wrong ]<-i[ wrong ] # should be corrected by replacing it with the original ranges
CIRCS.controls.seqs.resized<-unlist(extractAt(CIRCS.controls.seqs, as(ir, 'IRangesList')))
x<-CIRCS.exons.seqs[ names(CIRCS.controls.seqs.resized) ]
y<-CIRCS.controls.seqs.resized
d<-width(x) - width(y)
cat('Control sequences with identical length as circRNA sequences = ', sum(d==0), ' (', round(sum(d==0)/length(CIRCS.exons.seqs)*100, 1), '%)\n', sep='')
#
# Control sequences with identical length as circRNA sequences = 5104 (98.1%)
# save everything and export circRNA sequences and resized control sequences
save(CIRCS, CIRCS.exons, CIRCS.exons.seqs, EXONS, CIRCS.controls, CIRCS.controls.seqs, CIRCS.controls.seqs.resized, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_sequences.RData')
writeXStringSet(CIRCS.exons.seqs, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_sequences.fa', format='fasta')
writeXStringSet(CIRCS.controls.seqs.resized, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_controls_sequences.fa', format='fasta')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_sequences.RData
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_sequences.fa
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_controls_sequences.fa
# [run once] construct upstream and downstream intronic sequences of circRNAs and controls
#
# circRNA introns:
#
# we pick the longest upstream and downstream introns (>=15nts) in each case when available
#
# controls:
#
# we identify all introns (>=15nts) not overlapping with the circRNA and its upstream and downstream introns
# among overlapping introns in that list we take the longest
# we keep as many introns as possible until their cumulative length is as long as the cumulative length of the circRNA introns
#
#{{{
rm(list=ls())
library(data.table)
library(GenomicFeatures)
library(rtracklayer)
library(BSgenome.Hsapiens.UCSC.hg38)
# load circRNA sequences
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_sequences.RData')
# load reference
hsa<-import('/fast/groups/ag_schulte/work/reference/annotation/GRCh38/GRCh38.gencode.v30.gtf')
hsa<-hsa[ hsa$type %in% 'transcript' ]
mcols(hsa)<-mcols(hsa)[, c('type', 'gene_id', 'gene_name', 'gene_type', 'transcript_id', 'transcript_name', 'transcript_type')]
# extract all introns of all transcripts that have at least one
# keep only those that are at least 15nts long
txdb<-loadDb('/fast/groups/ag_schulte/work/reference/annotation/GRCh38/TxDb_GRCh38.gencode.v30.RData')
INTRONS<-intronsByTranscript(txdb, use.names=T)
seqlevels(INTRONS, pruning.mode='coarse')<-seqlevels(CIRCS) # if one hits the seqlevel, all will hit it
INTRONS<-unlist(INTRONS[lengths(INTRONS)>0])
INTRONS$transcript_id<-names(INTRONS)
names(INTRONS)<-NULL
INTRONS$gene_id<-hsa$gene_id[ match(INTRONS$transcript_id, hsa$transcript_id) ]
INTRONS<-INTRONS[ width(INTRONS)>=15 ]
# keep only introns of genes that produce our circRNAs
INTRONS<-INTRONS[ INTRONS$gene_id %in% CIRCS$gene_id ]
# identify the list of unique introns per gene
x<-data.table(data.frame(INTRONS))[, c('width', 'transcript_id', 'pos'):=list(NULL, NULL, paste(start, end, sep='-'))][, .(pos=unique(pos)), by=.(gene_id, seqnames,strand)][, c('start', 'end'):=tstrsplit(pos, '-', fixed=T)][, pos:=NULL]
INTRONS<-GRanges(seqnames=x$seqnames, strand=x$strand, ranges=IRanges(start=as.integer(x$start), end=as.integer(x$end)), gene_id=x$gene_id)
rm(x)
# CDR1as is in GENCODE v30 LINC00632 which does have introns defined, so nothing drops out
CIRCS[ CIRCS$gene_id %in% setdiff(CIRCS$gene_id, INTRONS$gene_id) ] # empty
# [~2min] identify upstream and downstream introns of circRNAs
#{{{
# plus strand 5' introns (upstream):
P<-CIRCS[ strand(CIRCS) %in% '+' ]
IN<-INTRONS[ strand(INTRONS)=='+' ]
end(IN)<-end(IN)+2 # move the intron end down by 2nts to make sure we hit the 5' donor site even if it is -1nt from the exon 5'
o<-findOverlaps(resize(IN, 1, fix='end'), resize(P, 2, fix='start'), type='any', select='all')
end(IN)<-end(IN)-2 # revert back to original ranges
o<-o[ IN[ queryHits(o) ]$gene_id==P[ subjectHits(o) ]$gene_id ]
P.UP<-unlist(GRangesList(lapply(split(queryHits(o), subjectHits(o)), function(n){ IN[n][which.max(width(IN[n]))] })))
P.UP$circ_name<-P[ as.integer(names(P.UP)) ]$circ_name
#
# plus strand 3' introns (downstream):
IN<-INTRONS[ strand(INTRONS)=='+' ]
start(IN)<-start(IN)-2 # move the intron start up by 2nts to make sure we hit the 3' acceptor site even if it is -1nt from the exon 3'
o<-findOverlaps(resize(IN, 1, fix='start'), resize(P, 2, fix='end'), type='any', select='all')
start(IN)<-start(IN)+2 # revert back to original ranges
o<-o[ IN[ queryHits(o) ]$gene_id==P[ subjectHits(o) ]$gene_id ]
P.DOWN<-unlist(GRangesList(lapply(split(queryHits(o), subjectHits(o)), function(n){ IN[n][which.max(width(IN[n]))] })))
P.DOWN$circ_name<-P[ as.integer(names(P.DOWN)) ]$circ_name
#
# minus strand 5' introns (upstream):
M<-CIRCS[ strand(CIRCS) %in% '-' ]
IN<-INTRONS[ strand(INTRONS)=='-' ]
start(IN)<-start(IN)-2 # move the intron end down by 2nts to make sure we hit the 5' donor site even if it is -1nt from the exon 5'
o<-findOverlaps(resize(IN, 1, fix='end'), resize(M, 2, fix='start'), type='any', select='all')
start(IN)<-start(IN)+2 # revert back to original ranges
o<-o[ IN[ queryHits(o) ]$gene_id==M[ subjectHits(o) ]$gene_id ]
M.UP<-unlist(GRangesList(lapply(split(queryHits(o), subjectHits(o)), function(n){ IN[n][which.max(width(IN[n]))] })))
M.UP$circ_name<-M[ as.integer(names(M.UP)) ]$circ_name
#
# minus strand 3' introns (downstream):
IN<-INTRONS[ strand(INTRONS)=='-' ]
end(IN)<-end(IN)+2 # move the intron start up by 2nts to make sure we hit the 3' acceptor site even if it is -1nt from the exon 3'
o<-findOverlaps(resize(IN, 1, fix='start'), resize(M, 2, fix='end'), type='any', select='all')
end(IN)<-end(IN)-2 # revert back to original ranges
o<-o[ IN[ queryHits(o) ]$gene_id==M[ subjectHits(o) ]$gene_id ]
M.DOWN<-unlist(GRangesList(lapply(split(queryHits(o), subjectHits(o)), function(n){ IN[n][which.max(width(IN[n]))] })))
M.DOWN$circ_name<-M[ as.integer(names(M.DOWN)) ]$circ_name
# merge plus and minus strands back together
CIRCS.introns.up<-c(P.UP, M.UP)
CIRCS.introns.down<-c(P.DOWN, M.DOWN)
names(CIRCS.introns.up)<-NULL
names(CIRCS.introns.down)<-NULL
rm(P.UP, P.DOWN, M.UP, M.DOWN, IN, P, M, o)
# announce to the world how many circRNAs with both up/down introns and how many with only up or only down
b<-length(intersect(intersect(CIRCS$circ_name, CIRCS.introns.up$circ_name), CIRCS.introns.down$circ_name))
u<-length(setdiff(CIRCS.introns.up$circ_name, CIRCS.introns.down$circ_name))
d<-length(setdiff(CIRCS.introns.down$circ_name, CIRCS.introns.up$circ_name))
n<-length(setdiff(setdiff(CIRCS$circ_name, CIRCS.introns.up$circ_name), CIRCS.introns.down$circ_name))
cat('Out of the', length(CIRCS), 'circRNAs:\n',
' ', b, '(', round(100*b/length(CIRCS), 2), '%) had both upstream and downstream introns\n',
' ', u, '(', round(100*u/length(CIRCS), 2), '%) had upstream only introns\n',
' ', d, '(', round(100*d/length(CIRCS), 2), '%) had downstream only introns\n',
' ', n, '(', round(100*n/length(CIRCS), 2), '%) had neither upstream nor downstream introns.\n')
#
# Out of the 5203 circRNAs:
# 5188 ( 99.71 %) had both upstream and downstream introns
# 5 ( 0.1 %) had upstream only introns
# 10 ( 0.19 %) had downstream only introns
# 0 ( 0 %) had neither upstream nor downstream introns.
rm(b,u,d)
# get the sequences
CIRCS.introns.up.seqs<-setNames(getSeq(BSgenome.Hsapiens.UCSC.hg38, CIRCS.introns.up), CIRCS.introns.up$circ_name)
CIRCS.introns.down.seqs<-setNames(getSeq(BSgenome.Hsapiens.UCSC.hg38, CIRCS.introns.down), CIRCS.introns.down$circ_name)
#}}}
# [~15min] identify control introns not overlapping with the circRNA introns or the circRNA putative exons
#{{{
CIRCS.controls.introns<-GRangesList()
for (g in seq_along(CIRCS.controls)){
n<-names(CIRCS.controls[g])
i<-INTRONS[ INTRONS$gene_id==CIRCS.controls[[g]]$gene_id[1] ]
# combine upstream intron, backspliced junction and downstream intron into one range
r<-reduce(c(CIRCS[ CIRCS$circ_name %in% n ],
CIRCS.introns.up[ CIRCS.introns.up$circ_name %in% n],
CIRCS.introns.down[ CIRCS.introns.down$circ_name %in% n]))
stopifnot(length(r)==1)
# find all the introns of this gene that do not overlap with the reduced range
o<-findOverlaps(r, i, type='any', select='all')
i<-i[-subjectHits(o)]
# find out if there are overlapping introns and take the longest
o<-findOverlaps(i, i, type='any', select='all')
if(!all(queryHits(o)==subjectHits(o))){
o<-data.frame(o[ queryHits(o)<subjectHits(o) ])
w<-width(i)
# pairwise comparison of indices, if one intron overlaps many then sequentially the shortest is always discarded, so the same
# index might appear multiple times in the list to discard but this is fine
i<-i[-apply(o, 1, function(x){ x[ which.min(w[x]) ] })]
}
if (length(i)==0){
CIRCS.controls.introns[[n]]<-i
next
}
# pick as many introns as possible of combined length at least as long as the combined length of the circRNA introns
w<-sum(width(c(CIRCS.introns.up[ CIRCS.introns.up$circ_name %in% n], CIRCS.introns.down[ CIRCS.introns.down$circ_name %in% n])))
i.w<-width(i)
o<-order(i.w, decreasing=T)
i<-i[o]
i.w<-cumsum(i.w[o])
o<-which(i.w>=w)[1]
if(!is.na(o)){
i<-i[1:o]
}
CIRCS.controls.introns[[n]]<-i
}
rm(g,n,i,r,o,w,i.w)
# unlist back to GRanges since each intron should have its own sequence and no sequence splicing should happen when we construct the sequences
CIRCS.controls.introns<-unlist(CIRCS.controls.introns)
CIRCS.controls.introns$circ_name<-names(CIRCS.controls.introns)
names(CIRCS.controls.introns)<-NULL
# define unique intron names by appending an index to the circ_name
x<-data.table(data.frame(circ_name=CIRCS.controls.introns$circ_name))[, .(n=seq_len(.N)), by=.(circ_name)]
stopifnot(all.equal( CIRCS.controls.introns$circ_name, x$circ_name ) )
CIRCS.controls.introns$intron_name<-x[, paste(circ_name, n, sep='_')]
# get the sequences
CIRCS.controls.introns.seqs<-setNames(getSeq(BSgenome.Hsapiens.UCSC.hg38, CIRCS.controls.introns), CIRCS.controls.introns$intron_name)
#}}}
# save
save(CIRCS.introns.up, CIRCS.introns.down, CIRCS.introns.up.seqs, CIRCS.introns.down.seqs, CIRCS.controls.introns, CIRCS.controls.introns.seqs, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns.RData')
writeXStringSet(CIRCS.introns.up.seqs, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns_up.fa', format='fasta')
writeXStringSet(CIRCS.introns.down.seqs, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns_down.fa', format='fasta')
writeXStringSet(CIRCS.controls.introns.seqs, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns_controls.fa', format='fasta')
#}}}
#
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns.RData
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns_up.fa
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns_down.fa
# => /fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_introns_controls.fa
######################################
#
#
# basic statistics and other analyses
#
#
######################################
# [CIRCOS plot + analysis] circRNA per chromosome localizations
#{{{
rm(list=ls())
library(GenomicFeatures)
library(rtracklayer)
library(data.table)
library(circlize)
library(ComplexHeatmap)
library(VariantAnnotation)
library(extrafont) # first time used need to run: font_import() , to load all for PDF device run: loadfonts(device='pdf')
loadfonts()
# [run once] create hg38 cytoband
# compute circRNA and gene number density per 1M of sequence
# compute circRNA/mRNA ratio per gene
# compute mean circular/(1+external junction) ratio per gene and per sample
#{{{
# load annotation
# exclude chrM and chrY
hsa<-import('/fast/groups/ag_schulte/work/reference/annotation/GRCh38/GRCh38.gencode.v30.gtf')
seqlevels(hsa, pruning.mode='coarse')<-setdiff(seqlevels(hsa), c('chrM', 'chrY'))
txs<-hsa[ hsa$type %in% 'transcript' ]
mcols(txs)<-mcols(txs)[, c('gene_id', 'gene_name', 'gene_type', 'transcript_id', 'transcript_name', 'transcript_type')]
hsa<-hsa[ hsa$type %in% 'gene' ]
mcols(hsa)<-mcols(hsa)[, c('gene_id', 'gene_name', 'gene_type')]
# GRCh38 cytoBand
# remove unplaced/decoy contigs, chrM, chrY
# order them by number (besides chrX) and by start position
# order chrX separately
cytoband<-fread('/data/genomes/GRCh38/GRCh38.cytoBand.tsv', header=T, sep='\t')
cytoband<-cytoband[ !grepl('_|chrM|chrY', seqnames) ][, index:=as.integer(sub('^chr', '', seqnames))][ order(index, start) ][, index:=NULL] # NAs introduced for chrX
cytoband[grep('chrX', seqnames)]<-cytoband[ grep('chrX', seqnames)][ order(seqnames, start) ]
cytoband<-cytoband[, c('start', 'end'):=list(as.numeric(start), as.numeric(end))]
cytoband.xlim<-cytoband[, .(start=min(start), end=max(end)), by=.(seqnames)]
# load summarized circRNAs
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_across_tissues_summarized.RData')
circs<-l
rm(l, l.table)
# compute density of circRNAs in 1Mb windows
circ.d<-cytoband[, .(length=tail(end, 1)), by=.(seqnames)] # chromosome lengths
circ.d<-circ.d[, .(start=list(seq(1, length, 1e6))), by=.(seqnames, length)]
circ.d<-circ.d[, .(start=unlist(start), end={i<-unlist(start)[-1]-1; append(i, length)}), by=.(seqnames)]
circ.d<-GRanges(seqnames=circ.d$seqnames, ranges=IRanges(start=circ.d$start, end=circ.d$end), n=rep(0, nrow(circ.d)))
ov<-findOverlaps(circs, circ.d, type='within', select='all')
m<-table(subjectHits(ov))
circ.d$n[ as.integer(names(m)) ]<-as.integer(m)
circ.d<-data.frame(circ.d)[, c('seqnames', 'start', 'end', 'n')]
rm(ov, m)
# count number of genes per Mb per chromosome
gene.d<-cytoband[, .(length=tail(end, 1)), by=.(seqnames)] # chromosome lengths
gene.d<-gene.d[, .(start=list(seq(1, length, 1e6))), by=.(seqnames, length)]
gene.d<-gene.d[, .(start=unlist(start), end={i<-unlist(start)[-1]-1; append(i, length)}), by=.(seqnames)]
gene.d<-GRanges(seqnames=gene.d$seqnames, ranges=IRanges(start=gene.d$start, end=gene.d$end), n=rep(0, nrow(gene.d)))
ov<-findOverlaps(hsa, gene.d, type='within', select='all')
m<-table(subjectHits(ov))
gene.d$n[ as.integer(names(m)) ]<-as.integer(m)
gene.d<-data.frame(gene.d)[, c('seqnames', 'start', 'end', 'n')]
rm(ov, m)
# compute number of circRNAs per gene and number of transcripts per gene
n<-data.table(data.frame(mcols(circs)[, c('gene_id', 'circ_name')]))[, .(n=.N), by=.(gene_id)]
circ.n<-hsa[ hsa$gene_id %in% n$gene_id ]
circ.n$number<-n[ match(circ.n$gene_id, gene_id), n]
n<-data.table(data.frame(mcols(txs)[, c('gene_id', 'transcript_id')]))[, .(n=.N), by=.(gene_id)]
gene.n<-hsa[ hsa$gene_id %in% n$gene_id ]
gene.n$number<-n[ match(gene.n$gene_id, gene_id), n]
rm(n)
# compute ratio of circRNA number/transcript number for the genes that give rise the circRNA(s)
g<-gene.n[ match(circ.n$gene_id, gene.n$gene_id) ]
stopifnot( all.equal( g$gene_id, circ.n$gene_id) )
circ.n$ratio<-circ.n$number/g$number
rm(g)
# annotate density peaks>10 for each chromosome and save
annot.d<-setNames(vector('list', length(unique(circ.d$seqnames))), unique(circ.d$seqnames))
for (chr in names(annot.d)){
p<-subset(circ.d, seqnames %in% chr & n>10)
if(nrow(p)==0){ next }
p<-GRanges(seqnames=p$seqnames, ranges=IRanges(start=p$start, end=p$end), n=p$n)
ov<-findOverlaps(circs, p, type='within', select='all')
ov<-split(queryHits(ov), subjectHits(ov))
ov<-lapply(ov, function(x){ unique(circs[ x ]$gene_name) })
p$gene_names<-ov
annot.d[[chr]]<-p
}
annot.d<-annot.d[ lengths(annot.d)>0 ]
annot.d<-unlist(GRangesList(annot.d))
names(annot.d)<-NULL
annot.d$gene_names<-as(annot.d$gene_names, 'CompressedCharacterList')
rm(chr,p,ov)
# generate sids out of the bids that will match the genomics ids
circs$sid<-as(lapply(circs$bid, function(s){ sub('-11.*$', '', s) }), 'CompressedList')
# identify the circRNAs residing on ratio peaks
circs$peaks<-F
circs$peaks[ circs$gene_name %in% circ.n[ circ.n$ratio>1.2]$gene_name ]<-T
table(circs$peaks)
#
# FALSE TRUE
# 4837 366
# load circular and linear junction counts
# convert all NA to zero
# compute mean ratio of circular/(1+external linear) counts per gene and across samples
#
# N.B. ignore the warning about "invalid .internal.selfref detected"
# N.B. some genes with not external junctions available drop out and should become NAs (NOT ZEROS!)
#
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_linear_vs_circular_collected_results.RData')
lin.cir<-lin.cir[ unique(unlist(circs$bid)) ]
r<-unlist(lin.cir)[ circ_name %in% circs$circ_name ]
r[is.na(c.count), c.count:=0]
r[is.na(l.count.out), l.count.out:=0]
r[is.na(l.count.out.max), l.count.out.max:=0]
r<-r[, expression_ratio:=c.count/(1+l.count.out)][, .(expression_ratio=mean(expression_ratio)), by=.(bid, gene_name)][, .(expression_ratio=mean(expression_ratio)), by=.(gene_name)]
circ.n$expression_ratio<-r[ match(circ.n$gene_name, gene_name), expression_ratio]
rm(r, lin.cir)
# anything interesting?
circ.n[ which(circ.n$expression_ratio>2) ]$gene_name # GUSBP1, LINC00632
# save
save(annot.d, gene.d, circ.d, gene.n, circ.n, circs, cytoband, cytoband.xlim, hsa, txs, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/figures/circos_circRNA_density.RData')
#}}}
# load back
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/figures/circos_circRNA_density.RData')
# load all CNVs into a GRanges object
# load the estimated tumor ploidy
# split CNVs per patient
# complement the CNV gaps with the tumor ploidy as copy-number in order to form full genome copy-number calls
#{{{
# identify all CNV calls
cn<-system2('find', args=c('/fast/projects/peifer_wgs/work/work/2017-09-25_BerlinWGS_hg38_jt/freec/ -maxdepth 2 -wholename \'*/*bam_CNVs\''), stdout=T)
names(cn)<-sub('^.*/freec/([^/]*)/.*$', '\\1', cn)
# remove CB2009 which failed in totalRNA-seq
cn<-cn[ setdiff(names(cn), 'CB2009') ]
cn<-cn[ order(names(cn)) ]
# collect the CNVs
p<-fread(sub('_CNVs$', '_info.txt', cn[1]), header=F, col.names=c('metric', 'value'))[ metric %in% 'Output_Ploidy', as.integer(value)]
cnv<-fread(cn[1], header=F, sep='\t', col.names=c('seqnames', 'start', 'end', 'copies', 'call'))[, call:=NULL][, seqnames:=paste0('chr', seqnames)][, sid:=names(cn[1])][, ploidy:=p]
for(n in 2:length(cn)){
p<-fread(sub('_CNVs$', '_info.txt', cn[n]), header=F, col.names=c('metric', 'value'))[ metric %in% 'Output_Ploidy', as.integer(value)]
cnv<-rbind(cnv, fread(cn[n], header=F, sep='\t', col.names=c('seqnames', 'start', 'end', 'copies', 'call'))[, call:=NULL][, seqnames:=paste0('chr', seqnames)][, sid:=names(cn[n])][, ploidy:=p])
}
cnv<-GRanges(seqnames=cnv$seqnames, strand='*', ranges=IRanges(start=cnv$start+1, end=cnv$end), data.frame(cnv[, c('copies', 'sid', 'ploidy'), with=F]))
seqlevels(cnv)<-c(paste0('chr', 1:22), 'chrX')
cnv<-sort(cnv)
rm(cn,n,p)
# add chromosome lengths info to the GRanges and split by patient
seqlengths(cnv)<-cytoband.xlim[ match(names(seqlengths(cnv)), seqnames), end]
cnv<-GRangesList(split(cnv, cnv$sid))
cnv<-endoapply(cnv, function(x){
g<-gaps(x)
g<-g[ strand(g) %in% '*' ]
copies<-rep(unique(x$ploidy), length(g))
sid<-rep(unique(x$sid), length(g))
mcols(g)<-DataFrame(copies=copies, sid=sid, ploidy=copies)
sort(c(x, g)) # checked it and it works!
})
#}}}
# load circular and linear junction counts
# compute log10(1+CPMs) for the external linear junctions to estimate host-gene expression
#
# N.B. the list of genes with external junctions is a subset of the list of genes with circRNAs
#
#{{{
# load the junction quantification results and keep only the tumors
load('/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/circRNAs_linear_vs_circular_collected_results.RData')
lin.cir<-lin.cir[ unique(unlist(circs$bid)) ]
# compute the across isoforms mean external linear junction CPMs
x<-do.call(rbind, lin.cir)[, c('ci.cpm', 'li.cpm'):=list(c.count/total*1e6, l.count.out/total*1e6)]
li.cpm<-dcast(x, bid ~ gene_name, value.var='li.cpm', fun.aggregate=mean, na.rm=T)
li.cpm<-t(data.frame(li.cpm[, -1], row.names=li.cpm[, bid], check.names=F))
rm(x)
# convert bids to sids
colnames(li.cpm)<-sub('-11.*$', '', colnames(li.cpm))
stopifnot( length(setdiff(unique(unlist(circs$sid)), colnames(li.cpm)))==0 )
# transform to log10(1+CPM)
li.cpm<-log10(1+li.cpm)
#}}}
# recycle
x11(width=14, height=14, title='', bg='white', type='cairo', pointsize=20, antialias='subpixel', family='Arial')
# CIRCOS plot with densities per 1M
#{{{
circos.clear()
circos.par('start.degree'=90, 'gap.degree'=2, 'track.margin'=c(0.01,0.01), 'cell.padding'=c(0.0,0.05,0.00,0.05), 'unit.circle.segments'=500)
circos.initializeWithIdeogram(as.data.frame(cytoband), sort.chr=F)
circos.genomicTrackPlotRegion(circ.d, panel.fun=function(region, value, ...){
circos.genomicLines(region, value, area=T, baseline=0, col='lightblue4', border='lightblue4', ...)
}, track.height=0.3, bg.border=NA)
circos.text(cytoband.xlim[ seqnames %in% 'chrX', end]*1.2, 28.0, 'circRNAs', sector.index='chrX', facing='bending', cex=1.4, col='lightblue4', niceFacing=T, font=2)
circos.genomicTrackPlotRegion(gene.d, panel.fun=function(region, value, ...){
circos.genomicLines(region, value, area=T, baseline=0, col='lightgoldenrod3', border='lightgoldenrod3', ...)
}, track.height=0.3, bg.border=NA)
circos.text(cytoband.xlim[ seqnames %in% 'chrX', end]*1.2, 118.0, 'genes', sector.index='chrX', facing='bending', cex=1.4, col='lightgoldenrod3', font=2, niceFacing=T)
dev.print(device=svg, file='/fast/projects/peifer_wgs/work/work/2017-11-08_Fuchs_totalRNAseq/raw/unified/figures/circos_circRNA_density.svg', width=10, height=10, bg='white', antialias='subpixel', pointsize=20, family='Arial')
#}}}
# CIRCOS plot with number of circRNAs/transcripts per gene
# distribution of ratio of circRNA number per gene to transcript number per gene
#{{{
circos.clear()
circos.par('start.degree'=90, 'gap.degree'=2, 'track.margin'=c(0.01,0.01), 'cell.padding'=c(0.0,0.05,0.00,0.05), 'unit.circle.segments'=500, 'canvas.xlim'=c(-0.5, 1.0), 'canvas.ylim'=c(-0.7, 1.0))
circos.initializeWithIdeogram(as.data.frame(cytoband), sort.chr=F)
circos.genomicTrackPlotRegion(data.frame(circ.n)[, c('seqnames', 'start', 'end', 'ratio')], panel.fun=function(region, value, ...){
circos.genomicLines(region, value, area=T, baseline=0, col='red4', border='red4', ...)
}, track.height=0.2, bg.border=NA)
circos.text(cytoband.xlim[ seqnames %in% 'chrX', end]*1.2, 3.5, 'ratio', sector.index='chrX', facing='bending', cex=1.4, col='red4', niceFacing=T, font=2)
circos.genomicTrackPlotRegion(data.frame(circ.n)[, c('seqnames', 'start', 'end', 'number')], panel.fun=function(region, value, ...){
circos.genomicLines(region, value, area=T, baseline=0, col='lightblue4', border='lightblue4', ...)
}, track.height=0.2, bg.border=NA)
circos.text(cytoband.xlim[ seqnames %in% 'chrX', end]*1.2, 24.0, 'circRNAs', sector.index='chrX', facing='bending', cex=1.4, col='lightblue4', niceFacing=T, font=2)
circos.genomicTrackPlotRegion(data.frame(gene.n[ gene.n$gene_id %in% circ.n$gene_id ])[, c('seqnames', 'start', 'end', 'number')], panel.fun=function(region, value, ...){
circos.genomicLines(region, value, area=T, baseline=0, col='lightgoldenrod3', border='lightgoldenrod3', ...)