-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAnalysisExonsIntrons.R
More file actions
1538 lines (1213 loc) · 55 KB
/
AnalysisExonsIntrons.R
File metadata and controls
1538 lines (1213 loc) · 55 KB
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
library(plyr)
library(GenomicRanges)
library(ggplot2)
library(Rmisc)
library(BSgenome.Hsapiens.UCSC.hg19)
library(bsseq)
library(prodlim) # for row matching
library(mixtools) # to get mixture gaussian approximation
library(stringr) # to count substring in a string
library(data.table) # for quick import of data
#cs = F
#shortening = F
#shift = 0.0
#inlength = 500
pipe = function(cs, shortening, shift, inlength, zero, celltype, plotcellnames) {
# write to log-file
log.file = paste0("plots/log/",cs,'.',shortening,'.txt')
file.create(log.file)
sink(file=log.file)
########################
## Get cufflink data ##
########################
# list of replica
patients.l = c('1','2')
# big matrix
cufflink.gene.df = matrix(ncol=7)
colnames(cufflink.gene.df) = c("chr","start","end","strand","geneID","expression","meanexpr")
# check if big matrix file already exists if not then create it
checkpoint0 = paste0('data/methPSI.cuff.bigtable.',celltype,'.tsv')
# for multiplott of ggplot
plots <- list()
postscript(file = paste0('plots/log/histogramCov',celltype,'.eps'), width=1400, height=800, family="Times")
par(cex = 2.0)
if ( file.exists(checkpoint0) == F ) {
# go over all patients
for (i in 1:length(patients.l) ) {
print(patients.l[i])
# read in cufflink data for patient
cufflink.exons.df <- read.delim(paste0('data/',celltype,'_',patients.l[i],'/cuff.exons.',celltype,'_',patients.l[i],'.tsv'), header=F)
colnames(cufflink.exons.df) = c("chr","start","end","score","strand","geneID","trID","FPKM","cov")
# make ggplot to see the distribution of the coverage
quantiles_cov = quantile(cufflink.exons.df[,9])
p <- ggplot(cufflink.exons.df, aes(x=cov)) +
theme(text=element_text(family="Times")) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.01,
colour="black", fill="grey") +
xlab('Read Coverage') +
ylab('Density') +
scale_x_continuous(trans='log10', breaks=c(quantiles_cov[2], quantiles_cov[4]),
labels = c(round(quantiles_cov[2],digits=1), round(quantiles_cov[4],digits=1))) +
# ggtitle(paste0('Distribution of Read Coverage for each Exon of Sample ',i)) +
ggtitle(paste0(plotcellnames,' Replica ',i)) +
geom_vline(xintercept = quantiles_cov[2], color = 'red', size = 1) +
geom_vline(xintercept = quantiles_cov[4], color = 'red', size = 1) +
theme(text = element_text(size=25), axis.title.y=element_text(margin=margin(0,20,0,0)),
axis.title.x=element_text(margin=margin(20,0,0,0)), plot.margin = unit(c(1,1,1,1),'cm'))
plots[[i]] <- p
############################
## Prepare cufflink data ##
############################
# order exons based on geneID and start position
ordered_cufflink.exons.df = cufflink.exons.df[order(cufflink.exons.df[,6], as.numeric(cufflink.exons.df[,2])),]
# unique genes from cufflink data
uniqueGenes = unique(ordered_cufflink.exons.df[,6])
# prepare gene matrix
patient.gene.df = matrix(ncol=7, nrow=length(uniqueGenes))
colnames(patient.gene.df) = c("chr","start","end","strand","geneID","expression","meanexpr")
# collect first and last exons
firstexons = which(duplicated(ordered_cufflink.exons.df[,6]) == F )
lastexons = which(duplicated(ordered_cufflink.exons.df[,6], fromLast=T) == F )
# fill matrix
patient.gene.df[,1] = ordered_cufflink.exons.df[firstexons,1]
patient.gene.df[,2] = ordered_cufflink.exons.df[firstexons,2]
patient.gene.df[,3] = ordered_cufflink.exons.df[lastexons,3]
patient.gene.df[,4] = as.character(ordered_cufflink.exons.df[lastexons,5])
patient.gene.df[,5] = as.character(ordered_cufflink.exons.df[lastexons,6])
row.matches = match(ordered_cufflink.exons.df[,6], uniqueGenes)
# chr start end strand geneID expression
# [1,] "chr1" "760728" "762886" "1" "1" "1"
# [2,] "chr1" "901877" "911245" "3" "2" "0"
# [3,] "chr1" "6472478" "6484730" "1" "3" "0"
# [4,] "chr1" "79353619" "79355169" "2" "4" "1"
# [5,] "chr6" "150070579" "150132044" "3" "5" "1"
# [6,] "chr6" "150139934" "150186199" "1" "6" "1"
# find out if gene is expressed or silenced
for (j in 1:length(uniqueGenes) ){
exons.l = which(row.matches == j)
# get score FPKM and coverage for the exon
score.l = ordered_cufflink.exons.df[exons.l,4]
FPKM.l = ordered_cufflink.exons.df[exons.l,8]
cov.l = ordered_cufflink.exons.df[exons.l,9]
# look if one of the exons has significant scores which
# would identify the gene as expressed
if ( max(score.l) > 1 && max(FPKM.l) > 1.0 && max(cov.l) > 20.0 ){
patient.gene.df[j,6] = 1
patient.gene.df[j,7] = mean(cov.l)
} else {
patient.gene.df[j,6] = 0
}
if(j%%1000 == 0){print(j)}
}
# bind the genes observed for each patient to the big matrix
cufflink.gene.df = rbind(cufflink.gene.df, patient.gene.df)
}
# change chromosome names from numbers to chr1 etc.
cufflink.gene.df[,1] = paste0('chr',cufflink.gene.df[,1])
# write table if the file not already exist
write.table(cufflink.gene.df, file = checkpoint0, sep='\t', append=F)
} else {
# make only plots
for (i in 1:length(patients.l) ) {
print(patients.l[i])
# read in cufflink data for patient
cufflink.exons.df <- read.delim(paste0('data/',celltype,'_',patients.l[i],'/cuff.exons.',celltype,'_',patients.l[i],'.tsv'), header=F)
colnames(cufflink.exons.df) = c("chr","start","end","score","strand","geneID","trID","FPKM","cov")
# make ggplot to see the distribution of the coverage
quantiles_cov = quantile(cufflink.exons.df[,9])
p <- ggplot(cufflink.exons.df, aes(x=cov)) +
theme(text=element_text(family="Times")) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.01,
colour="black", fill="grey") +
xlab('Read Coverage') +
ylab('Density') +
scale_x_continuous(trans='log10', breaks=c(quantiles_cov[2], quantiles_cov[4]),
labels = c(round(quantiles_cov[2],digits=1), round(quantiles_cov[4],digits=1))) +
ggtitle(paste0(plotcellnames, ' Replica ',i)) +
geom_vline(xintercept = quantiles_cov[2], color = 'red', size = 1) +
geom_vline(xintercept = quantiles_cov[4], color = 'red', size = 1) +
theme(text = element_text(size=25), axis.title.y=element_text(margin=margin(0,20,0,0)),
axis.title.x=element_text(margin=margin(20,0,0,0)), plot.margin = unit(c(1,1,1,1),'cm'))
plots[[i]] <- p
}
}
multiplot(plotlist = plots, cols = 2)
dev.off()
# read table
cufflink.gene.df = read.delim(checkpoint0, header=T)
# remove first row (it has NAs in it)
cufflink.gene.df = cufflink.gene.df[-1,]
# change strand of genes '.' to '*' because of GenomeRanges
cufflink.gene.df[,4] = as.character(cufflink.gene.df[,4])
cufflink.gene.df[which(!cufflink.gene.df[,4] %in% c('+','-')),4] = '*'
###############
## Filter 1 ##
###############
# remove first and last exon of each gene
filter1_psi.df = psi.df
firstexons = which(duplicated(filter1_psi.df[,5]) == F )
lastexons = which(duplicated(filter1_psi.df[,5], fromLast=T) == F )
rowNumExons = c(firstexons, lastexons)
# get only unique rows
rowNumExons = unique(rowNumExons)
# remove exons
filter1_psi.df = filter1_psi.df[-rowNumExons,]
rownames(filter1_psi.df) <- NULL
#################
## Group Exons ##
#################
if( length(which(is.na(filter1_psi.df[,10]))) != 0 ) {
print('[INFO] some MAP are NA')
filter1_psi.df[which(is.na(filter1_psi.df[,10])),10] = 0
}
if ( celltype != 'IMR90' && celltype != 'Gm12878' && celltype != 'H1hesc' ) {
# set seed for the EM algorithm
set.seed(123)
# model mixture of two gaussian distribution on the whole population
mixmdl = normalmixEM(as.numeric(filter1_psi.df[,10]))
# get the mean
mu = mixmdl$mu
# get the standard deviation
sigma = mixmdl$sigma
# get the raw ordered data
ordered_x = unique(mixmdl$x[order(mixmdl$x, decreasing=F)])
# get first distribution
firstDnorm.df = as.data.frame(list(ordered_x, dnorm(ordered_x, mean=mu[1], sd=sigma[1])))
firstDnorm.df[,2] = log(firstDnorm.df[,2] + 1)
colnames(firstDnorm.df) = c('x','density')
# get second distribution
secondDnorm.df = as.data.frame(list(ordered_x, dnorm(ordered_x, mean=mu[2], sd=sigma[2])))
secondDnorm.df[,2] = log(secondDnorm.df[,2] + 1)
colnames(secondDnorm.df) = c('x','density')
# make ggplot to see the distribution of MAP_PSI + mixture model
postscript(file = 'plots/log/histogramMAP_PSI.eps', width = 600, height = 600, family="Times")
print(ggplot(filter1_psi.df, aes(x=max_aposterior_PSI)) +
theme(text=element_text(family="Times")) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.05,
colour="white", fill="grey") +
xlab('Maximum A Posterior Probability of Inclusion') +
ylab('Log Density') +
scale_y_continuous(trans='log1p', breaks=c(0,1,3,4,5,9,10)) +
geom_line(data=firstDnorm.df, aes(x=x, y=density), size=1.0, color='red') +
geom_line(data=secondDnorm.df, aes(x=x, y=density), size=1.0, color='black', linetype="dotted") +
geom_vline(xintercept = (mu[1] + sigma[1]), color = 'red', size = 1) +
geom_vline(xintercept = (mu[2] - sigma[2]), color = 'black', size = 1, linetype="dotted") +
annotate("text", x = c((mu[1] + sigma[1]) - 0.04, (mu[2] - sigma[2]) + 0.04),
y = c(-0.05,-0.05),
label = c(round((mu[1] + sigma[1]),3), round((mu[2] - sigma[2]),3))) +
ggtitle(plotcellnames) +
theme(text = element_text(size=25), axis.title.y=element_text(margin=margin(0,20,0,0)),
axis.title.x=element_text(margin=margin(20,0,0,0)), plot.margin = unit(c(1,1,1,1),'cm'))
)
dev.off()
if (cs) {
thres = mu[2] - sigma[2]
} else {
thres = mu[1] + sigma[1]
}
} else {
postscript(file = paste0('plots/log/histogramMAP_PSI_',celltype,'.eps'), width = 600, height = 600, family="Times")
print(ggplot(filter1_psi.df, aes(x=max_aposterior_PSI)) +
theme(text=element_text(family="Times")) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.05,
colour="white", fill="grey") +
xlab('Maximum A Posterior Probability of Inclusion') +
ylab('Log Density') +
scale_y_continuous(trans='log1p', breaks=c(0,1,3,4,5,9,10)) +
scale_x_continuous(breaks=c(0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)) +
geom_vline(xintercept = 0.6, color = 'red', size = 1) +
geom_vline(xintercept = 0.8, color = 'red', size = 1) +
ggtitle(plotcellnames) +
theme(text = element_text(size=25), axis.title.y=element_text(margin=margin(0,20,0,0)),
axis.title.x=element_text(margin=margin(20,0,0,0)), plot.margin = unit(c(1,1,1,1),'cm'))
)
dev.off()
apirori.df <- as.data.frame(filter1_psi.df[,9])
colnames(apirori.df) <- 'Priori'
apirori.df[which(is.na(apirori.df[,1])),1] = 0.0
postscript(file = paste0('plots/log/histogramPSI_',celltype,'.eps'), width = 600, height = 600, family="Times")
print(ggplot(apirori.df, aes(x=Priori)) +
theme(text=element_text(family="Times")) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.05,
colour="white", fill="grey") +
xlab('Probability of Inclusion') +
ylab('Log Density') +
scale_y_continuous(trans='log1p', breaks=c(0,1,3,4,5,9,10)) +
#scale_x_continuous(breaks=c(0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)) +
#geom_vline(xintercept = 0.6, color = 'red', size = 1) +
#geom_vline(xintercept = 0.8, color = 'red', size = 1) +
ggtitle(plotcellnames) +
theme(text = element_text(size=25), axis.title.y=element_text(margin=margin(0,20,0,0)),
axis.title.x=element_text(margin=margin(20,0,0,0)), plot.margin = unit(c(1,1,1,1),'cm'))
)
dev.off()
if (cs) {
thres = 0.8
} else {
thres = 0.4
}
}
inclusions = filter1_psi.df[which(as.numeric(filter1_psi.df[,10]) >= thres),]
exclusions = filter1_psi.df[which(as.numeric(filter1_psi.df[,10]) <= thres),]
################################################################
## Remove Exons belonging to chromosome X, Y and M Filter 2 ##
################################################################
# find rows
removeXYM.inc.l = c(which(inclusions[,1] == 'chrX'), which(inclusions[,1] == 'chrY'), which(inclusions[,1] == 'chrM'))
removeXYM.exc.l = c(which(exclusions[,1] == 'chrX'), which(exclusions[,1] == 'chrY'), which(exclusions[,1] == 'chrM'))
# remove rows
removeXYM_inclusions = inclusions[-removeXYM.inc.l,]
removeXYM_exclusions = exclusions[-removeXYM.exc.l,]
chosenExons = c()
if(cs) {
chosenExons = removeXYM_inclusions
} else {
chosenExons = removeXYM_exclusions
}
# remove exons where Ninc = 0 and Nexc = 0
remove_exons.l = intersect(which(chosenExons[,6] == 0 ), which(chosenExons[,7] == 0 ))
if ( length(remove_exons.l) != 0 ) {
chosenExons = chosenExons[-remove_exons.l,]
}
rownames(chosenExons) = c(1:nrow(chosenExons))
print(paste('[NOTE] before cufflink filtering number of exons =',nrow(chosenExons)))
####################################
## Check with Cufflink Filter 3 ##
####################################
chosenExons.gr = GRanges(seqnames=as.character(chosenExons[,1]),
ranges=IRanges(start=as.numeric(chosenExons[,2]),
end=as.numeric(chosenExons[,3])),
strand=as.character(chosenExons[,4]))
cufflink.gr = GRanges(seqnames=as.character(cufflink.gene.df[,1]),
ranges=IRanges(start=as.numeric(cufflink.gene.df[,2]),
end=as.numeric(cufflink.gene.df[,3])),
strand=as.character(cufflink.gene.df[,4]))
# included/excluded exons have to be inside of a region the cufflink data
overlaps = findOverlaps(chosenExons.gr, cufflink.gr, type='within')
# exon hits
exonhits = queryHits(overlaps)
# cufflink region hits
cufflinkhits = subjectHits(overlaps)
# unique exons
uniqe_exonhits = unique(exonhits)
# list holds the bitwise vector from cufflink
# 0 = silenced, 1 = expressed
expression.l = numeric(length(uniqe_exonhits))
# probability of expression (number of 1 divided by total num observations)
prob.expression.l = numeric(length(uniqe_exonhits))
# mean expression
# mean.expression.l = numeric(length(uniqe_exonhits))
# go over all unqie exons
for ( i in 1:length(uniqe_exonhits) ){
# pick entries for each individual exons in the overlaps
entries = which(exonhits == uniqe_exonhits[i] )
# get cufflink data and look if exon is identified as expressed or not
expression = cufflink.gene.df[cufflinkhits[entries],6]
# collapse expression values into a string
expression.l[i] = paste0(expression, collapse='')
# get probability of expression
prob.expression.l[i] = mean(expression)
if(i%%1000 == 0){print(i)}
# get mean expression
# mean.expression.l[i] = cufflink.gene.df[cufflinkhits[entries],7]
}
# bind to matrix cufflink expression values
# offset = -1 for exons which werent coffered by cufflink
chosenExons = cbind(chosenExons, -1)
colnames(chosenExons)[11] = 'CuffExp'
# bind to matrix cufflink expression values
# offset = -1 for exons which werent coffered by cufflink
chosenExons = cbind(chosenExons, -1)
colnames(chosenExons)[12] = 'MeanCuffExp'
chosenExons[uniqe_exonhits, 11] = expression.l
chosenExons[uniqe_exonhits, 12] = prob.expression.l
# find genes which could be silenced
maybe_silenced.genes.l = chosenExons[intersect(which(chosenExons[,12] <= 0.5), which(chosenExons[,12] != -1)),5]
maybe_silenced.genes.l = unique(maybe_silenced.genes.l)
# get max read coverage for the gene (exon with the maximum read coverage)
# offset = -1 for gene which are not silenced and should not be removed
chosenExons = cbind(chosenExons, -1)
colnames(chosenExons)[13] = 'MaxReads'
print(length(maybe_silenced.genes.l))
# go over all genes which could be possibly be silenced
for ( i in 1:length(maybe_silenced.genes.l) ){
# get rows for individual gene
rows = which(chosenExons[,5] %in% maybe_silenced.genes.l[i] )
# check if all exons could be silenced or if some exons
# did not overlap with cufflinks data and therefore have a -1 as offset
if ( length(which(chosenExons[rows,12] == 1)) != 0 ) {
chosenExons[rows,13] = -1
} else {
# get exons total number of reads and look for the maximum value
max.reads = max(chosenExons[rows,8])
chosenExons[rows,13] = max.reads
}
if(i%%1000 == 0){print(i)}
}
# remove whole gene if the threshold is not -1 (offset)
remove.l = which(chosenExons[,13] != -1)
# check if everything went right
if ( length(which(chosenExons[remove.l,12] == 1.0)) != 0 ) {
print('[ERROR] something went wrong with the cufflinks filtering')
}
print(paste('[NOTE] removing',length(remove.l),'samples because gene could be silenced'))
if ( length(remove.l) != 0 ) {
chosenExons = chosenExons[-remove.l,]
}
#######################################
## Get Expression Rate for each Exon ##
#######################################
expression.df <- as.data.frame(expression.df)
m <- row.match(chosenExons[,1:4], expression.df[,1:4])
chosenExons <- cbind(chosenExons, expression.df[m,ncol(expression.df)])
#########################################
## Remove bad sampled Exons Filter 4 ##
#########################################
# make ggplot to see the distribution of the average read depth for Ninc and Nexc
t = 5
postscript(file = paste0('plots/log/histogramMaxReads',celltype,'_',cs,'.eps'), width = 800, height = 800, family="Times")
print(ggplot(chosenExons, aes(x=total)) +
theme(text=element_text(family="Times")) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.01,
colour="black", fill="grey") +
xlab('Number of splitted Reads') +
ylab('Density') +
scale_x_continuous(trans='log10', breaks = c(t, 100, 1000, 10000)) +
ggtitle(plotcellnames) +
geom_vline(xintercept = t, color = 'red', size = 1) +
theme(text = element_text(size=25), axis.title.y=element_text(margin=margin(0,20,0,0)))
)
dev.off()
# look how many bad samples you have
badSamples = which(chosenExons[,8] < t)
print(paste('[NOTE] remove total number of reads <',t,'=', length(badSamples)))
if ( length(badSamples) != 0 ) {
chosenExons = chosenExons[-badSamples,]
}
#################
## Get Introns ##
#################
if ( length(which(chosenExons[,4] == '*')) != 0 ){
stop('[Error] found undefined strand in one exon entry')
}
print(paste0('[NOTE] number of exons for testing = ',nrow(chosenExons)))
# replicate the exons
Upintrons.df = Dointrons.df = chosenExons
rownames(Upintrons.df) = rownames(Dointrons.df) = NULL
# checkpoint
checkpoint1 = paste0('data/unfiltered/PSI.unfiltered.chosenExons.',cs,'.',celltype,'.tsv')
if ( file.exists(checkpoint1) ) {
file.remove(checkpoint1)
}
write.table(chosenExons, file = checkpoint1, sep='\t', append=F)
# continue pipeline
intronLength = inlength
s1 = 1 + shift
s2 = 1 + shift
if(shortening) {
s1 = 20
s2 = 6
}
# first end pos, second start pos (+ upstream introns)
Upintrons.df[which(Upintrons.df[,4] == "+"),3] = as.numeric(Upintrons.df[which(Upintrons.df[,4] == "+"),2]) - s1
Upintrons.df[which(Upintrons.df[,4] == "+"),2] = as.numeric(Upintrons.df[which(Upintrons.df[,4] == "+"),2]) - intronLength - (s1 - 1)
# first start pos, second end pos (- downstream introns)
Dointrons.df[which(Dointrons.df[,4] == "-"),3] = as.numeric(Dointrons.df[which(Dointrons.df[,4] == "-"),2]) - s2
Dointrons.df[which(Dointrons.df[,4] == "-"),2] = as.numeric(Dointrons.df[which(Dointrons.df[,4] == "-"),2]) - intronLength - (s2 - 1)
# first start pos, second end pos (+ downstream introns)
Dointrons.df[which(Dointrons.df[,4] == "+"),2] = as.numeric(Dointrons.df[which(Dointrons.df[,4] == "+"),3]) + s2
Dointrons.df[which(Dointrons.df[,4] == "+"),3] = as.numeric(Dointrons.df[which(Dointrons.df[,4] == "+"),3]) + intronLength + (s2 - 1)
# first end pos, second start pos (- upstream introns)
Upintrons.df[which(Upintrons.df[,4] == "-"),2] = as.numeric(Upintrons.df[which(Upintrons.df[,4] == "-"),3]) + s1
Upintrons.df[which(Upintrons.df[,4] == "-"),3] = as.numeric(Upintrons.df[which(Upintrons.df[,4] == "-"),3]) + intronLength + (s1 - 1)
# create GRanges objects
all.exons.gr = GRanges(seqnames=all.exons.df[[1]],
ranges=IRanges(start=as.numeric(all.exons.df[[2]]),
end=as.numeric(all.exons.df[[3]])),
strand=as.character(all.exons.df[[6]]))
Upintrons.gr = GRanges(seqnames=Upintrons.df[,1],
ranges=IRanges(start=as.numeric(Upintrons.df[,2]),
end=as.numeric(Upintrons.df[,3])),
strand=Upintrons.df[,4])
Dointrons.gr = GRanges(seqnames=Dointrons.df[,1],
ranges=IRanges(start=as.numeric(Dointrons.df[,2]),
end=as.numeric(Dointrons.df[,3])),
strand=Dointrons.df[,4])
#########################################################
## Remove introns which overlaps with exons (Filter 5) ##
#########################################################
overlaps1 = findOverlaps(all.exons.gr, Upintrons.gr)
removeIntrons1 = unique(subjectHits(overlaps1))
overlaps2 = findOverlaps(all.exons.gr, Dointrons.gr)
removeIntrons2 = unique(c(removeIntrons1,unique(subjectHits(overlaps2))))
# testing how many introns overlap with another version of the exon
chosenExons.test.gr = GRanges(seqnames=chosenExons[,1],
ranges=IRanges(start=as.numeric(chosenExons[,2]),
end=as.numeric(chosenExons[,3])),
strand=chosenExons[,4])
unique_queries = unique(c(queryHits(overlaps1), queryHits(overlaps2)))
unique_queries.gr = all.exons.gr[unique_queries]
print(paste('[NOTE] Number of samples I uneseccary lose, due to different versions of the exon =',
length(which(countOverlaps(chosenExons.test.gr, unique_queries.gr) > 1)) ) )
# remove samples which are not good
filtered_Upintrons.df = Upintrons.df[-removeIntrons2,]
filtered_Dointrons.df = Dointrons.df[-removeIntrons2,]
chosenExons = chosenExons[-removeIntrons2,]
print(paste0('[NOTE] number of upstream introns for testing = ',nrow(filtered_Upintrons.df)))
print(paste0('[NOTE] number of exons for testing = ',nrow(chosenExons)))
print(paste0('[NOTE] number of downstream introns for testing = ',nrow(filtered_Dointrons.df)))
# checkpoint
checkpoint2 = paste0('data/filtered/PSI.filtered.chosenExons.',cs,'.',shift,'.',inlength,'.',celltype,'.tsv')
if ( file.exists(checkpoint2) ) {
file.remove(checkpoint2)
}
write.table(chosenExons, file = checkpoint2, sep='\t', append=F)
#######################################
## Methylation content and C content ##
#######################################
reference = BSgenome.Hsapiens.UCSC.hg19
#############
### Exons ###
#############
# create GRanges object out of the exons
grExons <- GRanges(seqnames = chosenExons[,1],
ranges = IRanges(start = as.numeric(chosenExons[,2]),
end = as.numeric(chosenExons[,3])),
strand = chosenExons[,4])
# count methylation loci per exon
overlapcountsExons <- countOverlaps(grExons,mCpGs.gr)
# create datatable
Ematrix <- matrix(ncol=7, nrow=length(grExons))
colnames(Ematrix) <- c("ID", "#Methylathions", "seqlength",
'lengthNorm', 'CpG', 'mCpG/CpG', 'FPKM')
Ematrix[,1] <- 1:nrow(Ematrix)
Ematrix[,2] <- overlapcountsExons
Ematrix[,3] <- width(grExons)
Ematrix[,4] <- (as.numeric(Ematrix[,2]) / as.numeric(Ematrix[,3]))
# calculate mCpG/CpG-ratio for exons
# count overlap with all CpGs
overlapcountsExons <- countOverlaps(grExons,CpGs.gr)
Ematrix[,5] = overlapcountsExons
Ematrix[,6] = (as.numeric(Ematrix[,2]) / as.numeric(Ematrix[,5]))
# check for NaNs
Ematrix[which(is.na(Ematrix[,6])),6] = -1
Ematrix[,7] <- chosenExons[,ncol(chosenExons)]
# print how many exons are not 100% or 0% methylated
print(paste('[DATA] number of exons with mCpG/CpG ratio != 0 or 1 :', length(which(!Ematrix[,6] %in% c(-1,1,0))) ) )
# check for Inf
if ( length(which(is.infinite(Ematrix[,6]))) != 0 ) {
print('[ERROR] something went wrong with the calculation of the mCpG/CpG Ratio exons, infinite valeus')
}
# check if mCpG/CpG makes sense
if( length(which(Ematrix[,6] > 1.0)) != 0 ){
print('[ERROR] something went wrong with the calculation of the mCpG/CpG Ratio exons, values bigger than 1')
}
################
### UPSTREAM ###
################
# create GRanges object out of the upstream introns
grUpIntrons <- GRanges(seqnames = filtered_Upintrons.df[,1],
ranges = IRanges(start = as.numeric(filtered_Upintrons.df[,2]),
end = as.numeric(filtered_Upintrons.df[,3])),
strand = filtered_Upintrons.df[,4])
# count methylation loci per exon
overlapcountsUpIntrons <- countOverlaps(grUpIntrons,mCpGs.gr)
# create datatable
UpImatrix <- matrix(ncol=6, nrow=length(grUpIntrons))
colnames(UpImatrix) <- c("ID", "#Methylathions", "seqlength",
'lengthNorm', 'CpG', 'mCpG/CpG')
UpImatrix[,1] <- 1:nrow(UpImatrix)
UpImatrix[,2] <- overlapcountsUpIntrons
UpImatrix[,3] = width(grUpIntrons)
UpImatrix[,4] = (as.numeric(UpImatrix[,2]) / as.numeric(UpImatrix[,3]))
# calculate mCpG/CpG-ratio for upstream introns
# count overlap with all CpGs
overlapcountsUpIntrons <- countOverlaps(grUpIntrons,CpGs.gr)
UpImatrix[,5] = overlapcountsUpIntrons
UpImatrix[,6] = (as.numeric(UpImatrix[,2]) / as.numeric(UpImatrix[,5]))
# check for NaNs
UpImatrix[which(is.na(UpImatrix[,6])),6] = -1
# print how many upstream introns are not 100% or 0% methylated
print(paste('[DATA] number of upstream introns with mCpG/CpG ratio != 0 or 1 :', length(which(!UpImatrix[,6] %in% c(-1,1,0))) ) )
# check for Inf
if ( length(which(is.infinite(UpImatrix[,6]))) != 0 ) {
print('[ERROR] something went wrong with the calculation of the mCpG/CpG Ratio exons, infinite valeus')
}
# check if mCpG/CpG makes sense
if( length(which(UpImatrix[,6] > 1.0)) != 0 ){
print('[ERROR] something went wrong with the calculation of the mCpG/CpG Ratio up introns, values bigger than 1')
}
##################
### DOWNSTREAM ###
##################
# create GRanges object out of the downstream introns
grDoIntrons <- GRanges(seqnames = filtered_Dointrons.df[,1],
ranges = IRanges(start = as.numeric(filtered_Dointrons.df[,2]),
end = as.numeric(filtered_Dointrons.df[,3])),
strand = filtered_Dointrons.df[,4])
# count methylation loci per exon
overlapcountsDoIntrons <- countOverlaps(grDoIntrons,mCpGs.gr)
# create datatable
DoImatrix <- matrix(ncol=6, nrow=length(grDoIntrons))
colnames(DoImatrix) <- c("ID", "#Methylathions", "seqlength",
'lengthNorm', 'CpG', 'mCpG/CpG')
DoImatrix[,1] <- 1:nrow(DoImatrix)
DoImatrix[,2] <- overlapcountsDoIntrons
DoImatrix[,3] = width(grDoIntrons)
DoImatrix[,4] = (as.numeric(DoImatrix[,2]) / as.numeric(DoImatrix[,3]))
# calculate mCpG/CpG-ratio for downstream introns
# count overlap with all CpGs
overlapcountsDoIntrons <- countOverlaps(grDoIntrons,CpGs.gr)
DoImatrix[,5] = overlapcountsDoIntrons
DoImatrix[,6] = (as.numeric(DoImatrix[,2]) / as.numeric(DoImatrix[,5]))
# check for NaNs
DoImatrix[which(is.na(DoImatrix[,6])),6] = -1
# print how many downstream introns are not 100% or 0% methylated
print(paste('[DATA] number of downstream introns with mCpG/CpG ratio != 0 or 1 :', length(which(!DoImatrix[,6] %in% c(-1,1,0))) ) )
# check for Inf
if ( length(which(is.infinite(DoImatrix[,6]))) != 0 ) {
print('[ERROR] something went wrong with the calculation of the mCpG/CpG Ratio exons, infinite valeus')
}
# check if mCpG/CpG makes sense
if( length(which(DoImatrix[,6] > 1.0)) != 0 ){
print('[ERROR] something went wrong with the calculation of the mCpG/CpG Ratio do introns, values bigger than 1')
}
print('[NOTE] found introns')
#########################
## Methylation Plots ##
#########################
# lists holding data
first.df = c()
second.df = c()
# make plots for methyaltion content and mCpG/CpG ratio
methC = F
for ( i in 1:2 ) {
path_for_plots = "plots/"
if(shortening) {
path_for_plots = paste0(path_for_plots,'short/')
} else {
path_for_plots = paste0(path_for_plots,'unshort/')
}
print(paste('[NOTE] path of image = ', path_for_plots))
if (cs == F) {
sgn = '<='
ge = 'exclusion'
} else {
sgn = '>='
ge = 'inclusion'
}
title = 'Methylation Rate'
values.up.l = as.numeric(UpImatrix[,4])
values.ex.l = as.numeric(Ematrix[,4])
values.do.l = as.numeric(DoImatrix[,4])
boxplotlimits = c(0.0, 0.4)
barplotlimits = c(0.0, 0.05)
if ( methC == T ) {
title = 'mCpG/CpG Ratio'
values.up.l = as.numeric(UpImatrix[,6])
values.ex.l = as.numeric(Ematrix[,6])
values.do.l = as.numeric(DoImatrix[,6])
boxplotlimits = c(0.0, 2.0)
barplotlimits = c(0.0, 2.0)
}
# need datafram for ggplot
data.df = data.frame(c(rep('Up', nrow(UpImatrix)), rep('Ex', nrow(Ematrix)), rep('Do', nrow(DoImatrix))),
c(values.up.l, values.ex.l, values.do.l))
colnames(data.df) = c('group', 'values')
# stop alphabetic ordering of ggplot
data.df$group <- factor(data.df$group, levels=unique(data.df$group))
if ( methC == F ){
first.df = data.df
} else {
second.df = data.df
}
# change to mCpG/CpG-ratio
methC = T
}
return( list(first.df, second.df, Ematrix[,3], Ematrix[,7]) )
sink()
}
# evaluates the significances of the tri-region (up,ex,do)
# i.e. how often the exon is more methylated than the up/do-introns
signMeth = function(up,ex,do){
k = 0
for(i in 1:nrow(ex) ){
if ( ex[i,4] > up[i,4] & ex[i,4] > do[i,4] ) {
k = k + 1
}
}
# total number of different methylations
n = nrow(ex)
# sample portion
p_hat = k/n
return(p_hat)
}
###############
## Get data ##
###############
args = commandArgs(trailingOnly = TRUE)
celltype <- args[1]
if(is.na(celltype)){
warning("[WARNING] define correct celltype: IMR90, Gm12878 and H1hesc")
}
plotcellnames = ''
if ( celltype == 'IMR90' ) {
plotcellnames <- 'IMR-90'
# load methylation data
# WGBS for methylated CpGs
mCpGs.df = fread('data/mCpG_IMR90.tsv', sep='\t', header=TRUE)
# remove chromosome M CpGs
keepCpGs = which(as.character(mCpGs.df[[1]]) != 'chrM')
mCpGs.df = mCpGs.df[keepCpGs,]
# create GRanges object
mCpGs.gr = GRanges(seqnames = mCpGs.df[[1]],
ranges = IRanges(start = as.numeric(mCpGs.df[[2]]),
end = as.numeric(mCpGs.df[[2]])),
strand = rep('*',nrow(mCpGs.df)) )
# remove big data from memory
rm(mCpGs.df)
# load methylation data
# WGBS (keep in mind that this is bed format see BismoothData.v*.R)
CpGs.df <- fread('data/CpG_IMR90.tsv', sep='\t', header=TRUE)
# remove chromosome M CpGs
keepCpGs = which(as.character(CpGs.df[[1]]) != 'chrM')
CpGs.df = CpGs.df[keepCpGs,]
# create GRanges object
CpGs.gr = GRanges(seqnames = CpGs.df[[1]],
ranges = IRanges(start = as.numeric(CpGs.df[[2]]), # changed start site
end = as.numeric(CpGs.df[[2]])), # same end position
strand = rep('*',nrow(CpGs.df)) )
# remove big data from memory
rm(CpGs.df)
# read data from PSI.R
psi.df = read.delim("data/PSI.10.IMR90.tsv", header=T)
row.names(psi.df) = NULL
}
if ( celltype == 'Gm12878' ) {
plotcellnames <- 'GM12878'
# load methylation data
# WGBS for methylated CpGs
mCpGs.df = fread('data/mCpG_Gm12878.tsv', sep='\t', header=TRUE)
# remove chromosome M CpGs
keepCpGs = which(as.character(mCpGs.df[[1]]) != 'chrM')
mCpGs.df = mCpGs.df[keepCpGs,]
# create GRanges object
mCpGs.gr = GRanges(seqnames = mCpGs.df[[1]],
ranges = IRanges(start = as.numeric(mCpGs.df[[2]]),
end = as.numeric(mCpGs.df[[2]])),
strand = rep('*',nrow(mCpGs.df)) )
# remove big data from memory
rm(mCpGs.df)
# load methylation data
# WGBS (keep in mind that this is bed format see BismoothData.v*.R)
CpGs.df <- fread('data/CpG_Gm12878.tsv', sep='\t', header=TRUE)
# remove chromosome M CpGs
keepCpGs = which(as.character(CpGs.df[[1]]) != 'chrM')
CpGs.df = CpGs.df[keepCpGs,]
# create GRanges Object
CpGs.gr = GRanges(seqnames = CpGs.df[[1]],
ranges = IRanges(start = as.numeric(CpGs.df[[2]]), # changed start site
end = as.numeric(CpGs.df[[2]])), # same end position
strand = rep('*',nrow(CpGs.df)) )
# remove big data from memory
rm(CpGs.df)
# read data from PSI.R
psi.df = read.delim("data/PSI.10.Gm12878.tsv", header=T)
row.names(psi.df) = NULL
}
if ( celltype == 'H1hesc' ) {
plotcellnames <- 'H1-hESC'
# load methylation data
# WGBS for methylated CpGs
mCpGs.df = fread('data/mCpG_H1hesc.tsv', sep='\t', header=TRUE)
# remove chromosome M CpGs
keepCpGs = which(as.character(mCpGs.df[[1]]) != 'chrM')
mCpGs.df = mCpGs.df[keepCpGs,]
# create GRanges object
mCpGs.gr = GRanges(seqnames = mCpGs.df[[1]],
ranges = IRanges(start = as.numeric(mCpGs.df[[2]]),
end = as.numeric(mCpGs.df[[2]])),
strand = rep('*',nrow(mCpGs.df)) )
# remove big data from memory
rm(mCpGs.df)
# load methylation data
# WGBS (keep in mind that this is bed format see BismoothData.v*.R)
CpGs.df <- fread('data/CpG_H1hesc.tsv', sep='\t', header=TRUE)
# remove chromosome M CpGs
keepCpGs = which(as.character(CpGs.df[[1]]) != 'chrM')
CpGs.df = CpGs.df[keepCpGs,]
# create GRanges object
CpGs.gr = GRanges(seqnames = CpGs.df[[1]],
ranges = IRanges(start = as.numeric(CpGs.df[[2]]), # changed start site
end = as.numeric(CpGs.df[[2]])), # same end position
strand = rep('*',nrow(CpGs.df)) )
# remove big data from memory
rm(CpGs.df)
# read data from PSI.R
psi.df = read.delim("/data/PSI.10.H1hesc.tsv", header=T)
row.names(psi.df) = NULL
}
# Load Expression data
expression.df = fread('data/new_counts.tsv', sep='\t', header=FALSE)
keep = which(!as.character(expression.df[[1]]) %in% c('chrM','chrX','chrY'))
expression.df = expression.df[keep,]
width <- abs(expression.df[[3]] - expression.df[[2]])
count <- expression.df[[8]]
N <- sum(as.numeric(count))
expression.df = cbind(expression.df,
mapply(function(C,L) ((10e9*C)/(N*L)),
as.numeric(count),
as.numeric(width)))
#####################
## Get other data ##
#####################
# get exons for hg19
all.exons.df = fread('data/sorted_exons.bed', sep='\t', header=FALSE)
######################
## Creathe folders ##
######################
dirs.l = c('plots/log',