-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaheatmap.R
1708 lines (1466 loc) · 51.9 KB
/
aheatmap.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
#' @include atracks.R
#' @include grid.R
#' @include colorcode.R
NULL
library(grid)
library(gridBase)
# extends gpar objects
c_gpar <- function(gp, ...){
x <- list(...)
do.call(gpar, c(gp, x[!names(x) %in% names(gp)]))
}
lo <- function (rown, coln, nrow, ncol, cellheight = NA, cellwidth = NA
, treeheight_col, treeheight_row, legend, main = NULL, sub = NULL, info = NULL
, annTracks, annotation_legend
, fontsize, fontsize_row, fontsize_col, gp = gpar()){
annotation_colors <- annTracks$colors
row_annotation <- annTracks$annRow
annotation <- annTracks$annCol
gp0 <- gp
coln_height <- unit(10, "bigpts")
if(!is.null(coln)){
longest_coln = which.max(nchar(coln))
coln_height <- coln_height + unit(1.1, "grobheight", textGrob(coln[longest_coln], rot = 90, gp = c_gpar(gp, fontsize = fontsize_col)))
}
rown_width <- rown_width_min <- unit(10, "bigpts")
if(!is.null(rown)){
longest_rown = which.max(nchar(rown))
rown_width <- rown_width_min + unit(1.2, "grobwidth", textGrob(rown[longest_rown], gp = c_gpar(gp, fontsize = fontsize_row)))
}
gp = c_gpar(gp, fontsize = fontsize)
# Legend position
if( !is_NA(legend) ){
longest_break = which.max(nchar(as.character(legend)))
longest_break = unit(1.1, "grobwidth", textGrob(as.character(legend)[longest_break], gp = gp))
# minimum fixed width: plan for 2 decimals and a sign
min_lw = unit(1.1, "grobwidth", textGrob("-00.00", gp = gp))
longest_break = max(longest_break, min_lw)
title_length = unit(1.1, "grobwidth", textGrob("Scale", gp = c_gpar(gp0, fontface = "bold")))
legend_width = unit(12, "bigpts") + longest_break * 1.2
legend_width = max(title_length, legend_width)
}
else{
legend_width = unit(0, "bigpts")
}
.annLegend.dim <- function(annotation, fontsize){
# Width of the corresponding legend
longest_ann <- unlist(lapply(annotation, names))
longest_ann <- longest_ann[which.max(nchar(longest_ann))]
annot_legend_width = unit(1, "grobwidth", textGrob(longest_ann, gp = gp)) + unit(10, "bigpts")
# width of the legend title
annot_legend_title <- names(annotation)[which.max(nchar(names(annotation)))]
annot_legend_title_width = unit(1, "grobwidth", textGrob(annot_legend_title, gp = c_gpar(gp, fontface = "bold")))
# total width
max(annot_legend_width, annot_legend_title_width) + unit(5, "bigpts")
}
# Column annotations
if( !is_NA(annotation) ){
# Column annotation height
annot_height = unit(ncol(annotation) * (8 + 2) + 2, "bigpts")
}
else{
annot_height = unit(0, "bigpts")
}
# add a viewport for the row annotations
if ( !is_NA(row_annotation) ) {
# Row annotation width
row_annot_width = unit(ncol(row_annotation) * (8 + 2) + 2, "bigpts")
}
else {
row_annot_width = unit(0, "bigpts")
}
# Width of the annotation legend
annot_legend_width <-
if( annotation_legend && !is_NA(annotation_colors) ){
.annLegend.dim(annotation_colors, fontsize)
}else unit(0, "bigpts")
# Tree height
treeheight_col = unit(treeheight_col, "bigpts") + unit(5, "bigpts")
treeheight_row = unit(treeheight_row, "bigpts") + unit(5, "bigpts")
# main title
main_height <- if(!is.null(main)) unit(1, "grobheight", main) + unit(20, "bigpts") else unit(0, "bigpts")
# sub title
sub_height <- if(!is.null(sub)) unit(1, "grobheight", sub) + unit(10, "bigpts") else unit(0, "bigpts")
# info panel
if( !is.null(info) ){
info_height <- unit(1, "grobheight", info) + unit(20, "bigpts")
info_width <- unit(1, "grobwidth", info) + unit(10, "bigpts")
}else{
info_height <- unit(0, "bigpts")
info_width <- unit(0, "bigpts")
}
# Set cell sizes
if(is.na(cellwidth)){
matwidth = unit(1, "npc") - rown_width - legend_width - row_annot_width - treeheight_row - annot_legend_width
}
else{
matwidth = unit(cellwidth * ncol, "bigpts")
}
if(is.na(cellheight)){
matheight = unit(1, "npc") - treeheight_col - annot_height - main_height - coln_height - sub_height - info_height
# recompute the cell width depending on the automatic fontsize
if( is.na(cellwidth) && !is.null(rown) ){
cellheight <- convertHeight(unit(1, "grobheight", rectGrob(0,0, matwidth, matheight)), "bigpts", valueOnly = T) / nrow
fontsize_row <- convertUnit(min(unit(fontsize_row, 'points'), unit(0.6*cellheight, 'bigpts')), 'points')
rown_width <- rown_width_min + unit(1.2, "grobwidth", textGrob(rown[longest_rown], gp = c_gpar(gp0, fontsize = fontsize_row)))
matwidth <- unit(1, "npc") - rown_width - legend_width - row_annot_width - treeheight_row - annot_legend_width
}
}
else{
matheight = unit(cellheight * nrow, "bigpts")
}
# HACK:
# - use 6 instead of 5 column for the row_annotation
# - take into account the associated legend's width
# Produce layout()
unique.name <- vplayout(NULL)
lo <- grid.layout(nrow = 7, ncol = 6
, widths = unit.c(treeheight_row, row_annot_width, matwidth, rown_width, legend_width, annot_legend_width)
, heights = unit.c(main_height, treeheight_col, annot_height, matheight, coln_height, sub_height, info_height))
hvp <- viewport( name=paste('aheatmap', unique.name, sep='-'), layout = lo)
pushViewport(hvp)
#grid.show.layout(lo); stop('sas')
# Get cell dimensions
vplayout('mat')
cellwidth = convertWidth(unit(1, "npc"), "bigpts", valueOnly = T) / ncol
cellheight = convertHeight(unit(1, "npc"), "bigpts", valueOnly = T) / nrow
upViewport()
height <- as.numeric(convertHeight(sum(lo$height), "inches"))
width <- as.numeric(convertWidth(sum(lo$width), "inches"))
# Return minimal cell dimension in bigpts to decide if borders are drawn
mindim = min(cellwidth, cellheight)
return( list(width=width, height=height, vp=hvp, mindim=mindim, cellwidth=cellwidth, cellheight=cellheight) )
}
draw_dendrogram = function(hc, horizontal = T){
.draw.dendrodram <- function(hc, ...){
# suppressWarnings( opar <- par(plt = gridPLT(), new = TRUE) )
( opar <- par(plt = gridPLT(), new = TRUE) )
on.exit(par(opar))
if( getOption('verbose') ) grid.rect(gp = gpar(col = "blue", lwd = 2))
if( !is(hc, 'dendrogram') )
hc <- as.dendrogram(hc)
plot(hc, horiz=!horizontal, xaxs="i", yaxs="i", axes=FALSE, leaflab="none", ...)
}
# create a margin viewport
if(!horizontal)
pushViewport( viewport(x=0,y=0,width=0.9,height=1,just=c("left", "bottom")) )
else
pushViewport( viewport(x=0,y=0.1,width=1,height=0.9,just=c("left", "bottom")) )
on.exit(upViewport())
.draw.dendrodram(hc)
}
# draw a matrix first row at bottom, last at top
draw_matrix = function(matrix, border_color, txt = NULL, gp = gpar()){
n = nrow(matrix)
m = ncol(matrix)
x = (1:m)/m - 1/2/m
y = (1:n)/n - 1/2/n
# substitute NA values with empty strings
if( !is.null(txt) ) txt[is.na(txt)] <- ''
for(i in 1:m){
grid.rect(x = x[i], y = y, width = 1/m, height = 1/n, gp = gpar(fill = matrix[,i], col = border_color))
if( !is.null(txt) ){
grid.text(label=txt[, i],
x=x[i],
y=y,
# just=just,
# hjust=hjust,
# vjust=vjust,
rot=0,
check.overlap= FALSE, #check.overlap,
default.units= 'npc', #default.units,
# name=name,
gp=gp,
# draw=draw,
# vp=vp
)
}
}
}
draw_colnames = function(coln, gp = gpar()){
m = length(coln)
# decide on the label orientation
width <- m * unit(1, "grobwidth", textGrob(coln[i <- which.max(nchar(coln))], gp = gp))
width <- as.numeric(convertWidth(width, "inches"))
gwidth <- as.numeric(convertWidth(unit(1, 'npc'), "inches"))
y <- NULL
if( gwidth < width ){
rot <- 270
vjust <- 0.5
hjust <- 0
y <- unit(1, 'npc') - unit(5, 'bigpts')
}else{
rot <- 0
vjust <- 0.5
hjust <- 0.5
}
if( is.null(y) ){
height <- unit(1, "grobheight", textGrob(coln[i], vjust = vjust, hjust = hjust, rot=rot, gp = gp))
y <- unit(1, 'npc') - height
}
x = (1:m)/m - 1/2/m
grid.text(coln, x = x, y = y, vjust = vjust, hjust = hjust, rot=rot, gp = gp)
}
# draw rownames first row at bottom, last on top
draw_rownames = function(rown, gp = gpar()){
n = length(rown)
y = (1:n)/n - 1/2/n
grid.text(rown, x = unit(5, "bigpts"), y = y, vjust = 0.5, hjust = 0, gp = gp)
}
draw_legend = function(color, breaks, legend, gp = gpar()){
height = min(unit(1, "npc"), unit(150, "bigpts"))
pushViewport(viewport(x = 0, y = unit(1, "npc"), just = c(0, 1), height = height))
legend_pos = (legend - min(breaks)) / (max(breaks) - min(breaks))
breaks = (breaks - min(breaks)) / (max(breaks) - min(breaks))
h = breaks[-1] - breaks[-length(breaks)]
grid.rect(x = 0, y = breaks[-length(breaks)], width = unit(10, "bigpts"), height = h, hjust = 0, vjust = 0, gp = gpar(fill = color, col = "#FFFFFF00"))
grid.text(legend, x = unit(12, "bigpts"), y = legend_pos, hjust = 0, gp = gp)
upViewport()
}
convert_annotations = function(annotation, annotation_colors){
#new = annotation
x <- sapply(seq_along(annotation), function(i){
#for(i in 1:length(annotation)){
a = annotation[[i]]
b <- attr(a, 'color')
if( is.null(b) )
b = annotation_colors[[names(annotation)[i]]]
if(class(a) %in% c("character", "factor")){
a = as.character(a)
#print(names(b))
#print(unique(a))
if ( FALSE && length(setdiff(names(b), a)) > 0){
stop(sprintf("Factor levels on variable %s do not match with annotation_colors", names(annotation)[i]))
}
#new[, i] = b[a]
b[match(a, names(b))]
}
else{
a = cut(a, breaks = 100)
#new[, i] = colorRampPalette(b)(100)[a]
ccRamp(b, 100)[a]
}
})
colnames(x) <- names(annotation)
return(x)
#return(as.matrix(new))
}
draw_annotations = function(converted_annotations, border_color, horizontal=TRUE){
n = ncol(converted_annotations)
m = nrow(converted_annotations)
if( horizontal ){
x = (1:m)/m - 1/2/m
y = cumsum(rep(8, n)) - 4 + cumsum(rep(2, n))
for(i in 1:m){
grid.rect(x = x[i], unit(y[n:1], "bigpts"), width = 1/m, height = unit(8, "bigpts"), gp = gpar(fill = converted_annotations[i, ], col = border_color))
}
}else{
x = cumsum(rep(8, n)) - 4 + cumsum(rep(2, n))
y = (1:m)/m - 1/2/m
for (i in 1:m) {
grid.rect(x = unit(x[1:n], "bigpts"), y=y[i], width = unit(8, "bigpts"),
height = 1/m, gp = gpar(fill = converted_annotations[i,]
, col = border_color))
}
}
}
draw_annotation_legend = function(annotation_colors, border_color, gp = gpar()){
y = unit(1, "npc")
text_height = convertHeight(unit(1, "grobheight", textGrob("FGH", gp = gp)), "bigpts")
for(i in names(annotation_colors)){
grid.text(i, x = 0, y = y, vjust = 1, hjust = 0, gp = c_gpar(gp, fontface = "bold"))
y = y - 1.5 * text_height
#if(class(annotation[[i]]) %in% c("character", "factor")){
acol <- annotation_colors[[i]]
if( attr(acol, 'afactor') ){
sapply(seq_along(acol), function(j){
grid.rect(x = unit(0, "npc"), y = y, hjust = 0, vjust = 1, height = text_height, width = text_height, gp = gpar(col = border_color, fill = acol[j]))
grid.text(names(acol)[j], x = text_height * 1.3, y = y, hjust = 0, vjust = 1, gp = gp)
y <<- y - 1.5 * text_height
})
}
else{
yy = y - 4 * text_height + seq(0, 1, 0.01) * 4 * text_height
h = 4 * text_height * 0.02
grid.rect(x = unit(0, "npc"), y = yy, hjust = 0, vjust = 1, height = h, width = text_height, gp = gpar(col = "#FFFFFF00", fill = ccRamp(acol, 100)))
txt = c(tail(names(acol),1), head(names(acol))[1])
yy = y - c(0, 3) * text_height
grid.text(txt, x = text_height * 1.3, y = yy, hjust = 0, vjust = 1, gp = gp)
y = y - 4.5 * text_height
}
y = y - 1.5 * text_height
}
}
vplayout <- function ()
{
graphic.name <- NULL
.index <- 0L
function(x, y, verbose = getOption('verbose') ){
# initialize the graph name
if( is.null(x) ){
.index <<- .index + 1L
graphic.name <<- paste0("AHEATMAP.VP.", .index) #grid:::vpAutoName()
return(graphic.name)
}
name <- NULL
if( !is.numeric(x) ){
name <- paste(graphic.name, x, sep='-')
if( !missing(y) && is(y, 'viewport') ){
y$name <- name
return(pushViewport(y))
}
if( !is.null(tryViewport(name, verbose=verbose)) )
return()
switch(x
, main={x<-1; y<-3;}
, ctree={x<-2; y<-3;}
, cann={x<-3; y<-3;}
, rtree={x<-4; y<-1;}
, rann={x<-4; y<-2;}
, mat={x<-4; y<-3;}
, rnam={x<-4; y<-4;}
, leg={x<-4; y<-5;}
, aleg={x<-4; y<-6;}
, cnam={x<-5; y<-3;}
, sub={x<-6; y<-3;}
, info={x<-7; y<-3;}
, stop("aheatmap - invalid viewport name")
)
}
if( verbose ) message("vp - create ", name)
pushViewport(viewport(layout.pos.row = x, layout.pos.col = y, name=name))
}
}
vplayout <- vplayout()
#' Open a File Graphic Device
#'
#' Opens a graphic device depending on the file extension
#'
#' @keywords internal
gfile <- function(filename, width, height, ...){
# Get file type
r = regexpr("\\.[a-zA-Z]*$", filename)
if(r == -1) stop("Improper filename")
ending = substr(filename, r + 1, r + attr(r, "match.length"))
f = switch(ending,
pdf = function(x, ...) pdf(x, ...),
svg = function(x, ...) svg(x, ...),
png = function(x, ...) png(x, ...),
jpeg = function(x, ...) jpeg(x, ...),
jpg = function(x, ...) jpeg(x, ...),
tiff = function(x, ...) tiff(x, compression = "lzw", ...),
bmp = function(x, ...) bmp(x, ...),
stop("File type should be: pdf, svg, png, bmp, jpg, tiff")
)
args <- c(list(filename), list(...))
if( !missing(width) ){
args$width <- as.numeric(width)
args$height <- as.numeric(height)
if( !ending %in% c('pdf','svg') && is.null(args[['res']]) ){
args$units <- "in"
args$res <- 300
}
}
do.call('f', args)
}
d <- function(x){
if( is.character(x) ) x <- rmatrix(dim(x))
nvp <- 0
on.exit(upViewport(nvp), add=TRUE)
lo <- grid.layout(nrow = 4, ncol = 3)
hvp <- viewport( name=basename(tempfile()), layout = lo)
pushViewport(hvp)
nvp <- nvp + 1
pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 1))
nvp <- nvp + 1
w = convertWidth(unit(1, "npc"), "bigpts", valueOnly = T) / 10
h = convertHeight(unit(1, "npc"), "bigpts", valueOnly = T) / 10
grid.rect()
upViewport()
nvp <- nvp - 1
pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2))
nvp <- nvp + 1
# add inner padding viewport
pushViewport( viewport(x=0,y=0,width=0.9,height=0.9,just=c("left", "bottom")) )
nvp <- nvp + 1
( opar <- par(plt = gridPLT(), new = TRUE) )
on.exit(par(opar), add=TRUE)
hc <- hclust(dist(x))
plot(as.dendrogram(hc), xaxs="i", yaxs="i", axes=FALSE, leaflab="none")
invisible(basename(tempfile()))
}
heatmap_motor = function(matrix, border_color, cellwidth, cellheight
, tree_col, tree_row, treeheight_col, treeheight_row
, filename=NA, width=NA, height=NA
, breaks, color, legend, txt = NULL
, annTracks, annotation_legend=TRUE
, new=TRUE, fontsize, fontsize_row, fontsize_col
, main=NULL, sub=NULL, info=NULL
, verbose=getOption('verbose')
, gp = gpar()){
annotation_colors <- annTracks$colors
row_annotation <- annTracks$annRow
annotation <- annTracks$annCol
writeToFile <- !is.na(filename)
# open graphic device (dimensions will be changed after computation of the correct height)
if( writeToFile ){
gfile(filename)
on.exit(dev.off())
}
# identify the plotting context: base or grid
#NB: use custom function current.vpPath2 instead of official
# grid::current.vpPath as this one creates a new page when called
# on a fresh graphic device
vpp <- current.vpPath_patched()
if( is.null(vpp) ){ # we are at the root viewport
if( verbose ) message("Detected path: [ROOT]")
mf <- par('mfrow')
#print(mf)
# if in in mfrow/layout context: setup fake-ROOT viewports with gridBase
# and do not call plot.new as it is called in grid.base.mix.
new <- if( !identical(mf, c(1L,1L)) ){
if( verbose ) message("Detected mfrow: ", mf[1], " - ", mf[2], ' ... MIXED')
opar <- grid.base.mix(trace=verbose>1)
on.exit( grid.base.mix(opar) )
FALSE
}
else{
if( verbose ){
message("Detected mfrow: ", mf[1], " - ", mf[2])
message("Honouring ", if( missing(new) ) "default "
,"argument `new=", new, '` ... '
, if( new ) "NEW" else "OVERLAY")
}
new
}
}else{
if( verbose ) message("Detected path: ", vpp)
# if new is not specified: change the default behaviour by not calling
# plot.new so that drawing occurs in the current viewport
if( missing(new) ){
if( verbose ) message("Missing argument `new` ... OVERLAY")
new <- FALSE
}else if( verbose ) message("Honouring argument `new=", new, '` ... '
, if( new ) "NEW" else "OVERLAY")
}
# reset device if necessary or requested
if( new ){
if( verbose ) message("Call: plot.new")
#grid.newpage()
plot.new()
}
# define grob for main
mainGrob <- if( !is.null(main) && !is.grob(main) ) textGrob(main, gp = c_gpar(gp, fontsize = 1.2 * fontsize, fontface="bold"))
subGrob <- if( !is.null(sub) && !is.grob(sub) ) textGrob(sub, gp = c_gpar(gp, fontsize = 0.8 * fontsize))
infoGrob <- if( !is.null(info) && !is.grob(info) ){
# infotxt <- paste(strwrap(paste(info, collapse=" | "), width=20), collapse="\n")
grobTree(gList(rectGrob(gp = gpar(fill = "grey80"))
,textGrob(paste(info, collapse=" | "), x=unit(5, 'bigpts'), y=0.5, just='left', gp = c_gpar(gp, fontsize = 0.8 * fontsize))))
}
# Set layout
glo = lo(coln = colnames(matrix), rown = rownames(matrix), nrow = nrow(matrix), ncol = ncol(matrix)
, cellwidth = cellwidth, cellheight = cellheight
, treeheight_col = treeheight_col, treeheight_row = treeheight_row
, legend = legend
, annTracks = annTracks, annotation_legend = annotation_legend
, fontsize = fontsize, fontsize_row = fontsize_row, fontsize_col = fontsize_col
, main = mainGrob, sub = subGrob, info = infoGrob, gp = gp)
# resize the graphic file device if necessary
if( writeToFile ){
if( verbose ) message("Compute size for file graphic device")
m <- par('mar')
if(is.na(height))
height <- glo$height
if(is.na(width))
width <- glo$width
dev.off()
if( verbose ) message("Resize file graphic device to: ", width, " - ", height)
gfile(filename, width=width, height=height)
# re-call plot.new if it was called before
if( new ){
if( verbose ) message("Call again plot.new")
op <- par(mar=c(0,0,0,0))
plot.new()
par(op)
}
if( verbose ) message("Push again top viewport")
# repush the layout
pushViewport(glo$vp)
if( verbose ) grid.rect(width=unit(glo$width, 'inches'), height=unit(glo$height, 'inches'), gp = gpar(col='blue'))
}
#grid.show.layout(glo$layout); return()
mindim <- glo$mindim
# Omit border color if cell size is too small
if(mindim < 3) border_color = NA
# Draw tree for the columns
if (!is_NA(tree_col) && treeheight_col != 0){
#vplayout(1, 2)
vplayout('ctree')
draw_dendrogram(tree_col, horizontal = T)
upViewport()
}
# Draw tree for the rows
if(!is_NA(tree_row) && treeheight_row !=0){
#vplayout(3, 1)
vplayout('rtree')
draw_dendrogram(tree_row, horizontal = F)
upViewport()
}
# recompute margin fontsizes
fontsize_row <- convertUnit(min(unit(fontsize_row, 'points'), unit(0.6*glo$cellheight, 'bigpts')), 'points')
fontsize_col <- convertUnit(min(unit(fontsize_col, 'points'), unit(0.6*glo$cellwidth, 'bigpts')), 'points')
# Draw matrix
#vplayout(3, 2)
vplayout('mat')
draw_matrix(matrix, border_color, txt = txt, gp = gpar(fontsize = fontsize_row))
#d(matrix)
#grid.rect()
upViewport()
# Draw colnames
if(length(colnames(matrix)) != 0){
#vplayout(4, 2)
vplayout('cnam')
draw_colnames(colnames(matrix), gp = c_gpar(gp, fontsize = fontsize_col))
upViewport()
}
# Draw rownames
if(length(rownames(matrix)) != 0){
#vplayout(3, 3)
vplayout('rnam')
draw_rownames(rownames(matrix), gp = c_gpar(gp, fontsize = fontsize_row))
upViewport()
}
# Draw annotation tracks
if( !is_NA(annotation) ){
#vplayout(2, 2)
vplayout('cann')
draw_annotations(annotation, border_color)
upViewport()
}
# add row annotations if necessary
if ( !is_NA(row_annotation) ) {
vplayout('rann')
draw_annotations(row_annotation, border_color, horizontal=FALSE)
upViewport()
}
# Draw annotation legend
if( annotation_legend && !is_NA(annotation_colors) ){
#vplayout(3, 5)
vplayout('aleg')
draw_annotation_legend(annotation_colors, border_color, gp = c_gpar(gp, fontsize = fontsize))
upViewport()
}
# Draw legend
if(!is_NA(legend)){
#vplayout(3, 4)
vplayout('leg')
draw_legend(color, breaks, legend, gp = c_gpar(gp, fontsize = fontsize))
upViewport()
}
# Draw main
if(!is.null(mainGrob)){
vplayout('main')
grid.draw(mainGrob)
upViewport()
}
# Draw subtitle
if(!is.null(subGrob)){
vplayout('sub')
grid.draw(subGrob)
upViewport()
}
# Draw info
if(!is.null(infoGrob)){
vplayout('info')
grid.draw(infoGrob)
upViewport()
}
# return current vp tree
#ct <- current.vpTree()
#print(current.vpPath())
upViewport()
#popViewport()
# grab current grob and return
# gr <- grid.grab()
# grid.draw(gr)
#ct
NULL
}
generate_breaks = function(x, n, center=NA){
if( missing(center) || is_NA(center) )
seq(min(x, na.rm = T), max(x, na.rm = T), length.out = n + 1)
else{ # center the breaks on the requested value
n2 <- ceiling((n+0.5)/2)
M <- max(abs(center - min(x, na.rm = TRUE)), abs(center - max(x, na.rm = TRUE)))
lb <- seq(center-M, center, length.out = n2)
rb <- seq(center, center+M, length.out = n2)
c(lb, rb[-1])
}
}
scale_vec_colours = function(x, col = rainbow(10), breaks = NA){
return(col[as.numeric(cut(x, breaks = breaks, include.lowest = T))])
}
scale_colours = function(mat, col = rainbow(10), breaks = NA){
mat = as.matrix(mat)
return(matrix(scale_vec_colours(as.vector(mat), col = col, breaks = breaks), nrow(mat), ncol(mat), dimnames = list(rownames(mat), colnames(mat))))
}
cutheight <- function(x, n){
# exit early if n <=1: nothing to do
if( n <=1 ) return( attr(x, 'height') )
res <- NULL
.heights <- function(subtree, n){
if( is.leaf(subtree) ) return()
if (!(K <- length(subtree)))
stop("non-leaf subtree of length 0")
# extract heights from each subtree
for( k in 1:K){
res <<- c(res, attr(subtree[[k]], 'height'))
}
# continue only if there is not yet enough subtrees
if( length(res) < n ){
for( k in 1:K){
.heights(subtree[[k]], n)
}
}
}
# extract at least the top h heights
.heights(x, n)
# sort by decreasing order
res <- sort(res, decreasing=TRUE)
res[n-1]
}
#' Fade Out the Upper Branches from a Dendrogram
#'
#' @param x a dendrogram
#' @param n the number of groups
#'
#' @import digest
#' @keywords internal
cutdendro <- function(x, n){
# exit early if n <=1: nothing to do
if( n <= 1 ) return(x)
# add node digest ids to x
x <- dendrapply(x, function(n){
attr(n, 'id') <- digest(attributes(n))
n
})
# cut x in n groups
# find the height where to cut
h <- cutheight(x, n)
cfx <- cut(x, h)
# get the ids of the upper nodes
ids <- sapply(cfx$lower, function(sub) attr(sub, 'id'))
# highlight the upper branches with dot lines
dts <- c(lty=2, lwd=1.2, col=8)
a <- dendrapply(x, function(node){
a <- attributes(node)
if( a$id %in% ids || (!is.leaf(node) && any(c(attr(node[[1]], 'id'), attr(node[[2]], 'id')) %in% ids)) )
attr(node, 'edgePar') <- dts
node
})
}
# internal class definition for
as_treedef <- function(x, ...){
res <- if( is(x, 'hclust') )
list(dendrogram=as.dendrogram(x), dist.method=x$dist.method, method=x$method)
else list(dendrogram=x, ...)
class(res) <- "aheatmap_treedef"
res
}
rev.aheatmap_treedef <- function(x){
x$dendrogram <- rev(x$dendrogram)
x
}
is_treedef <- function(x) is(x, 'aheatmap_treedef')
isLogical <- function(x) isTRUE(x) || identical(x, FALSE)
# Convert an index vector usable on the subset data into one usable on the
# original data
subset2orginal_idx <- function(idx, subset){
if( is.null(subset) || is.null(idx) ) idx
else{
res <- subset[idx]
attr(res, 'subset') <- idx
res
}
}
cluster_mat = function(mat, param, distfun, hclustfun, reorderfun, na.rm=TRUE, subset=NULL, verbose = FALSE){
# do nothing if an hclust object is passed
parg <- deparse(substitute(param))
Rowv <-
if( is(param, 'hclust') || is(param, 'dendrogram') ){ # hclust or dendrograms are honoured
res <- as_treedef(param)
# subset if requested: convert into an index vector
# the actuval subsetting is done by first case (index vector)
if( !is.null(subset) ){
warning("Could not directly subset dendrogram/hclust object `", parg
,"`: using subset of the dendrogram's order instead.")
# use dendrogram order instead of dendrogram itself
param <- order.dendrogram(res$dendrogram)
}else # EXIT: return treedef
return(res)
}else if( is(param, 'silhouette') ){ # use silhouette order
si <- sortSilhouette(param)
param <- attr(si, 'iOrd')
}
# index vectors are honoured
if( is.integer(param) && length(param) > 1 ){
# subset if requested: reorder the subset indexes as in param
if( !is.null(subset) )
param <- order(match(subset, param))
param
}else{ # will compute dendrogram (NB: mat was already subset before calling cluster_mat)
param <-
if( is.integer(param) )
param
else if( is.null(param) || isLogical(param) ) # use default reordering by rowMeans
rowMeans(mat, na.rm=na.rm)
else if( is.numeric(param) ){ # numeric reordering weights
# subset if necessary
if( !is.null(subset) )
param <- param[subset]
param
}else if( is.character(param) || is.list(param) ){
if( length(param) == 0 )
stop("aheatmap - Invalid empty character argument `", parg, "`.")
# set default names if no names were provided
if( is.null(names(param)) ){
if( length(param) > 3 ){
warning("aheatmap - Only using the three first elements of `", parg, "` for distfun and hclustfun respectively.")
param <- param[1:3]
}
n.allowed <- c('distfun', 'hclustfun', 'reorderfun')
names(param) <- head(n.allowed, length(param))
}
# use the distance passed in param
if( 'distfun' %in% names(param) ) distfun <- param[['distfun']]
# use the clustering function passed in param
if( 'hclustfun' %in% names(param) ) hclustfun <- param[['hclustfun']]
# use the reordering function passed in param
if( 'reorderfun' %in% names(param) ) reorderfun <- param[['reorderfun']]
TRUE
}else
stop("aheatmap - Invalid value for argument `", parg, "`. See ?aheatmap.")
# compute distances
d <- if( isString(distfun) ){
distfun <- distfun[1]
corr.methods <- c("pearson", "kendall", "spearman")
av <- c("correlation", corr.methods, "euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski")
i <- pmatch(distfun, av)
if( is_NA(i) )
stop("aheatmap - Invalid dissimilarity method, must be one of: ", str_out(av, Inf))
distfun <- av[i]
if(distfun == "correlation") distfun <- 'pearson'
if(distfun %in% corr.methods){ # distance from correlation matrix
if( verbose ) message("Using distance method: correlation (", distfun, ')')
d <- dist(1 - cor(t(mat), method = distfun))
attr(d, 'method') <- distfun
d
}else{
if( verbose ) message("Using distance method: ", distfun)
dist(mat, method = distfun)
}
}else if( is(distfun, "dist") ){
if( verbose ) message("Using dist object: ", distfun)
distfun
}else if( is.function(distfun) ){
if( verbose ) message("Using custom dist function")
distfun(mat)
}else
stop("aheatmap - Invalid dissimilarity function: must be a character string, an object of class 'dist', or a function")
# do hierarchical clustering
hc <- if( is.character(hclustfun) ){
av <- c('ward', 'single', 'complete', 'average', 'mcquitty', 'median', 'centroid')
i <- pmatch(hclustfun, av)
if( is.na(i) )
stop("aheatmap - Invalid clustering method, must be one of: ", paste("'", av, "'", sep='', collapse=', '))
hclustfun <- av[i]
if( verbose ) message("Using clustering method: ", hclustfun)
hclust(d, method=hclustfun)
}else if( is.function(hclustfun) )
hclustfun(d)
else
stop("aheatmap - Invalid clustering function: must be a character string or a function")
#convert into a dendrogram
dh <- as.dendrogram(hc)
# customize the dendrogram plot: highlight clusters
if( is.integer(param) )
dh <- cutdendro(dh, param)
else if( is.numeric(param) && length(param)==nrow(mat) ) # reorder the dendrogram if necessary
dh <- reorderfun(dh, param)
# wrap up into a aheatmap_treedef object
as_treedef(dh, dist.method=hc$dist.method, method=hc$method)
}
}
scale_mat = function(x, scale, na.rm=TRUE){
av <- c("none", "row", "column", 'r1', 'c1')
i <- pmatch(scale, av)
if( is_NA(i) )
stop("scale argument shoud take values: 'none', 'row' or 'column'")
scale <- av[i]
switch(scale, none = x
, row = {
x <- sweep(x, 1L, rowMeans(x, na.rm = na.rm), check.margin = FALSE)
sx <- apply(x, 1L, sd, na.rm = na.rm)
sweep(x, 1L, sx, "/", check.margin = FALSE)
}
, column = {
x <- sweep(x, 2L, colMeans(x, na.rm = na.rm), check.margin = FALSE)
sx <- apply(x, 2L, sd, na.rm = na.rm)
sweep(x, 2L, sx, "/", check.margin = FALSE)
}
, r1 = sweep(x, 1L, rowSums(x, na.rm = na.rm), '/', check.margin = FALSE)
, c1 = sweep(x, 2L, colSums(x, na.rm = na.rm), '/', check.margin = FALSE)
)
}
.Rd.seed <- new.env()
round.pretty <- function(x, min=2){
if( is.null(x) ) return(NULL)
n <- 0
y <- round(sort(x), n)
if( all(diff(y)==0) ) return( round(x, min) )
while( any(diff(y)==0) ){
n <- n+1
y <- round(sort(x), n)
}
dec <- max(min,n)
round(x, dec)
}
generate_annotation_colours = function(annotation, annotation_colors, seed=TRUE){
if( is_NA(annotation_colors) ){
annotation_colors = list()
}
# use names from annotations if necessary/possible
if( length(annotation_colors) > 0L
&& length(annotation_colors) <= length(annotation)
&& is.null(names(annotation_colors)) ){
names(annotation_colors) <- head(names(annotation), length(annotation_colors))
}
count = 0
annotationLevels <- list()
anames <- names(annotation)
sapply(seq_along(annotation), function(i){
a <- annotation[[i]]
if( class(annotation[[i]]) %in% c("character", "factor")){
# convert to character vector
a <- if( is.factor(a) ) levels(a) else unique(a)
count <<- count + nlevels(a)
# merge if possible
if( !is.null(anames) && anames[i]!='' )
annotationLevels[[anames[i]]] <<- unique(c(annotationLevels[[anames[i]]], a))
else
annotationLevels <<- c(annotationLevels, list(a))
}else
annotationLevels <<- c(annotationLevels, annotation[i])