Debian Codegraph @

R/rotate.R

raw
1 # Copyright (C) Tal Galili
2 #
3 # This file is part of dendextend.
4 #
5 # dendextend is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # dendextend is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # A copy of the GNU General Public License is available at
16 # http://www.r-project.org/Licenses/
17 #
18
19
20
21 #' @title Rotate a tree object
22 #' @export
23 #' @rdname rotate
24 #' @description
25 #' Rotates, rev and sort the branches of a tree object (dendrogram, hclust)
26 #' based on a vector - either of labels order (numbers) or the labels in their
27 #' new order (character).
28 #'
29 #' @param x a tree object (either a \code{dendrogram} or \code{hclust})
30 #' @param order Either numeric or character vector.
31 #' Is numeric: it is a numeric vector with the order of the value to be
32 #' assigned to object's label. The numbers say are just like when you use \link{order}:
33 #' which of the items on the tree-plot should be "first" (e.g: most left),
34 #' second etc. (this is relevant only to \code{rotate})
35 #' Is character: it must be a vector with the content of labels(x), in the
36 #' order we'd like to have the new tree.
37 #' @param decreasing logical. Should the sort be increasing or decreasing? Not available for partial sorting. (relevant only to \code{sort})
38 #' @param ... parameters passed (for example, in case of sort)
39 #' @param type a character indicating how to sort. If "labels" then by lexicographic
40 #' order of the labels. If "nodes", then by using \link{ladderize} (order so that
41 #' recursively, the leftmost branch will be the smallest)
42 #' @param phy a placeholder in case the user uses "phy ="
43 #' @details
44 #' The motivation for this function came from the function
45 #' \code{\link{order.dendrogram}} NOT being very intuitive.
46 #' What \code{rotate} aims to do is give a simple tree rotation function which
47 #' is based on the order which the user would like to see the tree rotated by
48 #' (just as \code{\link{order}} works for numeric vectors).
49 #'
50 #' \code{\link{rev.dendrogram}} is part of base R, and returns the tree object
51 #' after rotating it so that the order of the labels is reversed.
52 #' Here we added an S3 method for hclust objects.
53 #'
54 #' The \code{sort} methods sort the labels of the tree (using \code{order})
55 #' and then attempts to rotate the tree to fit that order.
56 #'
57 #' The hclust method of "\code{rotate}" works by first changing the object into
58 #' dendrogram, performing the rotation, and then changing it back to hclust.
59 #' Special care is taken in preserving some of the properties of the hclust
60 #' object.
61 #'
62 #' The ape package has its own \code{\link[ape]{rotate}} function (which is sadly not S3, so cannot be easily connected with the
63 #' current implementation). Still, there is an S3 plug that makes sure people
64 #' loading ape first and then dendextend will still be able to
65 #' use \code{rotate} without a problem.
66 #' Notice that if you first load ape and only then dendextend,
67 #' using "rotate" will fail with the error: "Error in rotate(dend, ____) :
68 #' object 'phy' is not of class 'phylo'" - this is because rotate in ape
69 #' is not S3 and will fail to find the rotate.dendrogram function.
70 #' In such a case, simply run \code{unloadNamespace(ape)}. Or, you can run:
71 #' \code{unloadNamespace("dendextend"); attachNamespace("dendextend")}
72 #' The solution for this is that if you have ape installed on your machine,
73 #' it will be loaded when you load dendextend (but after it).
74 #' This way, \code{rotate} will work fine for both dendrogram and phylo
75 #' objects.
76 #'
77 #' @return A rotated tree object
78 #' @seealso \code{\link{order.dendrogram}}, \code{\link{order}},
79 #' \code{\link{rev.dendrogram}}, \code{\link[ape]{rotate}}, \link{ladderize}
80 #' @examples
81 #' hc <- hclust(dist(USArrests[c(1, 6, 13, 20, 23), ]), "ave")
82 #' dend <- as.dendrogram(hc)
83 #'
84 #' # For dendrogram objects:
85 #' labels_colors(dend) <- rainbow(nleaves(dend))
86 #' # let's color the labels to make the followup of the rotation easier
87 #' par(mfrow = c(1, 2))
88 #' plot(dend, main = "Original tree")
89 #' plot(rotate(dend, c(2:5, 1)),
90 #' main =
91 #' "Rotates the left most leaf \n into the right side of the tree"
92 #' )
93 #' par(mfrow = c(1, 2))
94 #' plot(dend, main = "Original tree")
95 #' plot(sort(dend), main = "Sorts the labels by alphabetical order \n
96 #' and rotates the tree to give the best fit possible")
97 #' par(mfrow = c(1, 2))
98 #' plot(dend, main = "Original tree")
99 #' plot(rev(dend), main = "Reverses the order of the tree labels")
100 #'
101 #' # For hclust objects:
102 #' plot(hc)
103 #' plot(rotate(hc, c(2:5, 1)), main = "Rotates the left most leaf \n
104 #' into the right side of the tree")
105 #'
106 #' par(mfrow = c(1, 3))
107 #' dend %>% plot(main = "Original tree")
108 #' dend %>%
109 #' sort() %>%
110 #' plot(main = "labels sort")
111 #' dend %>%
112 #' sort(type = "nodes") %>%
113 #' plot(main = "nodes (ladderize) sort")
114 rotate <- function(x, ...) {
115 UseMethod("rotate")
116 }
117
118 ### TODO: maybe add k, h parameters.
119 # ' @param k numeric scalar, with the number of clusters
120 # ' the tree should be cut into. The tree is rotate based on the cluster groups.
121 # ' @param h numeric scalar, with a height where the tree
122 # ' should be cut. The tree is rotate based on the cluster groups.
123
124
125 #' @export
126 #' @rdname rotate
127 rotate.default <- function(x, order, ...) {
128 stop("object x must be a dendrogram/hclust/phylo object")
129 }
130
131 #' @export
132 #' @rdname rotate
133 rotate.dendrogram <- function(x, order, ...) {
134 if (missing(order)) { # if order is missing - return the same tree.
135 warning("'order' parameter is missing, returning the tree as it was.")
136 return(x)
137 }
138
139 labels_x <- labels(x)
140 order_x <- order.dendrogram(x)
141 number_of_leaves <- length(order_x)
142
143
144 if (!is.numeric(order)) {
145 order <- as.character(order)
146 if (length(intersect(order, labels_x)) != number_of_leaves) {
147 stop("'order' is neither numeric nor a vector with ALL of the labels (in the order you want them to be)")
148 }
149 # order has all the labels, now, let's match:
150 # match(c("c", "a", "b"), c("c","b", "a")) # order for making 2 into 1!
151 # c("c", "b", "a", "d")[match(c("c", "d", "b", "a"), c("c","b","a", "d"))] # WORKS
152 # c("c", "d", "b", "a")[match(c("c", "d", "b", "a"), c("c","b","a", "d"))] # FAIL
153 order <- match(order, labels_x)
154 }
155
156 weights <- seq_len(number_of_leaves)
157 weights_for_order <- numeric(number_of_leaves)
158 weights_for_order[order_x[order]] <- weights
159 reorder(x, weights_for_order, mean, ...)
160 }
161
162
163 #' @export
164 #' @rdname rotate
165 rotate.hclust <- function(x, order, ...) {
166 x_dend <- as.dendrogram(x)
167 x_dend_rotated <- rotate(x_dend, order, ...)
168 x_rotated <- as_hclust_fixed(x_dend_rotated, x)
169
170 return(x_rotated)
171 }
172
173
174 #' @export
175 #' @rdname rotate
176 rotate.phylo <- function(x, ..., phy) {
177 if (!missing(phy)) x <- phy
178 # library(ape)
179 ape::rotate(phy = x, ...)
180 }
181
182
183 #' @export
184 #' @rdname rotate
185 sort.dendrogram <- function(x, decreasing = FALSE, type = c("labels", "nodes"), ...) {
186 type <- match.arg(type)
187 switch(type,
188 "labels" = rotate(x, order(labels(x), decreasing = decreasing, ...)),
189 "nodes" = ladderize(x, right = decreasing, ...)
190 )
191 }
192
193 #' @export
194 #' @rdname rotate
195 sort.hclust <- function(x, decreasing = FALSE, ...) {
196 rotate(x, order(labels(x), decreasing = decreasing, ...))
197 }
198
199
200 #' @export
201 #' @rdname rotate
202 sort.dendlist <- function(x, ...) {
203 for (i in seq_len(length(x))) {
204 x[[i]] <- sort(x[[i]], ...)
205 }
206 x
207 }
208
209
210
211 # flip <- function(x, ...) {
212 # rev_order <- rev(seq_len(nleaves(x)))
213 # rotate(x, rev_order)
214 # }
215
216 #' @export
217 #' @rdname rotate
218 rev.hclust <- function(x, ...) {
219 rev_order <- rev(seq_len(nleaves(x)))
220 rotate(x, rev_order, ...)
221 }
222
223
224 # methods(rotate)
225 # methods(sort)
226 # help(flip)
227 # example(rotate)
228
229
230 ###### Some debugging of "rotate" with ape vs dendextend
231 # library(ape)
232 # library(dendextend)
233 # "package:ape" %in% search() # TRUE
234 # ### to write: package_in_search ???
235 # tre <- rtree(25)
236 # detach("package:ape")
237 # hc <- hclust(dist(USArrests[c(1,6,13,20, 23),]), "ave")
238 # rotate(hc)
239 # loadedNamespaces()
240 # unloadNamespace(ape)
241 # search()
242 # unloadNamespace("dendextend"); attachNamespace("dendextend")
243 # some thoughts: http://www.ats.ucla.edu/stat/r/faq/referencing_objects.htm
244
245
246
247
248 #
249 #
250 # rotate_group_right <- function(x, ...) {
251 # fac_x <- factor(x) # , levels=unique(x))
252 # levels_fac_x <- levels(fac_x)
253 # levels(fac_x) <- c(tail(levels_fac_x, -1), head(levels_fac_x, 1))
254 # return(fac2num(fac_x))
255 # }
256 #
257 #
258 # hc <- hclust(dist(USArrests[1:5,]), "ave")
259 # dend <- as.dendrogram(hc)
260 # x = cutree(dend, k = 3)
261 # rotate_group_right(rotate_group_right(x))
262 #
263
264 #
265
266
267
268
269
270
271
272 #' @title Interactively rotate a tree object
273 #' @export
274 #' @rdname click_rotate
275 #' @description
276 #' Lets te user click a plot of dendrogram
277 #' and rotates the tree based on the location of the click.
278 #'
279 #' @description
280 #' Code for mouse selection of (sub-)cluster to be rotated
281 #'
282 #' @param x a tree object (either a \code{dendrogram} or \code{hclust})
283 #' @param plot (logical) should the dendrogram first be plotted.
284 #' @param plot_after (logical) should the dendrogram be plotted after
285 #' the rotation?
286 #' @param horiz logical. Should the plot be normal or horizontal?
287 #' @param continue logical. If TRUE, allows the user to keep
288 #' clicking the plot until a click is made on the labels.
289 #' @param ... parameters passed to the plot
290 #'
291 #' @author Andrej-Nikolai Spiess, Tal Galili
292 #' @return A rotated tree object
293 #' @seealso \code{\link{rotate.dendrogram}}
294 #' @examples
295 #' # create the dend:
296 #' dend <- USArrests %>%
297 #' dist() %>%
298 #' hclust("ave") %>%
299 #' as.dendrogram() %>%
300 #' color_labels()
301 #' \dontrun{
302 #' # play with the rotation once
303 #' dend <- click_rotate(dend)
304 #' dend <- click_rotate(dend, horiz = TRUE)
305 #' # keep playing with the rotation:
306 #' while (TRUE) dend <- click_rotate(dend)
307 #' # the same as
308 #' dend <- click_rotate(dend, continue = TRUE)
309 #' }
310 #'
311 click_rotate <- function(x, ...) {
312 UseMethod("click_rotate")
313 }
314
315 #' @export
316 #' @rdname click_rotate
317 click_rotate.default <- function(x, ...) {
318 stop("object x must be a dendrogram/hclust/phylo object")
319 }
320
321 #' @export
322 #' @rdname click_rotate
323 click_rotate.dendrogram <- function(x, plot = TRUE, plot_after = plot, horiz = FALSE, continue = FALSE, ...) {
324 if (plot) plot(x, horiz = horiz, ...)
325
326 labels_x <- labels(x)
327 order_x <- order.dendrogram(x)
328 number_of_leaves <- length(order_x)
329
330 only_once <- !continue
331 continue <- TRUE
332
333 while (isTRUE(continue)) {
334 cat("Please click on top branch of cluster to be rotated...\n")
335 if (!only_once) cat("Clicking on the leaf labels will exit...\n\n")
336 LOC <- locator(1)
337 X <- ifelse(horiz, round(LOC$y), round(LOC$x))
338 Y <- ifelse(horiz, LOC$x, LOC$y)
339 CLUSTERS <- cutree(x, h = Y, order_clusters_as_data = FALSE)
340 order <- 1:length(CLUSTERS)
341 CLUSNUM <- CLUSTERS[X]
342 SEL <- which(CLUSTERS == CLUSNUM)
343 order[SEL] <- rev(order[SEL])
344
345 x <- rotate(x, order)
346 if (plot_after) plot(x, horiz = horiz, ...)
347
348 if (Y < 0 | only_once) continue <- FALSE
349 }
350
351 cat("Done rotating.\n")
352
353 return(x)
354 }
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375 #' @title Ladderize a Tree
376 #' @export
377 #' @rdname ladderize
378 #' @description
379 #' This function reorganizes the internal structure of the tree to get the ladderized effect when plotted.
380 #'
381 #' @param x a tree object (either a \link{dendrogram}, \link{dendlist}, or \link[ape]{phylo})
382 #' @param right a logical (TRUE) specifying whether the smallest clade is on the right-hand side (when the tree is plotted upwards), or the opposite (if FALSE).
383 #' @param which an integer (can have any number of elements).
384 #' It indicates the elements in the \link{dendlist} to ladderize.
385 #' If missing, it will ladderize all the dendrograms in the dendlist.
386 #' @param ... Currently ignored.
387 #' @param phy a placeholder in case the user uses "phy ="
388 #'
389 #' @return A rotated tree object
390 #' @seealso \code{\link[ape]{ladderize}}, \code{\link{rev.dendrogram}}, \code{\link[dendextend]{rotate}}, \code{\link[ape]{rotate}}
391 #' @examples
392 #'
393 #' dend <- USArrests[1:8, ] %>%
394 #' dist() %>%
395 #' hclust() %>%
396 #' as.dendrogram() %>%
397 #' set("labels_colors") %>%
398 #' set("branches_k_color", k = 5)
399 #' set.seed(123)
400 #' dend <- shuffle(dend)
401 #'
402 #' par(mfrow = c(1, 3))
403 #' dend %>% plot(main = "Original")
404 #' dend %>%
405 #' ladderize(TRUE) %>%
406 #' plot(main = "Right (default)")
407 #' dend %>%
408 #' ladderize(FALSE) %>%
409 #' plot(main = "Left (rev of right)")
410 ladderize <- function(x, right = TRUE, ...) {
411 UseMethod("ladderize")
412 }
413
414
415 #' @export
416 #' @rdname ladderize
417 ladderize.dendrogram <- function(x, right = TRUE, ...) {
418 if (!is.dendrogram(x)) stop("'object' should be a dendrogram.")
419
420 ladderize_node <- function(node) {
421 all_children_leaves <- all(sapply(x, is.leaf))
422 if (is.leaf(node) | all_children_leaves) {
423 return(unclass(node))
424 }
425 # else
426 attr_backup <- attributes(node)
427 new_order <- order(sapply(node, nleaves), decreasing = TRUE)
428 node <- node[new_order]
429 attributes(node) <- attr_backup # fix attributes
430
431 for (i in 1:length(node)) {
432 node[[i]] <- ladderize_node(node[[i]])
433 }
434
435 return(unclass(node))
436 }
437
438 new_x <- ladderize_node(x)
439 class(new_x) <- "dendrogram"
440 new_x <- suppressWarnings(stats_midcache.dendrogram(new_x)) # fixes the attributes
441
442 if (!right) new_x <- rev(new_x)
443
444 return(new_x)
445 }
446
447
448
449 #' @export
450 #' @rdname ladderize
451 ladderize.phylo <- function(x, right = TRUE, phy, ...) {
452 if (!missing(phy)) x <- phy
453 # library(ape)
454 ape::ladderize(phy = x, right = right)
455 }
456
457 #' @export
458 #' @rdname ladderize
459 ladderize.dendlist <- function(x, right = TRUE, which, ...) {
460 seq_trees <- seq_len(length(x))
461 if (missing(which)) which <- seq_trees
462
463 for (i in seq_trees) {
464 if (i %in% which) x[[i]] <- ladderize(x[[i]], right = right, ...)
465 }
466 x
467 }
468
469 # TODO: add tests to ladderize!
470 # TODO: this is probably a nice starting point for untangle (better than sort). Maybe play with it.