-
Notifications
You must be signed in to change notification settings - Fork 2
/
RNAseqWrapper.R
3411 lines (3276 loc) · 178 KB
/
RNAseqWrapper.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
# This file is part of RNAseqWrapper.
#
# RNAseqWrapper is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RNAseqWrapper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# See <http://www.gnu.org/licenses/> for a a copy of the GNU General Public License.
#'@title a global variable for plotting control.
#'@note using quartz on MacOSX disables the lzw compression of tiffs - this variable changes the default to "Xlib" (only on MacOS)
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}
GLOBAL_VARIABLE_TIFF_LIB <- getOption("bitmapType"); if (Sys.info()['sysname'] == "Darwin") { GLOBAL_VARIABLE_TIFF_LIB <- "Xlib" }
#'@title a global variable for plotting control.
#'@note set to true if you wish some plots to be saved as svg instead of tiff/png.
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}
GLOBAL_VARIABLE_USE_SVG <- TRUE; if (Sys.info()['sysname'] == "Darwin") { GLOBAL_VARIABLE_USE_SVG <- FALSE }
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title read tables with identical columns from a directory
#'@param aDir the path to the files in "aFiles"
#'@param aExp a regular expression required within the file name
#'@param aExt a file extension required for the file to be read
#'@param aExc a regular expression which should be omitted in the file names
#'@param aHead a vector with the column names
#'@param aSep the separator used in the files
#'@param useHeader set to TRUE if tables contain column names. WARNING: aHead is still required.
#'@return a list of matrices containing values from all files - so for every header/datatype one matrix
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.read.files.from.directory <- function(aDir, aExp, aExt, aExc, aHead, aSep, useHeader = FALSE) {
# WARNING useHeader still neads aHead (it just tells if the first row shall be removed or not)
# read all the files from a given directory that contain a regular expression aExp and the ending aExt. All with aExc will be excluded
# aHead is a vector with the column names, aSep is the separator
fList <- grep(aExp, list.files(aDir, aExt), value = TRUE)
if (aExc != "") { fList <- fList[-grep(aExc,fList)] }
sList <- sapply(fList, function(x) substr(x, 1, nchar(x)-nchar(aExt)))
# read first all the files in a list and get a list of all the rownames (RID)
RID <- c()
tList <- list()
for (sampleName in sList) {
if (useHeader) {tList[[sampleName]] <- read.table(file.path(aDir,paste(sampleName, aExt, sep="")), header = TRUE, sep = aSep, quote = "", row.names = 1)}
else {tList[[sampleName]] <- read.table(file.path(aDir,paste(sampleName, aExt, sep="")), header = FALSE, sep = aSep, quote = "", row.names = 1)}
colnames(tList[[sampleName]]) <- aHead
RID <- union(RID, rownames(tList[[sampleName]]))
}
# create a list of matrices containing values from all samples - for every datatype one matrix
out <- list()
for (h in aHead) {
out[[h]] <- matrix(0, length(RID), length(sList), FALSE, list(RID, sList))
for (sampleName in sList) {
out[[h]][rownames(tList[[sampleName]]), sampleName] <- tList[[sampleName]][,h]
}
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title read tables with identical columns from a given list of files
#'@param aDir the path to the files in "aFiles"
#'@param aFiles a vector with file names
#'@param aHead a vector with the column names
#'@param aSep the separator used in the files
#'@param useHeader set to TRUE if tables contain column names. WARNING: aHead is still required.
#'@return a list of matrices containing values from all files - so for every header/datatype one matrix
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.read.files.from.given.list <- function(aDir, aFiles, aHead, aNames = c(), aSep = '\t', useHeader = FALSE) {
# WARNING useHeader still neads aHead (it just tells if the first row shall be removed or not)
# read all the given files from a given directory
# aHead is a vector with the column names, aSep is the separator
# read first all the files in a list and get a list of all the rownames (RID)
RID <- c()
temp <- list()
for (fn in aFiles) {
if (useHeader) { temp[[fn]] <- read.table(file.path(aDir, fn), header = TRUE, sep = aSep, quote = "", row.names = 1) }
else { temp[[fn]] <- read.table(file.path(aDir, fn), header = FALSE, sep = aSep, quote = "", row.names = 1) }
colnames(temp[[fn]]) <- aHead
RID <- union(RID, rownames(temp[[fn]]))
}
# create a list of matrices containing values from all files - so for every header/datatype one matrix
out <- list()
for (h in aHead) {
out[[h]] <- matrix(0, length(RID), length(aFiles), FALSE, list(RID, aFiles))
for (fn in aFiles) {
out[[h]][rownames(temp[[fn]]), fn] <- temp[[fn]][,h]
}
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title read simple "list-files" (one column) from a directory
#'@param aDir a directory with the files
#'@param aExp a regular expression required within the file name
#'@param aExt a file extension required for the file to be read
#'@param aExc a regular expression which should be omitted in the file names
#'@return a list of vectors read from the files
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.read.lists.from.directory <- function(aDir, aExp, aExt, aExc) {
#
fList <- grep(aExp, list.files(aDir, aExt), value = TRUE)
if (aExc != "") { fList <- fList[-grep(aExc,fList)] }
sList <- sapply(fList, function(x) substr(x, 1, nchar(x)-nchar(aExt)))
# read all the files in a list with the fileName as key to the list
out <- list()
for (fn in sList) {
out[[fn]] <- scan(file.path(aDir, paste(fn, aExt, sep = '')), what = "character")
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title read Rcount tables
#'@param aDir a directory with the files
#'@param aExp a regular expression required within the file name
#'@param aExc a regular expression which should be omitted in the file names
#'@param toReturn the column of interest (normally TH)
#'@return a data.frame with Rcount gene expression values
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.read.Rcount <- function(aDir, aExp = "", aExc = "", toReturn = "TH") {
fullData <- f.read.files.from.directory(aDir, aExp, ".txt", aExc, c("sumUnAmb", "sumAmb", "sumAllo", "sumDistUnAmb", "sumDistAmb", "sumDistAllo", "TH", "VAL"), "\t")
out <- round(fullData[[toReturn]])
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title read featureCounts tables
#'@param aDir a directory with the files
#'@param aExp a regular expression required within the file name
#'@param aExc a regular expression which should be omitted in the file names
#'@return a data.frame with featureCounts expression values
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.read.featureCounts <- function(aDir, aExp = "", aExc = "") {
fullData <- f.read.files.from.directory(aDir, aExp, ".txt", aExc, c("counts"), "\t", TRUE)
out <- fullData$counts
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Check whether a FASTQ file has a PHRED offset of 33 or 64
#'@param fastq a fastq file (may be gzipped)
#'@return the PHRED offset: either 33 or 64
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.check.phred.offset <- function(fastq) {
# open a connection to the file
isZipped <- (length(grep("*.gz$", fastq)) > 0)
if (isZipped) {
fq <- gzcon(file(fastq, "rb"))
} else {
fq <- file(fastq, open = "rt")
}
# the different formats and their ranges:
# Sanger: 0 to 93 (rarely above 60) with ASCII 33 to 126
# SOLiD: like Sanger ?
# Illumina 1.8: like Sanger ?
# Solexa/Illumina 1.0: -5 to 62 (normally only -5 to 40) with ASCII 59 to 126
# Illumina 1.3: 0 to 62 (normally only 0 to 40) with ASCII 64 to 126
# Illumina 1.5: Phred scores 0 to 2 have a slightly different meaning. The values 0 and 1 are no longer used and the value 2,
# encoded by ASCII 66 "B", is used also at the end of reads as a Read Segment Quality Control Indicator.
# check the quality range of the first 10'000 reads
lines <- readLines(fq, 4e4)
qualStrings <- lines[seq(4, 4e4, by = 4)]
qualStrings <- gsub('\\', '\\\\', qualStrings, fixed = TRUE) # otherwise the backslash is an escape character
ranges <- t(sapply(qualStrings, function(x) range(as.integer(charToRaw(x))), USE.NAMES = FALSE))
lowest <- min(ranges[,1])
highest <- max(ranges[,2])
cat("FILE: ", fastq, "has quality values from", lowest, "to", highest, "\n")
if (lowest < 58) {
out <- 33
} else {
out <- 64
}
# close the file connection and return the PHRED offset
close(fq)
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title summarize a table according to groups and names
#'@param x <dataframe, matrix>: numeric, colnames as in byTab
#'@param byTab <dataframe>: at least two columns: sample and group
#'@param summaryFunction: a function like mean, median, sum
#'@return the summarized table (a matrix)
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.summarize.columns <- function(x, byTab, summaryFunction) {
byTab$sample <- as.character(byTab$sample)
byTab$group <- as.character(byTab$group)
groupnames <- unique(byTab$group)
out <- matrix(0, nrow = nrow(x), ncol = length(groupnames), dimnames = list(rownames(x), groupnames))
for (gn in groupnames) {
toSummarize <- byTab$sample[byTab$group == gn]
if (length(toSummarize) > 1) {out[,gn] <- apply(x[,toSummarize], 1, summaryFunction)}
else { out[,gn] <- x[,toSummarize] }
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title simple comparison function which makes either >= x or > 0
#'@param x values
#'@param rt threshold
#'@return logical vector
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.comp <- function(x,rt){
if(rt==0){y <- x>0}
else{y <- x>=rt}
return(y)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title trim a table according to a column
#'@param x table
#'@param cn the column to trim
#'@param ext fraction of extreme values to remove (two-sided! 0.05 removes in total 10\% of all values)
#'@param viaRanks filter based on ranks - I don't remember anymore why I did this
#'@return table without the "ext" highest and the "ext" lowest values in the specified column
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.trim <- function(x, cn, ext = 0.05, viaRanks = FALSE) {
if (viaRanks) {
tot <- nrow(x)
num_remove <- floor(tot*ext)
min_rank <- num_remove
max_rank <- tot-num_remove
y <- rank(x[[cn]])
out <- rownames(x)[(y > min_rank) & (y < max_rank)]
} else {
lowerBound <- quantile(data[,cn], ext)
upperBound <- quantile(data[,cn], 1-ext)
out <- rownames(data)(data[,cn] >= lowerBound & data[,cn] <= upperBound)
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title merge two matrices with different columns (rownames don't need to match completely)
#'@param x a matrix
#'@param y another matrix
#'@param rt a threshold - remove rows which are all below it (in case of 0, it tests for >, not >=)
#'@return merged matrix
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.merge.two.matrices <- function(x,y,rt){
RID <- union(rownames(x), rownames(y))
CID <- c(colnames(x), colnames(y))
com <- matrix(0, nrow = length(RID), ncol = length(CID), dimnames = list(RID, CID))
for (cname in colnames(x)) {
com[rownames(x),cname] <- x[,cname]
}
for (cname in colnames(y)) {
com[rownames(y),cname] <- y[,cname]
}
com.use <- rownames(com)[which(apply(f.comp(com,rt),1,sum)>0)]
com <- com[com.use,]
return(com)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title take the logarithm of the absolute value and append the original sign
#'@param x a vector
#'@param logFun a logarithm funtion
#'@return a vector with the log values
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.log.twosided <- function(x, logFun) {
if (sum(is.na(x))>0) {
cat("NA values replaced by 0\n")
x[is.na(x)] <- 0
}
x[x>0] <- logFun(x[x>0])
x[x<0] <- -logFun(-x[x<0])
return(x)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title alternative transformation for count data
#'@param x a vector with cound data
#'@return a vector with the transformed values
#'@references
#'TODO: ADD THE REFERENCE
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.stahel.trafo <- function(x) {
med <- median(x, na.rm = TRUE)
qua <- quantile(x, 0.25, na.rm = TRUE)
if (qua == 0) {
cat("f.stahel.trafo(): the first quartile equals to zero. Removing all zero counts to avoid -Inf.\n")
temp <- x
temp[temp==0] <- NA
med <- median(temp, na.rm = TRUE)
qua <- quantile(temp, 0.25, na.rm = TRUE)
}
con <- med/((med/qua)^2.9)
out <- log(x + con)
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title calculate a GSEA-like cumulative sum
#'@param sortedGenes a named (genes) vector (e.g. logFC) - SORTED!
#'@param myGOIs genes of interest
#'@return cumulative sum (like in the GSEA plot)
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.calculate.GSEA.sum <- function(sortedGenes, myGOIs) {
numGOIs <- length(myGOIs)
numGenes <- length(sortedGenes)
observed <- sortedGenes %in% myGOIs
posStep <- (numGenes - numGOIs)/numGOIs
forSum <- rep(-1, numGenes)
forSum[observed] <- posStep
if (abs(sum(forSum)) > 1) {cat(posStep*length(myGOIs), posStep, length(myGOIs))}
cumSum <- cumsum(forSum)
return(cumSum)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title calculate the maximal enrichment for a given gene set of interest
#'@param sortedGenes a named (genes) vector (e.g. logFC) - SORTED!
#'@param myGOIs genes of interest
#'@return maximal enrichment value (used to compare to random sampling)
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.calculate.max.GSEA.enrichment <- function(sortedGenes, myGOIs) {
cumSum <- f.calculate.GSEA.sum(sortedGenes, myGOIs)
cumSumMax <- cumSum[which.max(abs(cumSum))]
return(cumSumMax)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Do a GSEA-like test
#'@param namedValues a sorted vector (e.g. logFC) with names (genes) vector (e.g. logFC) - SORTED!
#'@param GOIs a vector with the genes of interest
#'@param rDir directory where the plot is saved
#'@param filePrefix prefix for the name of the plot
#'@param mainTitle title in the plot
#'@param sortName a label vor the values (e.g., "logFC")
#'@param numReps number of random sets
#'@return a plot (saved as svg) and list with the pValue and enrichment scores
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.do.GSEA.like.test <- function(namedValues, GOIs, rDir, filePrefix = "", mainTitle = "", sortName = "LFC", numReps = 10000) {
sortedGenes <- names(namedValues)
## check for existence of genes
notInSorted <- setdiff(GOIs, sortedGenes)
if (length(notInSorted) > 0) {f.print.message(filePrefix, "- removed", length(notInSorted), "/", length(GOIs), "GOIs - they were not in the set of sorted genes")}
GOIs <- intersect(GOIs, sortedGenes)
observedES <- f.calculate.max.GSEA.enrichment(sortedGenes, GOIs)
observedSum <- f.calculate.GSEA.sum(sortedGenes, GOIs)
sampledValues <- rep(0, numReps)
for (i in 1:numReps) {
sampledGenes <- sample(sortedGenes, length(GOIs))
sampledValues[i] <- f.calculate.max.GSEA.enrichment(sortedGenes, sampledGenes)
}
ylimits <- c(-1000, 2000)
ylimits <- c(min(observedES, sampledValues), max(observedES, sampledValues))
pValue <- mean(abs(observedES) < abs(sampledValues))
svgOutfile <- file.path(rDir, paste(filePrefix, "GSEA.svg", sep = ''))
#pngOutfile <- file.path(rDir, paste(filePrefix, "GSEA.png", sep = ''))
svg(svgOutfile, height = 7, width = 5)
par(oma = c(2,2,1,1))
layout(matrix(1:3, nrow = 3), heights = c(1, 0.2, 0.2))
par(mar = c(0, 2, 1, 1))
plot(observedSum, type = "l", bty = "n", xaxs = "r", xaxt = "n", yaxs = "r", xlab = "", ylab = "enrichment score", las = 1, main = mainTitle, ylim = ylimits)
text(par("usr")[1] + par("usr")[2]/15, par("usr")[4] - par("usr")[4]/15, adj = c(0,1),labels = paste(c("P-value:", "n:"),c(round(pValue, digits = 3), length(GOIs)), collapse = "\n", sep=" "))
plot(1:length(sortedGenes), as.numeric(sortedGenes %in% GOIs), type = "h", bty = "n", xaxt = "n", yaxt = "n", xaxs = "r", yaxs = "r", xlab = "", ylab = "GOI-density", las = 1, main = "", ylim = c(0,1), col = "#00000064")
par(mar = c(2, 2, 0, 1))
plot(namedValues, type = "h", bty = "n", xaxs = "r", yaxs = "r", xlab = paste("genes sorted accoring to", sortName), ylab = sortName, las = 1, main = "")
dev.off()
#system(paste("rsvg-convert -a -d 300 -p 300 ", svgOutfile," > ", pngOutfile, sep = ''))
out <- list(pValue = pValue, observedSum = observedSum, observedES = observedES, sampledES = sampledValues, observedESat = which.max(abs(observedSum)))
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title join a list of overlapping or adjacent genomic regions
#'@param data a data frame with at least three columns: chrom, start, and end
#'@param otherCols a character vector with column names which should be summarized as well using the summaryFunction
#'@param summaryFunction see "otherCols"
#'@param gap the maximal size of the gap between two fragments to be merged
#'@return a data frame with the joined fragments (cols are chrom, start, end, count, otherCols)
#'@note WARNING: THIS FUNCTION DOES NOT WORK IF FRAGMENTS ARE ENTIRELY WITHIN ANOTHER FRAGMENT - IT ASSUMES PARTIAL OVERLAP FROM ONE TO THE NEXT
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.join.overlapping.fragments <- function(data, otherCols, summaryFunction, gap = 0) {
data <- data[with(data, order(chrom, start, end)),]
data$regNum <- 1
offset <- 1
for (chr in unique(data$chrom)) {
subData <- subset(data, chrom == chr)
subData$regNum[1] <- offset
if (nrow(subData) > 1) {
temp <- (subData$start[2:nrow(subData)] - subData$end[1:(nrow(subData)-1)]) > gap
subData$regNum[2:nrow(subData)] <- offset + cumsum(temp)
}
data[data$chrom == chr, ] <- subData
offset <- max(data$regNum) + 1
}
out <- data.frame(
chrom = aggregate(data$chrom, by=list(region=data$regNum), unique, simplify = TRUE)$x,
start = aggregate(data$start, by=list(region=data$regNum), min, simplify = TRUE)$x,
end = aggregate(data$end, by=list(region=data$regNum), max, simplify = TRUE)$x,
count = aggregate(data$chrom, by=list(region=data$regNum), length, simplify = TRUE)$x,
stringsAsFactors = FALSE
)
for (cn in otherCols) {
out[[cn]] = aggregate(data[[cn]], by=list(region=data$regNum), summaryFunction, simplify = TRUE)$x
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title join a list of overlapping or adjacent genomic regions - only if an additional variable has the same sign in both
#'@param data a data frame with at least three columns: chrom, start, and end
#'@param otherCols a character vector with column names which should be summarized as well using the summaryFunction
#'@param summaryFunction see "otherCols"
#'@param dirCol the name of the column which is used to decide wheter two fragments should be merged or not (based on the sign of the values)
#'@param gap the maximal size of the gap between two fragments to be merged
#'@return a data frame with the joined fragments (cols are chrom, start, end, count, otherCols)
#'@note WARNING: THIS FUNCTION DOES NOT WORK IF FRAGMENTS ARE ENTIRELY WITHIN ANOTHER FRAGMENT - IT ASSUMES PARTIAL OVERLAP FROM ONE TO THE NEXT
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.join.overlapping.fragments.directional <- function(data, otherCols, summaryFunction, dirCol, gap = 0) {
data <- data[with(data, order(chrom, start, end)),]
data$regNum <- 1
offset <- 1
for (chr in unique(data$chrom)) {
subData <- subset(data, chrom == chr)
subData$regNum[1] <- offset
if (nrow(subData) > 1) {
temp <- (subData$start[2:nrow(subData)] - subData$end[1:(nrow(subData)-1)]) > gap
dirCheck <- sign(subData[[dirCol]][2:nrow(subData)]) != sign(subData[[dirCol]][1:(nrow(subData)-1)])
subData$regNum[2:nrow(subData)] <- offset + cumsum(temp | dirCheck)
}
data[data$chrom == chr, ] <- subData
offset <- max(data$regNum) + 1
}
out <- data.frame(
chrom = aggregate(data$chrom, by=list(region=data$regNum), unique, simplify = TRUE)$x,
start = aggregate(data$start, by=list(region=data$regNum), min, simplify = TRUE)$x,
end = aggregate(data$end, by=list(region=data$regNum), max, simplify = TRUE)$x,
count = aggregate(data$chrom, by=list(region=data$regNum), length, simplify = TRUE)$x,
stringsAsFactors = FALSE
)
for (cn in otherCols) {
out[[cn]] = aggregate(data[[cn]], by=list(region=data$regNum), summaryFunction, simplify = TRUE)$x
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title search nearest genomic regions given a set of genomic regions
#'@param data a data frame with at least four columns: chrom, start, end, and strand (encoded as 1 and -1)
#'@param otherRegions a data frame with the regions to search in, three columns: chrom, start, and end
#'@return a data frame with the upstream and downstream distances
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.get.closest.region <- function(data, otherRegions) {
f.get.min.dist <- function(x, y) {
startDist <- c(x[1]-y$end, y$start-x[1])
endDist <- c(x[2]-y$end, y$start-x[2])
if (is.list(startDist)) {
startDist <- c()
} else {
startDist <- startDist[startDist>0]
}
if (is.list(endDist)) {
endDist <- c()
} else {
endDist <- endDist[endDist>0]
}
minStart <- min(startDist, na.rm = TRUE)
minEnd <- min(endDist, na.rm = TRUE)
out <- c(minStart, minEnd)
if (x[3] == (-1)) { out <- rev(out) }
return(out)
}
out <- list()
for (chr in unique(data$chrom)) {
subDat <- subset(data, chrom == chr)
subReg <- subset(otherRegions, chrom == chr)
if (nrow(subReg) == 0) {
cat("no regions on chromosome", chr, "\n")
out[[chr]] <- matrix(Inf, ncol = 2, nrow = nrow(subDat), dimnames = list(rownames(subDat), NULL))
next
}
if (nrow(subDat) > 1) {
out[[chr]] <- t(apply(subDat[,c("start", "end", "strand")], 1, function(x) f.get.min.dist(x, subReg)))
} else {
out[[chr]] <- f.get.min.dist(subDat[1, c("start", "end", "strand")], subReg)
}
}
out <- do.call("rbind", out)
colnames(out) <- c("upStream", "downStream")
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title convert a dataframe from wide format to long format
#'@param tab a dataframe in wide format
#'@param cols the columns which should be merged
#'@param newName the name of the merged column
#'@return a data frame in long format
#'@note aside the column <newName> with the merged data, there will be another column
#'called "factor_<newName>". The latter specifies the origin of the data in the <newName>
#'column.
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.wide.to.long <- function(tab, cols, newName) {
outList <- list()
otherCols <- setdiff(colnames(tab), cols)
if (length(otherCols) > 0) {
for (cn in cols) {
if (length(otherCols) == 1) {
temp <- data.frame(t = tab[,otherCols], stringsAsFactors = FALSE)
colnames(temp) <- otherCols
} else {
temp <- as.data.frame(tab[,otherCols], stringsAsFactors = FALSE)
}
outList[[cn]] <- temp
outList[[cn]][[newName]] <- tab[,cn]
outList[[cn]][[paste(newName, 'factor', sep = '_')]] <- rep(cn, nrow(tab))
}
} else {
for (cn in cols) {
outList[[cn]] <- data.frame(A = tab[,cn], B = rep(cn, nrow(tab)))
colnames(outList[[cn]]) <- c(newName, paste(newName, 'factor', sep = '_'))
}
}
out <- do.call("rbind",outList)
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title convert a dataframe from long format to wide format
#'@param tab a dataframe in long format
#'@param futureRows the column containing the rownames of the wide table
#'@param futureCols the column containing the rownames of the wide table
#'@param futureEntries the column containing the values
#'@return a data frame in wide format
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.long.to.wide <- function(tab, futureRows, futureCols, futureEntries) {
#empty <- ifelse(is.numeric(tab[[futureEntries]]), 0, "")
empty <- NA
rn <- unique(as.character(tab[[futureRows]]))
cn <- unique(as.character(tab[[futureCols]]))
out <- as.data.frame(matrix(empty, nrow = length(rn), ncol = length(cn), dimnames = list(rn, cn)))
temp <- split(tab[,c(futureCols, futureEntries)], tab[[futureRows]])
for (r in names(temp)) {
out[r, temp[[r]][,futureCols]] <- temp[[r]][,futureEntries]
}
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.genetodensity <- function(x,y) {
require("MASS")
est <- kde2d(x, y, n = 50) # needs MASS - calculates the two dimensional density
if (sum(is.na(est$z)) > 0) {
est <- kde2d(x, y, n = 50, h = c(bw.nrd0(x), bw.nrd0(y))) # needs MASS - calculates the two dimensional density
}
dvec <- as.vector(est$z) # note: as.vector takes columnwise, rows correspond to the value of x, columns to the value of y - the y index counts therefore 50 times
xind <- findInterval(x, est$x) # find the intervals to which a gene belongs
yind <- findInterval(y, est$y) # find the intervals to which a gene belongs
vecind <- (yind-1)*50 + xind # this is a vector with indices for dvec.
dens <- dvec[vecind]
names(dens) <- names(x)
return(dens)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.genetodensitycolor <- function(x,y) {
require("MASS")
require("colorRamps")
## NOTE would not work if two spots have exactly the same density or?
## important for a nice picture is that one removes the grid points with no gene (the ones with the lowest density)
grids <- 100
out <- list()
est <- kde2d(x, y, n = grids) # needs MASS - calculates the two dimensional density
if (sum(is.na(est$z)) > 0) {
est <- kde2d(x, y, n = grids, h = c(bw.nrd0(x), bw.nrd0(y))) # needs MASS - calculates the two dimensional density
}
dvec <- as.vector(est$z) # note: as.vector takes columnwise, rows correspond to the value of x, columns to the value of y - the y index counts therefore grids times
xind <- findInterval(x, est$x) # find the intervals to which a gene belongs
yind <- findInterval(y, est$y) # find the intervals to which a gene belongs
vecind <- (yind-1)*grids + xind # this is a vector with indices for dvec.
dens <- dvec[vecind]
dens_with_genes <- unique(dens)
names(dens) <- names(x)
out$dens <- dens
out$denschar <- as.vector(dens, mode = "character")
colgrad <- blue2red(length(dens_with_genes))
#colgrad <- rainbow(length(dens_with_genes), start = 0, end = 1, alpha = 0.8)
#colgrad <- heat.colors(length(dens_with_genes), alpha = 0.8)
#colgrad <- terrain.colors(length(dens_with_genes), alpha = 0.8)
#colgrad <- topo.colors(length(dens_with_genes), alpha = 0.8)
#colgrad <- cm.colors(length(dens_with_genes), alpha = 0.8)
sdens_with_genes <- sort(dens_with_genes, decreasing = FALSE)
names(colgrad) <- sdens_with_genes
out$cols <- colgrad
genecols <- colgrad[as.vector(dens, mode = "character")]
names(genecols) <- names(x)
out$genecols <- genecols
return(out)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.yellowblueblack <- function(x) {
#rg <- approx(c(0, 0.5, 1), c(1, 1/3, 0), n = x)$y
#b <- approx(c(0, 0.5, 1), c(2/3, 2/3, 0), n = x)$y
rg <- approx(c(0, 0.5, 1), c(1, 0, 0), n = x)$y
b <- approx(c(0, 0.5, 1), c(0, 1, 0), n = x)$y
return(rgb(rg, rg, b))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.yellowblackblue <- function(x) {
#rg <- approx(c(0, 1, 0.5), c(1, 1/3, 0), n = x)$y
#b <- approx(c(0, 1, 0.5), c(2/3, 2/3, 0), n = x)$y
rg <- approx(c(0, 0.5, 1), c(1, 0, 0), n = x)$y
b <- approx(c(0, 0.5, 1), c(0, 0, 1), n = x)$y
return(rgb(rg, rg, b))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.yellowredblue <- function(x) {
r <- approx(c(0, 0.5, 1), c(1, 1, 0), n = x)$y
g <- approx(c(0, 0.5, 1), c(1, 0, 0), n = x)$y
b <- approx(c(0, 0.5, 1), c(0, 0, 1), n = x)$y
return(rgb(r, g, b))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.yellowblack <- function(x) {
rg <- approx(c(0, 1), c(1, 0), n = x)$y
b <- approx(c(0, 1), c(0, 0), n = x)$y
return(rgb(rg, rg, b))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.yellowredblack <- function(x) {
r <- approx(c(0, 0.5, 1), c(1, 1, 0), n = x)$y
g <- approx(c(0, 0.5, 1), c(1, 0, 0), n = x)$y
b <- approx(c(0, 0.5, 1), c(0, 0, 0), n = x)$y
return(rgb(r, g, b))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.redwhiteblack <- function(x) {
r <- approx(c(0, 0.5, 1), c(1, 1, 0), n = x)$y
g <- approx(c(0, 0.5, 1), c(0, 1, 0), n = x)$y
b <- approx(c(0, 0.5, 1), c(0, 1, 0), n = x)$y
return(rgb(r, g, b))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.blackblueyellow <- function(x) {
return(rev(f.yellowblueblack(x)))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.blueblackyellow <- function(x) {
return(rev(f.yellowblackblue(x)))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.blueredyellow <- function(x) {
return(rev(f.yellowredblue(x)))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.blackyellow <- function(x) {
return(rev(f.yellowblack(x)))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.blackredyellow <- function(x) {
return(rev(f.yellowredblack(x)))
}
#'@title undocumented internal function
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
f.blackwhitered <- function(x) {
return(rev(f.redwhiteblack(x)))
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Draw an image() with the values printed as text
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.image.with.text <- function(x, y, z, xLabel, yLabel, mainLabel, useLog = FALSE, ...) {
xChars <- as.character(x)
yChars <- as.character(y)
xPos <- 1:length(xChars)
yPos <- 1:length(yChars)
if (useLog) {
toPlot <- log2(z+1)
} else {
toPlot <- z
}
image(xPos, yPos, toPlot, xlab = xLabel, ylab = yLabel, main = mainLabel, yaxt = "n", xaxt = "n", ...)
axis(1, at = xPos, labels = xChars, outer = FALSE)
axis(2, at = yPos, labels = yChars, outer = FALSE, las = 1)
text(rep(xPos, each = length(yPos)), yPos, t(z), cex = 1)
return(NULL)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Draw a histogram (frequency or density)
#'@param x values
#'@param xName x-axis label
#'@param useFreq plot frequencies instead of densities
#'@param doNotShowSummary omit printing mean/median/sd
#'@param useLog log2-transform the data
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.histogram <- function(x, y = c(), xName = "", useFreq = FALSE, doNotShowSummary = FALSE, useLog = FALSE, ...)
{
if (length(x) == length(y)) {
toPlot <- list(x = x, y = y)
class(toPlot) <- "density"
} else {
toPlot <- density(x)
}
if (useFreq) {
toPlot$y <- toPlot$y * length(x)
}
if (useLog) {
if (useFreq) { toPlot$y <- log2(toPlot$y+1) }
else { cat("log only possible for useFreq = TRUE\n") }
}
par(mar = c(5,4,1,1))
plot(
toPlot,
#main = "",
bty = "n",
xaxs = "r",
yaxs = "r",
xlab = xName,
ylab = "",
las = 1,
cex = 0.4,
tck = 0.01,
...
)
if (!doNotShowSummary) {
text(
par("usr")[1] + par("usr")[2]/15,
par("usr")[4] - par("usr")[4]/15,
adj = c(0,1),
labels = paste(c("median:", "mean:", "sd:"),
c(round(median(x), digits = 3),
round(mean(x), digits = 3),
round(sd(x), digits = 3)),
collapse = "\n", sep=" ")
)
}
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Draw a scatterplot
#'@param x x-values
#'@param y y-values
#'@param xName x-axis label
#'@param yName y-axis label
#'@param ... other arguments passed on to plot()
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.scatter <- function(x, y, xName = "", yName = "", cexFactor = 1, ...)
{
par(mar = c(5,5,1,1))
plot(
y ~ x,
#main = "",
bty = "n",
xaxs = "r",
yaxs = "r",
xlab = xName,
ylab = yName,
las = 1,
cex = 0.2*cexFactor,
tck = 0.01,
pch = 19,
...
)
text(
par("usr")[1] + par("usr")[2]/15,
par("usr")[4] - par("usr")[4]/15,
adj = c(0,1),
labels = paste(c("corP:", "corS:", "n:"),
c(round(cor(x,y,method="pearson"), digits = 3),
round(cor(x,y,method="spearman"), digits = 3),
length(x)),
collapse = "\n", sep=" ")
)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Replace Inf/-Inf with the next highes/lowest value.
#'@param x a numeric vector
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.replace.Inf.by.next <- function(x) {
if (sum(abs(x) == Inf, na.rm = TRUE) == 0) {return(x)}
cat("replacing Inf/-Inf with the next highest/lowest value\n")
notNA <- !is.na(x)
minInf <- x == -Inf
pluInf <- x == Inf
nx <- x[notNA&(!minInf)&(!pluInf)]
x[notNA&pluInf] <- max(nx)
x[notNA&minInf] <- min(nx)
return(x)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Draw a scatterplot with heat colors indicating the point density
#'@param x x-values
#'@param y y-values
#'@param xName x-axis label
#'@param yName y-axis label
#'@param tryToScale EXPERIMENTAL - replace outliers (10 times bigger than the median) with 10*median
#'@param ... other arguments passed on to plot()
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.density.scatter <- function(x, y, xName = "", yName = "", main = "", tryToScale = FALSE, ...) {
x <- f.replace.Inf.by.next(x)
y <- f.replace.Inf.by.next(y)
if (tryToScale) {
if (max(x) > 10*median(x)) {
isExtreme <- x > 10*median(x)
cat("limiting data to 10*median(x) - i.e. replacing", sum(isExtreme), "in percent:", mean(isExtreme)*100," extreme values\n")
x[isExtreme] <- 10*median(x)
}
if (max(y) > 10*median(y)) {
isExtreme <- y > 10*median(y)
cat("limiting data to 10*median(y) - i.e. replacing", sum(isExtreme), "in percent:", mean(isExtreme)*100," extreme values\n")
y[isExtreme] <- 10*median(y)
}
}
# xLimits <- range(x)
# if (max(x) > 10*median(x)) {
# cat("limiting plot to a quantile(x, 0.99)\n")
# xLimits[2] <- quantile(x, 0.99)
# }
# yLimits <- range(y)
# if (max(y) > 10*median(y)) {
# cat("limiting plot to a quantile(y, 0.99)\n")
# yLimits[2] <- quantile(y, 0.99)
# }
colorGrad <- f.genetodensitycolor(x, y)
# f.scatter(x, y, xName, yName, cexFactor = 1, col = colorGrad$genecols, main = main, xlim = xLimits, ylim = yLimits)
f.scatter(x, y, xName, yName, cexFactor = 1, col = colorGrad$genecols, main = main, ...)
return(NULL)
}
#######################################################################################################################################
#######################################################################################################################################
#######################################################################################################################################
#'@title Draw scatter plots, sorted scatter plots and histograms for all columns in a data frame
#'@param data matrix or dataframe, not too many columns (there will be ncol(data)*ncol(data) plots in total)
#'@param rDir folder for the figure
#'@param rt threshold for the data (it will test >= threshold, except if the threshold is zero, then > 0)
#'@param prefix prefix for the name of the plot
#'@author Marc W. Schmid \email{contact@@mwschmid.ch}.
#'@export
f.allinone <- function(data, rDir, rt = 0, prefix = "", scaleToSample = FALSE)
{
hits.union <- rownames(data)[which(apply(f.comp(data,rt),1,sum) > 0)]
data <- data[hits.union,]
# get sorted data and make sure everything is a data frame
s.data <- apply(data,2,sort)
data <- as.data.frame(data)
s.data <- as.data.frame(s.data)
# some variables
ns = ncol(data)
sn = colnames(data)
# use CairoSVG if you are on windows
afname <- paste(prefix,'_allinone_',rt,'_',paste(sn,collapse='_'),sep='')
if (nchar(afname) > 50) { afname <- paste(prefix,'_allinone_',rt,'_many',sep='') }
afpath <- file.path(rDir,paste(afname, '.tiff', sep = ''))
tiff(file=afpath, width = 600*ns, height = 600*ns, units = "px", pointsize = 20, compression = "lzw", bg = "white", type = GLOBAL_VARIABLE_TIFF_LIB)
# plot everything
layout(mat=matrix(c(1:(ns*ns)), nrow=ns, byrow = TRUE))
cat(paste("plotting", ns, "rows\n"))
cat(paste(c("|", rep(' ', ns),"|\n|"),sep='',collapse=''))
for (i in c(1:ns))
{
for (k in c(1:ns))
{
if (scaleToSample) {
xMin <- floor(min(data[,k]))
xMax <- ceiling(max(data[,k]))
yMin <- floor(min(data[,i]))
yMax <- ceiling(max(data[,i]))
} else {
xMin <- floor(min(data))
xMax <- ceiling(max(data))
yMin <- floor(min(data))
yMax <- ceiling(max(data))
}
if (i == k)
{
# histogram in the diagonal
f.histogram(data[f.comp(data[,k],rt),k], xName = sn[k], xlim = c(xMin, xMax), main = "")
}
else if (i < k)
{
# scatterplot with densities on the top right
if ((length(unique(data[,k][!is.na(data[,k])])) > 2) & (length(unique(data[,i][!is.na(data[,i])])) > 2)) {
colorGrad <- f.genetodensitycolor(data[,k], data[,i])
} else {
colorGrad <- list(genecols = rep("black", nrow(data)))
}
f.scatter(data[,k], data[,i], sn[k], sn[i], cexFactor = 1.5, col = colorGrad$genecols, xlim = c(xMin, xMax), ylim = c(yMin, yMax), main = "")