Debian Codegraph @

R/unbranch.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
22 #' @title get attributes from the dendrogram's root(!) branches
23 #' @description get attributes from the dendrogram's root(!) branches
24 #' @export
25 #' @param dend dendrogram object
26 #' @param the_attr the attribute to get from the branches (for example "height")
27 #' @param warn logical (default from dendextend_options("warn") is FALSE).
28 #' Set if warning are to be issued, it is safer to keep this at TRUE,
29 #' but for keeping the noise down, the default is FALSE.
30 #' Should a warning be printed when
31 #' the function is used on an object which is NOT a dendrogram.
32 #' @param ... passed on to attr
33 #' @return The attributes of the branches (often two) of the dendrogram's root
34 #' @seealso \link{attr}
35 #' @examples
36 #' hc <- hclust(dist(USArrests[2:9, ]), "com")
37 #' dend <- as.dendrogram(hc)
38 #'
39 #' get_root_branches_attr(dend, "height") # 0.00000 71.96247
40 #' # plot(dend)
41 #' str(dend, 2)
42 get_root_branches_attr <- function(dend, the_attr, warn = dendextend_options("warn"), ...) {
43 if (!is.dendrogram(dend)) {
44 if (warn) warning("dend wasn't of class dendrogram - be sure it makes sense...")
45 # I might make this S3 at some point, but I don't see a need for it...
46 # class(dend) <- "dendrogram"
47 # dend <- as.dendrogram(dend)
48 }
49 sapply(dend, function(x) {
50 attr(x, the_attr, ...)
51 })
52 }
53
54
55
56
57
58
59 #' @title Raise the height of a dendrogram tree
60 #' @description Raise the height of nodes in a dendrogram tree.
61 #' @export
62 #' @param dend dendrogram object
63 #' @param heiget_to_add how much height to add to all the branches (not leaves) in the dendrogram
64 #' @param ... passed on (not used)
65 #' @return A raised dendrogram
66 #' @examples
67 #' hc <- hclust(dist(USArrests[2:9, ]), "com")
68 #' dend <- as.dendrogram(hc)
69 #'
70 #' par(mfrow = c(1, 2))
71 #' plot(dend, main = "original tree")
72 #' plot(raise.dendrogram(dend, 100), main = "Raised tree")
73 raise.dendrogram <- function(dend, heiget_to_add, ...) {
74 # Only if you are not a leaf - then do things
75 if (!is.leaf(dend)) {
76 # first - move through all the branches and implement this function on them (they will return higher...
77 num_of_branches <- length(dend)
78 for (i in seq_len(num_of_branches))
79 {
80 dend[[i]] <- raise.dendrogram(dend[[i]], heiget_to_add) # go into the tree with recursion...
81 }
82 # change the height of our current branch
83 attr(dend, "height") <- attr(dend, "height") + heiget_to_add
84 }
85 return(dend)
86 }
87
88
89
90
91
92
93
94 #' @title unbranch trees
95 #' @description unbranch trees and merges the subtree to the parent node.
96 #' @export
97 #' @rdname unbranch
98 #'
99 #' @param dend a dendrogram (or hclust) object
100 #' @param branch_becoming_root a numeric choosing the branch of the root which will become the new root (from left to right)
101 #' @param new_root_height the new height of the branch which will become the new root.
102 #' If the parameter is not given - the height of the original root is used.
103 #' @param ... passed on
104 #' @return An unbranched dendrogram
105 #' @seealso \link[ape]{unroot}
106 #' @examples
107 #' hc <- hclust(dist(USArrests[2:9, ]), "com")
108 #' dend <- as.dendrogram(hc)
109 #'
110 #' par(mfrow = c(1, 3))
111 #' plot(dend, main = "original tree")
112 #' plot(unbranch(dend, 1), main = "unbranched tree (left branch)")
113 #' plot(unbranch(dend, 2), main = "tree without (right branch)")
114 unbranch <- function(dend, ...) {
115 UseMethod("unbranch")
116 }
117
118 #' @export
119 #' @rdname unbranch
120 unbranch.default <- function(dend, ...) stop("object dend must be a dendrogram/hclust/phylo object")
121
122
123 #' @export
124 #' @rdname unbranch
125 unbranch.dendrogram <- function(dend, branch_becoming_root = 1, new_root_height, ...) {
126
127 # dend <- x # (since this function is based on dendrograms)
128 if (is.leaf(dend[[branch_becoming_root]])) {
129 warning("unbranch.dendrogram can't have the new root being a leaf.
130 The original dendrogram is returned.
131 Please choose another branch to be the root.")
132 return(dend)
133 }
134 new_dend <- list()
135
136 # add branches from the new root branch to the new tree
137 number_of_branches_in_root <- length(dend[[branch_becoming_root]])
138 i_new_root <- branch_becoming_root + 0:(number_of_branches_in_root - 1)
139 for (i in seq_len(number_of_branches_in_root))
140 {
141 new_dend[[i_new_root[i]]] <- dend[[branch_becoming_root]][[i]] # add the branches of the branc_becoming_root to the new tree
142 }
143
144 # add all other branches of the old tree to the root of the new tree
145 number_of_branches_in_dend <- length(dend)
146 number_of_branches_in_dend_minus_root <- number_of_branches_in_dend - 1
147 branches_to_add_to_root <- seq_len(number_of_branches_in_dend)[-branch_becoming_root]
148 i_old_branches <- (1:(number_of_branches_in_dend_minus_root + number_of_branches_in_root))[-i_new_root]
149 # id of branches to add to the root of the new tree
150 for (i in seq_len(number_of_branches_in_dend_minus_root))
151 {
152 new_dend[[i_old_branches[i]]] <- dend[[branches_to_add_to_root[i]]] # add the branches of the branc_becoming_root to the new tree
153 }
154
155
156 # set the proper attributes of the root of the new tree
157 if (!missing(new_root_height)) {
158 attr(new_dend, "height") <- new_root_height
159 } else {
160 attr(new_dend, "height") <- attr(dend, "height") # + attr(dend[[branch_becoming_root]], "height")
161 }
162 class(new_dend) <- "dendrogram"
163 attr(new_dend, "members") <- sum(get_root_branches_attr(new_dend, "members")) # the new members of the root is the sum of the members in all of his branches
164 attr(new_dend, "midpoint") <-
165 suppressWarnings(mean(get_root_branches_attr(new_dend, "midpoint"), na.rm = TRUE))
166 # the new midpoint of the root is the mean of the midpoint in all of his branches
167 # if some are NA, they are ignored
168
169
170 # Bad idea: we only use labels for the leafs...
171 # attr(new_dend, "label") <- "merged root" # might cause problems in the future?
172 new_dend <- suppressWarnings(stats_midcache.dendrogram(new_dend)) # might through warnings if we have 3 branches (but it will keep the "midpoints" in check
173
174 return(new_dend)
175 }
176
177
178
179 #' @export
180 #' @rdname unbranch
181 unbranch.hclust <- function(dend, branch_becoming_root = 1, new_root_height, ...) {
182 x_dend <- as.dendrogram(dend)
183 x_dend_unbranch <- unbranch(x_dend, branch_becoming_root, new_root_height, ...)
184 x_unbranch <- as_hclust_fixed(x_dend_unbranch, dend)
185
186 return(x_unbranch)
187 }
188
189
190 #' @export
191 #' @rdname unbranch
192 unbranch.phylo <- function(dend, ...) {
193 # ape::unbranch(phy = x)
194 # library(ape)
195 x_dend <- as.dendrogram(dend)
196 x_dend_unbranch <- unbranch(x_dend, ...) # branch_becoming_root , new_root_height,
197 x_unbranch <- ape::as.phylo(x_dend_unbranch)
198
199 return(x_unbranch)
200 }
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218 #' @title Flatten the branches of a dendrogram's root
219 #' @description
220 #' The function makes sure the two branches of the root of a dendrogram will have the same height.
221 #' The user can choose how to decide which height to use.
222 #' @export
223 #' @param dend dendrogram object
224 #' @param FUN how to choose the new height of both branches (defaults to taking the max between the two)
225 #' @param new_height overrides FUN, and sets the new height of the two branches manually
226 #' @param ... passed on (not used)
227 #' @return A dendrogram with both of the root's branches of the same height
228 #' @examples
229 #' hc <- hclust(dist(USArrests[2:9, ]), "com")
230 #' dend <- as.dendrogram(hc)
231 #' attr(dend[[1]], "height") <- 150 # make the height un-equal
232 #'
233 #' par(mfrow = c(1, 2))
234 #' plot(dend, main = "original tree")
235 #' plot(flatten.dendrogram(dend), main = "Raised tree")
236 flatten.dendrogram <- function(dend, FUN = max, new_height, ...) {
237 if (missing(new_height)) {
238 dend_branches_height <- get_root_branches_attr(dend, "height")
239 new_height <- FUN(dend_branches_height)
240 }
241 for (i in seq_len(length(dend))) attr(dend[[i]], "height") <- new_height
242 return(dend)
243 }
244
245
246
247 # get_all_leaves(dend)
248 get_all_leaves <- function(dend, ...) {
249 leaves <- as.list(rep(NA, nleaves(dend)))
250
251 # this function is used to modify object_attr. What it returns is not important.
252 i_leaf <- 0
253 get_attr_from_node <- function(dend_node) {
254 if (is.leaf(dend_node)) {
255 i_leaf <<- i_leaf + 1
256 leaves[[i_leaf]] <<- unclass(dend_node)
257 }
258 return(invisible())
259 }
260 dendrapply(dend, get_attr_from_node)
261
262 leaves
263 }
264
265
266
267
268
269 #' @title Collapse branches under a tolerance level
270 #' @description
271 #' Collapse branches under a tolerance level
272 #' @export
273 #' @param dend dendrogram object
274 #' @param tol a numeric value giving the tolerance to consider a branch length significantly greater than zero
275 #' @param lower logical (TRUE). collapse branches which are lower than tol?
276 #' @param ... passed on (not used)
277 #' @return A dendrogram with both of the root's branches of the same height
278 #' @seealso \link[ape]{multi2di}
279 #' @examples
280 #'
281 #' # # ladderize is like sort(..., type = "node")
282 #' dend <- iris[1:5, -5] %>%
283 #' dist() %>%
284 #' hclust() %>%
285 #' as.dendrogram()
286 #' par(mfrow = c(1, 3))
287 #' dend %>%
288 #' ladderize() %>%
289 #' plot(horiz = TRUE)
290 #' abline(v = .2, col = 2, lty = 2)
291 #' dend %>%
292 #' collapse_branch(tol = 0.2) %>%
293 #' ladderize() %>%
294 #' plot(horiz = TRUE)
295 #' dend %>%
296 #' collapse_branch(tol = 0.2) %>%
297 #' ladderize() %>%
298 #' hang.dendrogram(hang = 0) %>%
299 #' plot(horiz = TRUE)
300 #'
301 #' par(mfrow = c(1, 2))
302 #' dend %>%
303 #' collapse_branch(tol = 0.2, lower = FALSE) %>%
304 #' plot(horiz = TRUE, main = "dendrogram")
305 #' library(ape)
306 #' dend %>%
307 #' as.phylo() %>%
308 #' di2multi(tol = 0.2) %>%
309 #' plot(main = "phylo")
310 collapse_branch <- function(dend, tol = 1e-08, lower = TRUE, ...) {
311 if (!is.dendrogram(dend)) stop("'dend' should be a dendrogram.")
312 if (nleaves(dend) == 1) {
313 warning("nleaves(dend) == 1 - returning dend")
314 if (attr(dend, "height") < tol) warning("dend height < tol")
315 return(dend)
316 }
317
318 fix_height_attr_per_node <- function(dend_node) {
319 if (is.leaf(dend_node)) {
320 return(unclass(dend_node))
321 }
322
323 the_leaves <- list()
324 nodes_to_rm <- NULL
325
326 for (i_nodes in seq_len(length(dend_node))) {
327 a_leaf <- is.leaf(dend_node[[i_nodes]])
328 short <- attr(dend_node[[i_nodes]], "height") < tol
329 if (!lower) short <- !short
330
331 if (!a_leaf & short) {
332 the_leaves <- c(the_leaves, get_all_leaves(dend_node[[i_nodes]]))
333 nodes_to_rm <- c(nodes_to_rm, i_nodes)
334 } else {
335 dend_node[[i_nodes]] <- fix_height_attr_per_node(dend_node[[i_nodes]])
336 }
337 }
338
339 if (!is.null(nodes_to_rm)) {
340 tmp_attr <- attributes(dend_node)
341 dend_node <- c(dend_node, the_leaves)
342 dend_node <- dend_node[-nodes_to_rm]
343 attributes(dend_node) <- tmp_attr
344 }
345 return(unclass(dend_node))
346 }
347
348 dend <- fix_height_attr_per_node(dend)
349 class(dend) <- "dendrogram"
350 dend <- suppressWarnings(stats_midcache.dendrogram(dend)) # might through warnings if we have 3 branches (but it will keep the "midpoints" in check
351 return(dend)
352 }
353
354 # TODO: add tests