Debian Codegraph @

R/branches_attr_by.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 # debug(branches_attr_by_clusters)
21
22
23
24
25 #' @title Change col/lwd/lty of branches based on clusters
26 #' @export
27 #' @description
28 #' The user supplies a dend, a vector of clusters, and what to modify (and how).
29 #'
30 #' And the function returns a dendrogram with branches col/lwd/lty accordingly.
31 #' (the function assumes unique labels)
32 #'
33 #' @details
34 #'
35 #' This is probably NOT a very fast implementation of the function, but it works.
36 #'
37 #' This function was designed to enable the manipulation (mainly coloring) of
38 #' branches, based on the results from the \link[dynamicTreeCut]{cutreeDynamic}
39 #' function.
40 #'
41 #' @param dend a dendrogram dend
42 #' @param clusters an integer vector of clusters.
43 #' This HAS to be of the same length as the number of leaves.
44 #' Items that belong to no cluster should get the value 0.
45 #' The vector should be of the same order as that of the labels in the dendrogram.
46 #' If you create the clusters from something like \link{cutree} you would first
47 #' need to use \link{order.dendrogram} on it, before using it in the function.
48 #' @param values the attributes to use for non 0 values.
49 #' This should be of the same length as the number of unique non-0 clusters.
50 #' If it is shorter, it is recycled.
51 #'
52 #' OR, this can also be of the same length as the number of leaves in the tree
53 #' In which case, the values will be aggreagted (i.e.: \link{tapply}), to match
54 #' the number of clusters. The first value of each cluster will be used as the main
55 #' value.
56 #'
57 #' TODO: So far, the function doesn't deal well with NA values. (this might be changed in the future)
58 #'
59 #' @param attr a character with one of the following values: col/lwd/lty
60 #' @param branches_changed_have_which_labels character with either "any" (default) or "all".
61 #' Inidicates how the branches should be updated.
62 #' @param ... ignored.
63 #'
64 #' @return
65 #' A dendrogram with modified branches (col/lwd/lty).
66 #' @seealso
67 #' \link{branches_attr_by_labels},
68 #' \link{get_leaves_attr}, \link{nnodes}, \link{nleaves}
69 #' \link[dynamicTreeCut]{cutreeDynamic},
70 #' \link[WGCNA]{plotDendroAndColors}
71 #' @examples
72 #'
73 #' \dontrun{
74 #'
75 #' ### Getting the hc object
76 #' iris_dist <- iris[, -5] %>% dist()
77 #' hc <- iris_dist %>% hclust()
78 #' # This is how it looks without any colors:
79 #' dend <- as.dendrogram(hc)
80 #' plot(dend)
81 #'
82 #' # Both functions give the same outcome
83 #' # options 1:
84 #' dend %>%
85 #' set("branches_k_color", k = 4) %>%
86 #' plot()
87 #' # options 2:
88 #' clusters <- cutree(dend, 4)[order.dendrogram(dend)]
89 #' dend %>%
90 #' branches_attr_by_clusters(clusters) %>%
91 #' plot()
92 #'
93 #' # and the second option is much slower:
94 #' system.time(set(dend, "branches_k_color", k = 4)) # 0.26 sec
95 #' system.time(branches_attr_by_clusters(dend, clusters)) # 1.61 sec
96 #' # BUT, it also allows us to do more flaxible things!
97 #'
98 #' #--------------------------
99 #' # Plotting dynamicTreeCut
100 #' #--------------------------
101 #'
102 #' # let's get the clusters
103 #' library(dynamicTreeCut)
104 #' clusters <- cutreeDynamic(hc, distM = as.matrix(iris_dist))
105 #' # we need to sort them to the order of the dendrogram:
106 #' clusters <- clusters[order.dendrogram(dend)]
107 #'
108 #' # get some functions:
109 #' library(colorspace)
110 #' no0_unique <- function(x) {
111 #' u_x <- unique(x)
112 #' u_x[u_x != 0]
113 #' }
114 #'
115 #' clusters_numbers <- no0_unique(clusters)
116 #' n_clusters <- length(clusters_numbers)
117 #' cols <- rainbow_hcl(n_clusters)
118 #' dend2 <- branches_attr_by_clusters(dend, clusters, values = cols)
119 #' # dend2 <- branches_attr_by_clusters(dend, clusters)
120 #' plot(dend2)
121 #' # add colored bars:
122 #' ord_cols <- rainbow_hcl(n_clusters)[order(clusters_numbers)]
123 #' tmp_cols <- rep(1, length(clusters))
124 #' tmp_cols[clusters != 0] <- ord_cols[clusters != 0][clusters]
125 #' colored_bars(tmp_cols, y_shift = -1.1, rowLabels = "")
126 #' # all of the ordering is to handle the fact that the cluster numbers are not ascending...
127 #'
128 #' # How is this compared with the usual cutree?
129 #' dend3 <- color_branches(dend, k = n_clusters)
130 #' labels(dend2) <- as.character(labels(dend2))
131 #' # this needs fixing, since the labels are not character!
132 #' # Well, both cluster solutions are not perfect, but at least they are interesting...
133 #' tanglegram(dend2, dend3,
134 #' main_left = "cutreeDynamic", main_right = "cutree",
135 #' columns_width = c(5, .5, 5),
136 #' color_lines = cols[iris[order.dendrogram(dend2), 5]]
137 #' )
138 #' # (Notice how the color_lines is of the true Species of each Iris)
139 #' # The main difference is at the bottom,
140 #' }
141 branches_attr_by_clusters <- function(dend, clusters, values, attr = c("col", "lwd", "lty"),
142 branches_changed_have_which_labels = c("any", "all"),
143 ...) {
144 attr <- match.arg(attr)
145
146 if (!is.dendrogram(dend)) warning("'dend' should be a dendrogram.")
147 if (missing(clusters)) stop("'clusters' parameter is missing.")
148 if (!is.numeric(clusters)) {
149 warning("'clusters' parameter was not a numeric vector, and was coerced into one.")
150 clusters <- as.numeric(clusters)
151 }
152
153 n_leaves <- nleaves(dend)
154
155 if (n_leaves != length(clusters)) stop("The number of values in 'clusters' does not equal the number of leaves.")
156
157 u_clusters <- unique(clusters)
158 u_clusters <- u_clusters[u_clusters != 0] # we only care about the unique clusters which are not 0!
159 # u_clusters <- sort(u_clusters) # and let's sort the clusters so that we would go
160 n_u_clusters <- length(u_clusters)
161
162 if (missing(values) & attr == "col") {
163 values <- rep(1, length(clusters)) # make a vector of black colors
164 # library(colorspace) # this package is now in imports
165 values <- rainbow_fun(n_u_clusters)
166 }
167
168
169 n_values <- length(values)
170
171 # if the value is of the length of the leaves
172 # then we aggregate the values to have one value for each cluster!
173 if (n_values == n_leaves) {
174 ss_not0 <- clusters != 0
175 values <- tapply(values[ss_not0], clusters[ss_not0], function(x) {
176 x[1]
177 })
178 }
179
180 if (n_values < n_u_clusters) {
181 # stop("Must give the same number of colors as number of clusters")
182 warning("Length of values vector was shorter than the number of clusters (Excluding 0) - vector was recycled")
183 values <- rep(values, length.out = n_u_clusters)
184 }
185
186 if (any(is.na(values))) {
187 warning("There are NA's in the colors used by branches_attr_by_clusters. This probably means a bug somewhere. The color was replaced by 'black', but make sure your code does what you wanted it to...")
188 values[is.na(values)] <- "black"
189 }
190
191 # let's find out which nodes we should modify for each cluster
192 nodes_cluster_TF_mat <- matrix(FALSE, nrow = nnodes(dend), ncol = n_u_clusters)
193 dend_labels <- labels(dend)
194
195 has_any_labels <- function(sub_dend, the_labels) any(labels(sub_dend) %in% the_labels)
196 has_all_labels <- function(sub_dend, the_labels) all(labels(sub_dend) %in% the_labels)
197
198 branches_changed_have_which_labels <- match.arg(branches_changed_have_which_labels)
199 #### This doesn't seem to work. Not sure why...
200 has_x_labels <- switch(branches_changed_have_which_labels,
201 all = has_all_labels,
202 any = has_any_labels
203 )
204 # if(branches_changed_have_which_labels == "any") has_x_labels <- has_any_labels
205 # if(branches_changed_have_which_labels == "all") has_x_labels <- has_all_labels
206
207
208 for (i in seq_along(u_clusters)) {
209 # looking at the labels of the current cluster:
210 ss <- clusters == u_clusters[i]
211 tmp_labels <- dend_labels[ss]
212 # find which node belongs to it:
213
214 #### DELETE:
215 # # tmp_nodes_TF <- noded_with_condition(dend, condition = has_x_labels,
216 # # the_labels = tmp_labels)
217 # if(branches_changed_have_which_labels == "any") {
218 # tmp_nodes_TF <- noded_with_condition(dend, condition = has_any_labels, the_labels = tmp_labels)
219 # }
220 # if(branches_changed_have_which_labels == "all") {
221 # tmp_nodes_TF <- noded_with_condition(dend, condition = has_all_labels, the_labels = tmp_labels)
222 # }
223
224 tmp_nodes_TF <- noded_with_condition(dend, condition = has_x_labels, the_labels = tmp_labels)
225
226
227 # and modify our TF cluster matrix:
228 nodes_cluster_TF_mat[, i] <- tmp_nodes_TF
229 }
230
231 # let's find all the places where we should NOT make any modification:
232 nodes_cluster_TF_mat_overlap <- apply(nodes_cluster_TF_mat, 1, function(x) {
233 sum(x) > 1
234 })
235
236 # no we can go through all of the clusters and modify the dend as we should:
237 for (i in seq_along(u_clusters)) {
238 # set tmp values to be the cluster value (for relevant nodes) or Inf (for the rest):
239 tmp_values <- ifelse(nodes_cluster_TF_mat[, i], values[i], Inf)
240 # but if we have an overlap, let's set values back to Inf!
241 tmp_values <- ifelse(nodes_cluster_TF_mat_overlap, Inf, tmp_values)
242
243 # update the dend:
244 dend <- assign_values_to_branches_edgePar(dend, value = tmp_values, edgePar = attr)
245 }
246
247 return(dend)
248 }
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263 #' @title Change col/lwd/lty of branches matching labels condition
264 #' @export
265 #' @description
266 #' The user supplies a dend, labels, and type of condition (all/any), and TF_values
267 #' And the function returns a dendrogram with branches col/lwd/lty accordingly
268 #' @param dend a dendrogram dend
269 #' @param labels a character vector of labels from the tree
270 #' @param TF_values a two dimensional vector with the TF_values to use in case a branch fulfills the condition (TRUE)
271 #' and in the case that it does not (FALSE). Defaults are 2/Inf for col, lwd and lty.
272 #' (so it will insert the first value, and will not change all the FALSE cases)
273 #' @param attr a character with one of the following values: col/lwd/lty
274 #' @param type a character vector of either "all" or "any", indicating which of
275 #' the branches should be painted: ones that all of their labels belong to the supplied labels,
276 #' or also ones that even some of their labels are included in the labels vector.
277 #' @param ... ignored.
278 #' @return
279 #' A dendrogram with modified branches (col/lwd/lty).
280 #' @seealso \link{noded_with_condition}, \link{get_leaves_attr}, \link{nnodes}, \link{nleaves}
281 #' @examples
282 #' \dontrun{
283 #'
284 #' library(dendextend)
285 #'
286 #' set.seed(23235)
287 #' ss <- sample(1:150, 10)
288 #'
289 #' # Getting the dend dend
290 #' dend <- iris[ss, -5] %>%
291 #' dist() %>%
292 #' hclust() %>%
293 #' as.dendrogram()
294 #' dend %>% plot()
295 #'
296 #' dend %>%
297 #' branches_attr_by_labels(c("123", "126", "23", "29")) %>%
298 #' plot()
299 #' dend %>%
300 #' branches_attr_by_labels(c("123", "126", "23", "29"), "all") %>%
301 #' plot() # the same as above
302 #' dend %>%
303 #' branches_attr_by_labels(c("123", "126", "23", "29"), "any") %>%
304 #' plot()
305 #'
306 #' dend %>%
307 #' branches_attr_by_labels(
308 #' c("123", "126", "23", "29"),
309 #' "any", "col", c("blue", "red")
310 #' ) %>%
311 #' plot()
312 #' dend %>%
313 #' branches_attr_by_labels(
314 #' c("123", "126", "23", "29"),
315 #' "any", "lwd", c(4, 1)
316 #' ) %>%
317 #' plot()
318 #' dend %>%
319 #' branches_attr_by_labels(
320 #' c("123", "126", "23", "29"),
321 #' "any", "lty", c(2, 1)
322 #' ) %>%
323 #' plot()
324 #' }
325 branches_attr_by_labels <- function(dend, labels, TF_values = c(2, Inf), attr = c("col", "lwd", "lty"), type = c("all", "any"), ...) {
326 if (!is.dendrogram(dend)) stop("'dend' should be a dendrogram.")
327 if (missing(labels)) stop("'labels' parameter is missing.")
328 if (!is.character(labels)) {
329 if (dendextend_options("warn")) warning("'labels' parameter was not a character vector, and was coerced into one.")
330 labels <- as.character(labels)
331 }
332
333
334 type <- match.arg(type)
335 attr <- match.arg(attr)
336
337 # make sure that if the TF_values has only one value,
338 # the other one will be Inf
339 if (length(TF_values) == 1) TF_values <- c(TF_values, Inf)
340
341 # deal with the case we have labels not included in the tree dend:
342 labels_in_dend <- labels %in% labels(dend)
343 if (!all(labels_in_dend)) {
344 warning(
345 "Not all of the labels you provided are included in the dendrogram.\n",
346 "The following labels were omitted:", labels[!labels_in_dend]
347 )
348 # cat("\n")
349 labels <- labels[labels_in_dend]
350 }
351
352 has_any_labels <- function(sub_dend, the_labels) any(labels(sub_dend) %in% the_labels)
353 has_all_labels <- function(sub_dend, the_labels) all(labels(sub_dend) %in% the_labels)
354
355 what_to_change <- switch(type,
356 all = noded_with_condition(dend, has_all_labels, the_labels = labels),
357 any = noded_with_condition(dend, has_any_labels, the_labels = labels)
358 )
359 the_TF_values <- ifelse(what_to_change, TF_values[1], TF_values[2])
360 # warnings()
361
362
363 switch(attr,
364 col = set(dend, "branches_col", the_TF_values),
365 lwd = set(dend, "branches_lwd", the_TF_values),
366 lty = set(dend, "branches_lty", the_TF_values)
367 )
368 }
369
370
371
372
373
374
375
376
377 ## provided by Manuela Hummel ([email protected])
378 # code partly taken from the 'globaltest' package (Jelle Goeman, Jan Oosting)
379
380 #' @title Change col/lwd/lty of branches from the root down to clusters defined by list of labels of respective members
381 #' @export
382 #' @description
383 #' The user supplies a dend, lists, and type of condition (all/any), and TF_values
384 #' And the function returns a dendrogram with branches col/lwd/lty accordingly
385 #' @param dend a dendrogram dend
386 #' @param lists a list where each element contains the labels of members in selected nodes
387 #' down to which the branches shall be adapted
388 #' @param TF_values a two dimensional vector with the TF_values to use in case a branch fulfills the condition (TRUE)
389 #' and in the case that it does not (FALSE). Defaults are 2/1 for col, lwd and lty.
390 #' (so it will insert the first value, and will not change all the FALSE cases)
391 #' @param attr a character with one of the following values: col/lwd/lty
392 #' @param ... ignored.
393 #' @return
394 #' A dendrogram with modified branches (col/lwd/lty).
395 #' @seealso \link{branches_attr_by_labels}
396 #' @examples
397 #' \dontrun{
398 #'
399 #' library(dendextend)
400 #'
401 #' set.seed(23235)
402 #' ss <- sample(1:150, 10)
403 #'
404 #' # Getting the dend dend
405 #' dend <- iris[ss, -5] %>%
406 #' dist() %>%
407 #' hclust() %>%
408 #' as.dendrogram()
409 #' dend %>% plot()
410 #'
411 #' # define a list of nodes
412 #' L <- list(c("109", "123", "126", "145"), "29", c("59", "67", "97"))
413 #' dend %>%
414 #' branches_attr_by_lists(L) %>%
415 #' plot()
416 #'
417 #' # choose different color, and also change lwd and lty
418 #' dend %>%
419 #' branches_attr_by_lists(L, TF_value = "blue") %>%
420 #' branches_attr_by_lists(L, attr = "lwd", TF_value = 4) %>%
421 #' branches_attr_by_lists(L, attr = "lty", TF_value = 3) %>%
422 #' plot()
423 #' }
424 branches_attr_by_lists <- function(dend, lists, TF_values = c(2, 1), attr = c("col", "lwd", "lty"), ...) {
425 if (!is.dendrogram(dend)) stop("'dend' should be a dendrogram.")
426 if (missing(lists)) stop("'lists' parameter is missing.")
427
428 attr <- match.arg(attr)
429 if (length(TF_values) == 1) TF_values <- c(TF_values, 1)
430 uit <- dend
431
432 # get nodes down to which attribute shall be changed
433 sig <- any(sapply(lists, function(x) all(x %in% labels(uit))))
434
435 attr(uit, "edgePar") <- switch(attr,
436 col = c(attr(uit, "edgePar"), list(col = ifelse(sig, TF_values[1], TF_values[2]))),
437 lwd = c(attr(uit, "edgePar"), list(lwd = ifelse(sig, TF_values[1], TF_values[2]))),
438 lty = c(attr(uit, "edgePar"), list(lty = ifelse(sig, TF_values[1], TF_values[2])))
439 )
440
441 # continue with the child branches
442 if (!is.leaf(dend)) {
443 select.branch <- 1:length(dend)
444 for (i in 1:length(select.branch)) {
445 uit[[i]] <- Recall(dend[[select.branch[i]]], lists, TF_values, attr)
446 }
447 }
448 return(uit)
449 }