-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathHeatmapAnnotation-class.R
More file actions
executable file
·1543 lines (1416 loc) · 49 KB
/
Copy pathHeatmapAnnotation-class.R
File metadata and controls
executable file
·1543 lines (1416 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# == title
# Class for Heatmap Annotations
#
# == details
# A complex heatmap contains a list of annotations which are represented as graphics
# placed on rows and columns. The `HeatmapAnnotation-class` contains a list of single annotations which are
# represented as a list of `SingleAnnotation-class` objects.
#
# == methods
# The `HeatmapAnnotation-class` provides following methods:
#
# - `HeatmapAnnotation`: constructor method.
# - `draw,HeatmapAnnotation-method`: draw the annotations.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
HeatmapAnnotation = setClass("HeatmapAnnotation",
slots = list(
name = "character",
anno_list = "list", # a list of `SingleAnnotation` objects
anno_size = "ANY",
which = "character",
width = "ANY",
height = "ANY",
gap = "ANY",
subsettable = "logical",
extended = "ANY",
param = "list"
),
prototype = list(
anno_list = list(),
which = "column",
gap = unit(0, "mm"),
subsettable = FALSE,
extended = unit(c(0, 0, 0, 0), "mm"),
param = list()
),
contains = "AdditiveUnit"
)
# == title
# Constructor Method for HeatmapAnnotation class
#
# == param
# -... Name-value pairs where the names correspond to annotation names and values can be a vector, a matrix and an
# annotation function. Each pair is sent to `SingleAnnotation` to contruct a single annotation.
# -df A data frame. Each column will be treated as a simple annotation. The data frame must have column names.
# -name Name of the heatmap annotation, optional.
# -col A list of colors which contain color mapping to ``df`` or simple annotations defined in ``...``.
# See `SingleAnnotation` for how to set colors.
# -na_col Color for ``NA`` values in simple annotations.
# -annotation_legend_param A list which contains parameters for annotation legends. See `color_mapping_legend,ColorMapping-method` for all possible options.
# -show_legend Whether show annotation legends. The value can be one single value or a vector.
# -which Are these row annotations or column annotations?
# -gp Graphic parameters for simple annotations (with ``fill`` parameter ignored).
# -border border of single annotations.
# -gap Gap between annotations. It can be a single value or a vector of `grid::unit` objects.
# -show_annotation_name Whether show annotation names? For column annotation, annotation names are drawn either on the left
# or the right, and for row annotations, names are draw either on top or at the bottom. The value can be a vector.
# -annotation_label Labels for the annotations. By default it is the same as individual annotation names.
# -annotation_name_gp Graphic parameters for anntation names. Graphic paramters can be vectors.
# -annotation_name_offset Offset to the annotation names, a `grid::unit` object. The value can be a vector.
# -annotation_name_side Side of the annotation names.
# -annotation_name_rot Rotation of the annotation names. The value can be a vector.
# -annotation_name_align Whether to align the annotation names.
# -annotation_height Height of each annotation if annotations are column annotations.
# -annotation_width Width of each annotation if annotations are row annotations.
# -height Height of the whole column annotations.
# -width Width of the whole heatmap annotations.
# -simple_anno_size Size of the simple annotation.
# -simple_anno_size_adjust Whether also adjust the size of simple annotations when adjusting the whole heatmap annotation.
# -use_raster Whether render the annotations as raster images. It helps to reduce file size when there are a huge number
# of columns (or rows for row annotations). The value is passed to all single annotations.
# -raster_device Graphic device which is used to generate the raster image.
# -raster_quality A value larger than 1.
# -raster_device_param A list of further parameters for the selected graphic device.
# -raster_by_magick Whether to use `magick::image_resize` to scale the image.
# -raster_magick_filter Pass to ``filter`` argument of `magick::image_resize`. A character scalar and all possible values
# are in `magick::filter_types`. The default is ``"Lanczos"``.
#
# == details
# For arguments ``show_legend``, ``border``, ``annotation_name_offset``, ``annotation_name_side``, ``annotation_name_rot``,
# ``show_annotation_name``, they can be set as named vectors to modify values for some of the annotations,
# e.g. assuming you have an annotation with name ``foo``, you can specify ``border = c(foo = TRUE)`` in `HeatmapAnnotation`.
#
# There are three ways to specify heatmap annotations:
#
# 1. If the annotation is simply a vector or a matrix, it can be specified like ``HeatmapAnnotation(foo = 1:10)``.
# 2. If the annotations are already stored as a data frame, it can be specified like ``HeatmapAnnotation(df = df)``.
# 3. For complex annotations, users can use the pre-defined annotation functions such as `anno_points`: ``HeatmapAnnotation(foo = anno_points(1:10))``.
#
# For more details and examples, please check https://jokergoo.github.io/ComplexHeatmap-reference/book/heatmap-annotations.html.
#
# == value
# A `HeatmapAnnotation-class` object.
#
# == seealso
# There are two helper functions: `rowAnnotation` and `columnAnnotation`.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
HeatmapAnnotation = function(...,
df = NULL, name, col, na_col = "grey",
annotation_legend_param = list(),
show_legend = TRUE,
which = c("column", "row"),
gp = gpar(col = NA),
border = FALSE,
gap = unit(1, "points"),
show_annotation_name = TRUE,
annotation_label = NULL,
annotation_name_gp = gpar(),
annotation_name_offset = NULL,
annotation_name_side = ifelse(which == "column", "right", "bottom"),
annotation_name_rot = NULL,
annotation_name_align = FALSE,
annotation_height = NULL,
annotation_width = NULL,
height = NULL,
width = NULL,
simple_anno_size = ht_opt$simple_anno_size,
simple_anno_size_adjust = FALSE,
use_raster = FALSE,
raster_device = NULL,
raster_quality = 1,
raster_device_param = list(),
raster_by_magick = requireNamespace("magick", quietly = TRUE),
raster_magick_filter = NULL
) {
dev.null()
is_height_set = !missing(height)
is_width_set = !missing(width)
is_annotation_height_set = !missing(annotation_height)
is_annotation_width_set = !missing(annotation_width)
.ENV$current_annotation_which = NULL
which = match.arg(which)[1]
.ENV$current_annotation_which = which
on.exit({
.ENV$current_annotation_which <- NULL
dev.off2()
})
fun_args = names(as.list(environment()))
# annotations built inside wrapper functions (oncoPrint(), UpSet(), pheatmap())
# never get `use_raster` passed to them, so the global option is the only way
# to rasterize those
if(missing(use_raster) && !is.null(ht_opt$annotation_use_raster)) {
use_raster = ht_opt$annotation_use_raster
}
verbose = ht_opt$verbose
.Object = new("HeatmapAnnotation")
anno_list = list()
if(missing(name)) {
name = paste0("heatmap_annotation_", get_row_annotation_index())
increase_row_annotation_index()
}
.Object@name = name
n_anno = 0
##### pull all annotation to `anno_value_list`####
if(!is.null(df)) {
if(is.matrix(df)) {
warning_wrap("`df` should be a data frame while not a matrix. Convert it to data frame.")
df = as.data.frame(df)
} else if(!is.data.frame(df)) {
oe = try(df <- as.data.frame(df), silent = TRUE)
if(inherits(oe, "try-errir")) {
stop_wrap("`df` should be a data frame.")
}
} else {
df = as.data.frame(df)
}
}
anno_arg_list = list(...)
anno_arg_names = names(anno_arg_list)
if(any(anno_arg_names == "")) {
stop_wrap("Annotations should have names.")
}
if(is.null(anno_arg_names)) {
if(length(anno_arg_list) == 1) {
stop_wrap("The annotation should be specified as name-value pairs or via argument `df` with a data frame.")
}
if(length(anno_arg_list) > 1) {
stop_wrap("Annotations should have names.")
}
}
if(!is.null(df) && length(anno_arg_list)) {
if(any(duplicated(c(names(df), anno_arg_names)))) {
stop_wrap("Annotation names are duplicated to those in `df`. Check the column names of `df`.")
}
}
anno_value_list = list()
for(nm in anno_arg_names) {
anno_value_list[[nm]] = anno_arg_list[[nm]]
}
if(!is.null(df)) {
for(nm2 in colnames(df)) {
if(is.null(rownames(df))) {
anno_value_list[[nm2]] = df[, nm2]
} else {
anno_value_list[[nm2]] = structure(df[, nm2], names = rownames(df))
}
}
}
l_simple_anno = sapply(anno_value_list, is.atomic)
n_simple_anno = sum(l_simple_anno)
simple_anno_name = names(anno_value_list[l_simple_anno])
if("anno_simple_size" %in% names(anno_value_list)) {
stop_wrap("Please use `simple_anno_size` as the argument.")
}
if(verbose) qqcat("in total there are @{length(anno_value_list)} annotations (@{n_simple_anno} simple annotations)\n")
# normalize `show_legend`
if(length(show_legend) == 1) {
show_legend = recycle_param(show_legend, simple_anno_name, TRUE)
}
if(length(show_legend) < length(anno_value_list) && length(show_legend) > 1) {
show_legend = recycle_param(show_legend, simple_anno_name, TRUE)
}
# check length of show_legend
if(length(show_legend) == length(anno_value_list) && !all(l_simple_anno)) {
show_legend = show_legend[l_simple_anno]
}
###### normalize `heatmap_legend_param` #######
if(length(annotation_legend_param) == 0) {
annotation_legend_param = rep.list(NULL, n_simple_anno)
} else if(inherits(annotation_legend_param, "list")) {
if(all(sapply(annotation_legend_param, inherits, "list"))) { # if it is a list of lists
nl = length(annotation_legend_param)
if(nl > n_simple_anno) {
stop_wrap("Amount of legend params is larger than the number of simple annotations.")
}
if(is.null(names(annotation_legend_param))) {
names(annotation_legend_param) = simple_anno_name[seq_len(nl)]
} else if(length(setdiff(names(annotation_legend_param), simple_anno_name))) {
stop_wrap("Some names in 'annotation_legend_param' are not in names of simple annotations.")
} else {
annotation_legend_param = annotation_legend_param[ intersect(simple_anno_name, names(annotation_legend_param)) ]
}
lp = rep.list(NULL, n_simple_anno)
names(lp) = simple_anno_name
for(i in seq_along(lp)) {
if(names(lp)[i] %in% names(annotation_legend_param)) {
lp[[i]] = annotation_legend_param[[names(lp)[i]]]
}
}
annotation_legend_param = lp
} else {
annotation_legend_param = rep.list(annotation_legend_param, n_simple_anno)
}
}
is_name_offset_called = !missing(annotation_name_offset)
is_name_rot_called = !missing(annotation_name_rot)
n_total_anno = length(anno_value_list)
an = names(anno_value_list)
show_annotation_name = recycle_param(show_annotation_name, an, TRUE)
annotation_name_side = recycle_param(annotation_name_side, an, ifelse(which == "column", "right", "bottom"))
if(inherits(annotation_name_offset, "unit")) annotation_name_offset = to_unit_str(annotation_name_offset)
annotation_name_offset = recycle_param(annotation_name_offset, an, NULL, as.list = TRUE)
annotation_name_rot = recycle_param(annotation_name_rot, an, NULL, as.list = TRUE)
if(missing(border)) {
if(!is.null(ht_opt$annotation_border)) border = ht_opt$annotation_border
}
border = recycle_param(border, an, FALSE)
annotation_name_gp = recycle_gp(annotation_name_gp, n_total_anno)
if(length(annotation_label)) {
if(inherits(annotation_label, "gridtext")) {
annotation_label = lapply(seq_along(annotation_label), function(i) annotation_label[i])
names(annotation_label) = an
}
}
annotation_label = recycle_list(annotation_label, an, NULL)
# if(length(annotation_label) > 0) {
# annotation_label = lapply(seq_along(annotation_label), function(i) annotation_label[i])
# names(annotation_label) == an
# }
if(!missing(col)) {
if(length(col) >= 1) {
if(is.null(names(col))) {
stop_wrap("`col` should be a named list.")
}
if(any(is.na(names(col)))) {
stop_wrap("`col` should be a named list.")
}
col = col[intersect(simple_anno_name, names(col))]
if(any(sapply(col, function(x) if(is.function(x)) FALSE else is.null(names(x))))) {
stop_wrap("elements in `col` should be named vectors.")
}
if(any(sapply(col, function(x) if(is.function(x)) FALSE else any(is.na(names(x)))))) {
stop_wrap("elements in `col` should be named vectors.")
}
}
}
### check the length of annotations
len = sapply(anno_value_list, function(x) {
if(is.matrix(x)) {
nrow(x)
} else if(inherits(x, "AnnotationFunction")) {
x@n
} else if(is.atomic(x)) {
length(x)
} else {
NA
}
})
len = len[!is.na(len)]
len = len[len > 0]
if(length(len)) {
if(length(unique(len)) > 1) {
stop_wrap(paste0("Length of annotations differs. ", paste(qq("@{names(len)}: @{len}", collapse = FALSE), collapse = ", ")))
}
}
i_simple = 0
i_anno = 0
simple_length = NULL
col_name_defined = NULL
for(ag in names(anno_value_list)) {
i_anno = i_anno + 1
arg_list = list(name = ag, which = which,
label = annotation_label[[i_anno]],
show_name = show_annotation_name[[i_anno]],
name_gp = subset_gp(annotation_name_gp, i_anno),
name_offset = annotation_name_offset[[i_anno]],
name_side = annotation_name_side[i_anno],
name_rot = annotation_name_rot[[i_anno]],
border = border[i_anno],
use_raster = use_raster,
raster_device = raster_device,
raster_quality = raster_quality,
raster_device_param = raster_device_param,
raster_by_magick = raster_by_magick,
raster_magick_filter = raster_magick_filter)
if(inherits(anno_value_list[[ag]], c("function", "AnnotationFunction"))) {
arg_list$fun = anno_value_list[[ag]]
if(inherits(anno_value_list[[ag]], "function")) {
if(which == "row") {
arg_list$width = unit(1, "cm")
} else {
arg_list$height = unit(1, "cm")
}
}
anno_list[[ag]] = do.call(SingleAnnotation, arg_list)
} else if(is.atomic(anno_value_list[[ag]])) {
arg_list$show_legend = show_legend[i_simple + 1]
arg_list$gp = gp
arg_list$legend_param = annotation_legend_param[[i_simple + 1]]
arg_list$value = anno_value_list[[ag]]
arg_list$na_col = na_col
arg_list$simple_anno_size = simple_anno_size
if(missing(col)) {
anno_list[[ag]] = do.call(SingleAnnotation, arg_list)
} else {
if(is.null(col[[ ag ]])) { # if the color is not provided
anno_list[[ag]] = do.call(SingleAnnotation, arg_list)
} else {
arg_list$col = col[[ ag ]]
anno_list[[ag]] = do.call(SingleAnnotation, arg_list)
col_name_defined = c(col_name_defined, ag)
}
}
i_simple = i_simple + 1
} else {
stop_wrap(paste0(ag, ": annotations should be vector/data frame (only `df`)/matrix/functions."))
}
}
if(!missing(col)) {
unused_col_name = setdiff(names(col), col_name_defined)
if(length(unused_col_name)) {
# warning(paste0("Following are defined in `col` while have no corresponding annotations:\n", paste(unused_col_name, collapse = ", ")))
}
}
n_total_anno = length(anno_list)
## check whether anno_list contains zoomed anno_empty
if(n_total_anno > 1) {
for(i in seq_len(n_total_anno)) {
anno = anno_list[[i]]@fun
if(identical(anno@fun_name, "anno_empty")) {
if(anno@var_env$zoom) {
stop_wrap("You set `zoom = TRUE` in `anno_empty()` for the empty annotation. The HeatmapAnnotation object only allows to contain one single annotation if it is a zoomed empty annotation.")
}
}
}
}
if(is.null(gap)) gap = unit(0, "mm")
if(identical(gap, 0)) gap = unit(0, "mm")
if(!inherits(gap, "unit")) stop_wrap("`gap` needs to be a unit object.")
# the nth gap does not really matter
if(length(gap) == 1) {
gap = rep(gap, n_total_anno)
} else if(length(gap) == n_total_anno - 1) {
gap = unit.c(gap, unit(0, "mm"))
} else if(length(gap) < n_total_anno - 1) {
stop_wrap("Length of `gap` is wrong.")
}
.Object@gap = gap
### calualte the width/heigit of annotations
global_height = NULL
global_width = NULL
if(which == "column") {
anno_size = do.call("unit.c", lapply(anno_list, height))
if(is.null(height)) {
height = sum(anno_size) + sum(gap) - gap[n_total_anno]
}
# for width, only look at `width`
if(is.null(width)) {
width = unit(1, "npc")
}
for(i in 1:n_total_anno) {
width(anno_list[[i]]) = width
}
} else if(which == "row") {
anno_size = do.call("unit.c", lapply(anno_list, width))
if(is.null(width)) {
width = sum(anno_size) + sum(gap) - gap[n_total_anno]
}
if(is.null(height)) {
height = unit(1, "npc")
}
for(i in 1:n_total_anno) {
height(anno_list[[i]]) = height
}
}
if(is_abs_unit(width)) {
width = convertWidth(width, "mm")
}
if(is_abs_unit(height)) {
height = convertWidth(height, "mm")
}
anno_size = convertWidth(anno_size, "mm")
names(anno_list) = sapply(anno_list, function(x) x@name)
if(annotation_name_align) {
# adjust x, y, offset slot in SingleAnnotation objects
l_bottom = sapply(anno_list, function(x) x@name_param$side == "bottom" & x@name_param$show & x@fun@fun_name != "anno_simple")
if(sum(l_bottom) > 1) {
max_offset = unit(max(sapply(anno_list[l_bottom], function(anno) {
unit_to_numeric(anno@name_param$offset)
})), "mm")
for(i in which(l_bottom)) {
anno_list[[i]]@name_param$offset = max_offset
anno_list[[i]]@name_param$y = unit(0, "npc") - max_offset
}
}
l_top = sapply(anno_list, function(x) x@name_param$side == "top" & x@name_param$show & x@fun@fun_name != "anno_simple")
if(sum(l_top) > 1) {
max_offset = unit(max(sapply(anno_list[l_top], function(anno) {
unit_to_numeric(anno@name_param$offset)
})), "mm")
for(i in which(l_bottom)) {
anno_list[[i]]@name_param$offset = max_offset
anno_list[[i]]@name_param$y = unit(1, "npc") + max_offset
}
}
l_left = sapply(anno_list, function(x) x@name_param$side == "left" & x@name_param$show & x@fun@fun_name != "anno_simple")
if(sum(l_left) > 1) {
max_offset = unit(max(sapply(anno_list[l_left], function(anno) {
unit_to_numeric(anno@name_param$offset)
})), "mm")
for(i in which(l_left)) {
anno_list[[i]]@name_param$offset = max_offset
anno_list[[i]]@name_param$x = unit(0, "npc") - max_offset
}
}
l_right = sapply(anno_list, function(x) x@name_param$side == "right" & x@name_param$show & x@fun@fun_name != "anno_simple")
if(sum(l_right) > 1) {
max_offset = unit(max(sapply(anno_list[l_right], function(anno) {
unit_to_numeric(anno@name_param$offset)
})), "mm")
for(i in which(l_right)) {
anno_list[[i]]@name_param$offset = max_offset
anno_list[[i]]@name_param$x = unit(1, "npc") + max_offset
}
}
}
.Object@anno_list = anno_list
.Object@anno_size = anno_size
.Object@which = which
.Object@width = width
.Object@height = height
.Object@subsettable = all(sapply(anno_list, function(x) x@subsettable))
extended = unit(c(0, 0, 0, 0), "mm")
for(i in 1:4) {
extended[i] = unit(max(sapply(anno_list, function(anno) {
unit_to_numeric(anno@extended[i])
})), "mm")
}
.Object@extended = extended
.Object@param = list(
simple_anno_size = simple_anno_size,
simple_anno_size_adjust = simple_anno_size_adjust,
is_height_set = is_height_set,
is_width_set = is_width_set,
is_annotation_height_set = is_annotation_height_set,
is_annotation_width_set = is_annotation_width_set
)
## adjust height/width if `width`/`annotation_width` is set
if(which == "column") {
.Object = re_size(.Object, height = height, annotation_height = annotation_height)
} else {
.Object = re_size(.Object, width = width, annotation_width = annotation_width)
}
return(.Object)
}
# == title
# Construct Row Annotations
#
# == param
# -... Pass to `HeatmapAnnotation`.
#
# == details
# The function is identical to
#
# HeatmapAnnotation(..., which = "row")
#
# == value
# A `HeatmapAnnotation-class` object.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
rowAnnotation = function(...) {
HeatmapAnnotation(..., which = "row")
}
# == title
# Construct Column Annotations
#
# == param
# -... Pass to `HeatmapAnnotation`.
#
# == details
# The function is identical to
#
# HeatmapAnnotation(..., which = "column")
#
# == value
# A `HeatmapAnnotation-class` object.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
columnAnnotation = function(...) {
HeatmapAnnotation(..., which = "column")
}
# == title
# Get a List of ColorMapping objects
#
# == param
# -object A `HeatmapAnnotation-class` object.
#
# == details
# Color mappings for visible simple annotations are only returned.
#
# This function is only for internal use.
#
# == values
# A list of `ColorMapping-class` objects or an empty list.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
setMethod(f = "get_color_mapping_list",
signature = "HeatmapAnnotation",
definition = function(object) {
color_mapping_list = list()
for(i in seq_along(object@anno_list)) {
if(object@anno_list[[i]]@show_legend) {
color_mapping_list = c.list(color_mapping_list, object@anno_list[[i]]@color_mapping)
}
}
return(color_mapping_list)
})
# == title
# Get a List of Annotation Legend Parameters
#
# == param
# -object A `HeatmapAnnotation-class` object.
#
# == details
# The annotation legend parameters for visible simple annotations are only returned.
#
# This function is only for internal use.
#
# == values
# A list.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
setMethod(f = "get_legend_param_list",
signature = "HeatmapAnnotation",
definition = function(object) {
color_mapping_param_list = list()
for(i in seq_along(object@anno_list)) {
if(object@anno_list[[i]]@show_legend) {
color_mapping_param_list = c.list(color_mapping_param_list, object@anno_list[[i]]@legend_param)
}
}
return(color_mapping_param_list)
})
# == title
# Draw the Heatmap Annotations
#
# == param
# -object A `HeatmapAnnotation-class` object.
# -index A vector of indices.
# -k The current slice index for the annotation if it is split.
# -n Total number of slices.
# -... Pass to `grid::viewport` which contains all the annotations.
# -test Is it in test mode? The value can be logical or a text which is plotted as the title of plot.
# -anno_mark_param It contains specific parameters for drawing `anno_mark` and pass to the
# `draw,SingleAnnotation-method`.
#
# == value
# No value is returned.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
setMethod(f = "draw",
signature = "HeatmapAnnotation",
definition = function(object, index, k = 1, n = 1, ...,
test = FALSE, anno_mark_param = list()) {
which = object@which
n_anno = length(object@anno_list)
anno_size = object@anno_size
gap = object@gap
vp_param = list(...)
if(is.character(test)) {
test2 = TRUE
} else {
test2 = test
test = ""
}
if(test2) {
grid.newpage()
if(which == "column") pushViewport(viewport(width = unit(1, "npc") - unit(3, "cm") - sum(object@extended[c(2,4)]), height = object@height))
if(which == "row") pushViewport(viewport(height = unit(1, "npc") - unit(3, "cm") - sum(object@extended[c(1,3)]), width = object@width))
} else {
pushViewport(do.call(viewport, vp_param))
}
if(missing(index)) {
n_anno = length(object@anno_list)
len = sapply(seq_len(n_anno), function(i) {
if(inherits(object@anno_list[[i]]@fun, "AnnotationFunction")) {
object@anno_list[[i]]@fun@n
} else {
NA
}
})
len = len[!is.na(len)]
if(length(len)) {
index = seq_len(len[1])
}
if(!length(index)) {
stop_wrap("Cannot infer the number of observations of the annotation.")
}
}
if(which == "column") {
# start from the last annoation which is put on bottom
for(i in seq_len(n_anno)) {
pushViewport(viewport(y = sum(anno_size[seq(i, n_anno)]) + sum(gap[seq(i, n_anno)]) - gap[n_anno],
height = anno_size[i], just = c("center", "top")))
draw(object@anno_list[[i]], index, k, n, anno_mark_param = anno_mark_param)
# oe = try(draw(object@anno_list[[i]], index, k, n))
# if(inherits(oe, "try-error")) {
# cat("Error when drawing annotation '", object@anno_list[[i]]@name, "'\n", sep = "")
# stop_wrap(oe)
# }
upViewport()
}
} else if(which == "row") {
for(i in seq_len(n_anno)) {
pushViewport(viewport(x = sum(anno_size[seq_len(i)]) + sum(gap[seq_len(i)]) - gap[i], width = anno_size[i], just = c("right", "center")))
draw(object@anno_list[[i]], index, k, n, anno_mark_param = anno_mark_param)
# oe = try(draw(object@anno_list[[i]], index, k, n))
# if(inherits(oe, "try-error")) {
# cat("Error when drawing annotation '", object@anno_list[[i]]@name, "'\n", sep = "")
# stop_wrap(oe)
# }
upViewport()
}
}
if(test2) {
grid.text(test, y = unit(1, "npc") + unit(2, "mm"), just = "bottom")
# grid.rect(unit(0, "npc") - object@extended[2], unit(0, "npc") - object@extended[1],
# width = unit(1, "npc") + object@extended[2] + object@extended[4],
# height = unit(1, "npc") + object@extended[1] + object@extended[3],
# just = c("left", "bottom"), gp = gpar(fill = "transparent", col = "red", lty = 2))
}
upViewport()
})
# == title
# Print the HeatmapAnnotation object
#
# == param
# -object A `HeatmapAnnotation-class` object.
#
# == value
# No value is returned.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
setMethod(f = "show",
signature = "HeatmapAnnotation",
definition = function(object) {
dev.null()
on.exit(dev.off2())
n = length(object@anno_list)
if(n == 1) {
cat("A HeatmapAnnotation object with 1 annotation\n")
} else {
cat("A HeatmapAnnotation object with", length(object@anno_list), "annotations\n")
}
cat(" name:", object@name, "\n")
cat(" position:", object@which, "\n")
n_anno = length(object@anno_list)
len = sapply(seq_len(n_anno), function(i) {
if(inherits(object@anno_list[[i]]@fun, "AnnotationFunction")) {
object@anno_list[[i]]@fun@n
} else {
NA
}
})
len = len[!is.na(len)]
len = len[len > 0]
cat(" items:", ifelse(length(len), len[1], "unknown"), "\n")
cat(" width:", as.character(object@width), "\n")
cat(" height:", as.character(object@height), "\n")
cat(" this object is ", ifelse(object@subsettable, "", "not "), "subsettable\n", sep = "")
dirt = c("bottom", "left", "top", "right")
for(i in 1:4) {
if(!identical(unit(0, "mm"), object@extended[i])) {
cat(" ", as.character(object@extended[i]), "extension on the", dirt[i], "\n")
}
}
cat("\n")
lt = list()
lt$name = names(object@anno_list)
lt$annotation_type = sapply(seq_len(n_anno), function(i) {
if(!is.null(object@anno_list[[i]]@color_mapping)) {
if(object@anno_list[[i]]@is_anno_matrix) {
paste0(object@anno_list[[i]]@color_mapping@type, " matrix")
} else {
paste0(object@anno_list[[i]]@color_mapping@type, " vector")
}
} else if(inherits(object@anno_list[[i]]@fun, "AnnotationFunction")) {
if(object@anno_list[[i]]@fun@fun_name != "") {
paste0(object@anno_list[[i]]@fun@fun_name, "()")
} else {
"AnnotationFunction"
}
} else if(inherits(object@anno_list[[i]]@fun, "function")) {
"function"
} else {
""
}
})
lt$color_mapping = sapply(seq_len(n_anno), function(i) {
ifelse(object@anno_list[[i]]@color_is_random, "random",
ifelse(is.null(object@anno_list[[i]]@color_mapping), "", "user-defined"))
})
size_name = ifelse(object@which == "column", "height", "width")
lt[[size_name]] = sapply(seq_len(n_anno), function(i) {
if(size_name == "height") {
u = object@anno_list[[i]]@height
if(is_abs_unit(u)) {
as.character(convertHeight(u, "mm"))
} else {
as.character(u)
}
} else if(size_name == "width") {
u = object@anno_list[[i]]@width
if(is_abs_unit(u)) {
as.character(convertWidth(u, "mm"))
} else {
as.character(u)
}
}
})
df = as.data.frame(lt)
print(df, row.names = FALSE)
})
# == title
# Number of Observations
#
# == param
# -object The `HeatmapAnnotation-class` object.
# -... other arguments.
#
# == value
# If there is no ``nobs`` information for any of its `SingleAnnotation-class` object,
# it returns ``NA``.
#
nobs.HeatmapAnnotation = function(object, ...) {
n_anno = length(object@anno_list)
len = sapply(seq_len(n_anno), function(i) {
if(inherits(object@anno_list[[i]]@fun, "AnnotationFunction")) {
nobs(object@anno_list[[i]]@fun)
} else {
NA
}
})
len = len[!is.na(len)]
len = len[len > 0]
if(length(len)) {
return(len[1])
} else {
NA
}
}
# == title
# Add Annotations or Heatmaps as a Heatmap List
#
# == param
# -object A `HeatmapAnnotation-class` object.
# -x A `Heatmap-class` object, a `HeatmapAnnotation-class` object or a `HeatmapList-class` object.
# -direction Whether it is horizontal list or a vertical list?
#
# == details
# Normally we directly use ``+`` for horizontal concatenation and `\%v\%` for vertical concatenation.
#
# == value
# A `HeatmapList-class` object.
#
# == author
# Zuguang Gu <z.gu@dkfz.de>
#
setMethod(f = "add_heatmap",
signature = "HeatmapAnnotation",
definition = function(object, x, direction = c("horizontal", "vertical")) {
direction = match.arg(direction)[1]
ht_list = new("HeatmapList")
ht_list@direction = direction
ht_list = add_heatmap(ht_list, object, direction = direction)
ht_list = add_heatmap(ht_list, x, direction = direction)
return(ht_list)
})
# == title
# Concatenate Heatmap Annotations
#
# == param
# -... `HeatmapAnnotation-class` objects.
# -gap Gap between the groups of annotations.
#
# == details
# The heatmap annotations should have same number of observations.
#
# == example
# ha1 = HeatmapAnnotation(foo = 1:10)
# ha2 = HeatmapAnnotation(bar = anno_points(10:1))
# ha = c(ha1, ha2)
# ha
# ha3 = HeatmapAnnotation(sth = cbind(1:10, 10:1))
# ha = c(ha1, ha2, ha3, gap = unit(c(1, 4), "mm"))
# ha
c.HeatmapAnnotation = function(..., gap = unit(1, "points")) {
anno_list = list(...)
if(length(anno_list) == 1) {
return(anno_list[[1]])
}
# remove NULL
anno_list = anno_list[ !sapply(anno_list, is.null) ]
if(length(anno_list) == 1) {
return(anno_list[[1]])
}
n = length(anno_list)
if(length(unique(sapply(anno_list, function(x) x@which))) != 1) {
stop_wrap("All annotations should be all row annotation or all column annotation.")
}
if(length(gap) == 1) gap = rep(gap, n)
if(length(gap) == n - 1) gap = unit.c(gap, unit(0, "mm"))
x = anno_list[[1]]
if(n > 1) {
x@gap[length(x@gap)] = gap[1]
}
for(i in seq_along(anno_list)[-1]) {
y = anno_list[[i]]
y@gap[length(y@gap)] = gap[i]
x@anno_list = c(x@anno_list, y@anno_list)
x@anno_size = unit.c(x@anno_size, y@anno_size)
x@gap = unit.c(x@gap, y@gap)
}
x@gap[length(x@gap)] = unit(0, "mm")
if(x@which == "column") {
x@height = convertHeight(sum(x@anno_size) + sum(x@gap) - x@gap[length(x@gap)], "mm")
} else {
x@width = convertWidth(sum(x@anno_size) + sum(x@gap) - x@gap[length(x@gap)], "mm")
}
nm = names(x)
ld = duplicated(nm)
if(any(ld)) {
dup = unique(nm[ld])
warning_wrap(paste0("Following annotation names are duplicated:\n ", paste(dup, collapse = ", ")))
nm2 = nm
nm2[unlist(split(seq_along(nm), nm))] = unlist(lapply(split(nm, nm), seq_along))
l = nm %in% dup
nm[l] = paste0(nm[l], "_", nm2[l])
names(x) = nm
}
extended = unit(c(0, 0, 0, 0), "mm")
for(i in 1:4) {
extended[i] = unit(max(sapply(x@anno_list, function(anno) {
unit_to_numeric(anno@extended[i])
})), "mm")
}
x@extended = extended
return(x)
}
# == title
# Annotation Names
#
# == param
# -x A `HeatmapAnnotation-class` object.
#