forked from deLaatLab/pipe4C
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.R
More file actions
executable file
·2396 lines (2084 loc) · 102 KB
/
Copy pathfunctions.R
File metadata and controls
executable file
·2396 lines (2084 loc) · 102 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
# FUNCTIONS 4C PIPELINE
createConfig <- function(confFile=argsL$confFile){
configF <- config::get(file=confFile)
baseFolder <- configF$fragFolder
normFactor <- configF$normalizeFactor
plotView <- configF$plot$plotView
maxY <- configF$plot$maxY
xaxisUnit <- configF$plot$xaxisUnit
plotType <- configF$plot$plotType
binSize <- configF$plot$binSize
qualityCutoff <- configF$qualityCutoff
trimLength <- configF$trimLength
minAmountReads <- configF$minAmountReads
readsQuality <- configF$readsQuality
cores <- configF$cores
wSize <- configF$wSize
nTop <- configF$nTop
mapUnique <- configF$mapUnique
nonBlind <- configF$nonBlind
bdg <- configF$bdg
wig <- configF$wig
fixedStepWig <- configF$fixedStepWig
fixedStepWigBin <- configF$fixedStepWigBin
cisplot <- configF$cisplot
genomePlot <- configF$genomePlot
tsv <- configF$tsv
bins <- configF$bins
mmMax <- configF$mismatchMax
peakC <- configF$peakC
replicates <- configF$replicates
chr_random <- configF$chr_random
chrUn <- configF$chrUn
chrM <- configF$chrM
vpRegion = configF$PeakC$vpRegion
alphaFDR = configF$PeakC$alphaFDR
qWd = configF$PeakC$qWd
qWr = configF$PeakC$qWr
minDist = configF$PeakC$minDist
min.gapwidth = configF$PeakC$min.gapwidth
DESeq2 = configF$PeakC$DESeq2
ctrl = configF$PeakC$ctrl
enzymes <- data.frame(
name=as.character(sapply(configF$enzymes, function(x) strsplit(x, split=' ')[[1]][1])),
RE.seq=as.character(sapply(configF$enzymes, function(x) strsplit(x, split=' ')[[1]][2])),
stringsAsFactors=FALSE, row.names=1)
genomes <- data.frame(
genome=as.character(sapply(configF$genomes, function(x) strsplit(x, split=' ')[[1]][1])),
BSgenome=as.character(sapply(configF$genomes, function(x) strsplit(x, split=' ')[[1]][2])),
stringsAsFactors=FALSE, row.names=1)
bt2Genomes <- data.frame(
genome=as.character(sapply(configF$bowtie2, function(x) strsplit(x, split=' ')[[1]][1])),
path=as.character(sapply(configF$bowtie2, function(x) strsplit(x, split=' ')[[1]][2])),
stringsAsFactors=FALSE, row.names=1)
return(list(baseFolder=baseFolder, normFactor=normFactor, enzymes=enzymes, genomes=genomes, bt2Genomes=bt2Genomes, plotView=plotView,
maxY=maxY, xaxisUnit=xaxisUnit, plotType=plotType, binSize=binSize, qualityCutoff=qualityCutoff, trimLength=trimLength, minAmountReads=minAmountReads,
readsQuality=readsQuality, cores=cores, wSize=wSize, nTop=nTop, mapUnique=mapUnique, nonBlind=nonBlind, bdg=bdg, wig=wig, fixedStepWig=fixedStepWig,
fixedStepWigBin=fixedStepWigBin, cisplot=cisplot, genomePlot=genomePlot, tsv=tsv, bins=bins, mmMax=mmMax, chr_random=chr_random, chrUn=chrUn, chrM=chrM,
peakC=peakC, replicates=replicates, vpRegion=vpRegion, alphaFDR=alphaFDR, qWd=qWd, qWr=qWr, minDist=minDist, min.gapwidth=min.gapwidth, DESeq2=DESeq2, ctrl=ctrl))
}
Read.VPinfo <- function(VPinfo.file, replicates){
#Indentify Fastq files, experiment names and primer sequence from VPinfo file
VPinfo <- read.table(VPinfo.file, sep="\t", stringsAsFactors=FALSE, header=TRUE)
if (! "spacer" %in% colnames(VPinfo)){
VPinfo$spacer<-0
}
if (ncol(VPinfo)==10){
defaultNames<-c('expname', 'spacer', 'primer', 'firstenzyme', 'secondenzyme', 'genome', 'vpchr', 'vppos', 'analysis', 'fastq')
headerCount <- sum(colnames(VPinfo) %in% defaultNames)
if (replicates == TRUE){
message("Replicates option activated! Condition and replicate column are required.")
return()
}
}
if (ncol(VPinfo)==12){
defaultNames<-c('expname','spacer', 'primer', 'firstenzyme', 'secondenzyme', 'genome', 'vpchr', 'vppos', 'analysis', 'fastq', 'condition', 'replicate')
headerCount <- sum(colnames(VPinfo) %in% defaultNames)
}
if (headerCount < ncol(VPinfo)){
message("Headers not correct in VPinfo file.")
return()
}
# Modification of duplicated exp.name depending of condition and replicate
if (replicates == TRUE){
while (any(duplicated(VPinfo$expname)) == TRUE){
dupName <- VPinfo$expname[which(duplicated(VPinfo$expname) == TRUE)[1]]
dupVPinfo <- VPinfo[VPinfo$expname == dupName,]
identicalNameRows <- rownames(dupVPinfo)
if (length(unique(dupVPinfo$vpchr)) != 1 || length(unique(dupVPinfo$vppos)) != 1){
message("Some duplicated exp.names do not present the same viewpoint (vpchr or vppos).")
return()
}
for (i in identicalNameRows){
newName = paste0(dupVPinfo$expname[rownames(dupVPinfo) == i], "_", dupVPinfo$condition[rownames(dupVPinfo) == i], "_Rep", dupVPinfo$replicate[rownames(dupVPinfo) == i])
dupVPinfo$expname[rownames(dupVPinfo) == i] <- newName
if (newName %in% unique(dupVPinfo$expname[duplicated(dupVPinfo$expname)])){
message("Some duplicated exp.names present the same condition and replicate.")
return()
} else {
VPinfo$expname[rownames(VPinfo) == i] <- newName
}
}
}
}
expname <- as.character(gsub("[^A-Za-z0-9_]", "", VPinfo$expname))
primer <- toupper(as.character(gsub("[^A-Za-z]", "", VPinfo$primer)))
firstenzyme <- as.character(gsub("[^A-Za-z0-9]", "", VPinfo$firstenzyme))
secondenzyme <- as.character(gsub("[^A-Za-z0-9]", "", VPinfo$secondenzyme))
genome <- as.character(gsub("[^A-Za-z0-9_]", "", VPinfo$genome))
#vpchr <- as.character(gsub("[^0-9XYMxym]", "",VPinfo$vpchr))
#To be sure that any kind of chromosome name for different species can be used I only remove spaces.
vpchr <- as.character(gsub(" ", "",VPinfo$vpchr))
if(is.numeric(VPinfo$vppos)){
vppos <- as.numeric(gsub("\\D+", "", VPinfo$vppos))
} else {
message("One of the vppos is not numeric.")
return()
}
analysis <- as.character(gsub("[^a-z]", "", VPinfo$analysis))
fastq <- as.character(VPinfo$fastq)
spacer <- as.numeric(gsub("\\D+", "", VPinfo$spacer))
if (ncol(VPinfo)==10){
VPinfo$condition<-NA
VPinfo$replicate<-1
}
condition <- as.character(gsub("[^A-Za-z0-9_]", "", VPinfo$condition))
if(is.numeric(VPinfo$replicate)){
replicate <- as.numeric(gsub("\\D+", "", VPinfo$replicate))
} else {
message("One of the replicate value is not numeric.")
return()
}
return(data.frame(expname=expname, spacer=spacer, primer=primer, firstenzyme=firstenzyme, secondenzyme=secondenzyme, genome=genome,
vpchr=vpchr, vppos=vppos, analysis=analysis, fastq=fastq, condition=condition, replicate=replicate, stringsAsFactors=FALSE))
}
demux.FASTQ <- function(VPinfo, FASTQ.F, FASTQ.demux.F, demux.log.path, overwrite = FALSE, mmMax){
# reading functions
if(!suppressMessages(require("ShortRead", character.only=TRUE))) stop("Package not found: ShortRead")
# Demultiplex FastQ files:
# 1. This will remove weird characters from VPinfo name and primer info.
# 2. Exclude experiments that have non-unique names
# 3. Demultiplex each Fastq file and save it as a new Fastq file which can be uploaded to GEO.
# If a spacer sequence is used with random nucleotides before the primer, the spacer option should be set.
#Demultiplex per FASTQ file
file.fastq <- sort(unique(VPinfo$fastq))
for (i in 1:length(file.fastq)){
VPinfo.fastq <- VPinfo[VPinfo$fastq == file.fastq[i],]
# Remove weird characters from VPinfo file
exp.name.all <- as.character(VPinfo$expname)
exp.name <- as.character(VPinfo.fastq$expname)
primer <- toupper(as.character(VPinfo.fastq$primer))
spacer <- as.numeric(VPinfo.fastq$spacer)
# Remove experiments with duplicated names
exp.name.unique <- NULL
primer.unique <- NULL
spacer.unique <- NULL
for (a in 1:length(exp.name)){
if (exp.name[a] %in% exp.name.all[duplicated(exp.name.all)]){
error.msg <- paste(" ### ERROR: Experiment name not unique for ", exp.name[a])
message(error.msg)
write(error.msg, demux.log.path, append = TRUE)
} else {
exp.name.unique <- c(exp.name.unique, exp.name[a])
primer.unique <- c(primer.unique, primer[a])
spacer.unique <- c(spacer.unique, spacer[a])
}
}
fq.df <- data.frame()
for (b in 1:length(exp.name.unique)){
outfile <- paste0(FASTQ.demux.F, exp.name.unique[b], ".fastq.gz")
if (file.exists(outfile)){
if (overwrite == TRUE){
unlink(outfile)
error.msg <- paste(" ### WARNING: File", outfile, "exists and will be overwritten.")
write(error.msg, demux.log.path, append = TRUE)
message(error.msg)
newrow <- data.frame(exp.name = exp.name.unique[b], primer = primer.unique[b], spacer = spacer.unique[b])
fq.df <- rbind(fq.df, newrow)
} else {
message(paste(" ### WARNING: File", outfile, "exists. continuing with existing file."))
}
} else {
newrow <- data.frame(exp.name = exp.name.unique[b], primer = primer.unique[b], spacer = spacer.unique[b])
fq.df <- rbind(fq.df, newrow)
}
}
#Check whether primers has enough distance with maximum allowed mismatches.
#
#https://www.rdocumentation.org/packages/DescTools/versions/0.99.19/topics/StrDist
#The function computes the Hamming and the Levenshtein (edit) distance of two given strings (sequences).
#The Hamming distance between two vectors is the number mismatches between corresponding entries.
#In case of the Hamming distance the two strings must have the same length.
#
if (nrow(fq.df)>1){
message("Check whether primer can be seperated")
primers.mm<-DNAStringSet(fq.df$primer)
names(primers.mm)<-fq.df$exp.name
for (c in seq_along(primers.mm)){
primers.mm2<-primers.mm[-c]
#dist <- srdistance(primers.mm2,primers.mm[c])[[1]]
dist <- srdistance(primers.mm2, primers.mm[c], method = "Hamming")[[1]]
#srdistanceFilter()
#http://manuals.bioinformatics.ucr.edu/home/ht-seq
if (min(dist)<= mmMax){
error.msg <- paste(" ### WARNING: primer sequence not unique for", fq.df$exp.name[c], "with", mmMax, "mismatches allowed.")
message(error.msg)
write(error.msg, demux.log.path, append = TRUE)
error.msg2 <- paste(" ### WARNING: primer overlaps with primer ", names(primers.mm2[dist<=mmMax]),"\n")
message(error.msg2)
write(error.msg2, demux.log.path, append = TRUE)
}
}
}
# Read FastQ
if (nrow(fq.df) > 0){
message(paste(" >>> Reading Fastq: ", file.fastq[i], " <<<"))
if (file.exists(paste0(FASTQ.F, "/", file.fastq[i]))){
# then we stream the fastq files at 1,000,000 reads each time (default)
stream <- FastqStreamer((paste0(FASTQ.F, "/", file.fastq[i])))
message(paste0(" ### ", fq.df$exp.name, " check for primer sequence ", fq.df$primer,
" spacer:", fq.df$spacer, " max mismatch:", mmMax, "\n"))
while (length(fq <- yield(stream))){
for (i in 1:nrow(fq.df)){
primer.seq <- as.character(fq.df$primer[i])
spacer <- as.numeric(fq.df$spacer[i])
if (mmMax == 0){
demultiplex.primer = srFilter(function(x){
substr(sread(x), spacer + 1, spacer + nchar(primer.seq)) == primer.seq
}, name = "demultiplex.primer")
demux.fq <- fq[demultiplex.primer(fq)]
} else {
shortreads <- narrow(sread(fq), start = spacer + 1, end = spacer + nchar(primer.seq))
dist <- srdistance(shortreads, primer.seq, method = "Hamming")[[1]]
demux.fq <- fq[dist <= mmMax]
}
writeFastq(demux.fq, paste0(FASTQ.demux.F, fq.df$exp.name[i], ".fastq.gz"), mode = "a")
}
}
close(stream)
}else{
error.msg <- paste(" ### WARNING: File", file.fastq[i], " does not exist. Experiment skipped.")
write(error.msg, demux.log.path, append = TRUE)
message(error.msg)
}
}
}
message("\n")
}
trim.FASTQ <- function(exp.name, firstcutter, secondcutter, file.fastq, trim.F, cutoff, trim.length=0, log.path, min.amount.reads=1000){
txt.tmp <- paste0(trim.F, exp.name, ".txt")
info.file <- paste0(trim.F, exp.name, ".info.rds")
if (file.exists(txt.tmp) & file.exists(info.file)){
error.msg <- paste0(" ### WARNING: trimmed file ", exp.name, " already exists, continuing with existing file.")
write(error.msg, log.path, append=TRUE)
message(error.msg)
return(readRDS(info.file))
} else {
message(paste(" ### Reading Fastq: ", file.fastq))
demux.fq <- readFastq(file.fastq)
# Qualtity trimming::remove? -- lets test it
if (cutoff > 0){
# Trim ends with qualtiy score < cutoff
# trimTailw remove low-quality reads from the right end using a sliding window
# trim as soon as 2 of 5 nucleotides has quality encoding less than phred score.
Phred.cutoff <- rawToChar(as.raw(cutoff + 33))
demux.fq <- trimTailw(demux.fq, 2, Phred.cutoff, 2)
# Alternatively use trimTails
# remove a tally of (successive) nucleotides falling at or below a quality threshold (trimTails).
# fq.trimTails.10 <- trimTails(fq, k=2, a=Phred.cutoff, successive=FALSE)
# successive: indicating whether failures can occur anywhere in the sequence, or must be successive
#Mean average base quality score>cutoff
#Does this make sense after end trimming? Should the cutoff be higher?
demux.fq <- demux.fq[(alphabetScore(demux.fq) / width(demux.fq)) > cutoff]
#Drop reads that are less than 30nt after quality filtering. Discuss lenght with Geert/Valerio
demux.fq <- demux.fq[width(demux.fq) >= 30]
#Maybe do this filtering afterwards? read len=Cap length?? (or a few nt less?)
} #close cutoff
sequences <- sread(demux.fq)
nReads <- length(sequences)
if (nReads < min.amount.reads){
error.msg <- paste0(" ### ERROR: ",exp.name," - Less reads in FASTQ than set as minimum. Reads: ", nReads)
write(error.msg, log.path, append=TRUE)
message(error.msg)
message(" ### To continue alter minAmountRead argument")
return()
} else {
message(paste0(" ### Total Reads: ", nReads))
}
if (trim.length > 0){
sequences <- substr( sequences, 1, ( trim.length-1+motif.1st.pos ) )
read.length.table <- sort(table(width(sequences)), decreasing=TRUE)[1]
} else {
read.length.table <- sort(table(width(demux.fq)), decreasing=TRUE)[1]
}
read.length<-as.numeric(names(read.length.table))
read.length.perc<-round(as.numeric(read.length.table/nReads*100),2)
if (read.length.perc < 60){
error.msg <- paste0(" ### WARNING:", exp.name," - Max read length in only ", read.length.perc, "% of the reads.")
write(error.msg, log.path, append=TRUE)
message(error.msg)
}
#Find the most occuring position of the firstcutter
motifPos<-sort(table(regexpr(firstcutter, sequences)), decreasing=TRUE)[1]
motif.1st.pos<-as.numeric(names(motifPos))
motifPos.perc<-round(as.numeric(motifPos/nReads*100),2)
motif.1st.pos.2nd <- FALSE
if (motif.1st.pos > 0){
#Check whether firstcutter motif is within the first 4 nts (as part of a barcode). If so take 2nd firstcutter pos.
if (motif.1st.pos < 5){
motif.1st.pos.2nd <- TRUE
#motif.1st.pos <- as.numeric(names(sort(table(gregexpr(firstcutter, sequences)[[1]][2]), decreasing=TRUE))[1])
motifPos<-sort(table(gregexpr(firstcutter, sequences)[[1]][2]), decreasing=TRUE)[1]
motif.1st.pos<-as.numeric(names(motifPos))
motifPos.perc<-round(as.numeric(motifPos/nReads*100),2)
}
if (motifPos.perc < 90){
error.msg <- paste0(" ### WARNING: ", exp.name, " - Most occuring position RE1 found in only", motifPos.perc, "% of the reads.")
write(error.msg, log.path, append=TRUE)
message(error.msg)
}
# Trim non-blind fragend sequences based on 2nd cutter
motif.2ndRE.pos <- as.numeric(names(sort(table(regexpr(secondcutter, sequences)), decreasing=TRUE))[1]) #Determine whether part of barcode
if (motif.2ndRE.pos > 5 | motif.2ndRE.pos == -1){
sequences.no.2nd.enzyme <- sub(paste0(secondcutter, ".*$"), secondcutter, sequences) # Changes only the 1st pattern match per string
} else { #part of bardcode. use the 2nd motif
sequences.no.2nd.enzyme <- sub(paste0("(", secondcutter, ".*?)", secondcutter, ".*$"), paste0("\\1", secondcutter), sequences)
}
# The . matches any character. .* matches zero or more instances of any character.
# But the matching is greedy; it would match as much as possible. I want matching that is not greedy (only up until the second .)
# so I added ? to suppress the greedy match and .*? matches any group of characters up until we hit the next thing in the regex.
# Because the first part was enclosed in parentheses (\\..*?) it is stored as \1,
# so the substitution pattern \\1 restores everything before the second . and the second . is replaced with the secondcutter.
# Trim 2nd first cutter motif (Trim blind fragments)
if (motif.1st.pos.2nd == FALSE){
sequences.no.2nd.enzyme <-sub(paste0("(", firstcutter, ".*?)", firstcutter, ".*$"), paste0("\\1", firstcutter), sequences.no.2nd.enzyme)
}else{
# Trim 3rd first cutter motif (Trim blind fragments) if present in barcode
sequences.no.2nd.enzyme <-sub(paste0("(", firstcutter, ".*?", firstcutter, ".*?)", firstcutter, ".*$"), paste0("\\1", firstcutter), sequences.no.2nd.enzyme)
}
# Trim sequences based on 1st cutter
keep <- substr(sequences.no.2nd.enzyme, motif.1st.pos, nchar(sequences.no.2nd.enzyme))
} # close if (motif.1st.pos>0)
if(motif.1st.pos == -1){
rm(sequences, demux.fq)
error.msg <- paste(" ### ERROR:", exp.name, "1st RE motif not found in reads")
write(error.msg, log.path, append=TRUE)
message(error.msg)
return()
}
write(keep, txt.tmp)
rm(sequences, demux.fq)
captureLen <- read.length - motif.1st.pos + 1
saveRDS(list(captureLen=captureLen, nReads=nReads, motifPosperc=motifPos.perc, readlenperc=read.length.perc ), file=info.file)
return(list(captureLen=captureLen, nReads=nReads, motifPosperc=motifPos.perc, readlenperc=read.length.perc))
}
}
makeBAM <- function(exp.name, BAM.F, NCORES, Bowtie2IndexFile, txt.tmp, log.path, bowtie.log.path, bamFile, map.unique, readsQual=1){
TEMPfile <- tempfile(pattern = "aln.", tmpdir = tempdir(), fileext = "")
check.trunc <- 1
while (check.trunc < 10){
message(paste0(" ### attempt ", check.trunc))
if (map.unique == TRUE){
bamFile.tmp <- paste0(BAM.F, exp.name, "_tmp.bam")
CMD <- paste0("(bowtie2 -p ", NCORES, " -r -x ", Bowtie2IndexFile, " -U ", txt.tmp,
" | samtools view -hbSu - | samtools sort -T ", TEMPfile, " -o ", bamFile.tmp, ") 2>&1")
bowtie.output <- system(command=CMD, intern=TRUE)
for(i in bowtie.output){
message(paste0(' ', i))
}
write(paste("Bowtie2 output:",exp.name), bowtie.log.path, append=TRUE)
write(bowtie.output, bowtie.log.path, append=TRUE)
#Check whether BAM in truncated (Due to pipe problems?). If truncated try 5 times.
if (length(grep("truncated file", bowtie.output)) == 1){
error.msg <- paste(" ### ERROR: ",exp.name," - Truncated BAM file. Repeating Bowtie mapping...")
message(error.msg)
write(error.msg, log.path, append=TRUE)
check.trunc <- check.trunc + 1
unlink(bamFile.tmp)
} else {
check.trunc <- 10
system(paste0("samtools view -H ", bamFile.tmp, " > header.sam")) #Output the header only
system(paste0("samtools view -F 4 ",bamFile.tmp, " | grep -v \"XS:\" | cat header.sam - | samtools view -b - > ", bamFile ))
system( paste0( "samtools index ", bamFile ))
unlink(bamFile.tmp)
}
} else{
# map with quality, default 1
CMD <- paste0("(bowtie2 -p ", NCORES, " -r -x ", Bowtie2IndexFile, " -U ", txt.tmp,
" | samtools view -q ", readsQual, " -bSu - | samtools sort -T ", TEMPfile, " -o ", bamFile, ") 2>&1")
bowtie.output <- system(command=CMD, intern=TRUE)
system( paste0("samtools index ", bamFile))
for(i in bowtie.output){
message(paste0(' ', i))
}
write(paste("Bowtie2 output:",exp.name), bowtie.log.path, append=TRUE)
write(bowtie.output, bowtie.log.path, append=TRUE)
#Check whether BAM in truncated. If truncated try 10 times.
if (length(grep("truncated file", bowtie.output)) == 1){
error.msg <-paste0(" ### ERROR: ",exp.name," - Truncated BAM file. Repeating Bowtie mapping...")
message(error.msg)
write(error.msg, log.path, append=TRUE)
check.trunc <- check.trunc + 1
unlink(bamFile)
} else{
check.trunc <- 10
}
}
}
unlink(TEMPfile)
}
norm4C <- function(readsGR, nReads=1e6, nTop=2, wSize=21){
readsGR$normReads <- 0
sumTop <- sum(-sort(-readsGR$reads)[1:nTop])
wNorm <- nReads/(sum(readsGR$reads)-sumTop)
readsGR$normReads <- wNorm*readsGR$reads
readsGR$norm4C <- runmean(x=readsGR$normReads, k=wSize, endrule="mean")
tmp <- readsGR$norm4C
tmp[tmp < 0] <- 0
readsGR$norm4C <- tmp
return(readsGR)
}
do.wigToBigWig <- function(wig_file, config_genomes, assemblyName){
if(!suppressMessages(require(as.character(config_genomes[assemblyName,]), character.only=TRUE))) stop(paste0("Package not found: ", as.character(config_genomes[assemblyName,])))
if(!suppressMessages(require("BSgenome", character.only=TRUE))) stop("Package not found: BSgenome")
do.call(require, args=list(config_genomes[assemblyName,]))
assign('genome', base::get(config_genomes[assemblyName,]))
info <- seqinfo(genome)
wigToBigWig(wig_file, info)
}
exportWig <- function(gR, expName, filename, vpPos, vpChr, plotView, config_genomes, assemblyName, fixed=FALSE, bin=50){
gzname<- paste0(filename, ".gz")
gz1 <- gzfile(gzname, "w")
browserPos <- paste0(vpChr,":", vpPos-plotView, "-", vpPos+plotView)
positionLine <- paste0("browser position ", browserPos, "\n")
cat(positionLine, file=gz1)
trackLine <- paste0("track type=wiggle_0 name=", expName, " visibility=full autoScale=off viewLimits=0.0:2500.0 maxHeightPixels=50:50:8 color=0,0,200 priority=10\n")
cat(trackLine, file=gz1, append=TRUE)
if (fixed){
data <- GRanges(seqnames=seqnames(gR), ranges=ranges(gR), strand = strand(gR), score=gR$norm4C)
#Remove the last tile of each chromosome if its length is not equal to the bin size
data <- data[-which(end(data) - start(data) != bin-1)]
} else {
data <- GRanges(seqnames=seqnames(gR), ranges=gR$pos, strand = strand(gR), score=round(gR$norm4C, digits=5))
}
export.wig(data, gz1, append = TRUE)
close(gz1)
do.wigToBigWig(wig_file=gzname, config_genomes=config_genomes, assemblyName=assemblyName)
}
exportBDG <- function(gR, expName, filename, vpPos, vpChr, plotView, interval=FALSE){
gzname<- paste0(filename, ".gz")
gz1 <- gzfile(gzname, "w")
positionLine <- paste0("browser position ", vpChr,":", vpPos-plotView, "-", vpPos+plotView, "\n")
cat(positionLine, file=gz1)
trackLine <- paste0("track type=bedGraph name=", expName, " visibility=full autoScale=off viewLimits=0.0:2500.0 maxHeightPixels=50:50:8 color=0,0,200 priority=10\n")
cat(trackLine, file=gz1, append=TRUE)
if (interval == TRUE){
data_bdg <- data.frame(seqnames=seqnames(gR), start=start(gR), end=end(gR), score4C=round(gR$norm4C, digits=5))
} else {
data_bdg <- data.frame(seqnames=seqnames(gR), start=gR$pos, end=gR$pos, score4C=round(gR$norm4C, digits=5))
}
write.table(data_bdg, file=gz1, append=TRUE, sep="\t", quote=FALSE, row.names=FALSE, col.names=FALSE)
close(gz1)
}
exportTSV <- function(gR, filename, merge=FALSE){
gzname<- paste0(filename, ".gz")
gz1 <- gzfile(gzname, "w")
if (merge) {
tsvdat <- data.frame(chr=seqnames(gR), start=start(gR), end=end(gR), pos=gR$pos, type=gR$type, fe_strand=gR$fe_strand,
fe_id=gR$fe_id, normReads=gR$normReads, norm4C=gR$norm4C)
} else {
tsvdat <- data.frame(chr=seqnames(gR), start=start(gR), end=end(gR), pos=gR$pos, type=gR$type, fe_strand=gR$fe_strand,
fe_id=gR$fe_id, reads=gR$reads, normReads=gR$normReads, norm4C=gR$norm4C)
}
write.table(tsvdat, file=gz1, append=FALSE, sep="\t", quote=FALSE, row.names=FALSE, col.names=TRUE)
close(gz1)
}
olRanges <- function(query, subject){
## Find overlapping ranges
olindex <- as.matrix(findOverlaps(query, subject))
query <- query[olindex[,1]]
subject <- subject[olindex[,2]]
olma <- cbind(Qstart=start(query), Qend=end(query), Sstart=start(subject), Send=end(subject))
## Pre-queries for overlaps
startup <- olma[,"Sstart"] < olma[,"Qstart"]
enddown <- olma[,"Send"] > olma[,"Qend"]
startin <- olma[,"Sstart"] >= olma[,"Qstart"] & olma[,"Sstart"] <= olma[,"Qend"]
endin <- olma[,"Send"] >= olma[,"Qstart"] & olma[,"Send"] <= olma[,"Qend"]
## Overlap types
olup <- startup & endin
oldown <- startin & enddown
inside <- startin & endin
contained <- startup & enddown
## Overlap types in one vector
OLtype <- rep("", length(olma[,"Qstart"]))
OLtype[olup] <- "olup"
OLtype[oldown] <- "oldown"
OLtype[inside] <- "inside"
OLtype[contained] <- "contained"
## Overlap positions
OLstart <- rep(0, length(olma[,"Qstart"]))
OLend <- rep(0, length(olma[,"Qstart"]))
OLstart[olup] <- olma[,"Qstart"][olup]
OLend[olup] <- olma[,"Send"][olup]
OLstart[oldown] <- olma[,"Sstart"][oldown]
OLend[oldown] <- olma[,"Qend"][oldown]
OLstart[inside] <- olma[,"Sstart"][inside]
OLend[inside] <- olma[,"Send"][inside]
OLstart[contained] <- olma[,"Qstart"][contained]
OLend[contained] <- olma[,"Qend"][contained]
## Absolute and relative length of overlaps
OLlength <- (OLend - OLstart) + 1
OLpercQ <- OLlength/width(query)*100
OLpercS <- OLlength/width(subject)*100
## Output type
oldf <- data.frame(Qindex=olindex[,1], Sindex=olindex[,2], olma, OLstart, OLend, OLlength, OLpercQ, OLpercS, OLtype)
elementMetadata(query) <- cbind(as.data.frame(elementMetadata(query)), oldf[,-c(3,4)])
return(query)
}
alignToFragends <- function(gAlign, fragments, firstcut){
strand(fragments) <- ifelse(fragments$fe_strand==3, "-", "+")
ovl <- olRanges(query=fragments, subject=as(gAlign, "GRanges"))
#remove sequences that overlap only with RE motif
ovl <- ovl[ovl$OLlength >= nchar(as.character(firstcut))+1]
#Sequence need to start within unique fragment
ovl <- ovl[strand(ovl)=="+" & ovl$Sstart >= start(ovl) | strand(ovl)=="-" & ovl$Send <= end(ovl)]
#To do: Make it more strict. Reads should start directly at a restriction enzyme cutting site.
#ovl <- ovl[strand(ovl)=="+" & ovl$Sstart >= start(ovl) & ovl$Sstart <= start(ovl)+nchar(as.character(firstcut))| strand(ovl)=="-" & ovl$Send <= end(ovl) & & ovl$Send >= start(ovl)-nchar(as.character(firstcut))]
nReads <- tapply(ovl$Sindex, ovl$Qindex, length)
fragments$reads <- 0
fragments$reads[as.numeric(names(nReads))] <- nReads
return(fragments)
}
Digest <- function(assemblyName, firstcutter_Digest, secondcutter_Digest, baseFolder_Digest, config_genomes, chr_random, chrUn, chrM){
if(!suppressMessages(require(as.character(config_genomes[assemblyName,]), character.only=TRUE))) stop(paste0("Package not found: ", as.character(config_genomes[assemblyName,])))
if(!suppressMessages(require("BSgenome", character.only=TRUE))) stop("Package not found: BSgenome")
firstcutter <- as.character(firstcutter_Digest)
secondcutter <- as.character(secondcutter_Digest)
rdsFile <- paste0(baseFolder_Digest, assemblyName, "_", firstcutter, "_", secondcutter, ".rds")
if (!file.exists(rdsFile)){
do.call(require, args=list(config_genomes[assemblyName,]))
assign('frag.genome', base::get(config_genomes[assemblyName,]))
chr <- unique(seqnames(frag.genome))
#The "hap" ones are alternate assemblies for certain regions.DO NOT USE THE *hap* files !!!!
chr <- chr[grep(pattern="_hap", x=chr, invert=TRUE)]
chr <- chr[grep(pattern="_alt", x=chr, invert=TRUE)]
#Make sure Bowtie2 index does not contain these chr
if (chr_random==FALSE){
chr <- chr[grep(pattern="_random", x=chr, invert=TRUE)]
}
if (chrUn==FALSE){
chr <- chr[grep(pattern="chrUn_", x=chr, invert=TRUE)]
}
if (chrM==FALSE){
chr <- chr[grep(pattern="chrM", x=chr, invert=TRUE)]
}
outFrags <- GRanges()
for (i in seq_along(chr)){
chrom <- chr[i]
print(paste("Processing ", chrom, sep=""))
RE1 <- GRanges(seqnames=chrom, ranges(matchPattern(pattern=firstcutter, subject=frag.genome[[chrom]])))
RE2 <- GRanges(seqnames=chrom, ranges(matchPattern(pattern=secondcutter, subject=frag.genome[[chrom]])))
frag.RE1 <- RE1[1:(length(RE1)-1)]
end(frag.RE1)[1:(length(RE1)-1)] <- end(RE1)[2:length(RE1)]
# Only keep RE2 sites that completely overlap with RE1 fragment
RE2.ol <- olRanges(frag.RE1, RE2)
RE2.ol <- RE2[RE2.ol[RE2.ol$OLpercS==100]$Sindex]
# blind = all RE1 frg which do not contain RE2 site
blinds <- frag.RE1[!(frag.RE1 %over% RE2.ol)]
blinds$type <- "blind"
blinds <- rep(blinds[blinds$type=="blind"], each = 2)
blinds$fe_strand <- rep(c(5,3), length.out = length(blinds))
# nonBlind = all RE1 frg which contain RE2 site
nonBlinds <- frag.RE1[unique(findOverlaps(frag.RE1,RE2.ol)@from)]
nonBlinds$type <- "non_blind"
#
nonBlinds.fe5 <- nonBlinds
end(nonBlinds.fe5) <- end(RE2.ol[findOverlaps(nonBlinds, RE2.ol, select="first")])
nonBlinds.fe5$fe_strand <- 5
#
nonBlinds.fe3 <- nonBlinds
start(nonBlinds.fe3) <- start(RE2.ol[findOverlaps(nonBlinds, RE2.ol, select="last")])
nonBlinds.fe3$fe_strand <- 3
nonBlinds.fe5.start <- GRanges()
nonBlinds.fe3.end <- GRanges()
#Add first and last fragends
if (start(head(RE1, 1)) > start(head(RE2, 1))){
frag <- GRanges(seqnames=chrom, IRanges(1, end(RE1[1])))
RE2.ol.start <- olRanges(frag, RE2)
RE2.ol.start <- RE2[RE2.ol.start[RE2.ol.start$OLpercS==100]$Sindex]
nonBlinds.fe5.start <- RE1[1]
start(nonBlinds.fe5.start) <- start(RE2.ol.start[findOverlaps(frag, RE2.ol.start,select="last")])
nonBlinds.fe5.start$type <- "non_blind"
nonBlinds.fe5.start$fe_strand <- 5
}
if (end(tail(RE1, 1)) < end(tail(RE2, 1))){
frag <- GRanges(seqnames=chrom, IRanges(start(RE1[length(RE1)]), end(RE2[length(RE2)])))
RE2.ol.start <- olRanges(frag, RE2)
RE2.ol.start <- RE2[RE2.ol.start[RE2.ol.start$OLpercS==100]$Sindex]
nonBlinds.fe3.end <- RE1[length(RE1)]
end(nonBlinds.fe3.end) <- end(RE2.ol.start[findOverlaps(frag, RE2.ol.start,select="first")])
nonBlinds.fe3.end$type <- "non_blind"
nonBlinds.fe3.end$fe_strand <- 3
}
outFrags <- sort(c(outFrags,blinds, nonBlinds.fe5,nonBlinds.fe3,nonBlinds.fe5.start,nonBlinds.fe3.end))
}
outFrags$fe_id <- 1:length(outFrags)
outFrags$pos <- ifelse(outFrags$fe_strand == 5, start(outFrags)+nchar(firstcutter), end(outFrags)-nchar(firstcutter))
#outFrags$posEnd <- ifelse(outFrags$fe_strand == 3, start(outFrags)+nchar(firstcutter), end(outFrags)-nchar(firstcutter))
#Save new RDS
saveRDS(outFrags, file=rdsFile)
return(outFrags)
} else {
message('Frag genome file already exists.')
return(0)
}
}
getUniqueFragends <- function(fragsGR_Unique, firstcutter_Unique, secondcutter_Unique, captureLen_Unique=50, nThreads_Unique=4, baseFolder_Unique,
Bowtie2IndexFile, assemblyName, config_genomes){
if(!suppressMessages(require(as.character(config_genomes[assemblyName,]), character.only=TRUE))) stop(paste0("Package not found: ", as.character(config_genomes[assemblyName,])))
if(!suppressMessages(require("BSgenome", character.only=TRUE))) stop("Package not found: BSgenome")
##If captureLen is not in colnames, generate this column
if (paste0("len", captureLen_Unique) %in% colnames(elementMetadata(fragsGR_Unique)) == FALSE){
message(paste(' ### Create FASTA file for capture length', captureLen_Unique))
fragends <- fragsGR_Unique
fragFile <- paste0(baseFolder_Unique, assemblyName, "_", firstcutter_Unique, "_", secondcutter_Unique, ".rds")
fastaFile <- paste0(baseFolder_Unique, assemblyName, "_", firstcutter_Unique, "_", secondcutter_Unique, "_", captureLen_Unique, ".fa")
bamFile <- paste0(baseFolder_Unique, assemblyName, "_", firstcutter_Unique, "_", secondcutter_Unique, "_", captureLen_Unique, ".bam")
uniquesFile <- paste0(baseFolder_Unique, assemblyName, "_", firstcutter_Unique, "_", secondcutter_Unique, "_", captureLen_Unique, "_unique.txt")
## Create FASTA files for mapping back to REFGENOMEs
#Extract sequence 3'ends
start(fragends)[fragends$fe_strand == 3 & end(fragends) > (start(fragends)+captureLen_Unique - 1)]<-
end(fragends)[fragends$fe_strand == 3 & end(fragends) > (start(fragends)+captureLen_Unique - 1)] - captureLen_Unique + 1
#Extract sequence 5'ends
end(fragends)[fragends$fe_strand == 5 & start(fragends) < (end(fragends)-captureLen_Unique + 1)]<-
start(fragends)[fragends$fe_strand == 5 & start(fragends) < (end(fragends)-captureLen_Unique + 1)] + captureLen_Unique - 1
do.call(require, args=list(config_genomes[assemblyName,]))
seqs <- getSeq(x=base::get(config_genomes[assemblyName,]), names=fragends)
names(seqs) <- fragends$fe_id
writeXStringSet(seqs,fastaFile)
message(paste(' ### Mapping FASTA file back to',assemblyName))
#cmd <- paste0("bowtie2 -p ",nThreads," -x ",Bowtie2IndexFile," -f ",fastaFile," | samtools view -q 1 -hbSu - | samtools sort -T /tmp - > ",bamFile)
#-q 1: Skip alignments with MAPQ smaller than 1
#-h Include the header in the output.
#-b Output in BAM format --> why do we need to output as a BAM file? This is just a temp file.
#-S Input is in SAM format
#-u Output uncompressed BAM.
#This option saves time spent on compression/decompression and is thus preferred when the output is piped to another samtools command.
#No sorting is quicker
cmd <- paste0("(bowtie2 -p ", nThreads_Unique, " -x ", Bowtie2IndexFile, " -f ", fastaFile, " | samtools view -q 1 -hbSu - > ", bamFile, ") 2>&1")
check.trunc <- 0
while (check.trunc < 1){
message(paste(" ### Bowtie2:", captureLen_Unique))
bowtie.output <- system(cmd, intern=TRUE)
if (length(grep("[main_samview] truncated file", bowtie.output)) == 1){
message(paste(" ### ERROR: Truncated BAM file: repeating Bowtie mapping"))
} else {
check.trunc <- 1
}
}
system(paste0("samtools view ", bamFile, " | grep -v \"XS:\" | cut -f 1 > ", uniquesFile))
ids <- as.numeric(readLines(uniquesFile))
elementMetadata(fragsGR_Unique)[[paste0("len", captureLen_Unique)]] <- fragsGR_Unique$fe_id%in%ids #Use Fragend coordinates. not coordinates for unique mapping.
fragsGR_Unique <- fragsGR_Unique[, order(colnames(elementMetadata(fragsGR_Unique)))]
saveRDS(object=fragsGR_Unique, file=fragFile)
unlink(c(fastaFile, bamFile, uniquesFile))
}
# if the unique capture len is already in fragGR, we just use that column and rename it to 'unique'
fragsGR2 <- fragsGR_Unique[, c("pos", "type", "fe_strand", "fe_id", paste0("len", captureLen_Unique))]
colnames(elementMetadata(fragsGR2))[5] <- "unique"
return(fragsGR2)
}
getFragMap <- function(vpChr_FragMap=NULL, firstcutter_FragMap, secondcutter_FragMap, genome_FragMap, captureLen_FragMap=60, nThreads_FragMap=10,
baseFolder_FragMap, Bowtie2IndexFile, config_genomes, chr_random=chr_random, chrUn=chrUn, chrM = chrM){
# here we want to check if we have the genome available for this analysis, in case yes, loading it, otherwise, advice on the
# missing genome and switch to the next guy
# message(paste(" >>> Create frag map for genome :",genome[i],"with re1 :",firstcutter," and re2 :",secondcutter,"and captureLen", captureLen, "<<<"))
fragFile <- paste0(baseFolder_FragMap, genome_FragMap,"_", firstcutter_FragMap, "_", secondcutter_FragMap, ".rds")
if (file.exists(fragFile)){
# File with unique fragends exists, use it to check for unique fragends for given capture length
message(' ### Loading: ', fragFile)
fragsGR <- readRDS(fragFile)
} else {
# Make the digest first
message(paste0(" ### Creating new digest for genome: ", genome_FragMap, " with re1: ", firstcutter_FragMap, " and re2: ", secondcutter_FragMap))
fragsGR <- Digest(assemblyName=genome_FragMap, firstcutter_Digest=firstcutter_FragMap, secondcutter_Digest=secondcutter_FragMap,
baseFolder_Digest=baseFolder_FragMap, config_genomes=config_genomes, chr_random=chr_random, chrUn=chrUn, chrM = chrM)
}
message(' ### Retrieve and store the unique fragends')
fragsGR <- getUniqueFragends(fragsGR_Unique=fragsGR, firstcutter_Unique=firstcutter_FragMap, secondcutter_Unique=secondcutter_FragMap,
captureLen_Unique=captureLen_FragMap, nThreads_Unique=nThreads_FragMap, baseFolder_Unique=baseFolder_FragMap, Bowtie2IndexFile=Bowtie2IndexFile,
assemblyName=genome_FragMap, config_genomes=config_genomes)
if (!is.null(vpChr_FragMap)){
message(' ### Selecting fragments from ', vpChr_FragMap)
fragsGR <- subset(fragsGR, as.character(seqnames(fragsGR)) == vpChr_FragMap & unique == TRUE)
} else {
message(' ### Selecting fragments from whole genome', vpChr_FragMap)
fragsGR <- fragsGR[fragsGR$unique]
}
return(fragsGR)
}
plot.chroms <- function(exp, reads, cutoff=0.999, yMax=2500){
chroms <- as.character(unique(seqnames(reads)))
total.reads <- sum(reads$norm4C)
abs.cut <- quantile(reads$norm4C, cutoff, na.rm=T)
reads$norm4C[reads$norm4C > abs.cut] <- abs.cut
reads$norm4C <- reads$norm4C/abs.cut
reads$chr <- sub("chr","",as.character(seqnames(reads)))
reads[seqnames(reads)=="chrX"]$chr<-length(chroms)-1
reads[seqnames(reads)=="chrY"]$chr<-length(chroms)
reads$chr <-as.numeric(reads$chr)
layout(cbind(c(rep(1,3),2)))
par(mar=c(5, 4, 4, 2))
plot(c(0,max(reads$pos)), c(0,length(chroms)), type='n', axes=F, xlab="Chromosome position (Mb)", ylab="", main = exp)
segments(reads$pos, reads$chr, reads$pos, reads$chr + reads$norm4C, lwd=0.5)
lab <- seq(0,ceiling(max(reads$pos)/10e6)*10, by=10)
axis(1, at = lab*1e6, label=lab, las=2)
axis(2, at= 1:length(chroms)+0.5, lab=chroms, lwd=0, las=2)
}
make.reads.and.bins <- function(reads, assemblyName, res=25e3, config_genomes, spacer=" "){
if(!suppressMessages(require(as.character(config_genomes[assemblyName,]), character.only=TRUE))) stop(paste0("Package not found: ", as.character(config_genomes[assemblyName,])))
if(!suppressMessages(require("BSgenome", character.only=TRUE))) stop("Package not found: BSgenome")
#Extract fragends with reads
Captures <- reads[reads$norm4C>0]
Captures.rds<-Captures[,1]
Captures.rds$normReads<-round(Captures$normReads,3)
Captures.rds$norm4C<-round(Captures$norm4C,3)
#make bins
#Get genome info
do.call(require, args=list(config_genomes[assemblyName,]))
assign('genome', base::get(config_genomes[assemblyName,]))
#Chr size
chr <- as.character(unique(seqnames(reads)))
x<-seqinfo(genome)
seqlevels(x) <- chr
spacer<- paste0(spacer, " ")
message(paste0(spacer, "making bins"))
bin.GR <- tileGenome(x, tilewidth=res, cut.last.tile.in.chrom=TRUE)
bin.GR$pos <- start(resize(bin.GR,width=1,fix="center"))
#overlap
message(paste0(spacer, "Overlapping reads with bins"))
reads <- Captures.rds
hits <- findOverlaps(reads,bin.GR)
reads$bin <- 0
reads[queryHits(hits),]$bin <- subjectHits(hits)
sum.reads <- aggregate(reads$normReads, by = list(reads$bin), FUN=sum)
bin.GR$normReads<-0
bin.GR$normReads[sum.reads$Group.1] <- sum.reads$x
sum.reads2 <- aggregate(reads$norm4C, by = list(reads$bin), FUN=sum)
bin.GR$norm4C<-0
bin.GR$norm4C[sum.reads2$Group.1] <- sum.reads2$x
return(list(reads=Captures.rds,bins=bin.GR))
}
doBins <- function(file, expname, bin, reads, assemblyName, config_genomes, report, vpInfo, log.path){
if (nrow(vpInfo) != 1){
spacer = " "
msg <- paste0(spacer, "--- ")
} else {
spacer = " "
msg <- paste0(spacer, "### ")
}
if (file.exists(file)){
if (bin < 1e3){
error.msg <- paste0(msg, "WARNING: rds bin file ", expname, " already exist with a bin of ", bin, ", continuing with exisiting file.")
} else {
error.msg <- paste0(msg, "WARNING: rds bin file ", expname, " already exist with a bin of ", (bin/1e3), "kb, continuing with exisiting file.")
}
write(error.msg, log.path, append=TRUE)
message(error.msg)
rds <- readRDS(file)
return(list(reads=rds$reads,bins=rds$bins))
} else {
message(paste0(msg, "counting normalized reads on bins."))
bin.GR <- make.reads.and.bins(reads=reads, assemblyName=assemblyName, res=bin, config_genomes=config_genomes, spacer=spacer)
saveRDS(object=list(reads=bin.GR$reads, bins=bin.GR$bins, report=report, vpInfo=vpInfo), file=file, compress=TRUE)
return(bin.GR)
}
}
export.report <- function(RDS.F, OUTPUT.F, logname){
files <- list.files(path=RDS.F, pattern=".rds", recursive=FALSE)
report.df <- data.frame()
for(i in 1:length(files)){
vpname <- gsub("[.].*$", "", files[i])
rds <- readRDS(paste0(RDS.F, files[i]))
report <- rds$report
newrow <- data.frame(vpname=vpname,report)
report.df <- rbind(report.df, newrow)
}
write.table(report.df, file=paste0(OUTPUT.F,"/report_", logname,".txt"), row.names=FALSE, quote=FALSE)
}
createReport <- function(allReads, mapReads, demuxReads, chromosome, vpPos, normFactor=1e6, wSize, nTop, motifPosperc, readlenperc){
nMapped <- length(mapReads)
uniqueReads <- sum(allReads$reads)
uniqueCaptures <- sum(allReads$reads>0)
reads <- allReads[as.vector(seqnames(allReads)) == chromosome]
cisReads <- sum(reads$reads)
percCis<-round(100*cisReads/uniqueReads, 2) #this does not exclude the Top reads..
cisCaptures <- sum(reads$reads>0)
nMappedCis <- length(mapReads[seqnames(mapReads) == chromosome])
nMappedCisperc <- round(100*nMappedCis/nMapped, 2)
topIdx <- 1:length(reads) %in% order(-reads$reads)[1:nTop]
topReads <- sum(reads$reads[topIdx])
topPct <- round(100*topReads/cisReads, digits=2)
readsGR <- reads[!topIdx]
allReads.nTop <- subsetByOverlaps(allReads, reads[topIdx], invert=T)
uniqueReads.nTop <- sum(allReads.nTop$reads)
cisReads.nTop <- sum(readsGR$reads)
percCis.nTop <- round(100*cisReads.nTop/uniqueReads.nTop, 2)
vpWithin100Kb <- readsGR[unique(queryHits(findOverlaps(ranges(readsGR), resize(IRanges(vpPos, vpPos), width=2e5, fix="center"))))]
capt100Kb <- round(100*mean(vpWithin100Kb$reads>0), digits=2)
cov100Kb <- round(100*sum(vpWithin100Kb$reads)/sum(readsGR$reads), digits=2)
vpWithin1Mb <- readsGR[unique(queryHits(findOverlaps(ranges(readsGR), resize(IRanges(vpPos, vpPos), width=2e6, fix="center"))))]
capt1Mb <- round(100*mean(vpWithin1Mb$reads>0), digits=2)
cov1Mb <- round(100*sum(vpWithin1Mb$reads)/sum(readsGR$reads), digits=2)
report <- data.frame(
nReads=demuxReads, # total demux reads
motifPosperc=motifPosperc,
readlenperc=readlenperc,
nMapped=nMapped, # Bowtie mapped read
nMappedCis=nMappedCis, # Bowtie mapped reads in Cis
nMappedCisperc=nMappedCisperc, # Bowtie mapped % reads in Cis
fragMapped=uniqueReads, # Toal unique reads
fragMappedCis=cisReads,
fragMappedCisPerc=percCis,
fragMappedCisCorr=cisReads.nTop,
fragMappedCisPercCorr=percCis.nTop,
nCaptures=uniqueCaptures,
nCisCaptures=cisCaptures,
topPct=topPct,
capt100Kb=capt100Kb,
cov100Kb=cov100Kb,
capt1Mb=capt1Mb,
cov1Mb=cov1Mb,
stringsAsFactors=FALSE
)
return(report)
}
createPlot <- function(plotTitle, vpPos, chromosome, fragGR, plotLegend=NULL, plotView=1e6, maxY=2500, minY=0, xaxisUnit=c('Mb', 'Kb', 'bp'),
plotRegion='cis', foldOut='./', plotType=c('PDF', 'PNG')){
xaxisUnit <- match.arg(xaxisUnit, c('Mb', 'Kb', 'bp'))
if(plotRegion == 'cis'){
if(xaxisUnit == 'Mb'){
scaleValue <- 1e6
} else if (xaxisUnit == 'Kb'){
scaleValue <- 1e3
} else {
scaleValue <- 1
}
zoom <- GRanges(seqnames=chromosome, IRanges(start=vpPos-plotView, end=vpPos+plotView))
if (start(zoom) < 1){
start(zoom) <- 1
}
reads.zoom <- fragGR[unique(findOverlaps(fragGR, zoom)@from)]
if(plotType == 'PDF'){
pdf(file=paste0(foldOut, plotTitle, ".pdf"))
} else {
png(file=paste0(foldOut, plotTitle, ".png"), width=3200, height=3200, res=300)
}
plot(reads.zoom$pos/scaleValue, reads.zoom$norm4C,
type = "h",
xlim = c(start(zoom)/scaleValue, end(zoom)/scaleValue),
ylim = c(minY, maxY),
xlab = paste0(chromosome," - Chromosome position (", xaxisUnit, ")"),
ylab = paste0("4C Coverage / ", scaleValue, " mapped reads"),
frame.plot = FALSE,