-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraas_utils.R
1095 lines (952 loc) · 36.4 KB
/
raas_utils.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
### PLOT UTILS
## COLOR-RAMP PALETTE ARNO
## generate colors similar to viridis::inferno but with a more visible
## yellow, taken from viridis::viridis. Named after Arno because it
## was his birthday:
mcol <- viridis::inferno(5)
vcol <- viridis::viridis(5)
mcol[5] <- vcol[5]
arno <- colorRampPalette(mcol)
# from->to as expression, e.g. for axis labels
ftlabels <- function(srt) {
axex <- rep("",length(srt))
names(axex) <- srt
for ( i in seq_along(srt) ) {
ft <- unlist(strsplit(srt[i],":"))
axex[i] <- as.expression(bquote(.(ft[1]) %->% .(ft[2])))
}
axex
}
### STATISTICS
## wilcox test with normalized U-statistic, to
## be used for statistical profile plots
w.test <- function(x,y) {
res <- wilcox.test(x,y)
## normalized U-statistic
tt <- res$statistic/(sum(!is.na(x))*sum(!is.na(y))) -0.5
rt <- list()
rt$statistic <- unlist(tt)
rt$p.value <- unlist(res$p.value)
rt
}
### HIGH LEVEL PLOT FUNCTIONS
## dotplot function used for RAAS dotplots
## TODO: generalize this and integrate into segmenTools
dotprofile <- function(x, value, vcols=viridis::viridis(100),
vbrks, p.dot=1e-10, dot.sze=c(.3,2), xpd=FALSE,
lg2=FALSE, mxr,
show.total=FALSE, tot.cex=.8,
test=FALSE, ...) {
## values for coloring
vals <- x[[value]]
if ( lg2 ) {
vals <- log2(vals)
if ( missing(mxr) ) mxr <- max(abs(vals))
vals[vals > mxr] <- mxr
vals[vals < -mxr] <- -mxr
}
## breaks
if ( missing(vbrks) )
vbrks <- seq(min(vals,na.rm=TRUE), max(vals, na.rm=TRUE),
length.out=length(vcols)+1)
navals <- vals
navals[] <- NA
image_matrix(navals, breaks=vbrks, col=vcols, ...)
p <- x$p.value
p <- -log10(p)
p[p>-log10(p.dot)] <- -log10(p.dot)
z <- p/-log10(p.dot)
## intersect data to colors
cols <- vcols[findInterval(t(vals),
seq(min(vbrks), max(vbrks),
length.out=length(vbrks)),
all.inside = TRUE)]
d.sze <- dot.sze[1]+dot.sze[2]*c(t(z))
if ( test )
points(x = rep(1:ncol(z), nrow(z)),
y = rep(nrow(z):1, each= ncol(z)), cex=d.sze)
points(x = rep(1:ncol(z), nrow(z)),
y = rep(nrow(z):1, each= ncol(z)),
cex=d.sze, pch=19,
col=cols, xpd=xpd)
toty <- totx <- FALSE
if (is.logical(show.total)) {
if (show.total)
toty <- totx <- TRUE
}
else if (is.character(show.total)) {
if (show.total == "x")
totx <- TRUE
if (show.total == "y")
toty <- TRUE
if (show.total %in% c("xy", "yx"))
toty <- totx <- TRUE
}
if (toty)
if ("num.query" %in% names(x))
axis(4, at = length(x$num.query):1,
labels = format(x$num.query, big.mark=",", trim=TRUE),
las = 2, lwd = 0, lwd.ticks = 1, cex.axis=tot.cex)
if (totx)
if ("num.target" %in% names(x))
axis(3, at = 1:length(x$num.target),
labels = format(x$num.target, big.mark=",", trim=TRUE),
las = 2, lwd = 0, lwd.ticks = 1, cex.axis=tot.cex)
}
## plots various plots of RAAS profiles generated by raasProfile
plotProfiles <- function(ovw, mai=c(.6,.5,.5,.5),
fw=.2, fh=.2,
ttcols=ttcols, p.min=p.min, p.txt=p.txt,
dot.sze=dot.sze, p.dot=p.dot, ## TODO: legend
value="median", vcols, vbrks,
count="unique", gcols=gcols,
fname="profile",
mtxt, mtxt1, mtxt.line=1.3, mtxt.cex=1,
llab, rlab, xlab=expression(log[10](RAAS)),
ffam="sans",
ftyp="png",
axis1.col,
axis2.col,
axis1.las=2,
bg="white",
tot.cex=.8,
col.lines, # column classes - vertical lines
plot.all=FALSE, plot.legend=FALSE, verb=0) {
## replace row labels with arrows
## TODO: adapt to plot by AA colors
rows <- rownames(ovw$p.value)
axex <- rep("",length(rows))
names(axex) <- rows
for ( i in seq_along(rows) ) {
if ( length(grep(":",rows[i])) ) {
ft <- unlist(strsplit(rows[i],":"))
ft[ft=="x"] <- ""
axex[i] <- as.expression(bquote(.(ft[1]) %->% .(ft[2])))
} else axex[i] <- as.expression(bquote(.(rows[i])))
}
## calculate optimal figure height: result fields + figure margins (mai)
nh <- nrow(ovw$p.value) *fh + mai[1] + mai[3]
nw <- ncol(ovw$p.value) *fw + mai[2] + mai[4]
## p-value profiles
if ( missing(vbrks) ) {
vals <- ovw[[value]]
vals <- vals[!is.na(vals)]
vbrks <- seq(min(vals), max(vals), length.out=101)
vcols <- viridis::viridis(100)
}
## combined effect size and p-value plot
if ( verb ) cat(paste("plotting dotplot\n"))
plotdev(paste0(fname,"_dotplot"),
height=nh, width=nw, res=300, type=ftyp, bg=bg)
par(mai=mai, mgp=c(1.3,.3,0), tcl=-.25, family=ffam)
dotprofile(x=ovw, value=value, vbrks=vbrks,
vcols=vcols, p.dot=p.dot,
dot.sze=dot.sze,
axis=NA, xlab=NA, ylab=NA)
box()
if ( !missing(axis1.col) )
Map(axis, 1, at=1:ncol(ovw$p.value),
labels=colnames(ovw$p.value), las=axis1.las, family=ffam,
col.axis=axis1.col, font=2)#, cex.axis=1.2)
else
axis(1, 1:ncol(ovw$p.value),
labels=colnames(ovw$p.value), las=axis1.las, family=ffam)
if ( !missing(axis2.col) ) {
Map(axis, 2, length(axex):1, labels=axex, las=2, family=ffam,
col.axis=axis2.col[rows], font=2, cex.axis=1.2)
}
else
axis(2, length(axex):1, labels=axex, las=2, family=ffam)
axis(3, at=1:ncol(ovw$num.target), cex.axis=tot.cex,
labels=format(ovw$num.target[1,], big.mark=",", trim=TRUE),las=2)
axis(4, at=nrow(ovw$num.query):1, cex.axis=tot.cex,
labels=format(ovw$num.query[,1], big.mark=",", trim=TRUE),las=2)
if ( !missing(mtxt) ) mtext(mtxt, 2, mtxt.line, cex=mtxt.cex)
if ( !missing(mtxt1) ) mtext(mtxt1, 1, mtxt.line, cex=mtxt.cex)
if ( !missing(llab) ) figlabel(llab, pos="bottomleft", cex=1.2)
if ( !missing(rlab) ) figlabel(rlab, pos="bottomright", cex=.8)
if ( !missing(col.lines) )
abline(v=.5+col.lines, lwd=1, xpd=FALSE)
dev.off()
##return(p)
## plot size adjusted legend
if ( plot.legend ) {
## vcols, vbreaks, p.min, p.dot, dot.sze
## tigtht RAAS range - legend for acols/abreaks
pp <- seq(0, -log10(p.dot), length.out=3)
rs <- unique(round(seq(min(vbrks),max(vbrks),length.out=4) ))
pm <- matrix(rep(pp, each=length(rs)), nrow=length(rs))
rm <- matrix(rep(rs, length(pp)), ncol=length(pp))
colnames(pm) <- colnames(rm) <- -pp
rownames(pm) <- rownames(rm) <- round(rs,1)
ovlg <- list(p.value=t(10^-pm), median=t(rm))
lmai <- c(.4,.5,.05,.06)
fh <- fw <- .2
lh <- nrow(ovlg$p.value) *fh + lmai[1] + lmai[3]
lw <- ncol(ovlg$p.value) *fw + lmai[2] + lmai[4]
plotdev(paste0(fname,"_dotplot_legend"),
height=lh, width=lw, res=300, type=ftyp, bg=bg)
par(mai=lmai, mgp=c(1.3,.3,0), tcl=-.25)
dotprofile(ovlg, value="median",
vbrks=vbrks,
vcols=vcols,
dot.sze=dot.sze, p.dot=p.dot, axis=1:2,
ylab=plab,
xlab=NA)
##mtext(xl.raas, 1, 1.1, adj=-.4)
text(1.5, -1, xlab, xpd=TRUE)
dev.off()
}
if ( !plot.all ) return()
if (verb>0) cat(paste("plotting",value,"counts\n"))
## BARPLOT OF COUNTS
mai.bar <- mai
##mai.bar[c(2,4)] <- mai.bar[c(2,4)] +.05
mai.bar[c(1,3)] <- .075
plotdev(paste0(fname,"_ccounts"),
height=.75, width=nw, res=300, type=ftyp)
par(mai=mai.bar, mgp=c(1.3,.3,0), tcl=-.25, xaxs="i", family=ffam)
bp <- barplot(c(ovw$num.target), axes=FALSE, xlab=NA, #beside=TRUE,
ylab="", las=2, xaxt='n',
width=.5, space=.5)
##mtext(expression(count), 2, 2.5)
if ( !missing(col.lines) ) {
cdn.cn <- head(col.lines, length(col.lines)-1)
abline(v=bp[cdn.cn,]+unique(diff(bp[,1]))/2)
}
for ( ax in c(2,4) )
axis(ax, las=2)
dev.off()
mai.bar <- mai
mai.bar[c(2,4)] <- .075
##mai.bar[c(1,3)] <- .075
plotdev(paste0(fname,"_rcounts"),
height=nh, width=.75, res=300, type=ftyp)
par(mai=mai.bar, mgp=c(1.3,.3,0), tcl=-.25, yaxs="i", family=ffam)
bp <- barplot(rev(c(ovw$num.query)), axes=FALSE, xlab=NA,
horiz=TRUE,
ylab="", las=2, yaxt='n',
width=.5, space=.5)
##mtext(expression(count), 2, 2.5)
for ( ax in c(1,3) )
axis(ax, las=2)
dev.off()
## classical p value profile
outf <- paste0(fname,"_wtests")
if (verb>0) cat(paste("plotting test profile",outf,p.min,p.txt,"\n"))
plotdev(outf, height=nh, width=nw, res=300, type=ftyp)
par(mai=mai, mgp=c(1.3,.3,0), tcl=-.25)
plotOverlaps(ovw, p.min=p.min, p.txt=p.txt,
text.cex=.8, axis=NA, ylab=NA, xlab=NA,
col=ttcols, show.total=TRUE)
if ( !missing(axis2.col) )
Map(axis, 2, length(axex):1, labels=axex, las=2, family=ffam,
col.axis=axis2.col[rows])
else
axis(2, length(axex):1, labels=axex, las=2, family=ffam)
if ( !missing(axis1.col) )
Map(axis, 1, 1:ncol(ovw$p.value),
labels=colnames(ovw$p.value), las=2, family=ffam,
col.axis=axis1.col)
else
axis(1, 1:ncol(ovw$p.value),
labels=colnames(ovw$p.value), las=2, family=ffam)
if ( !missing(mtxt) ) mtext(mtxt, 2, mtxt.line, cex=mtxt.cex)
if ( !missing(mtxt1) ) mtext(mtxt1, 1, mtxt.line, cex=mtxt.cex)
if ( !missing(llab) ) figlabel(llab, pos="bottomleft", cex=1.2)
if ( !missing(rlab) ) figlabel(rlab, pos="bottomright", cex=.8)
if ( !missing(col.lines) )
abline(v=.5+col.lines, lwd=1, xpd=FALSE)
dev.off()
if (verb>0) cat(paste("plotting",value,"RAAS\n"))
plotdev(paste0(fname,"_raas_",value),
height=nh, width=nw, res=300, type=ftyp)
par(mai=mai, mgp=c(1.3,.3,0), tcl=-.25)
txt <- ovw[["count"]]
txt[txt==0] <- ""
q1 <- quantile(c(ovw[[value]]), probs=.4, na.rm=TRUE)
txt.col <- ifelse(ovw[[value]]<q1, "white","black")
image_matrix(ovw[[value]], col=vcols, breaks=vbrks, axis=NA,
text=txt, text.col=txt.col, xlab=NA, ylab=NA, text.cex=.8)
if ( !missing(axis1.col) )
Map(axis, 1, 1:ncol(ovw$p.value),
labels=colnames(ovw$p.value), las=2, family=ffam,
col.axis=axis1.col)
else
axis(1, 1:ncol(ovw$p.value),
labels=colnames(ovw$p.value), las=2, family=ffam)
if ( !missing(axis2.col) )
Map(axis, 2, length(axex):1, labels=axex, las=2, family=ffam,
col.axis=axis2.col[rows])
else
axis(2, length(axex):1, labels=axex, las=2, family=ffam)
if ( !missing(mtxt) ) mtext(mtxt, 2, mtxt.line, cex=mtxt.cex)
if ( !missing(mtxt1) ) mtext(mtxt1, 1, mtxt.line, cex=mtxt.cex)
if ( !missing(llab) ) figlabel(llab, pos="bottomleft", cex=1.2)
if ( !missing(rlab) ) figlabel(rlab, pos="bottomright", cex=.8)
if ( !missing(col.lines) )
abline(v=.5+col.lines, lwd=1, xpd=FALSE, col="white")
dev.off()
if (verb>0) cat(paste("plotting unique number\n"))
plotdev(paste0(fname,"_count_unique"),
height=nh, width=nw, res=300, type=ftyp)
par(mai=mai, mgp=c(1.3,.3,0), tcl=-.25)
cnt <- ovw$unique
cnt[cnt==0] <- NA
txt <- ovw$unique
txt[txt==0] <- ""
txt.col <- ifelse(ovw$unique>quantile(c(ovw$unique),.95),"white","black")
image_matrix(cnt, col=gcols, axis=1:2,
text=txt, text.col=txt.col, ylab=NA, xlab=NA, text.cex=.8)
##axis(2, length(axex):1, labels=axex, las=2)
if ( !missing(mtxt) ) mtext(mtxt, 2, mtxt.line, cex=mtxt.cex)
if ( !missing(mtxt1) ) mtext(mtxt1, 1, mtxt.line, cex=mtxt.cex)
if ( !missing(llab) ) figlabel(llab, pos="bottomleft", cex=1.2)
if ( !missing(rlab) ) figlabel(rlab, pos="bottomright", cex=.8)
if ( !missing(col.lines) )
abline(v=.5+col.lines,
lwd=1, xpd=FALSE)
dev.off()
if (verb>0) cat(paste("plotting volcano\n"))
plotdev(paste0(fname,"_volcano"),
height=3, width=4, res=300, type=ftyp)
par(mai=c(.5,.75,.1,.75), mgp=c(1.3,.3,0), tcl=-.25)
volcano(ovw, cut=100, p.txt=-log10(p.txt),
v.txt=c(-Inf,-1), density=TRUE,
xlab=paste(value,"TMT RAAS"), value=value)
abline(v=get(value, mode="function")(ovw[[value]],na.rm=TRUE))
if ( !missing(llab) ) figlabel(llab, pos="bottomleft", cex=1.2)
if ( !missing(rlab) ) figlabel(rlab, pos="bottomright", cex=.8)
dev.off()
if (verb>0) cat(paste("plotting histograms\n"))
## common histogram with color by sign and
## first, calculate densities
dns <- ovw$ALL
for ( i in 1:nrow(ovw$p.value) ) {
for ( j in 1:ncol(ovw$p.value) ) {
rw <- rownames(ovw$p.value)[i]
cl <- colnames(ovw$p.value)[j]
vls <- ovw$ALL[[rw]][[cl]]
if (length(vls)>1 ) {
dns[[rw]][[cl]] <- density(vls)
}
}
}
## get max
mxs <- rep(NA, length(dns))
for ( i in seq_along(dns) )
mxs[i] <- max(unlist(lapply(dns[[i]],
function(z)
ifelse("y"%in%names(z),
max(unlist(z["y"])),-10))))
plotdev(paste0(fname,"_densities"),
res=300, width=4, height=2, type=ftyp)
par(mai=c(.5,.5,.1,.1), mgp=c(1.3,.3,0), tcl=-.25)
dns <- ovw$ALL
hist(unlist(dns), col="#77777755", border=NA,
xlim=c(-6,4),
xlab=expression(TMT~level~log[10]*RAAS), ylab=NA, main=NA, axes=FALSE)
par(new=TRUE)
plot(1, col=NA, xlim=c(-6,4), ylim=c(0,max(mxs)),
xlab=NA, ylab=NA, axes=FALSE)
for ( i in 1:nrow(ovw$p.value) ) {
for ( j in 1:ncol(ovw$p.value) ) {
rw <- rownames(ovw$p.value)[i]
cl <- colnames(ovw$p.value)[j]
vls <- ovw$ALL[[rw]][[cl]]
if (length(vls)>1 ) {
dns[[rw]][[cl]] <- density(vls)
if ( ovw$p.value[i,j] <1e-3 )
lines(dns[[rw]][[cl]],
col=ifelse(ovw$sign[i,j]==-1,"blue","red"),
lwd=-log10(ovw$p.value[i,j])/-log10(p.min))
## TODO: annotate
}
}
}
axis(2)#, labels=NA)
mtext("density",2,1.3)
axis(1)
dev.off()
}
## NOTE: CV for log-normal data, see @Canchola2017
## cv = sqrt(10^(log(100)*var) -1)
cvl <- function(x) sqrt(10^(log(10)*var(x,na.rm=TRUE)) -1)
## CALCULATE STATISTICS FOR LISTS OF VALUES (here RAAS)
## TODO: generalize and integrate into segmenTools
## mean, median, and unpaired t/w tests
listProfile <- function(x, y, delog=TRUE, use.test=t.test, min=3) {
stat <- lapply(x, function(x) {
tt=NA
tp=NA
if ( length(x)>=min) {
tts <- use.test(x, y)
tt <- unname(tts$statistic)
tp <- tts$p.value
}
lx <- x
if ( delog )
lx <- 10^x
xmn <- mean(lx)
xsd <- sd(lx)
xcv <- xsd/xmn
xcvl <- cvl(lx)
xmd <- median(lx)
xmx <- lx[which.max(abs(lx-xmd))] # maximal distance from median!
if ( delog ) {
xmn <- log10(xmn)
xmd <- log10(xmd)
xsd <- log10(xsd)
xmx <- log10(xmx)
}
c(mean=xmn, median=xmd,
sd=xsd, cv=xcv, cvl=xcvl,
statistic=tt, p.value=tp,
n=length(x), absmax=xmx)
})
as.data.frame(do.call(rbind, stat))
}
## merge clusterOverlap objectes from raasProfile
## TODO: generalize and move to segmenTools
mergeProfiles <- function(ovll) {
## result list that will contain all merged
## entries
ovl <- list()
## content of invididual clusterOverlap structures
flags <- c("delog", "p.adjust")
mats <- c("p.value", "statistic", "count",
"mean", "median", "unique", "sign", "num.query")
lsts <- c("ALL")
## collect flags and test for concistency
for ( flag in flags ) {
ovl[[flag]] <- unlist(lapply(ovll, function(y) y[[flag]]))
## check consistency of flags
if ( length(unique(ovl[[flag]]))>1 )
stop("inconsistent processing flags")
ovl[[flag]] <- unique(ovl[[flag]])
}
## collect numbers of targets (columns)
## NOTE: only for SAME TARGETS/COLUMNS
## TODO: check whether target or query is consistent and fuse accordingly
num.target <- do.call(rbind, lapply(ovll, function(x) x$num.target))
if ( any(apply(num.target, 2, sd)>0) )
stop("inconsistent number of targets (columns)")
ovl$num.target <- t(as.matrix(apply(num.target, 2, unique)))
## rbind all matrices
for ( mat in mats )
ovl[[mat]] <- do.call(rbind, lapply(ovll, function(x) x[[mat]]))
## append lists
for ( lst in lsts ) {
tmp <- list()
for ( i in 1:length(ovll) )
tmp <- append(tmp, ovll[[i]][[lst]])
ovl[[lst]] <- tmp
}
class(ovl) <- "clusterOverlaps"
ovl
}
## calculate statistical profiles, similar to segmenTools::clusterProfiler,
## but working on lists of unequal lengths instead of a matrix
raasProfile <- function(x, rows, ...) {
## catch traditional case for nonoverlapping class in
## a single row.
if ( inherits(rows, "character") )
return(raasProfile.row(x=x, rows=rows, ...))
cat(paste("NOTE: using loop over matrix of classes\n"))
## loop through rows matrix
covw <- list()
for ( j in 1:ncol(rows) ) {
mid <- colnames(rows)[j]
mclass <- rep("n.a.", nrow(rows))
mclass[rows[,j]] <- mid
x$TEST <- mclass
ovw <- raasProfile(x=x,
rows="TEST", row.srt=mid, ...)
covw[[mid]] <- ovw
}
mergeProfiles(covw)
}
## the actual work horse function to calculate raasProfiles,
## originally defined to work on subsets defined in one input column
## of the passed data structure x
raasProfile.row <- function(x=tmtf, id="SAAP",
value="RAAS", delog=TRUE, replace=TRUE,
bg=FALSE, bg.dir="col", na.rm=FALSE,
rows="to", cols="aacodon",
row.srt, col.srt, filter=TRUE,
use.test=use.test, p.adjust="none",
min.obs=2,
do.plots=FALSE,
xlab="value", fname="profile_",
verb=FALSE) {
if ( missing(cols) ) {
x$call <- "all"
cols <- "call"
}
if ( missing(cols) ) {
x$rall <- "all"
cols <- "rall"
}
## check presence
if ( any(!c(value, rows, cols)%in%colnames(x)) )
stop("one of the requested values ",
paste(value, rows, cols, sep=";"),
" is not present in the data",
paste(colnames(x), collapse=";"))
## sorting of row and column classes
if ( !missing(row.srt) ) aas <- row.srt
else aas <- sort(unique(x[,rows]))
if ( !missing(col.srt) ) acod <- col.srt
else acod <- sort(unique(x[,cols]))
## remove rows with missing values
if ( na.rm ) {
ina <- is.na(x[,value])
if ( sum(ina)>0 ) {
wrn <- paste0(sum(ina), " rows with NA values removed")
cat(paste("WARNING: ", wrn, "\n"))
warning(wrn)
x <- x[!ina,]
}
}
## filter for available classes
if ( filter ) {
aas <- aas[aas%in%x[,rows]]
acod <- acod[acod%in%x[,cols]]
}
## result structures
tt <- matrix(0, ncol=length(acod), nrow=length(aas))
colnames(tt) <- acod
rownames(tt) <- aas
tc <- tp <- tm <- td <- uq <- tt
tp[] <- 1
tm[] <- td[] <- NA
allvals <- list()
for ( i in seq_along(aas) ) {
aa <- aas[i]
allvals[[aa]] <- list()
for ( j in seq_along(acod) ) {
cod <- acod[j]
## get all rows for the current intersection
idx <- x[,cols]==cod & x[,rows]==aa
if ( any(is.na(idx)) ) {
wrn <- paste0(sum(is.na(idx)), " NA in ", aa, "/", cod)
cat(paste0("WARNING: ", wrn,"\n"))
warning(wrn)
idx[is.na(idx)] <- FALSE
}
## local background: column type!
bgidx <- !idx
if ( bg ) {
if ( bg.dir=="col" )
bgidx <- x[,cols]==cod
else if ( bg.dir=="row" )
bgidx <- x[,rows]==aa
}
if ( !replace ) ## do not include foreground in background!
bgidx <- bgidx & !idx
if ( any(is.na(bgidx)) ) {
wrn <- paste0(sum(is.na(bgidx)), " NA in ",
aa, "/", cod, "background")
cat(paste0("WARNING: ", wrn,"\n"))
warning(wrn)
idx[is.na(idx)] <- FALSE
}
## collect unique counter by ID column
if ( !missing(id) )
uq[i,j] <- length(unique(x[idx,id]))
if (verb>0) cat(paste("testing",cod,"to", aa, "\n"))
## get all RAAS values
y <- unlist(x[ idx, value])
X <- unlist(x[bgidx, value])
## store all values for this class
allvals[[aa]][[cod]] <- y
## value count
tc[i,j] <- length(y)
if ( length(y)==0 ) {
if ( verb>0 )
cat(paste0("WARNING: no values for ",aa, "/", cod,"\n"))
next
}
## MEAN AND MEDIAN
## delog for mean and median
ly <- y
if ( delog )
ly <- 10^y
ymn <- mean(ly)
ymd <- median(ly)
if ( delog ) {
ymn <- log10(ymn)
ymd <- log10(ymd)
}
tm[i,j] <- ymn
td[i,j] <- ymd
## T-TEST or RANK SUM TEST
if ( sum(!is.na(y)) >= min.obs ) {
tts <- use.test(y, X)
tt[i,j] <- tts$statistic
tp[i,j] <- tts$p.value
if ( do.plots ) {
outfile <- paste0(fname,cod,"_",aa,".png")
hcol <- ifelse(tts$statistic<0, "#0000ff","#ff0000")
if ( verb>0 ) cat(paste("plotting", outfile, "\n"))
png(outfile, width=3, height=2,
units="in", res=100)
par(mai=c(.5,.15,.25,.15), tcl=-.25, mgp=c(1.3,.3,0))
brks <- seq(min(X), max(X), length.out=20)
hist(y, freq=FALSE, border=NA,
col=paste0(hcol,77),
xlim=range(X), main=NA,
xlab=xlab, breaks=brks, axes=FALSE)
par(new=TRUE)
hist(X, freq=FALSE, col="#77777777", border=NA,
xlim=range(X), main=NA, xlab=NA, ylab=NA, axes=FALSE,
breaks=brks)
abline(v=median(X), col=1, lwd=2)
abline(v=td[i,j], col=hcol, lwd=2)
axis(1)
mtext(as.expression(bquote(.(cod) %->% .(aa))),
3,-.1, font=2, cex=1.5)
legend(ifelse(tts$statistic<0, "topright","topleft"),
c(paste0("n=", length(y)),
paste0("u/t=", round(tts$statistic,1)),
paste0("p=", signif(tts$p.value,1))),
bty="n", seg.len=0, x.intersp=0)
dev.off()
}
}
}
}
if ( verb>0 ) cat(paste("DONE\n"))
## construct overlap object
ova <- list()
ova$p.value <- tp
ova$statistic <- tt
ova$count <- tc
ova$mean <- tm
ova$median <- td
ova$unique <- uq
ova$delog <- delog
## sign of change, used in plotOverlaps
sg <- sign(tt)
sg[is.na(sg)] <- 1
sg[sg==0] <- 1
ova$sign <- sg
## add counts
ova$num.target <-
t(as.matrix(table(x[,cols])[colnames(tp)]))
ova$num.query <-
as.matrix(table(x[,rows]))[rownames(tp),,drop=FALSE]
## attach all raw values
ova$ALL <- allvals
## multiple testing
if ( p.adjust=="q" )
ova$p.value[] <- qvalue::qvalue(c(ova$p.value))$qvalues
else
ova$p.value[] <- p.adjust(c(ova$p.value), method=p.adjust)
ova$p.adjust <- p.adjust
class(ova) <- "clusterOverlaps"
ova
}
## calculated two-sided hypergeo tests for an amino acid
## table, for each column
#' @param x a matrix of character values, e.g. amino acids, where
#' rows are protein sequences and columns relative positions
#' @param abc list of characters to consider, e.g. all amino acids
aaProfile <- function(x, abc, k=1, p.min, alternative="two.sided",
p.adjust="none", verb=0) {
if ( missing(abc) )
abc <- sort(unique(c(x)))
if ( is.null(colnames(x)) )
colnames(x) <- 1:ncol(x)
aam <- matrix(1, ncol=ncol(x), nrow=length(abc))
rownames(aam) <- abc
colnames(aam) <- colnames(x)
aac <- aap <- aar <- aam
aac[] <- 0
for ( i in 1:nrow(aam) ) {
if ( verb>0 ) cat(paste("testing", rownames(aam)[i], "\n"))
for ( j in 1:ncol(aam) ) {
if ( verb>1 ) cat(paste("\t", colnames(aam)[j], "\n"))
aa <- rownames(aam)[i]
pos <- colnames(aam)[j]
m <- sum(c(x)==aa) # white balls
n <- sum(x%in%abc)-m # black balls
N <- m+n # total number of balls
q <- sum(x[,j]==aa) # white balls drawn - AT CURRENT POSITION
k <- sum(x[,j]%in%abc) # number of balls drawn
aac[i,j] <- q
## enriched
if ( alternative%in%c("two.sided","greater") )
aam[i,j] <- phyper(q=q-1, m=m, n=n, k=k, lower.tail=FALSE)
## deprived
if ( alternative%in%c("two.sided","less") )
aap[i,j] <- phyper(q=q, m=m, n=n, k=k, lower.tail=TRUE)
## frequency ratio
aar[i,j] <- q/k * N/m
}
}
if ( alternative=="less" )
aam <- aap
## FILTER SIGNIFICANT
if ( !missing(p.min) ) {
pval <- aam
if ( alternative%in%c("two.sided") ) {
pval[aap<aam] <- aap[aap<aam]
}
sig <- apply(pval, 1, function(x) any(x<p.min))
aam <- aam[sig,,drop=FALSE]
aap <- aap[sig,,drop=FALSE]
aac <- aac[sig,,drop=FALSE]
aar <- aar[sig,,drop=FALSE]
}
## construct overlap class
ovl <- list()
ovl$count <- aac
ovl$ratio <- aar
ovl$p.value <- aam
if ( alternative%in%c("two.sided") ) {
ovl$p.value[aap<aam] <- aap[aap<aam]
ovl$sign <- ifelse(aap<aam,-1,1)
}
ovl$num.query <-
t(t(table(c(x))[rownames(aam)]))
ovl$num.target <-
t(apply(x, 2, function(x) sum(x%in%rownames(aam))))
## convert table to matrix
ovl$num.query <- unclass(ovl$num.query)
ovl$num.target <- unclass(ovl$num.target)
## multiple testing correction
if ( p.adjust=="q" )
ovl$p.value[] <- qvalue::qvalue(c(ovl$p.value))$qvalues
else
ovl$p.value[] <- p.adjust(c(ovl$p.value), method=p.adjust)
ovl$p.adjust <- p.adjust
class(ovl) <- "clusterOverlaps"
ovl
}
## derived from segmenTools::sortOverlaps but trying
## to better handle two-sided tests -
## TODO: integrate in segmenTools; allow to only sort enriched or deprived.
sortOverlaps2 <- function (ovl, axis = 2, p.min = 0.05, cut = FALSE,
srt, symmetric = "no") {
## handle triangle matrix
## NOTE: currently only produced by segmentOverlaps, where
## p.values=1 and counts=0 in the lower triangle
if (symmetric != "no") {
if (symmetric == "upper")
symm.tri <- lower.tri
else if (symmetric == "lower")
symm.tri <- upper.tri
## copy upper to lower
pvl <- abs(ovl$p.value)
n <- nrow(pvl)
m <- ncol(pvl)
if (n != m)
stop("symmetric handling requested for non-symmetric matrix")
for (i in 1:length(ovl)) {
x <- ovl[[i]]
if (inherits(x, "matrix"))
if (nrow(x) == n & ncol(x) == m)
x[symm.tri(x)] <- t(x)[symm.tri(x)]
ovl[[i]] <- x
}
}
## transpose all, if sorting of x-axis (1) is requested
if (axis == 1)
ovl <- t.clusterOverlaps(ovl)
pvl <- ovl$p.value * -ovl$sign ## NOTE: *sign is NEW FOR TWO-SIDED
## sort by significance
if (missing(srt)) {
cls.srt <- colnames(pvl)
if ( is.null(colnames(pvl)) )
stop("missing column names in p-value matrix")
sig.srt <- NULL
## first, get highly significant
for (cl in cls.srt) {
tmp.srt <- order(pvl[, cl], decreasing = FALSE)
## cut by p value
sig.srt <- c(sig.srt,
tmp.srt[tmp.srt %in% which(abs(pvl[,cl]) < p.min)])
## NOTE: abs(pvl) is NEW FOR TWO-SIDED
}
## second, sort rest by increasing pval
rest.srt <- which(!(1:nrow(pvl)) %in% sig.srt)
rest.srt <- rest.srt[order(apply(pvl[rest.srt, , drop = FALSE],
1, max), decreasing = FALSE)]
new.srt <- sig.srt[!duplicated(sig.srt)]
if (!cut)
new.srt <- c(new.srt, rest.srt)
## remember row split between sig and non-sig
nsig <- sum(!duplicated(sig.srt))
}
else {
## used passed sorting!
new.srt <- srt
nsig <- NULL
## 202307 - tested well in clusterGo.R
## warning("custom sorting via `srt` is untested!")
}
## resort all matrices in overlap structure (overlap, pvalue, jaccard, ...)
## TODO: do this safer, check if everything got sorted?
n <- nrow(pvl)
m <- ncol(pvl)
for (i in 1:length(ovl))
if (inherits(ovl[[i]], "matrix")) { ## check if matrix is of same dim
if (nrow(ovl[[i]]) == n)
ovl[[i]] <- ovl[[i]][new.srt, , drop = FALSE]
if (symmetric != "no" & ncol(ovl[[i]]) == m) ## symmetric case!
ovl[[i]] <- ovl[[i]][, new.srt, drop = FALSE]
}
## transpose back
if (axis == 1)
ovl <- t.clusterOverlaps(ovl)
## symmetric case: set other to NA
if (symmetric != "no") {
## copy upper to lower
pvl <- abs(ovl$p.value)
n <- nrow(pvl)
m <- ncol(pvl)
if (n != m)
stop("symmetric handling requested for non-symmetric matrix")
for (i in 1:length(ovl)) {
x <- ovl[[i]]
replace <- ifelse(names(ovl)[i] == "p.value", 1,
0)
if (inherits(x, "matrix"))
if (nrow(x) == n & ncol(x) == m)
x[symm.tri(x)] <- replace
ovl[[i]] <- x
}
}
## add number of sorted sig
ovl$nsig <- nsig
ovl$nsigdir <- axis # remember direction
ovl
}
## generate position frequencies matrices
getPFM <- function(aa, alphabet=ASN$chars) {
## column-wise table of AA
ctl <- apply(aa, 2, table)
## aaids
if ( inherits(ctl,"list") ) {
aaids <- unique(unlist(lapply(ctl, names)))
ctl <- do.call(cbind, lapply(ctl, function(x) x[aaids]))
rownames(ctl) <- aaids
}
ctl[is.na(ctl)] <- 0
## remove all not in alphabet before taking col sum
ctm <- matrix(0, nrow=length(alphabet), ncol=ncol(aa))
rownames(ctm) <- alphabet
ctm[alphabet[alphabet%in%rownames(ctl)],] <-
ctl[alphabet[alphabet%in%rownames(ctl)],]
ctm[is.na(ctm)] <- 0
## frequencies
ctf <- t(t(ctm)/apply(ctm,2,sum))
as.data.frame(ctf)
}
## add significance indicators, modified
## from code in the DiffLogo package
diffLogo_addPvals <- function(dfop, ymin, levels=10^-c(3,5,10)) {
leftOffset = 0
if (!is.null(dfop$unaligned_from_left)) {
leftOffset = dfop$unaligned_from_left
}
if (!is.null(dfop$unaligned_from_right)) {
rightOffset = dfop$unaligned_from_right
}
npos = ncol(dfop$pwm1)
for (j in (leftOffset + 1):(npos - rightOffset)) {
if (dfop$pvals[j] < levels[3]) {
text(j, ymin, "***", xpd=TRUE, cex=1.5)
} else if (dfop$pvals[j] < levels[2]) {
text(j, ymin, "**", xpd=TRUE, cex=1.5)
} else if (dfop$pvals[j] < levels[1]) {