forked from jokergoo/ComplexHeatmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.R
executable file
·1144 lines (1027 loc) · 32.6 KB
/
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
# environment that contains global variables
INDEX_ENV = new.env()
INDEX_ENV$I_FIGURE = 0
INDEX_ENV$I_HEATMAP = 0
INDEX_ENV$I_ONCOPRINT = 0
INDEX_ENV$I_ANNOTATION = 0
INDEX_ENV$I_ROW_ANNOTATION = 0
INDEX_ENV$I_COLOR_MAPPING = 0
get_figure_index = function() {
INDEX_ENV$I_FIGURE
}
increase_figure_index = function() {
INDEX_ENV$I_FIGURE = INDEX_ENV$I_FIGURE + 1
}
get_heatmap_index = function() {
INDEX_ENV$I_HEATMAP
}
increase_heatmap_index = function() {
INDEX_ENV$I_HEATMAP = INDEX_ENV$I_HEATMAP + 1
}
get_oncoprint_index = function() {
INDEX_ENV$I_ONCOPRINT
}
increase_oncoprint_index = function() {
INDEX_ENV$I_ONCOPRINT = INDEX_ENV$I_ONCOPRINT + 1
}
get_annotation_index = function() {
INDEX_ENV$I_ANNOTATION
}
increase_annotation_index = function() {
INDEX_ENV$I_ANNOTATION = INDEX_ENV$I_ANNOTATION + 1
}
get_row_annotation_index = function() {
INDEX_ENV$I_ROW_ANNOTATION
}
increase_row_annotation_index = function() {
INDEX_ENV$I_ROW_ANNOTATION = INDEX_ENV$I_ROW_ANNOTATION + 1
}
get_color_mapping_index = function() {
INDEX_ENV$I_COLOR_MAPPING
}
increase_color_mapping_index = function() {
INDEX_ENV$I_COLOR_MAPPING = INDEX_ENV$I_COLOR_MAPPING + 1
}
# default colors for matrix or annotations
# this function should be improved later
default_col = function(x, main_matrix = FALSE) {
if(is.factor(x)) {
x = as.vector(x)
}
if(length(unique(as.vector(x))) == 1) {
x = as.character(x)
}
attributes(x) = NULL
x = x[!is.na(x)]
if(is.character(x)) { # discrete
levels = unique(x)
#colors = hsv(runif(length(levels)), 1-runif(1)/2, 1-runif(1)/2)
colors = rand_color(length(levels), luminosity = sample(c("bright", "light", "dark", "random"), 1))
names(colors) = levels
return(colors)
} else if(is.numeric(x)) {
if(main_matrix) {
p = sum(x > 0)/sum(x != 0)
if(p > 0.25 & p < 0.75) {
if(ht_opt$verbose) {
cat("This matrix has both negative and positive values, use a color mapping symmetric to zero\n")
}
if(length(unique(x)) >= 100) {
q1 = quantile(abs(x), 0.99, na.rm = TRUE)
col_fun = colorRamp2(seq(-q1, q1, length.out = length(ht_opt$COLOR)), ht_opt$COLOR)
if(any(x > q1*3 | x < -q1*3)) {
message_wrap("The automatically generated colors map from the minus and plus 99^th of the absolute values in the matrix. There are outliers in the matrix whose patterns might be hidden by this color mapping. You can manually set the color to `col` argument.\n\nUse `suppressMessages()` to turn off this message.")
}
} else {
q1 = max(abs(x))
col_fun = colorRamp2(seq(-q1, q1, length.out = length(ht_opt$COLOR)), ht_opt$COLOR)
}
} else {
if(length(unique(x)) >= 100) {
q1 = quantile(x, 0.01, na.rm = TRUE)
q2 = quantile(x, 0.99, na.rm = TRUE)
if(q1 == q2) {
col_fun = colorRamp2(seq(min(x), max(x), length.out = length(ht_opt$COLOR)), ht_opt$COLOR)
} else if(length(unique(x[x > q1 & x < q2])) == 1) {
col_fun = colorRamp2(seq(min(x), max(x), length.out = length(ht_opt$COLOR)), ht_opt$COLOR)
} else {
col_fun = colorRamp2(seq(q1, q2, length.out = length(ht_opt$COLOR)), ht_opt$COLOR)
if(any(x > q2 + (q2-q1) | x < q1 - (q2-q1))) {
message_wrap("The automatically generated colors map from the 1^st and 99^th of the values in the matrix. There are outliers in the matrix whose patterns might be hidden by this color mapping. You can manually set the color to `col` argument.\n\nUse `suppressMessages()` to turn off this message.")
}
}
} else {
col_fun = colorRamp2(seq(min(x), max(x), length.out = length(ht_opt$COLOR)), ht_opt$COLOR)
}
}
} else {
#col_fun = colorRamp2(range(min(x), max(x)), c("white", hsv(runif(1), 1, 1)))
rc = rand_color(1, luminosity = sample(c("bright", "dark"), 1))
col_fun = colorRamp2(range(min(x), max(x)), c("white", rc))
}
return(col_fun)
}
}
# == title
# Calculate Pairwise Distance from a Matrix
#
# == param
# -x A matrix or a list. If it is a matrix, the distance is calculated by rows.
# -pairwise_fun A function which calculates distance between two vectors.
# -... Pass to `stats::as.dist`.
#
# == detail
# You can construct any type of distance measurements by defining a pair-wise distance function.
# The function is implemented by two nested ``for`` loops, so the efficiency may not be so good.
#
# == value
# A `stats::dist` object.
#
# == author
# Zuguang Gu <[email protected]>
#
# == example
# lt = lapply(1:10, function(i) {
# sample(letters, sample(6:10, 1))
# })
# dist2(lt, function(x, y) {
# length(intersect(x, y))/length(union(x, y))
# })
dist2 = function(x, pairwise_fun = function(x, y) sqrt(sum((x - y)^2)), ...) {
if(is.matrix(x)) {
if(nrow(x) < 2) {
stop_wrap("`x` should have at least two rows.")
}
nr = nrow(x)
mat2 = matrix(NA, nrow = nr, ncol = nr)
rownames(mat2) = colnames(mat2) = rownames(x)
for(i in 2:nr) {
for(j in 1:(nr-1)) {
mat2[i, j] = pairwise_fun(x[i, ], x[j, ])
}
}
as.dist(mat2, ...)
} else if(is.list(x)) {
if(length(x) < 2) {
stop_wrap("`x` should have at least length of 2.")
}
nr = length(x)
mat2 = matrix(NA, nrow = nr, ncol = nr)
rownames(mat2) = colnames(mat2) = names(x)
for(i in 2:nr) {
for(j in 1:(nr-1)) {
mat2[i, j] = pairwise_fun(x[[i]], x[[j]])
}
}
as.dist(mat2, ...)
} else {
stop_wrap("`x` can be a matrix or a list.")
}
}
get_dist = function(matrix, method) {
if(is.function(method)) {
nargs = length(as.list(args(method)))
if(nargs == 2) { # a distance function
dst = method(matrix)
} else if(nargs == 3) {
dst = dist2(matrix, method)
} else {
stop_wrap("Since your distance method is a function, it can only accept one or two arguments.")
}
} else if(inherits(method, "dist")) {
return(method)
} else if(method %in% c("euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski")) {
# if(any(is.na(matrix))) {
# dst = get_dist(matrix, function(x, y) {
# l = is.na(x) | is.na(y)
# x = x[!l]
# y = y[!l]
# as.vector(dist(rbind(x, y), method = method))
# })
# warning("NA exists in the matrix, calculating distance by removing NA values.")
# } else {
dst = dist(matrix, method = method)
# }
} else if(method %in% c("pearson", "spearman", "kendall")) {
if(any(is.na(matrix))) {
dst = get_dist(matrix, function(x, y) {
l = is.na(x) | is.na(y)
x = x[!l]
y = y[!l]
1 - cor(x, y, method = method)
})
warning_wrap("NA exists in the matrix, calculating distance by removing NA values.")
} else {
dst = switch(method,
pearson = as.dist(1 - cor(t(matrix), method = "pearson")),
spearman = as.dist(1 - cor(t(matrix), method = "spearman")),
kendall = as.dist(1 - cor(t(matrix), method = "kendall")))
}
} else {
stop_wrap(qq("method @{method} not supported"))
}
return(dst)
}
get_dend_order = function(x) {
switch(class(x),
hclust = x$order,
dendrogram = order.dendrogram(x))
}
recycle_gp = function(gp, n = 1) {
for(i in seq_along(gp)) {
x = gp[[i]]
if(n > 0) {
gp[[i]] = c(rep(x, floor(n/length(x))), x[seq_len(n %% length(x))])
} else {
gp[[i]] = x[1]
}
}
return(gp)
}
check_gp = function(gp) {
if(!"lineheight" %in% names(gp)) {
gp$lineheight = 0.9
}
if(!inherits(gp, "gpar")) {
stop_wrap("Graphic parameters should be specified by `gpar()`.")
}
return(gp)
}
# == title
# Subset a gpar Object
#
# == param
# -gp A `gpar` object.
# -i A vector of indices.
#
# == value
# A `grid::gpar` object.
#
# == example
# gp = gpar(col = 1:10, fill = 1)
# subset_gp(gp, 1:5)
subset_gp = function(gp, i) {
gp = lapply(gp, function(x) {
if(length(x) == 1) x
else x[i]
})
class(gp) = "gpar"
return(gp)
}
get_text_just = function(rot, side) {
rot = rot %% 360
if(! rot %in% c(0, 90, 270)) {
stop_wrap("Only support horizontal or vertical rotations for text.\n")
}
if(side == "left") {
if(rot == 0) {
return(c(1, 0.5))
} else if(rot == 90) {
return(c(0.5, 0))
} else if(rot == 270) {
return(c(0.5, 1))
}
} else if(side == "right") {
if(rot == 0) {
return(c(0, 0.5))
} else if(rot == 90) {
return(c(0.5, 1))
} else if(rot == 270) {
return(c(0.5, 0))
}
} else if(side == "top") {
if(rot == 0) {
return(c(0.5, 0))
} else if(rot == 90) {
return(c(0, 0.5))
} else if(rot == 270) {
return(c(1, 0.5))
}
} else if(side == "bottom") {
if(rot == 0) {
return(c(0.5, 1))
} else if(rot == 90) {
return(c(1, 0.5))
} else if(rot == 270) {
return(c(0, 0.5))
}
}
}
c.list = function(lt, ..., list = NULL) {
if(length(lt) == 0) lt = list()
if(is.null(list)) {
lt_add = list(...)
n = length(lt)
for(i in seq_along(lt_add)) {
lt[[n+i]] = lt_add[[i]]
}
} else {
lt = c(lt, list)
}
return(lt)
}
rep.list = function(x, n) {
lt = vector("list", n)
for(i in seq_len(n)) {
lt[i] = list(x)
}
return(lt)
}
# == title
# List All Heatmap Components
#
# == param
# -pattern A regular expression.
#
# == value
# A vector of viewport names.
#
list_components = function(pattern = NULL) {
vp = grid.ls(viewports = TRUE, grobs = FALSE, flatten = FALSE, print = FALSE)
vp = unlist(vp)
attributes(vp) = NULL
vp = vp[!grepl("^\\d+$", vp)]
vp = vp[!grepl("GRID.VP", vp)]
# unique(vp)
if(!is.null(pattern)) {
vp = grep(pattern, vp, value = TRUE)
}
vp
}
# == title
# Maximum Width of Text
#
# == param
# -text A vector of text.
# -gp Graphic parameters for text.
# -rot Rotation of the text, scalar.
#
# == details
# It simply calculates maximum width of a list of `grid::textGrob` objects.
#
# Note it ignores the text rotation.
#
# == value
# A `grid::unit` object which is in "mm".
#
# == author
# Zuguang Gu <[email protected]>
#
# == seealso
# `max_text_height` calculates the maximum height of a text vector.
#
# == example
# x = c("a", "bb", "ccc")
# max_text_width(x, gp = gpar(fontsize = 10))
#
max_text_width = function(text, gp = gpar(), rot = 0) {
if(is.null(text)) {
return(unit(0, "mm"))
}
n = length(text)
gp = recycle_gp(gp, n)
u = max(do.call("unit.c", lapply(seq_len(n), function(i) grobWidth(textGrob(text[i], gp = subset_gp(gp, i), rot = rot)))))
convertWidth(u, "mm")
}
# == title
# Maximum Height of Text
#
# == param
# -text A vector of text.
# -gp Graphic parameters for text.
# -rot Rotation of the text, scalar.
#
# == details
# It simply calculates maximum height of a list of `grid::textGrob` objects.
#
# Note it ignores the text rotation.
#
# == value
# A `grid::unit` object.
#
# == author
# Zuguang Gu <[email protected]>
#
# == seealso
# `max_text_width` calculates the maximum width of a text vector.
#
# == example
# x = c("a", "b\nb", "c\nc\nc")
# max_text_height(x, gp = gpar(fontsize = 10))
#
max_text_height = function(text, gp = gpar(), rot = 0) {
if(is.null(text)) {
return(unit(0, "mm"))
}
n = length(text)
gp = recycle_gp(gp, n)
u = max(do.call("unit.c", lapply(seq_len(n), function(i) grobHeight(textGrob(text[i], gp = subset_gp(gp, i), rot = rot)))))
convertHeight(u, "mm")
}
text_width = function(text, gp = gpar()) {
if(is.null(text)) {
return(unit(0, "mm"))
}
n = length(text)
gp = recycle_gp(gp, n)
u = do.call("unit.c", lapply(seq_len(n), function(i) grobWidth(textGrob(text[i], gp = subset_gp(gp, i)))))
convertWidth(u, "mm")
}
text_height = function(text, gp = gpar()) {
if(is.null(text)) {
return(unit(0, "mm"))
}
n = length(text)
gp = recycle_gp(gp, n)
u = do.call("unit.c", lapply(seq_len(n), function(i) grobHeight(textGrob(text[i], gp = subset_gp(gp, i)))))
convertHeight(u, "mm")
}
dev.null = function(...) {
pdf(file = NULL, ...)
}
stop_wrap = function (...) {
x = paste0(...)
x = paste(strwrap(x), collapse = "\n")
stop(x, call. = FALSE)
}
warning_wrap = function (...) {
x = paste0(...)
x = paste(strwrap(x), collapse = "\n")
warning(x, call. = FALSE)
}
message_wrap = function (...) {
x = paste0(...)
x = paste(strwrap(x), collapse = "\n")
message(x)
}
generate_param_list_fun = function(default) {
if(!is.list(default)) {
stop_wrap("`default` needs to be a list.")
}
lt = default
function(..., list = NULL) {
if(missing(list)) {
lt2 = list(...)
} else {
lt2 = list
}
for(nm in intersect(names(lt), names(lt2))) {
lt[[nm]] = lt2[[nm]]
}
return(lt)
}
}
add_vp_name = function(vpname) {
grid.text(vpname, 0, 1, just = c("left", "top"), gp = gpar(fontsize = 6, col = "red"))
}
upViewport = function(...) {
if(ht_global_opt$show_vp) {
grid.rect(gp = gpar(fill = "transparent", col = "black", lty = 3))
vpname = current.viewport()$name
if(!grepl("^GRID.VP", vpname)) {
add_vp_name(vpname)
}
}
grid::upViewport(...)
}
popViewport = function(...) {
if(ht_global_opt$show_vp) {
grid.rect(gp = gpar(fill = "transparent", col = "black", lty = 3))
vpname = current.viewport()$name
if(!grepl("^GRID.VP", vpname)) {
add_vp_name(vpname)
}
}
grid::popViewport(...)
}
dev.off2 = function () {
i1 = dev.prev()
i2 = dev.cur()
if (i1 == 2) {
dev.set(i1)
} else if(i1 > 2) {
i11 = dev.prev(i1)
if(names(i11) == "RStudioGD") {
dev.set(i11)
} else {
dev.set(i1)
}
}
dev.off(i2)
}
unit.c = function(...) {
lt = list(...)
lt = lt[!sapply(lt, is.null)]
do.call(grid::unit.c, lt)
}
">.unit" = function(x, y) {
if(!unit_in_mm(x)) {
stop_wrap("x should be in mm unit")
}
if(!unit_in_mm(y)) {
stop_wrap("y should be in mm unit")
}
as.numeric(x) > as.numeric(y)
}
"<.unit" = function(x, y) {
if(!unit_in_mm(x)) {
stop_wrap("x should be in mm unit")
}
if(!unit_in_mm(y)) {
stop_wrap("y should be in mm unit")
}
as.numeric(x) < as.numeric(y)
}
unit_in_mm = function(x) {
identical(unitType(x), "mm")
}
unit_to_numeric = function(x) {
as.numeric(x)
}
normalize_graphic_param_to_mat = function(x, nc, nr, name) {
if(is.matrix(x)) {
if(nrow(x) == nr && ncol(x) == nc) {
return(x)
} else {
stop_wrap(paste0(name, "needs to be a matrix with ", nc, " columns and ", nr, " rows."))
}
} else {
if(length(x) == nc) {
return(matrix(rep(x, each = nr), ncol = nc))
} else if(length(x) == nr) {
return(matrix(rep(x, times = nc), ncol = nc))
} else if(length(x) == 1) {
return(matrix(x, ncol = nc, nrow = nr))
} else {
stop_wrap(paste0("Since ", name, " is a vector, it should have length of ", nc, " or ", nr, "."))
}
}
}
recycle_param = function(x, all_names, default, as.list = FALSE) {
n = length(all_names)
if(length(x) == 0) {
if(as.list) {
rep(list(default), n)
} else {
rep(default, n)
}
} else if(length(x) == n) {
if(as.list) {
x = lapply(1:n, function(i) x[i])
}
return(x)
} else {
nm = names(x)
if(length(intersect(nm, all_names)) == 0) {
nm = NULL
}
if(is.null(nm)) {
if(length(x) == 1) {
if(as.list) {
x = rep(list(x), n)
} else {
x = rep(x, n)
}
} else {
if(length(x) > n) {
x = x[1:n]
if(as.list) {
x = lapply(1:n, function(i) x[i])
}
} else {
if(as.list) {
x = c(lapply(seq_along(x), function(i) x[i],
rep(list(default), n - length(x))))
} else {
x = c(x, rep(default, n - length(x)))
}
}
}
} else {
if(as.list) {
x2 = rep(list(default), n)
names(x2) = all_names
for(cn in intersect(nm, all_names)) {
x2[[cn]] = x[cn]
}
x = x2
} else {
x2 = structure(rep(default, n), names = all_names)
x2[intersect(nm, all_names)] = x[intersect(nm, all_names)]
x = x2
}
}
return(x)
}
}
# recycle_list(list(a = 1), "a")
# recycle_list(1, c("a", "b"))
# recycle_list(list(a = 1), c("a", "b"), 0)
recycle_list = function(x, all_names, default = NULL) {
n = length(all_names)
if(is.null(x)) {
lt = rep(list(default), n)
names(lt) = all_names
return(lt)
}
if(length(x) == 1 && !is.list(x) && n == 1) {
lt = list(x)
names(lt) = all_names
return(lt)
}
if(length(x) == 1 && !is.list(x)) {
lt = rep(list(x), n)
names(lt) = all_names
return(lt)
}
if(is.list(x)) {
lt = rep(list(default), n)
names(lt) = all_names
for(nm in names(x)) {
lt[[nm]] = x[[nm]]
}
return(lt)
}
if(length(x) == n) {
lt = lapply(x, function(y) y)
names(lt) = all_names
return(lt)
}
stop_wrap("Not compatible with the annotations.")
}
# == title
# Convert XY in a Parent Viewport
#
# == param
# -u A list of two units which correspond to x and y.
# -vp_name The name of the parent viewport.
#
# == details
# It converts a coordinate measured in current viewport to the coordinate in a parent viewport.
#
# In the conversion, all units are recalculated as absolute units, so if you change the size
# of the interactive graphic window, you need to rerun the function.
#
# == value
# A list of two units.
#
# == example
# grid.newpage()
# pushViewport(viewport(x = 0.5, y = 0.5, width = 0.5, height = 0.5, just = c("left", "bottom")))
# grid.rect()
# grid.points(x = unit(2, "cm"), y = unit(2, "cm"), pch = 1)
# u = list(x = unit(2, "cm"), y = unit(2, "cm"))
# u2 = getXY_in_parent_vp(u)
# popViewport()
# grid.rect(gp = gpar(col = "red"))
# grid.points(x = u2$x, u2$y, pch = 2)
getXY_in_parent_vp = function(u, vp_name = "ROOT") {
if(inherits(u, "unit")) {
if(length(u) == 2) {
u = list(x = u[1], y = u[2])
} else {
stop_wrap("If `u` is a unit vector, it must have length of 2.")
}
}
if(length(u) != 2) {
stop_wrap("`u` should be a list of length of 2 (two elements: `x` and `y`).")
}
if(is.null(names(u))) {
names(u) = c("x", "y")
}
vp = current.viewport()
current_vp_name = vp$name
original_vp_name = current_vp_name
on.exit(seekViewport(original_vp_name))
if(current_vp_name == "ROOT") {
return(u)
}
while(current_vp_name != vp_name) {
if(current_vp_name == "ROOT") {
stop_wrap(qq("Cannot find a parent viewport with name \"@{vp_name}\"."))
}
u$x = convertX(u$x, "mm")
u$y = convertX(u$y, "mm")
# vp is measured in parent vp
current_vp_x = vp$x - vp$width*vp$valid.just[1]
current_vp_y = vp$y - vp$height*vp$valid.just[2]
upViewport(1)
offset_x = convertX(current_vp_x, "mm")
offset_y = convertY(current_vp_y, "mm")
u$x = u$x + offset_x
u$y = u$y + offset_y
vp = current.viewport()
current_vp_name = vp$name
}
return(u)
}
# == title
# Get Values in a Matrix by Pair-wise Indices
#
# == param
# -m A matrix or a 3-dimension array.
# -i Row indices or the indices in the first dimension.
# -j Column indicies or the indices in the second dimension.
#
# == value
# If ``m`` is a matrix, the value returned is a vector ``c(m[i1, j1], m[i2, j2], ...)```.
#
# If ``m`` is an array, the value returned is a matrix ``rbind(m[i1, j1, ], m[i2, j2, ], ...)```.
#
# == example
# m = matrix(rnorm(100), 10)
# m2 = m[m > 0]
# ind = do.call("rbind", lapply(1:10, function(ci) {
# i = which(m[, ci] > 0)
# cbind(i = i, j = rep(ci, length(i)))
# }))
# pindex(m, ind[, 1], ind[, 2])
# identical(pindex(m, ind[, 1], ind[, 2]), m[m > 0])
#
# # 3d array
# arr = array(1:27, dim = c(3, 3, 3))
# pindex(arr, 1:2, 2:3)
# identical(pindex(arr, 1:2, 2:3),
# rbind(arr[1, 2, ], arr[2, 3, ]))
pindex = function(m, i, j) {
if(length(i) == 1) i = rep(i, length(j))
if(length(j) == 1) j = rep(j, length(i))
if(length(i) != length(j)) {
stop_wrap("Length of index i and j should be the same.")
}
nr = nrow(m)
nc = ncol(m)
ind = (j-1)*nr + i
dm = dim(m)
if(length(dm) == 2) {
v = as.vector(m)
v[ind]
} else if(length(dm) == 3) {
v = m
dim(v) = c(dm[1]*dm[2], dm[3])
v[ind, , drop = FALSE]
} else {
stop_wrap("dimension of `m` can only be 2 and 3.")
}
}
# == title
# Restore the index vector to index matrix in layer_fun
#
# == param
# -j Column indices directly from ``layer_fun``.
# -i Row indices directly from ``layer_fun``.
# -x Position on x-direction directly from ``layer_fun``.
# -y Position on y-direction directly from ``layer_fun``.
#
# == details
# The values that are sent to ``layer_fun`` are all vectors (for the vectorization
# of the grid graphic functions), however, the heatmap slice where
# ``layer_fun`` is applied to, is still represented by a matrix, thus, it would be
# very convinient if all the arguments in ``layer_fun`` can be converted to the
# sub-matrix for the current slice. Here, as shown in above example,
# `restore_matrix` does the job. `restore_matrix` directly accepts the first
# four argument in ``layer_fun`` and returns an index matrix, where rows and
# columns correspond to the rows and columns in the current slice, from top to
# bottom and from left to right. The values in the matrix are the natural order
# of e.g. vector ``j`` in current slice.
#
# For following code:
#
# Heatmap(small_mat, name = "mat", col = col_fun,
# row_km = 2, column_km = 2,
# layer_fun = function(j, i, x, y, w, h, fill) {
# ind_mat = restore_matrix(j, i, x, y)
# print(ind_mat)
# }
# )
#
# The first output which is for the top-left slice:
#
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 4 7 10 13
# [2,] 2 5 8 11 14
# [3,] 3 6 9 12 15
#
# As you see, this is a three-row and five-column index matrix where the first
# row corresponds to the top row in the slice. The values in the matrix
# correspond to the natural index (i.e. 1, 2, ...) in ``j``, ``i``, ``x``, ``y``,
# ... in ``layer_fun``. Now, if we want to add values on the second column in the
# top-left slice, the code which is put inside ``layer_fun`` would look like:
#
# for(ind in ind_mat[, 2]) {
# grid.text(small_mat[i[ind], j[ind]], x[ind], y[ind], ...)
# }
#
# == example
# set.seed(123)
# mat = matrix(rnorm(81), nr = 9)
# Heatmap(mat, row_km = 2, column_km = 2,
# layer_fun = function(j, i, x, y, width, height, fill) {
# ind_mat = restore_matrix(j, i, x, y)
# print(ind_mat)
# })
#
# set.seed(123)
# mat = matrix(round(rnorm(81), 2), nr = 9)
# Heatmap(mat, row_km = 2, column_km = 2,
# layer_fun = function(j, i, x, y, width, height, fill) {
# ind_mat = restore_matrix(j, i, x, y)
# ind = unique(c(ind_mat[2, ], ind_mat[, 3]))
# grid.text(pindex(mat, i[ind], j[ind]), x[ind], y[ind])
# })
restore_matrix = function(j, i, x, y) {
x = as.numeric(x)
y = as.numeric(y)
od = order(x, rev(y))
ind = seq_along(i)
j = j[od]
i = i[od]
x = x[od]
y = y[od]
ind = ind[od]
nr = length(unique(i))
nc = length(unique(j))
# I = matrix(i, nrow = nr, ncol = nc)
# J = matrix(j, nrow = nr, ncol = nc)
IND = matrix(ind, nrow = nr, ncol = nc)
return(IND)
}
unit_with_vp = function(..., vp = current.viewport()$name) {
u = unit(...)
attr(u, "viewport") = vp
return(u)
}
# == title
# Draw a Single Boxplot
#
# == param
# -value A vector of numeric values.
# -pos Position of the boxplot.
# -outline Whether draw outlines?
# -box_width width of the box.
# -pch Point type.
# -size Point size.
# -gp Graphic parameters.
# -direction Whether the box is vertical or horizontal.
#
# == details
# All the values are measured with ``native`` coordinate.
#
# == example
# lt = list(rnorm(100), rnorm(100))
# grid.newpage()
# pushViewport(viewport(xscale = c(0.5, 2.5), yscale = range(lt)))
# grid.boxplot(lt[[1]], pos = 1, gp = gpar(fill = "red"))
# grid.boxplot(lt[[2]], pos = 2, gp = gpar(fill = "green"))
# popViewport()
grid.boxplot = function(value, pos, outline = TRUE, box_width = 0.6,
pch = 1, size = unit(2, "mm"), gp = gpar(fill = "#CCCCCC"),
direction = c("vertical", "horizontal")) {
direction = match.arg(direction)[1]
boxplot_stats = boxplot(value, plot = FALSE)$stats
if(direction == "vertical") {
grid.rect(x = pos, y = boxplot_stats[2, 1],
height = boxplot_stats[4, 1] - boxplot_stats[2, 1], width = 1*box_width, just = "bottom",
default.units = "native", gp = gp)
grid.segments(pos - 0.5*box_width, boxplot_stats[5, 1],
pos + 0.5*box_width, boxplot_stats[5, 1],
default.units = "native", gp = gp)
grid.segments(pos, boxplot_stats[5, 1],
pos, boxplot_stats[4, 1],
default.units = "native", gp = gp)
grid.segments(pos, boxplot_stats[1, 1],
pos, boxplot_stats[2, 1],
default.units = "native", gp = gp)
grid.segments(pos - 0.5*box_width, boxplot_stats[1, 1],
pos + 0.5*box_width, boxplot_stats[1, 1],
default.units = "native", gp = gp)
grid.segments(pos - 0.5*box_width, boxplot_stats[3, 1],
pos + 0.5*box_width, boxplot_stats[3, 1],
default.units = "native", gp = gp)
if(outline) {
l1 = value > boxplot_stats[5, 1]
if(sum(l1)) grid.points(x = rep(pos, sum(l1)), y = value[l1],
default.units = "native", gp = gp, pch = pch, size = size)
l2 = value < boxplot_stats[1, 1]
if(sum(l2)) grid.points(x = rep(pos, sum(l2)), y = value[l2],
default.units = "native", gp = gp, pch = pch, size = size)
}
} else {
grid.rect(y = pos, x = boxplot_stats[2, 1],
width = boxplot_stats[4, 1] - boxplot_stats[2, 1], height = 1*box_width, just = "left",
default.units = "native", gp = gp)
grid.segments(boxplot_stats[5, 1], pos - 0.5*box_width,
boxplot_stats[5, 1], pos + 0.5*box_width,
default.units = "native", gp = gp)
grid.segments(boxplot_stats[5, 1], pos,
boxplot_stats[4, 1], pos,
default.units = "native", gp = gp)
grid.segments(boxplot_stats[1, 1], pos,
boxplot_stats[2, 1], pos,
default.units = "native", gp = gp)
grid.segments(boxplot_stats[1, 1], pos - 0.5*box_width,
boxplot_stats[1, 1], pos + 0.5*box_width,
default.units = "native", gp = gp)
grid.segments(boxplot_stats[3, 1], pos - 0.5*box_width,
boxplot_stats[3, 1], pos + 0.5*box_width,
default.units = "native", gp = gp)
if(outline) {