-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchicdiff.R
2163 lines (1631 loc) · 71.8 KB
/
chicdiff.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
## Settings functions -----------------
defaultChicdiffSettings <- function()
{
list(
inputfiles= NA,
peakfiles= NA,
chicagoData= NA,
countData= NA,
rmapfile= NA,
targetColumns= NA,
baitmapfile= NA,
RUexpand= 5L,
score= 5,
norm="combined",
theta = NULL,
theta_grid = seq(0,1,0.25),
saveAuxData = FALSE,
parallel = FALSE,
device = "png",
printMemory = FALSE,
outprefix = ""
)
}
### This is where we now set the defaults
### Order of priority:
### settings override settings from settingsFile
### both override chicdiff.settings
setChicdiffExperiment = function(designDir="", chicagoData = NA, countData = NA, peakfiles = NA,
outprefix = "test", settings=list(), settingsFile=NULL, inputfiles = NA,
chicdiff.settings=defaultChicdiffSettings())
{
if(designDir == "" & identical(settings, list()) & is.null(settingsFile) & identical(chicdiff.settings, defaultChicdiffSettings()))
{
stop("Design not specified. Please specify a design directory or design files.")
}
chicdiff.settings = .updateChicdiffSettings(designDir, chicagoData, countData, peakfiles, outprefix,
settings, settingsFile, inputfiles, chicdiff.settings)
saveRDS(chicdiff.settings, paste0(chicdiff.settings[["outprefix"]], "_settings.Rds"))
chicdiff.settings
}
.updateChicdiffSettings = function(designDir, chicagoData, countData, peakfiles, outprefix,
settings, settingsFile, inputfiles, chicdiff.settings,
updateDesign=FALSE){
modSettings = vector("list")
if(!is.null(settingsFile)){
message(paste0("Reading custom experimental settings from ", settingsFile, "..."))
# http://stackoverflow.com/questions/6602881/text-file-to-list-in-r
sf <- scan(settingsFile, what="", sep="\n")
modSettings <- strsplit(sf, "[[:space:]]+")
names(modSettings) <- sapply(modSettings, `[[`, 1)
modSettings <- lapply(modSettings, `[`, -1)
# convert numerically defined settings to numbers
# do the same for logical settings
# suppressing "NAs introduced by coercion" warnings
suppressWarnings({
modSettings <- lapply(modSettings, function(s){
num_s = as.numeric(s);
if(!is.na(num_s)) { return (num_s) };
bool_s = as.logical(s);
if(!is.na(bool_s)) { return(bool_s) };
s
})
})
}
for (s in names(settings)){
modSettings[[s]] = settings[[s]]
}
for (s in names(modSettings)){
chicdiff.settings[[s]] = modSettings[[s]]
}
chicdiff.settings[["outprefix"]] = outprefix
chicdiff.settings[["chicagoData"]] = chicagoData
chicdiff.settings[["countData"]] = countData
if(any(is.na(chicagoData)) | any(is.na(countData))){
if(is.na(chicdiff.settings[["inputfiles"]])){
chicdiff.settings[["inputfiles"]] = inputfiles
}else{
if (!file.exists(chicdiff.settings[["inputfiles"]])){
stop(paste("No config file found at the specified location", chicdiff.settings[["inputfiles"]]))
}
}
} else{
if(!(all.equal(names(chicagoData), names(countData)))){
stop("Conditions for the RDS/RDA files and chinputs must be the same")
}
temp <- unlist(chicagoData)
temp_2 <- unlist(countData)
if(!(length(temp) == length(temp_2))){
stop("Must provide the same number of RDS/RDA files as chinputs")
}
}
if(!is.na(inputfiles)){
input_lists <- .makeTargetFilesList(inputfiles)
chicagoData <- input_lists[[1]]
countData <- input_lists[[2]]
}
chicdiff.settings[["peakfiles"]] = peakfiles
if(is.na(chicdiff.settings[["peakfiles"]])){
stop("No peak files provided")
} else if(!file.exists(chicdiff.settings[["peakfiles"]])){
stop(paste("No peak files found at the specified location", chicdiff.settings[["peakfiles"]]))
}
targetColumns <- .getTargetColumns(chicagoData)
chicdiff.settings[["targetColumns"]] = targetColumns
# peakfile_columns <- colnames(.multimerge(peakfiles))
#if(!all(targetColumns %in% peakfile_columns)){
# stop("All specified columns must be present in the peak files")
#}
if(is.na(chicdiff.settings[["baitmapfile"]]) | (updateDesign & !is.null(designDir))){
chicdiff.settings[["baitmapfile"]] = .locateFile("<baitmapfile>.baitmap", designDir, "\\.baitmap$")
}else{
if (!file.exists(chicdiff.settings[["baitmapfile"]])){
stop(paste("No baitmap file found at the specified location", chicdiff.settings[["baitmapfile"]]))
}
}
if(is.na(chicdiff.settings[["rmapfile"]]) | (updateDesign & !is.null(designDir))){
chicdiff.settings[["rmapfile"]] = .locateFile("<rmapfile>.rmap", designDir, "\\.rmap$")
}else{
if (!file.exists(chicdiff.settings[["rmapfile"]])){
stop(paste("No rmap file found at the specified location", chicdiff.settings[["rmapfile"]]))
}
}
chicdiff.settings[["norm"]] = tolower(chicdiff.settings[["norm"]])
if (length(chicdiff.settings[["norm"]])>1){ stop ("Parameter error: Only one normalisation method can be specified at a time") }
if (!chicdiff.settings[["norm"]] %in% c("standard", "fullmean", "combined")){
stop ("Parameter error: normalisation method should be one of 'standard', 'fullmean', 'combined'")
}
message("Checking the design files...")
baitmapfile = Chicago:::.readBaitmap(chicdiff.settings)
rmapfile = Chicago:::.readRmap(chicdiff.settings)
if (ncol(rmapfile)<4){
stop("There are fewer columns in the rmap file than expected. This file should have 4 columns, listing the genomic coordinates and IDs for each restriction fragment.")
}
if (ncol(rmapfile)>4){
stop("There are more columns in the rmap file than expected. This file should have 4 columns, listing the genomic coordinates and IDs for each restriction fragment. Check that rmapfile and baitmap files aren't swapped round\n")
}
if (any(duplicated(rmapfile[[4]]))){
stop(paste("Duplicated fragment IDs found in rmapfile (listed below):\n",
paste(rmapfile[[4]][duplicated(rmapfile[[4]])], collapse=",")))
}
chicdiff.settings
}
# ----------
.getTargetColumns <- function(chicagoData){
conditions <- names(chicagoData)
targetColumns <- vector("list", length(conditions))
for(i in seq_along(conditions)){
temp <- conditions[[i]]
targetColumns[[i]] <- names(chicagoData[[temp]])
}
targetColumns <- unlist(targetColumns)
if(is.null(targetColumns)){
targetColumns <- conditions
}
okay = (length(targetColumns) == length(conditions) | length(targetColumns) == length(unlist(chicagoData)))
if(!okay){ stop("Peak file columns incorrectly specified") }
targetColumns
}
.strsplit_unlist <- function(x){
temp <- strsplit(x, split= ",")
unlist(temp)
}
.makeTargetFilesList <- function(config){
temp <- fread(config, header = FALSE)
temp_1 <- temp[, paste(V2, collapse = ","), by = V1]
temp_2 <- temp[, paste(V3, collapse = ","), by = V1]
names(temp_1) <- c("condition", "files")
names(temp_2) <- c("condition", "files")
temp_1_2 <- lapply(temp_1[,files], .strsplit_unlist)
temp_2 <- lapply(temp_2[,files], .strsplit_unlist)
names(temp_1_2) <- temp_1[, condition]
names(temp_2) <- temp_1[, condition]
return(list(temp_1_2, temp_2))
}
#-------------------------------Auxilliary functions-----------------------------------------------#
.multimerge <- function(peakFiles, targetColumns)
{
peakDTs <- lapply(peakFiles, fread)
peakMatrix <- Reduce(function(x,y)
merge(x, y,
by=c("baitChr","baitStart","baitEnd","baitID",
"baitName","oeChr","oeStart","oeEnd",
"oeID","oeName","dist"), all=T), peakDTs)
peakMatrix
}
readAndFilterPeakMatrix <- function(peakFiles, targetColumns, chicagoData, conditions, score, outprefix=""){
## Essentially reads in the peak matrix, taking the target columns if specified (else just takes everything) and filters for rows where at least
##one score is > 5 (or whatever is specified) and filters out trans interactions.
if(length(peakFiles) > 1){
x <- .multimerge(peakFiles, targetColumns)
} else {
x <- fread(peakFiles)
}
peakfile_columns <- colnames(x)
if(!all(targetColumns %in% peakfile_columns)){
stop("All specified targetColumns must be present in the peak file(s)")
}
all_baits <- unique(x$baitID)
sel <- which(colnames(x) %in% targetColumns)
x <- x[,c(1:11, sel), with=FALSE]
sel <- rep(FALSE, nrow(x))
for(cl in targetColumns)
{
sel <- sel | x[,get(cl) > score & !is.na(get(cl))] ##Get any rows where at least one score > 5.
}
x <- x[sel,]
if(length(targetColumns) > length(conditions)){
sel2 <- rep(TRUE, nrow(x))
for(i in seq_along(conditions)){
temp <- conditions[[i]]
cols <- colnames(x)[colnames(x) %in% names(chicagoData[[temp]])]
sel2 <- sel2 & rowSums(x[,!is.na(.SD[,cols, with = FALSE])]) >= 2 ##Remove any rows where there isn't at least 2 replicates for each condition with non-NA values
}
x <- x[sel2]
}
x <- x[!is.na(dist),] ## <- FILTER OUT TRANS INTERACTIONS - Assumed in (*)
x <- x[!(oeID == (baitID + 1) | oeID == (baitID - 1)),] ## FILTER OUT DIRECTLY ADJACENT INTERACTIONS
filtered_baits <- all_baits[which(!(all_baits %in% unique(x$baitID)))]
filtered_baits <- list(filtered_baits)
fwrite(filtered_baits, paste0(outprefix, "_filteredBaits.txt"))
x
}
.printMemory <- function(printMemory){
if(printMemory == TRUE){
print(gc(reset=TRUE))
}
}
.locateFile = function(what, where, pattern){
message("Locating ", what, " in ", where, "...")
filename = list.files(where, pattern)
if (length(filename)!=1){
stop(paste0("Could not unambigously locate a ", what, " in ", where, ". Please specify explicitly in settings\n"))
}
message("Found ", filename)
file.path(where, filename)
}
#--------------------------------------Pipeline ---------------------------------------------#
#Pipeline - many of these arguments have defaults, but are assigned here explicitly for clarity.
chicdiffPipeline <- function(chicdiff.settings)
{
message("\n*** Running getRegionUniverse\n")
RU <- getRegionUniverse(chicdiff.settings)
.printMemory(chicdiff.settings[["printMemory"]])
message("\n*** Running getControlRegionUniverse\n")
RUcontrol <- getControlRegionUniverse(chicdiff.settings, RU)
.printMemory(chicdiff.settings[["printMemory"]])
message("\n*** Running getFullRegionData\n")
FullRegionData <- getFullRegionData(chicdiff.settings, RU, RUcontrol, suffix = "")
.printMemory(chicdiff.settings[["printMemory"]])
message("\n*** Running DESeq2Wrap for FullRegion\n")
DESeqOut <- DESeq2Wrap(chicdiff.settings, RU, FullRegionData[[1]])
.printMemory(chicdiff.settings[["printMemory"]])
message("\n*** Running DESeq2Wrap for FullControlRegion\n")
if(chicdiff.settings[["norm"]]=="combined" &
is.null(attributes(DESeqOut)$theta) &
is.null(chicdiff.settings[["theta"]])){
warning("Normalisation weight theta is not defined and its inference may fail on control regions")
}
DESeqOutControl <- DESeq2Wrap(chicdiff.settings, RUcontrol, FullRegionData[[2]],
suffix = "Control", theta = attributes(DESeqOut)$theta)
.printMemory(chicdiff.settings[["printMemory"]])
message("\n*** Running IHWcorrection\n")
output <- IHWcorrection(chicdiff.settings, DESeqOut, FullRegionData[[1]],
DESeqOutControl, FullRegionData[[2]], countput = FullRegionData[[3]])
.printMemory(chicdiff.settings[["printMemory"]])
print(chicdiff.settings)
print(sessionInfo())
output
}
#-------------------------------Pipeline functions----------------------------------#
####------------------------------- getRegionUniverse-------------------------------#
.expandAvoidBait <- function(bait, oe, s)
{
##Function usually returns (oe-s):(oe+s) - range around oe
##But if bait too close to oe, stop the range short.
if(abs(bait - oe) > s+1)
{
return((oe - s):(oe + s))
} else if (oe > bait) {
return((bait + 2L):(oe + s))
} else if (oe < bait){
return((oe - s):(bait - 2L))
} else {
stop("Invalid parameters bait=",bait," oe=",oe," s=",s)
}
}
getRegionUniverse <- function(chicdiff.settings, suffix = ""){
RUexpand = chicdiff.settings[["RUexpand"]]
rmapfile = chicdiff.settings[["rmapfile"]]
peakFiles = chicdiff.settings[["peakfiles"]]
targetColumns = chicdiff.settings[["targetColumns"]]
chicagoData = chicdiff.settings[["chicagoData"]]
score = chicdiff.settings[["score"]]
saveRDS = chicdiff.settings[["saveAuxData"]]
outprefix = chicdiff.settings[["outprefix"]]
conditions <- names(chicagoData)
x <- readAndFilterPeakMatrix(peakFiles = peakFiles, score = score, targetColumns = targetColumns, chicagoData=chicagoData, conditions = conditions, outprefix = outprefix)
## Expand the "point universe" to get "region universe" by "window" mode------------------
#baits <- unique(x$baitID)
#baits <- head(baits, 5000)
#x <- x[baitID %in% baits,]
##Just expand calls by s in each direction
RU.DT <- x[,c("baitID", "oeID"),with=FALSE]
RU.DT$regionID <- 1:nrow(RU.DT)
RU.DT <- RU.DT[,
list(otherEndID = .expandAvoidBait(baitID, oeID, RUexpand)),
by=c("baitID","regionID")
]
## Ensure regions remain within the genome
rmap <- fread(rmapfile)
maxfrag <- max(rmap$V4)
RU.DT <- RU.DT[otherEndID <= maxfrag,]
## Ensure that regions stay on the correct chromosome (*)
## get chr info
colnames(rmap) <- c("chr", "start", "end", "ID")
setkey(RU.DT, otherEndID)
setkey(rmap, ID)
RU.DT <- rmap[,c("chr", "ID"),with=FALSE][RU.DT]
setnames(RU.DT, "ID", "otherEndID")
setkey(RU.DT, baitID)
RU.DT <- rmap[,c("chr", "ID"),with=FALSE][RU.DT]
setnames(RU.DT, "ID", "baitID")
## keep only cis interactions
RU.DT <- RU.DT[chr == i.chr,]
RU.DT[,chr:=NULL]
RU.DT[,i.chr:=NULL]
if(saveRDS == TRUE){
saveRDS(RU.DT, paste0(outprefix, "_RegionUniverse", suffix, ".Rds"))
}
RU.DT
}
#-----------------------Functions needed for getControlRegionUniverse ----------------------------#
giveOneSeed <- function(bait, dist, min, max){
ifelse(bait + dist < min, bait - dist, ifelse(bait + dist > max, bait - dist, bait + dist))
}
giveDists <- function(bait, min, max, std){
dist <- round(rnorm(n = 1, mean = 0, sd = std))
onChr_notBait <- (((bait + abs(dist)) < max) | ((bait - abs(dist)) > min)) & (dist != 0)
while(!onChr_notBait){
dist <- round(rnorm(n = 1, mean = 0, sd = std))
onChr_notBait <- (((bait + abs(dist)) < max) | ((bait - abs(dist)) > min)) & (dist != 0)
}
dist
}
giveManySeeds <- function(bait, min, max, std){
dists <- unlist(lapply(bait, giveDists, min = min, max = max, std = std))
mapply(giveOneSeed, bait, dists, MoreArgs = list(min = min, max = max))
}
#-------------------------------------------getControlRegionUniverse----------------------------------------#
getControlRegionUniverse <- function(chicdiff.settings, RU){
RUexpand <- chicdiff.settings[["RUexpand"]]
saveRDS <- chicdiff.settings[["saveAuxData"]]
outprefix <- chicdiff.settings[["outprefix"]]
bmap <- fread(chicdiff.settings[["baitmapfile"]])
rmap <- fread(chicdiff.settings[["rmapfile"]])
colnames(rmap) <- c("chr", "start", "end", "ID")
colnames(bmap) <- c("chr", "start", "end", "ID", "baitname")
RUshorter <- merge(RU, rmap[,c("chr", "ID")], by.x = "baitID", by.y = "ID")
max_contacts <- RUshorter[, list(max_contact = max(abs(baitID - otherEndID))),by = "chr"]
RUcontrol <- as.data.table(sample(bmap$ID, size = length(unique(RU$regionID)), replace = TRUE))
setnames(RUcontrol, "V1", "baitID")
RUcontrol <- merge(bmap[chr %in% max_contacts$chr, c("chr", "ID")], RUcontrol, by.x = "ID", by.y = "baitID")
for(ch in unique(RUcontrol[,chr])){
std <- max_contacts[chr == ch, max_contact]/3
max <- rmap[chr == ch, max(ID)]
min <- rmap[chr == ch, min(ID)]
RUcontrol[chr == ch, seed := giveManySeeds(ID, min = min, max = max, std = std)]
}
colnames(RUcontrol) <- c("baitID", "chr", "oeID")
setkey(RUcontrol, baitID, oeID)
RUcontrol[,regionID:=1:nrow(RUcontrol)]
RUcontrol <- RUcontrol[,
list(otherEndID = .expandAvoidBait(baitID, oeID, RUexpand)),
by=c("baitID","regionID")
]
## Ensure regions remain within the genome
maxfrag <- max(rmap[,ID])
RUcontrol <- RUcontrol[otherEndID <= maxfrag,]
## Ensure regions stay on the correct chromosome
setkey(RUcontrol, otherEndID)
setkey(rmap, ID)
RUcontrol <- rmap[,c("chr", "ID"),with=FALSE][RUcontrol]
setnames(RUcontrol, "ID", "otherEndID")
setkey(RUcontrol, baitID)
RUcontrol <- rmap[,c("chr", "ID"),with=FALSE][RUcontrol]
setnames(RUcontrol, "ID", "baitID")
## keep only cis interactions
RUcontrol <- RUcontrol[chr == i.chr,]
RUcontrol[,chr:=NULL]
RUcontrol[,i.chr:=NULL]
if(saveRDS){
saveRDS(RUcontrol, paste0(outprefix, "_ControlRegionUniverse.Rds"))
}
return(RUcontrol)
}
#-------------------------------Function combining 02, 03 and 04 R scripts ----------------------------------#
#Function should collect the count data from the chinputs, get the dispersions and
#interaction parameters and then merge to give full data for each region
readRDSorRDA <- function(file){
tmpEnv <- new.env()
suppressWarnings(tmp <- try(load(file, envir = tmpEnv), silent = TRUE))
if("try-error" %in% class(tmp)){
#message("Not an RDA. Checking whether RDS.")
suppressWarnings(tmp <- try(output <- readRDS(file), silent = TRUE))
if("try-error" %in% class(tmp)){
message("Cannot read file. Must be an RDS or RDA file.")
} else{
#message("Detected RDS")
output
}
} else{
#message("Detected RDA")
get(ls(envir=tmpEnv)[1], envir=tmpEnv)
}
}
#------------------------------------------------------------------------------#
.chicEstimateDistFun <- function (x, settings=Chicago::defaultSettings()) {
# Take the "refBinMean" column of the data x as f(d_b)
# then interpolate & extrapolate to get f(d).
# Get f(d_b)
setkey(x, distbin, refBinMean)
f.d <- unique(x, by=key(x))[is.na(refBinMean)==FALSE][, c("distbin", "refBinMean"), with=FALSE]
f.d <- f.d[order(refBinMean, decreasing=TRUE)]
setDF(f.d) # f.d is tiny, so no need to bother with it being a data.table
f.d$midpoint <- seq(from=round(settings$binsize/2), by=settings$binsize, length.out=nrow(f.d))
obs.min <- log(min(f.d$midpoint))
obs.max <- log(max(f.d$midpoint))
##Spline - Cubic fit over observed interval, linear fit elsewhere, assume continuity of f(d) & f'(d).
distFunParams <- list(method="cubic")
##cubic fit (quadratic not immensely different TBH)
f.d.cubic <- lm(log(refBinMean) ~ log(midpoint) + I(log(midpoint)^2) + I(log(midpoint)^3), data = f.d)
fit <- f.d.cubic$coefficients
distFunParams[["cubicFit"]] <- fit
##Extrapolation: Fit the "head" and "tail" of f using continuity
distFunParams[["obs.min"]] <- log(min(f.d$midpoint))
distFunParams[["obs.max"]] <- log(max(f.d$midpoint))
beta <- fit[2] + 2*fit[3]*c(obs.min, obs.max) + 3*fit[4]*(c(obs.min, obs.max)^2)
alpha <- fit[1] + (fit[2] - beta)*c(obs.min, obs.max) + fit[3]*c(obs.min, obs.max)^2 + fit[4]*c(obs.min, obs.max)^3
distFunParams[["head.coef"]] <- c(alpha[1], beta[1])
distFunParams[["tail.coef"]] <- c(alpha[2], beta[2])
distFunParams
}
#--------------------------------------Non-parallel version--------------------------------------#
getFullRegionData1 <- function(chicdiff.settings, RU, is_control = FALSE, suffix = ""){
countData = chicdiff.settings[["countData"]]
chicagoData = chicdiff.settings[["chicagoData"]]
rmapfile = chicdiff.settings[["rmapfile"]]
saveRDS = chicdiff.settings[["saveAuxData"]]
outprefix = chicdiff.settings[["outprefix"]]
targetRDSorRDAFiles <- unlist(chicagoData)
targetChFiles <- unlist(countData)
## 03getInteractionParameters
RU_IntParams <- copy(RU)
RU_IntParams[,regionID:=NULL]
RU_IntParams <- unique(RU_IntParams)
##prep output
outData <- vector("list", length(targetRDSorRDAFiles))
dispersions <- numeric(length(targetRDSorRDAFiles))
tempForCounts <- vector("list", length(targetRDSorRDAFiles))
if(!is_control){
conditions <- rep(names(chicagoData), sapply(chicagoData, length))
countput <- lapply(unique(conditions), assign,
value = vector("list", length(targetRDSorRDAFiles)))
names(countput) <- unique(conditions)
}
##1) Read in each file...
for(i in 1:length(targetRDSorRDAFiles))
{
message("\nReading Chicago dataset ",i, " of ", length(targetRDSorRDAFiles), " : ", names(targetRDSorRDAFiles)[i])
file <- targetRDSorRDAFiles[i]
#load(file) ##this produces the object 'x' --old
x <- readRDSorRDA(file)
##1a) collect the dispersion
if("chicagoData" %in% class(x)){
dispersions[i] <- x@params$dispersion
x <- as.data.table(x@x)
} else{
dispersions[i] <- attributes(x)$dispersion
setDT(x)
}
# message("Finished reading")
##1b) collect the Bmean, Tmean information that is present
message("Collecting Bmean and Tmean")
setkey(x, baitID, otherEndID)
setkey(RU_IntParams, baitID, otherEndID)
out <- x[RU_IntParams, c("baitID", "otherEndID","distSign","Bmean", "Tmean", "score"), with=FALSE]
##(note that score=NA occurs when N=0 - hence replace score=0)
##1c) recalculate distSign (need to do this for control regions)
message("Recalculating distSign")
if(any(is.na(out$distSign)))
{
rmap <- Chicago:::.readRmap(list(rmapfile=rmapfile))
colnames(rmap) <- c("chr", "start", "end", "ID")
setkey(rmap, "ID")
temp <- merge(RU_IntParams, rmap, all.x=TRUE, by.x="baitID", by.y="ID")
temp <- merge(temp, rmap, all.x=TRUE, by.x="otherEndID", by.y="ID")
setkey(temp, baitID, otherEndID)
temp[,distSign:=round(((start.y + end.y)-(start.x + end.x))/2)]
if(any(abs(temp$distSign - out$distSign) > 1, na.rm=TRUE))
{
stop("Error calculating distances.")
}
out$distSign <- temp$distSign
}
##1d) bait annotation: collect s_js, tblb
##Note that s_j can be NA (for baits that were filtered out!)
message("Collecting bait parameters (s_j and tblb)")
temp <- x[,list(s_j=s_j[1], tblb=tblb[1]),by="baitID"]
setkey(temp, baitID)
setkey(out, baitID)
out <- merge(out, temp, all.x=TRUE)
##1e) OE annotation: collect s_is, tlb
##s_i not allowed to be NA - just assume 1.
## => s_i should be 0)
message("Collecting other end parameters (s_i and tlb)")
temp <- x[,list(s_i=s_i[1], tlb=tlb[1]),by="otherEndID"]
setkey(temp, otherEndID)
setkey(out, otherEndID)
out <- merge(out, temp, all.x=TRUE)
out[is.na(s_i),s_i:=1]
setkey(out, baitID, otherEndID)
##1f) reconstruct Tmean information
message("Collecting Tmean")
setkey(x, tlb, tblb)
setkey(out, tlb, tblb)
temp <- x[,Tmean[1],by=c("tblb", "tlb")]
setnames(temp, "V1", "Tmean")
out[,Tmean:=NULL]
out <- merge(out, temp, all.x=TRUE)
##1g) impute some of the missing Tmeans
## missing tlb suggests that the other end was rarely observed, so assume lowest
## Tmean corresponding to the appropriate tblb.
message("Imputing missing Tmeans")
templowest <- temp[,c(Tmean = min(Tmean)),by="tblb"]
tempDictionary <- templowest$V1
names(tempDictionary) <- templowest$tblb
out[is.na(tlb) & !is.na(tblb), Tmean := tempDictionary[tblb]]
##2) Reconstruct the distance function from distbin info
message("Reconstructing the distance function")
distFunParams <- .chicEstimateDistFun(x)
##3) Reconstruct Bmean information (But!! When s_j = NA,
## ensure that Bmean comes out as NA too.)
message("Reconstructing Bmean")
out <- Chicago:::.estimateBMean(out, distFunParams)
out[is.na(s_j),Bmean:=NA]
setkey(out, baitID, otherEndID)
outData[[i]] <- out
if(!is_control){
rmap_copy <- copy(rmap)
rmap_copy[, chr := NULL]
rmap_copy[, midpoint := (start + end)/2]
rmap_copy[, c("start", "end") := NULL]
setnames(rmap_copy, "ID", "otherEndID")
x <- x[!is.na(x[,distSign])]
if("newScore" %in% names(x)){
x[, names(x)[!(names(x) %in% c("baitID", "otherEndID", "N", "Bmean", "newScore"))] := NULL]
setnames(x, "newScore", "score")
} else{
x[, names(x)[!(names(x) %in% c("baitID", "otherEndID", "N", "Bmean", "score"))] := NULL]
}
gc()
x <- merge(x, rmap_copy, by= "otherEndID")
gc()
#message("Assigning conditions")
for(n in 1:length(countput)){
if(conditions[[i]] == names(countput)[[n]]){
countput[[n]][[i]] <- x
}
}
}
#This just keeps all of the loaded RDAs if we still need them for the count data because we don't have chinputs
if(is.null(countData)){
x <- x[, c("baitID", "otherEndID", "N"), with = FALSE]
columnNames <- paste0("N.", names(targetRDSorRDAFiles))
setnames(x, old="N", new=columnNames[i])
setkey(x, baitID, otherEndID)
tempForCounts[[i]] <- x
rm(x)
}
}
message("")
if(!is_control){
message("Saving counts\n")
for(i in 1:length(countput)){
countput[[i]] <- rbindlist(countput[[i]])
gc()
countput[[i]] <- countput[[i]][,list(Nav = mean(N), Bav = mean(Bmean), score = max(score), midpoint = midpoint[1]), by = c("baitID", "otherEndID")]
gc()
countput[[i]][, condition := rep(names(countput)[[i]], nrow(countput[[i]]))]
}
countput <- rbindlist(countput)
setnames(countput, "midpoint", "oeID_mid")
saveRDS(countput, paste0(outprefix, "_countput.Rds"))
}
baits <- sort(unique(RU$baitID)) ##baits to get information from
if(is.null(countData)){
message("Reconstructing countData")
gc()
mergedFiles <- Reduce(merge, tempForCounts)
countData <- vector("list", length(targetRDSorRDAFiles))
for(i in seq_along(countData)){
countData[[i]] <- mergedFiles[, c("baitID", "otherEndID", columnNames[i]), with = FALSE]
setkey(countData[[i]], baitID)
countData[[i]] <- countData[[i]][J(baits),]
setkey(countData[[i]], baitID)
}
x <- RU
setkey(x, baitID, otherEndID)
message("Merging countData")
for(i in seq_along(countData))
{
temp <- countData[[i]]
setnames(temp, old = columnNames[i], new = "N")
setkey(temp, baitID, otherEndID)
x <- merge(x, temp, all.x=TRUE)
x[is.na(N), N:=0]
setnames(x, old="N", new=columnNames[i])
}
# message("no chinput case finished")
}
#Recall that outData and dispersions are our useful outputs from this part above
## 02getCounts.R
##Given a region universe, collect the number of reads in each region from the chinputs.
##Inputs and parameters:
##requires countData
##2) Collect all of the read count information ----------------
if(!is.null(countData)){
message("")
countData <- vector("list", length(targetChFiles))
gc()
for(i in 1:length(countData))
{
message("Reading count data for ", names(targetChFiles)[i])
x <- fread(targetChFiles[i])
setkey(x, baitID)
x <- x[J(baits),]
setkey(x, baitID) ##Required for countData[4:7], where key is dropped - not sure why
countData[[i]] <- x
rm(x)
gc()
}
##2a) For each region, count the number of reads in each replicate -----------------
x <- RU
setkey(x, baitID, otherEndID)
for(i in 1:length(countData))
{
columnName <- paste0("N.", names(targetChFiles)[i])
temp <- countData[[i]][,c("baitID","otherEndID","N"), with=FALSE]
setkey(temp, baitID, otherEndID)
x <- merge(x, temp, all.x=TRUE)
x[is.na(N), N:=0]
setnames(x, old="N", new=columnName)
#message("count the number of reads in each replicate for CountOut")
}
}
##3) Collect distance -----------------
##3a) Distance ------------
message("\nCollecting distances for CountOut")
rmap <- Chicago:::.readRmap(list(rmapfile=rmapfile))
colnames(rmap) <- c("chr","start","end","fragID")
setkey(rmap, fragID)
rmap[,midpoint:=round(0.5*(start+end))]
rmap[,start:=NULL]
rmap[,end:=NULL]
x <- merge(x, rmap, by.x="otherEndID", by.y="fragID")
x <- merge(x, rmap, by.x="baitID", by.y="fragID")
setkey(x, baitID, otherEndID)
x[, distSign :=
ifelse(chr.x == chr.y,
midpoint.x - midpoint.y,
NA)]
x[, c("chr.x","midpoint.x","chr.y","midpoint.y"):=NULL]
CountOut <- x
message("Processing count data")
setkey(CountOut, baitID, otherEndID)
for(i in 1:length(targetRDSorRDAFiles))
{
s <- names(targetRDSorRDAFiles[i])
temp <- outData[[i]][,c("baitID", "otherEndID", "s_j", "Bmean", "Tmean", "score"), with=FALSE]
temp <- unique(temp)
temp[,FullMean:=Bmean+Tmean]
for(nm in colnames(temp))
if(!nm %in% c("baitID", "otherEndID"))
{
setnames(temp, nm, paste0(nm, ".", s))
}
setkey(temp, baitID, otherEndID)
CountOut <- merge(CountOut, temp, all.x=TRUE)
#message("count + interaction parameter data together")
}
myCols <- c("N", "s_j", "Bmean", "Tmean", "score", "FullMean")
getCols <- function(col) {grep(paste0("^", col), colnames(CountOut), perl=TRUE)}
sels <- lapply(myCols, getCols)
recast = melt(CountOut, measure = sels, value.name = myCols,
variable.name="sample")
recast$sample <- names(targetRDSorRDAFiles)[recast$sample]
recast$condition <- rep(
rep(names(chicagoData), sapply(chicagoData, length))
, each=nrow(CountOut))
setkey(recast, regionID)
#message("recast")
if(saveRDS == TRUE){
message("Saving FullRegionData")
if(!is_control){
saveRDS(recast, paste0(outprefix, "_FullRegionData", suffix, ".Rds"))
}else{
saveRDS(recast, paste0(outprefix, "_FullControlRegionData", suffix, ".Rds"))
}
}
if(!is_control){
resultsList <- vector("list", length = 3)
resultsList[[1]] <- recast
resultsList[[3]] <- countput
resultsList
}else{
recast
}
}
#--------------------------- The version which reads significant and control interactions in parallel-------------#
getFullRegionData2 <- function(chicdiff.settings, RU, RUcontrol, suffix = ""){
countData = chicdiff.settings[["countData"]]
chicagoData = chicdiff.settings[["chicagoData"]]
targetColumns = chicdiff.settings[["targetColumns"]]
rmapfile = chicdiff.settings[["rmapfile"]]
saveRDS = chicdiff.settings[["saveAuxData"]]
outprefix = chicdiff.settings[["outprefix"]]
targetRDSorRDAFiles <- unlist(chicagoData)
targetChFiles <- unlist(countData)
## 03getInteractionParameters.R
##Given a region universe, collect Bmean + Tmean
##Inputs and parameters:
##requires targetRDAs
RU_IntParams <- copy(RU)
RU_IntParams[,regionID:=NULL]
RU_IntParams <- unique(RU_IntParams)
RUcontrol_IntParams <- copy(RUcontrol)
RUcontrol_IntParams[,regionID:=NULL]
RUcontrol_IntParams <- unique(RUcontrol_IntParams)
##prep output
outData <- vector("list", length(targetRDSorRDAFiles))
outDataControl <- vector("list", length(targetRDSorRDAFiles)) #New to collect control data
dispersions <- numeric(length(targetRDSorRDAFiles)) #only need one of these
tempForCounts <- vector("list", length(targetRDSorRDAFiles))
conditions <- rep(names(chicagoData), sapply(chicagoData, length))
countput <- lapply(unique(conditions), assign,
value = vector("list", length(targetRDSorRDAFiles)))
names(countput) <- unique(conditions)
##1) Read in each file...
for(i in 1:length(targetRDSorRDAFiles))
{
message("\nReading Chicago dataset ",i, " of ", length(targetRDSorRDAFiles), " : ", names(targetRDSorRDAFiles)[i])
file <- targetRDSorRDAFiles[i]
x <- readRDSorRDA(file)
##1a) collect the dispersion
if("chicagoData" %in% class(x)){
dispersions[i] <- x@params$dispersion
x <- as.data.table(x@x)