Debian Codegraph @

R/untangle.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
23
24 #' @title untangle dendrograms
25 #' @export
26 #' @rdname untangle
27 #' @description
28 #' One untangle function to rule them all.
29 #'
30 #' This function untangles dendrogram lists (dendlist),
31 #' Using various heuristics.
32 #'
33 #' @author Tal Galili
34 #'
35 #' @param dend1 a dendrogram or a dendlist object
36 #' @param dend2 A second dendrogram (to untangle against)
37 #' @param which an integer vector of length 2, indicating
38 #' which of the trees in the dendlist object should be plotted
39 #' @param method a character indicating the type of untangle
40 #' heuristic to use. The options are:
41 #' ("labels", "ladderize", "random", "step1side", "step2side", "stepBothSides",
42 #' "DendSer")
43 #' @param ... passed to the relevant untangle function
44 #' @details
45 #' This function wraps all of the untangle functions,
46 #' in order to make it easier to find our about (and use) them.
47 #' @return A \link{dendlist}, with two trees after
48 #' they have been untangled.
49 #'
50 #' If the dendlist was originally larger than 2, it will return the original dendlist
51 #' but with the relevant trees properly rotate.
52 #'
53 #' @seealso
54 #' \link{tanglegram}, \link{untangle_random_search},
55 #' \link{untangle_step_rotate_1side}, \link{untangle_step_rotate_2side},
56 #' \link{untangle_DendSer},
57 #' \link{entanglement}
58 #' @examples
59 #' \dontrun{
60 #' set.seed(23235)
61 #' ss <- sample(1:150, 10)
62 #' dend1 <- iris[ss, -5] %>%
63 #' dist() %>%
64 #' hclust("com") %>%
65 #' as.dendrogram()
66 #' dend2 <- iris[ss, -5] %>%
67 #' dist() %>%
68 #' hclust("sin") %>%
69 #' as.dendrogram()
70 #' dend12 <- dendlist(dend1, dend2)
71 #'
72 #' dend12 %>% tanglegram()
73 #'
74 #' untangle(dend1, dend2, method = "random", R = 5) %>% tanglegram()
75 #'
76 #' # it works, and we get something different:
77 #' set.seed(1234)
78 #' dend12 %>%
79 #' untangle(method = "random", R = 5) %>%
80 #' tanglegram()
81 #'
82 #' set.seed(1234)
83 #' # fixes it completely:
84 #' dend12 %>%
85 #' untangle(method = "random", R = 5) %>%
86 #' untangle(method = "step1") %>%
87 #' tanglegram()
88 #' # not good enough
89 #' dend12 %>%
90 #' untangle(method = "step1") %>%
91 #' tanglegram()
92 #' # not good enough
93 #' dend12 %>%
94 #' untangle(method = "step2") %>%
95 #' tanglegram()
96 #' # How we might wish to use it:
97 #' set.seed(12777)
98 #' dend12 %>%
99 #' untangle(method = "random", R = 1) %>%
100 #' untangle(method = "step2") %>%
101 #' tanglegram()
102 #' }
103 untangle <- function(dend1, ...) {
104 UseMethod("untangle")
105 }
106
107 #' @export
108 #' @rdname untangle
109 untangle.default <- function(dend1, ...) {
110 stop("No default function for tanglegram - must use a dendrogram/hclust/phylo object")
111 }
112
113
114
115 #' @export
116 #' @rdname untangle
117 untangle_labels <- function(dend1, dend2, ...) {
118 dend2 <- rotate(dend2, labels(dend1))
119 dendlist(dend1, dend2)
120 }
121
122
123
124
125 #' @export
126 #' @rdname untangle
127 untangle.dendrogram <- function(dend1, dend2,
128 method = c("labels", "ladderize", "random", "step1side", "step2side", "stepBothSides", "DendSer"), ...) {
129 method <- match.arg(method)
130
131 switch(method,
132 random = untangle_random_search(dend1, dend2, ...),
133 step1side = untangle_step_rotate_1side(dend1, dend2, ...),
134 step2side = untangle_step_rotate_2side(dend1, dend2, ...),
135 stepBothSides = untangle_step_rotate_both_side(dend1, dend2, ...),
136 DendSer = untangle_DendSer(dendlist(dend1, dend2), ...),
137 ladderize = ladderize(dendlist(dend1, dend2), ...),
138 labels = untangle_labels(dend1, dend2, ...)
139 )
140 }
141
142 #' @export
143 #' @rdname untangle
144 untangle.dendlist <- function(dend1,
145 method = c("labels", "ladderize", "random", "step1side", "step2side", "DendSer"),
146 which = c(1L, 2L), ...) {
147 method <- match.arg(method)
148 the_names <- names(dend1)[which]
149
150 untangle_result <- untangle(dend1[[which[1]]], dend1[[which[2]]], method = method, ...)
151
152 if (length(dend1) > 2) {
153 dend1[[which[1]]] <- untangle_result[[1]]
154 dend1[[which[2]]] <- untangle_result[[2]]
155 names(dend1) <- the_names
156 return(dend1)
157 } else { # no need for all the copying if the list had only two elements in it.
158 names(untangle_result) <- the_names
159 return(untangle_result)
160 }
161 }
162
163
164 # center <- function(type = c("mean", "median", "trimmed")) {
165 # print(match.arg(type))
166 # }
167 # center(type="tri")
168
169
170
171 # get("sort")
172 #' 'shuffle' is a function that randomilly rotates ("shuffles") a tree.
173 #' a dendrogram leaves order (by means of rotation)
174
175 #' @title Random rotation of trees
176 #' @export
177 #' @rdname shuffle
178 #'
179 #' @description
180 #' 'shuffle' randomilly rotates ("shuffles") a tree, changing its presentation
181 #' while preserving its topolgoy.
182 #' 'shuffle' is based on \link[dendextend]{rotate} and through its methods can
183 #' work for any of the major tree objects in R (\link{dendrogram}/\link{hclust}/\link[ape]{phylo}).
184 #'
185 #' This function is useful in combination with \link{tanglegram} and \link{entanglement}.
186 #'
187 #' @param dend a tree object (\link{dendrogram}/\link{hclust}/\link[ape]{phylo})
188 #' @param which an integer vector for indicating
189 #' which of the trees in the dendlist object should be plotted
190 #' default is missing, in which case all the dends in dendlist
191 #' will be shuffled
192 #' @param ... Ignored.
193 #'
194 #' @return A randomlly rotated tree object
195 #' @seealso \code{\link{tanglegram}}, \code{\link{entanglement}},
196 #' \code{\link[dendextend]{rotate}}
197 #' @examples
198 #' dend <- USArrests %>%
199 #' dist() %>%
200 #' hclust() %>%
201 #' as.dendrogram()
202 #' set.seed(234238)
203 #' dend2 <- shuffle(dend)
204 #'
205 #' tanglegram(dend, dend2, margin_inner = 7)
206 #' entanglement(dend, dend2) # 0.3983
207 #'
208 #' # although these ARE the SAME tree:
209 #' tanglegram(sort(dend), sort(dend2), margin_inner = 7)
210 shuffle <- function(dend, ...) {
211 UseMethod("shuffle")
212 }
213
214 #' @export
215 #' @rdname shuffle
216 shuffle.default <- function(dend, ...) {
217 # takes a dendrogram object and shuffles its branches in a random fashion
218 # n_leaves <- length(labels(dend)) # leaves.value is faster then labels!
219 n_leaves <- nleaves(dend)
220 random_weights <- sample(seq_len(n_leaves)) # a random ordaring of 1:n_leaves weights
221 rotate(dend, random_weights) # since we have a method here for dend/hclust/phylo - this makes this function rather generic...
222 }
223
224
225 #' @export
226 #' @rdname shuffle
227 shuffle.dendrogram <- shuffle.default
228
229
230 #' @export
231 #' @rdname shuffle
232 shuffle.dendlist <- function(dend, which, ...) {
233
234 # if(T) 1 else 2
235 # if(F) 1 else 2
236 # if(F) 1 else
237 # 2
238 what_to_shuffle <- if (missing(which)) seq_len(length(dend)) else which
239
240 for (i in what_to_shuffle) {
241 dend[[i]] <- shuffle(dend[[i]])
242 }
243
244 dend
245 }
246
247
248 #' @export
249 #' @rdname shuffle
250 shuffle.hclust <- shuffle.default
251
252 #' @export
253 #' @rdname shuffle
254 shuffle.phylo <- shuffle.default
255
256
257
258
259
260 #' @title Untangle - random search
261 #' @export
262 #' @description
263 #' Searches for two untangled dendrogram by randomlly shuflling them and each
264 #' time checking if their entanglement was improved.
265 #'
266 #' @param dend1 a tree object (of class dendrogram/hclust/phylo).
267 #' @param dend2 a tree object (of class dendrogram/hclust/phylo).
268 #' @param R numeric (default is 100). The number of shuffles to perform.
269 #' @param L the distance norm to use for measuring the distance between the
270 #' two trees. It can be any positive number, often one will want to
271 #' use 0, 1, 1.5, 2 (see 'details' for more).
272 #' It is passed to \link{entanglement}.
273 #' @param leaves_matching_method a character scalar passed to \link{entanglement}.
274 #' It can be either "order" or "labels" (default). If using "labels",
275 #' then we use the labels for matching the leaves order value.
276 #' And if "order" then we use the old leaves order value for matching the
277 #' leaves order value.
278 #'
279 #' Using "order" is faster, but "labels" is safer. "order" will assume that
280 #' the original two trees had their labels and order values MATCHED.
281 #'
282 #' Hence, it is best to make sure that the trees used here have the same labels
283 #' and the SAME values matched to these values - and then use "order" (for
284 #' fastest results).
285 #'
286 #' If "order" is used, the function first calls \link{match_order_by_labels}
287 #' in order to make sure that the two trees have their labels synced with
288 #' their leaves order values.
289 #'
290 #' @param ... not used
291 #'
292 #' @details
293 #'
294 #' Untangaling two trees is a hard combinatorical problem without a closed
295 #' form solution. One way for doing it is to run through a random spectrom
296 #' of options and look for the "best" two trees. This is what this function
297 #' offers.
298 #'
299 #' @return A dendlist with two trees with the best entanglement that was found.
300 #' @seealso \link{tanglegram}, \link{match_order_by_labels},
301 #' \link{entanglement}.
302 #' @examples
303 #'
304 #' \dontrun{
305 #' dend1 <- iris[, -5] %>%
306 #' dist() %>%
307 #' hclust("com") %>%
308 #' as.dendrogram()
309 #' dend2 <- iris[, -5] %>%
310 #' dist() %>%
311 #' hclust("sin") %>%
312 #' as.dendrogram()
313 #' tanglegram(dend1, dend2)
314 #'
315 #' set.seed(65168)
316 #' dend12 <- untangle_random_search(dend1, dend2, R = 10)
317 #' tanglegram(dend12[[1]], dend12[[2]])
318 #' tanglegram(dend12)
319 #'
320 #' entanglement(dend1, dend2, L = 2) # 0.8894
321 #' entanglement(dend12[[1]], dend12[[2]], L = 2) # 0.0998
322 #' }
323 untangle_random_search <- function(dend1, dend2, R = 100L, L = 1, leaves_matching_method = c("labels", "order"), ...) {
324 # this is a simple random search algorithm for the optimal tanglegram layout problem.
325 # it shufflers the trees, and see if we got a better entanglement or not
326
327 leaves_matching_method <- match.arg(leaves_matching_method)
328 if (leaves_matching_method == "order") {
329 old_dend2 <- dend2
330 dend2 <- match_order_by_labels(old_dend2, dend1)
331 if (!identical(dend2, old_dend2) & dendextend_options("warn")) warning("The leaves order in 'dend2' were changed. If you want to avoid that, use leaves_matching_method = 'labels'.")
332 }
333
334 optimal_dend1 <- dend1
335 optimal_dend2 <- dend2
336
337 best_ordaring_entanglement <- entanglement(dend1, dend2, L, leaves_matching_method)
338
339 for (i in 1:R) {
340 s_dend1 <- shuffle(dend1)
341 s_dend2 <- shuffle(dend2)
342 current_entanglement <- entanglement(s_dend1, s_dend2, L, leaves_matching_method)
343
344 # if we came across a better ordaring, then update the "Best" treerograms
345 if (current_entanglement < best_ordaring_entanglement) {
346 best_ordaring_entanglement <- current_entanglement
347 optimal_dend1 <- s_dend1
348 optimal_dend2 <- s_dend2
349 }
350 }
351
352 return(dendlist(optimal_dend1, optimal_dend2))
353 }
354
355
356
357
358 flip_strings <- function(STRING, str1, str2) {
359 # gets a string which includes str1 and str2, and makes sure to flip them in the string
360 STRING <- sub(str1, "_____1_", STRING, fixed = T) # substitutes the first string with a place holder (1)
361 STRING <- sub(str2, "_____2_", STRING, fixed = T) # substitutes the second string with a place holder (2)
362 STRING <- sub("_____1_", str2, STRING, fixed = T) # substitutes the place holder (1) with the second string
363 STRING <- sub("_____2_", str1, STRING, fixed = T) # substitutes the place holder (2) with the first string
364 return(STRING)
365 }
366 # flip_strings("abcdefgh", "ab", "fgh") # "fghcdeab"
367
368 add_zzz <- function(x) {
369 # this function adds a"_" character to the end of every element of the vector.
370 # this is used to make numeric values unique (so to not confuse 1 and 10 or 17 and 7 !)
371 x <- as.character(x)
372 x <- paste("zzz", x, "zzz", sep = "")
373 x
374 }
375 remove_zzz <- function(x) {
376 gsub("zzz", "", x, fixed = T)
377 }
378 # remove_zzz(add_zzz(1:6))
379 collapse_with_pipes <- function(x) {
380 paste(x, collapse = "||")
381 }
382 collapse_pipes_zzz <- function(x) {
383 paste(add_zzz(x), collapse = "||")
384 }
385 remove_pipes_and_zzz <- function(x) {
386 strsplit(remove_zzz(x), "||", fixed = T)[[1]]
387 }
388
389
390 #' @title Flip leaves
391 #' @export
392 #' @description
393 #' Rotate a branch in a tree so that the locations of two bundles of leaves
394 #' are flipped.
395 #'
396 #' @param dend a dendrogram object
397 #' @param leaves1 a vector of leaves order value to flip.
398 #' @param leaves2 a (second) vector of leaves order value to flip.
399 #' @param ... not used
400 #' @details
401 #' This function is based on a bunch of string manipulation functions. There
402 #' may be a smarter/better way for doing it...
403 #'
404 #' @return A dendrogram object with flipped leaves.
405 #' @seealso \link{tanglegram}, \link{match_order_by_labels},
406 #' \link{entanglement}.
407 #' @examples
408 #'
409 #' \dontrun{
410 #' dend1 <- USArrests[1:5, ] %>%
411 #' dist() %>%
412 #' hclust() %>%
413 #' as.dendrogram()
414 #' dend2 <- flip_leaves(dend1, c(3, 5), c(1, 2))
415 #' tanglegram(dend1, dend2)
416 #' entanglement(dend1, dend2, L = 2) # 0.4
417 #' }
418 flip_leaves <- function(dend, leaves1, leaves2, ...) {
419 # flip a node in a tree based on the leaves in each branch in the node:
420 # this function gets a dendgram with two vector of leaves that needs to be flipped with one another on the tree
421 # we assume here unique values of leaves.
422 # also notice that this is based on the values of the leaves and NOT their labels.
423 leaves_order <- order.dendrogram(dend)
424 weights <- seq_along(leaves_order)
425
426 # turn the values of leaves and leaves1/2 to strings with || delim:
427 leaves_order_string <- collapse_pipes_zzz(leaves_order)
428 leaves1_string <- collapse_pipes_zzz(leaves1)
429 leaves2_string <- collapse_pipes_zzz(leaves2)
430 # then flips the locations of leaves1 and 2 in the string
431 flipped_leaves_order_string <- flip_strings(leaves_order_string, leaves1_string, leaves2_string)
432 # and turn the string back to a vector of flipped leaves values:
433 flipped_leaves_order <- as.integer(remove_pipes_and_zzz(flipped_leaves_order_string))
434
435 new_order_weights <- match(flipped_leaves_order, leaves_order) # order the leaves_order to be like flipped_leaves_order
436 # leaves_order[new_order_weights]
437 # now use this order to order the weights!
438 new_weights <- weights[new_order_weights]
439
440 flipped_dend <- rotate(dend, new_weights) # and lastly - rotate the dend by the leaves to flip.
441
442 return(flipped_dend)
443 }
444
445
446 # I didn't use this evantually:
447 # library(combinat)
448 # source for this package: https://stackoverflow.com/questions/7906332/how-to-calculate-combination-and-permutation-in-r
449
450
451
452 #' @title Rotate tree branches for k
453 #' @export
454 #' @description
455 #' Given a tree and a k number of clusters, the tree is rotated so that the
456 #' extra clusters added from k-1 to k clusters are flipped.
457 #'
458 #' This is useful for finding good trees for a \link{tanglegram}.
459 #' @param dend a dendrogram object
460 #' @param k integer scalar with the number of clusters the tree should be cut into.
461 #' @param dend_heights_per_k a named vector that resulted from running
462 #' \link{heights_per_k.dendrogram}. When running the function many times,
463 #' supplying this object will help improve the running time if using the
464 #' \link{cutree.dendrogram} method..
465 #'
466 #' @param ... not used
467 #' @return A list with dendrogram objects with all the possible rotations
468 #' for k clusters (beyond the k-1 clusters!).
469 #' @seealso \link{tanglegram}, \link{match_order_by_labels},
470 #' \link{entanglement}, \link{flip_leaves}.
471 #' @examples
472 #'
473 #' \dontrun{
474 #' dend1 <- USArrests[1:5, ] %>%
475 #' dist() %>%
476 #' hclust() %>%
477 #' as.dendrogram()
478 #' dend2 <- all_couple_rotations_at_k(dend1, k = 2)[[2]]
479 #' tanglegram(dend1, dend2)
480 #' entanglement(dend1, dend2, L = 2) # 0.5
481 #'
482 #' dend2 <- all_couple_rotations_at_k(dend1, k = 3)[[2]]
483 #' tanglegram(dend1, dend2)
484 #' entanglement(dend1, dend2, L = 2) # 0.4
485 #'
486 #' dend2 <- all_couple_rotations_at_k(dend1, k = 4)[[2]]
487 #' tanglegram(dend1, dend2)
488 #' entanglement(dend1, dend2, L = 2) # 0.05
489 #' }
490 all_couple_rotations_at_k <- function(dend, k, dend_heights_per_k, ...) {
491 # This function gets the dend tree, and a k number of clusters
492 # and returns all of the permutated dendrogram trees, rotating only two of the k clusters at each permutation
493 # if this was done for ALL permutation, the algorithm would not be feasable.
494 # practically, for a binary tree - this only gives two trees as an output (the original, and the flipped new k'th cluster)
495
496 if (length(k) != 1L) {
497 warning("'k' should be an integer SCALAR, using only the first element of k.")
498 k <- k[1L]
499 }
500 if (k == 1) {
501 return(dend)
502 } # there are no possible rotations for k==1
503
504 if (missing(dend_heights_per_k)) {
505 dend_heights_per_k <- heights_per_k.dendrogram(dend)
506 } # since this function takes a looong time, I'm running it here so it will need to run only once!
507 # And I would MUCH rather give this vector upfront - so the entire thing will be faster...
508
509 leaves_order <- order.dendrogram(dend)
510 k_cluster_leaves <- cutree(dend, k,
511 order_clusters_as_data = FALSE,
512 dend_heights_per_k = dend_heights_per_k, # makes it faster
513 use_labels_not_values = FALSE
514 ) # makes it 10 times faster (and we don't use the labels of the clusters, only the cluster vector)
515 km1_cluster_leaves <- cutree(dend, k - 1,
516 order_clusters_as_data = FALSE,
517 dend_heights_per_k = dend_heights_per_k, # makes it faster
518 use_labels_not_values = FALSE
519 ) # makes it 10 times faster (and we don't use the labels of the clusters, only the cluster vector)
520
521 # if we can't cut the current stage (for example, because we have more than 2 branches, than return the original tree
522 if (any(is.na(k_cluster_leaves))) {
523 return(list(dend))
524 }
525 # If we can't cut the tree above us, then loop up until you find a k for which you can cut.
526 # there might be bugs for this code, more careful thought should be made in such cases...
527 while (any(is.na(km1_cluster_leaves))) {
528 k <- k - 1
529 km1_cluster_leaves <- cutree(dend, k - 1,
530 order_clusters_as_data = FALSE,
531 dend_heights_per_k = dend_heights_per_k, # makes it faster
532 use_labels_not_values = FALSE
533 ) # makes it 10 times faster (and we don't use the labels of the clusters, only the cluster vector)
534 warning(paste("couldn't cut tree at k-1, trying it for", k - 1))
535 }
536
537
538 # kkm1_df <-
539 # data.frame(km1_cluster_leaves, k_cluster_leaves)
540
541 permutated_dend <- list(dend) # this one will hold all of the permutations
542 permutation_indx <- 1 # this one will tell us at what stage of the permutation we are at
543
544 for (i in unique(km1_cluster_leaves)) {
545 ss <- i == km1_cluster_leaves
546 unique_clusters_in_branch <- unique(k_cluster_leaves[ss])
547
548 if (length(unique_clusters_in_branch) > 1) { # the only way there is a reason to do permutations here is if the current cluster we are looking at has more than 1 member
549 number_of_clusters_in_branch <- length(unique_clusters_in_branch)
550 branches_permutations <- as.matrix(combn(unique_clusters_in_branch, 2)) # a matrix were each column is a permutation of 2 out of the clusters in this branch (most often just 2, but sometimes more...)
551 # as.matrix(combn(1:3, 2))
552 # permn(number_of_clusters_in_branch) # this will be 2 most of the time, but this structure allows one to deal with clusters which have more than 2 branches
553 n_permutations <- ncol(branches_permutations)
554
555 for (j in seq_len(n_permutations)) { # would often run just once.
556
557 # choosing the leaves belonging to each of the two clusters
558 ss_leaves1 <- k_cluster_leaves == branches_permutations[1, j]
559 ss_leaves2 <- k_cluster_leaves == branches_permutations[2, j]
560 leaves1 <- leaves_order[ss_leaves1]
561 leaves2 <- leaves_order[ss_leaves2]
562
563 # plot(flip_leaves(dend, leaves1, leaves2))
564 # Flipping the branches of the two adjecent clusters:
565 permutation_indx <- permutation_indx + 1
566 permutated_dend[[permutation_indx]] <- flip_leaves(dend, leaves1, leaves2) # this will not work for hclust (will for dend)
567 }
568 }
569 }
570 return(permutated_dend)
571 }
572
573
574
575
576
577 #' @title Stepwise untangle one tree compared to another
578 #' @export
579 #' @description
580 #' Given a fixed tree and a tree we wish to rotate, this function goes
581 #' through all of the k number of clusters (from 2 onward), and each time
582 #' rotates the branch which was introduced in the new k'th cluster.
583 #' This rotated tree is compared with the fixed tree, and if it has a better
584 #' entanglement, it will be used for the following iterations.
585 #'
586 #' This is a greedy forward selection algorithm for rotating the tree and
587 #' looking for a better match.
588 #'
589 #' This is useful for finding good trees for a \link{tanglegram}.
590 #' @param dend1 a dendrogram object. The one we will rotate to best fit
591 #' dend2_fixed.
592 #' @param dend2_fixed a dendrogram object. This one is kept fixed.
593 #' @param L the distance norm to use for measuring the distance between the
594 #' two trees. It can be any positive number,
595 #' often one will want to use 0, 1, 1.5, 2 (see 'details' in \link{entanglement}).
596 #'
597 #' @param direction a character scalar, either "forward" (default) or "backward".
598 #' Impacts the direction of clustering that are tried. Either from 2 and up
599 #' (in case of "forward"), or from nleaves to down (in case of "backward")
600 #'
601 #' If k_seq is not NULL, then it overrides "direction".
602 #'
603 #' @param k_seq a sequence of k clusters to go through for improving
604 #' dend1. If NULL (default), then we use the "direction" parameter.
605 #'
606 #' @param dend_heights_per_k a numeric vector of values which indicate which height will produce which number of clusters (k)
607 #'
608 #' @param leaves_matching_method a character scalar passed to \link{entanglement}.
609 #' It can be either "order" or "labels" (default). If using "labels",
610 #' then we use the labels for matching the leaves order value.
611 #' And if "order" then we use the old leaves order value for matching the
612 #' leaves order value.
613 #'
614 #' Using "order" is faster, but "labels" is safer. "order" will assume that
615 #' the original two trees had their labels and order values MATCHED.
616 #'
617 #' Hence, it is best to make sure that the trees used here have the same labels
618 #' and the SAME values matched to these values - and then use "order" (for
619 #' fastest results).
620 #'
621 #' If "order" is used, the function first calls \link{match_order_by_labels}
622 #' in order to make sure that the two trees have their labels synced with
623 #' their leaves order values.
624 #'
625 #' @param ... not used
626 #'
627 #' @return A dendlist with
628 #' 1) dend1 after it was rotated to best fit dend2_fixed.
629 #' 2) dend2_fixed.
630 #' @seealso \link{tanglegram}, \link{match_order_by_labels},
631 #' \link{entanglement}, \link{flip_leaves}, \link{all_couple_rotations_at_k},
632 #' \link{untangle_step_rotate_2side}.
633 #'
634 #' @examples
635 #'
636 #' \dontrun{
637 #' dend1 <- USArrests[1:10, ] %>%
638 #' dist() %>%
639 #' hclust() %>%
640 #' as.dendrogram()
641 #' set.seed(3525)
642 #' dend2 <- shuffle(dend1)
643 #' tanglegram(dend1, dend2)
644 #' entanglement(dend1, dend2, L = 2) # 0.4727
645 #'
646 #' dend2_corrected <- untangle_step_rotate_1side(dend2, dend1)[[1]]
647 #' tanglegram(dend1, dend2_corrected) # FIXED.
648 #' entanglement(dend1, dend2_corrected, L = 2) # 0
649 #' }
650 untangle_step_rotate_1side <- function(dend1, dend2_fixed, L = 1.5, direction = c("forward", "backward"),
651 k_seq = NULL, dend_heights_per_k, leaves_matching_method = c("labels", "order"), ...) {
652 # this function gets two dendgrams, and goes over each k splits of the first dend1, and checks if the flip at level k of splitting imporves the entanglement between dend1 and dend2 (Which is fixed)
653 n_leaves <- nleaves(dend1)
654 best_dend <- dend1
655 if (missing(dend_heights_per_k)) dend_heights_per_k <- heights_per_k.dendrogram(best_dend) # since this function takes a looong time, I'm running it here so it will need to run only once!
656
657 leaves_matching_method <- match.arg(leaves_matching_method)
658 if (leaves_matching_method == "order") {
659 old_dend2_fixed <- dend2_fixed
660 dend2_fixed <- match_order_by_labels(old_dend2_fixed, dend1)
661 if (!identical(dend2_fixed, old_dend2_fixed) & dendextend_options("warn")) warning("The leaves order in 'dend2_fixed' were changed. If you want to avoid that, use leaves_matching_method = 'labels'.")
662 }
663
664 direction <- match.arg(direction)
665 if (is.null(k_seq)) {
666 # choose step direction:
667 if (direction == "backward") {
668 k_seq <- n_leaves:2
669 } else { # forward
670 k_seq <- 2:n_leaves
671 }
672 }
673
674
675 for (k in k_seq) {
676 dend1_k_rotated <- all_couple_rotations_at_k(best_dend, k, dend_heights_per_k = dend_heights_per_k)
677 dend1_cut_k_entanglements <- lapply(dend1_k_rotated, entanglement, dend2 = dend2_fixed, L = L, leaves_matching_method = leaves_matching_method)
678 ss_best_dend <- which.min(dend1_cut_k_entanglements)
679 current_best_dend <- dend1_k_rotated[[ss_best_dend]]
680
681 # if this loop's best dendro is not identical to our last best dendro - then we should pick it as the new best dendro
682 # And that means we'll have to update the heights_per_k.dendrogram (which takes time, and we would like to avoid if it is not necessary)
683 if (!identical(current_best_dend, best_dend)) {
684 best_dend <- current_best_dend
685 # We don't need to run the next line twice since the heights per k are the same for any rotated tree...
686 # best_dend_heights_per_k <- heights_per_k.dendrogram(best_dend)
687 } # however, if the current dend is just like our best dend - then there is NO NEED to update heights_per_k.dendrogram (and we just saved some time!!)
688 # this combination is only useful if we have a tree for which there are only a few rotations which are useful
689 }
690
691 return(dendlist(best_dend = best_dend, dend2_fixed = dend2_fixed))
692 }
693
694
695
696
697
698
699
700
701 #' @title Stepwise untangle two trees one at a time
702 #' @export
703 #' @description
704 #' This is a greedy forward selection algorithm for rotating the tree and
705 #' looking for a better match.
706 #'
707 #' This is useful for finding good trees for a \link{tanglegram}.
708 #'
709 #' It goes through rotating dend1, then dend2, and so on - until a locally optimal solution is found.
710 #'
711 #' Similar to "step1side", one tree is held fixed and the other tree is rotated.
712 #' This function goes through all of the k number of clusters (from 2 onward),
713 #' and each time rotates the branch which was introduced in the new k'th cluster.
714 #' This rotated tree is compared with the fixed tree, and if it has a better
715 #' entanglement, it will be used for the following iterations.
716 #' Once finished the rotated tree is held fixed, and the fixed tree
717 #' is now rotated. This continues until a local optimal solution is reached.
718 #'
719 #' @param dend1 a dendrogram object. The one we will rotate to best fit
720 #' dend2.
721 #' @param dend2 a dendrogram object. The one we will rotate to best fit
722 #' dend1.
723 #' @param L the distance norm to use for measuring the distance between the
724 #' two trees. It can be any positive number,
725 #' often one will want to use 0, 1, 1.5, 2 (see 'details' in \link{entanglement}).
726 #'
727 #' @param direction a character scalar, either "forward" (default) or "backward".
728 #' Impacts the direction of clustering that are tried. Either from 2 and up
729 #' (in case of "forward"), or from nleaves to down (in case of "backward")
730 #'
731 #' If k_seq is not NULL, then it overrides "direction".
732 #'
733 #' @param max_n_iterations integer. The maximal number of times to switch between optimizing one tree with another.
734 #' @param print_times logical (TRUE), should we print how many times we switched between rotating the two trees?
735 #' @param k_seq a sequence of k clusters to go through for improving
736 #' dend1. If NULL (default), then we use the "direction" parameter.
737 #' @param ... not used
738 #'
739 #' @return A list with two dendrograms (dend1/dend2),
740 #' after they are rotated to best fit one another.
741 #'
742 #' @seealso \link{tanglegram}, \link{match_order_by_labels},
743 #' \link{entanglement}, \link{flip_leaves}, \link{all_couple_rotations_at_k}.
744 #' \link{untangle_step_rotate_1side}.
745 #' @examples
746 #'
747 #' \dontrun{
748 #' dend1 <- USArrests[1:20, ] %>%
749 #' dist() %>%
750 #' hclust() %>%
751 #' as.dendrogram()
752 #' dend2 <- USArrests[1:20, ] %>%
753 #' dist() %>%
754 #' hclust(method = "single") %>%
755 #' as.dendrogram()
756 #' set.seed(3525)
757 #' dend2 <- shuffle(dend2)
758 #' tanglegram(dend1, dend2, margin_inner = 6.5)
759 #' entanglement(dend1, dend2, L = 2) # 0.79
760 #'
761 #' dend2_corrected <- untangle_step_rotate_1side(dend2, dend1)
762 #' tanglegram(dend1, dend2_corrected, margin_inner = 6.5) # Good.
763 #' entanglement(dend1, dend2_corrected, L = 2) # 0.0067
764 #' # it is better, but not perfect. Can we improve it?
765 #'
766 #' dend12_corrected <- untangle_step_rotate_2side(dend1, dend2)
767 #' tanglegram(dend12_corrected[[1]], dend12_corrected[[2]], margin_inner = 6.5) # Better...
768 #' entanglement(dend12_corrected[[1]], dend12_corrected[[2]], L = 2) # 0.0045
769 #'
770 #'
771 #' # best combination:
772 #' dend12_corrected_1 <- untangle_random_search(dend1, dend2)
773 #' dend12_corrected_2 <- untangle_step_rotate_2side(dend12_corrected_1[[1]], dend12_corrected_1[[2]])
774 #' tanglegram(dend12_corrected_2[[1]], dend12_corrected_2[[2]], margin_inner = 6.5) # Better...
775 #' entanglement(dend12_corrected_2[[1]], dend12_corrected_2[[2]], L = 2) # 0 - PERFECT.
776 #' }
777 untangle_step_rotate_2side <- function(dend1, dend2, L = 1.5, direction = c("forward", "backward"), max_n_iterations = 10L, print_times = dendextend_options("warn"),
778 k_seq = NULL, ...) {
779 # this function gets two dendgrams, and orders dend1 and 2 until a best entengelment is reached.
780
781 direction <- match.arg(direction)
782
783 dend1_heights_per_k <- heights_per_k.dendrogram(dend1)
784 dend2_heights_per_k <- heights_per_k.dendrogram(dend2)
785
786 # Next, let's try to improve upon this tree using a forwared rotation of our tree:
787 dend1_better <- untangle_step_rotate_1side(dend1, dend2, L = L, dend_heights_per_k = dend1_heights_per_k, direction = direction, k_seq = k_seq)[[1]]
788 dend2_better <- untangle_step_rotate_1side(dend2, dend1_better, L = L, dend_heights_per_k = dend2_heights_per_k, direction = direction, k_seq = k_seq)[[1]]
789
790 entanglement_new <- entanglement(dend1_better, dend2_better, L = L)
791 entanglement_old <- entanglement_new + 1
792
793 times <- 1
794
795 while (times < max_n_iterations & !identical(entanglement_new, entanglement_old)) { # if we got an improvement from last entaglement, we'll keep going!
796 entanglement_old <- entanglement_new
797
798 dend1_better_loop <- untangle_step_rotate_1side(dend1_better, dend2_better,
799 L = L,
800 dend_heights_per_k = dend1_heights_per_k, direction = direction, k_seq = k_seq
801 )[[1]]
802 # if the new dend1 is just like we just had - then we can stop the function since we found the best solution - else - continue
803 if (identical(dend1_better_loop, dend1_better)) {
804 break
805 } else {
806 dend1_better <- dend1_better_loop
807 }
808
809 # if the new dend2 is just like we just had - then we can stop the function since we found the best solution - else - continue
810 dend2_better_loop <- untangle_step_rotate_1side(dend2_better, dend1_better,
811 L = L,
812 dend_heights_per_k = dend2_heights_per_k, direction = direction, k_seq = k_seq
813 )[[1]]
814 if (identical(dend2_better_loop, dend2_better)) {
815 break
816 } else {
817 dend2_better <- dend2_better_loop
818 }
819
820 entanglement_new <- entanglement(dend1_better, dend2_better, L = L)
821 times <- times + 1
822 }
823
824 # identical(1,1+.00000000000000000000000001) # T
825 if (print_times) cat("\nWe ran untangle ", times, " times\n")
826
827 return(dendlist(dend1_better, dend2_better))
828 }
829
830
831
832
833 #' @title Stepwise untangle two trees at the same time
834 #' @export
835 #' @description
836 #' This is a greedy forward selection algorithm for rotating the tree and
837 #' looking for a better match.
838 #'
839 #' This is useful for finding good trees for a \link{tanglegram}.
840 #'
841 #' It goes through simultaneously rotating branches of dend1 and dend2
842 #' until a locally optimal solution is found.
843 #'
844 #'
845 #' Step 1: The algorithm begins by executing the 'step2side' operation on the pair
846 #' of dendograms.
847 #'
848 #' Step 2: The algorithm generates new alternative tanglegrams by simultaneously
849 #' rotating one branch from tree 1 and one branch from tree 2. This rotation is
850 #' applied to every possible combination of branches between tree 1 and tree 2,
851 #' resulting in a set of new alternative tanglegrams. The tanglegram with the lowest
852 #' entanglement is retained.
853 #'
854 #' Step 3: Steps 1 and 2 are repeated until either a locally optimal solution is
855 #' found or the maximum number of iterations is reached.
856 #'
857 #' @param dend1 a dendrogram object. The one we will rotate to best fit
858 #' dend2.
859 #' @param dend2 a dendrogram object. The one we will rotate to best fit
860 #' dend1.
861 #' @param L the distance norm to use for measuring the distance between the
862 #' two trees. It can be any positive number,
863 #' often one will want to use 0, 1, 1.5, 2 (see 'details' in \link{entanglement}).
864 #'
865 #' @param max_n_iterations integer. The maximal number of times to switch between optimizing one tree with another.
866 #' @param print_times logical (TRUE), should we print how many times we executed steps 1 and 2?
867 #' @param ... not used
868 #'
869 #' @return A list with two dendrograms (dend1/dend2),
870 #' after they are rotated to best fit one another.
871 #'
872 #' @seealso \link{tanglegram}, \link{match_order_by_labels},
873 #' \link{entanglement}, \link{flip_leaves}, \link{all_couple_rotations_at_k}.
874 #' \link{untangle_step_rotate_1side}, \link{untangle_step_rotate_2side}.
875 #' @references
876 #' Nghia Nguyen, Kurdistan Chawshin, Carl Fredrik Berg, Damiano Varagnolo, Shuffle & untangle: novel untangle methods for solving the tanglegram layout problem, Bioinformatics Advances, Volume 2, Issue 1, 2022, vbac014, https://doi.org/10.1093/bioadv/vbac014
877 #'
878 #' @examples
879 #'
880 #' \dontrun{
881 #' # Figures recreated from 'Shuffle & untangle: novel untangle
882 #' # methods for solving the tanglegram layout problem' (Nguyen et al. 2022)
883 #' library(tidyverse)
884 #' example_labels <- c("Versicolor 90", "Versicolor 54", "Versicolor 81",
885 #' "Versicolor 63", "Versicolor 72", "Versicolor 99", "Virginica 135",
886 #' "Virginica 117", "Virginica 126", "Virginica 108", "Virginica 144",
887 #' "Setosa 27", "Setosa 18", "Setosa 36", "Setosa 45", "Setosa 9")
888 #'
889 #' iris_modified <-
890 #' iris %>%
891 #' mutate(Row = row_number()) %>%
892 #' mutate(Label = paste(str_to_title(Species), Row)) %>%
893 #' filter(Label %in% example_labels)
894 #' iris_numeric <- iris_modified[,1:4]
895 #' rownames(iris_numeric) <- iris_modified$Label
896 #'
897 #' # Single Linkage vs. Complete Linkage comparison (Fig. 1)
898 #' dend1 <- as.dendrogram(hclust(dist(iris_numeric), method = "single"))
899 #' dend2 <- as.dendrogram(hclust(dist(iris_numeric), method = "complete"))
900 #' tanglegram(dend1, dend2,
901 #' color_lines = TRUE,
902 #' lwd = 2,
903 #' margin_inner = 6) # Good.
904 #' entanglement(dend1, dend2, L = 2) # 0.207
905 #'
906 #' # The step2side algorithm (Fig. 2)
907 #' result <- untangle_step_rotate_2side(dend1, dend2)
908 #' tanglegram(result[[1]], result[[2]],
909 #' color_lines = TRUE,
910 #' lwd = 2,
911 #' margin_inner = 6) # Better...
912 #' entanglement(result[[1]], result[[2]], L = 2) # 0.185
913 #'
914 #' # The stepBothSides algorithm (Fig. 4)
915 #' result <- untangle_step_rotate_both_side(dend1, dend2)
916 #' tanglegram(result[[1]], result[[2]],
917 #' color_lines = TRUE,
918 #' lwd = 2,
919 #' margin_inner = 6,
920 #' lty = 1) # PERFECT.
921 #' entanglement(result[[1]], result[[2]], L = 2) # 0.000
922 #' }
923 untangle_step_rotate_both_side <- function(dend1, dend2, L = 1.5, max_n_iterations = 10L, print_times = dendextend_options("warn"), ...) {
924 # Implemented as described by pseudo-code in the paper 'Shuffle & untangle: novel untangle methods for solving the tanglegram layout problem' (Nguyen et al. 2022)
925
926 # Initialize placeholder values to be overwritten in first iteration
927 entanglement_new <- 0
928 entanglement_old <- 1
929
930 # Step 3: Repeat Steps 1 and 2 until the entanglement does not reduce any further
931 times <- 1
932 while (times < max_n_iterations & !identical(entanglement_new, entanglement_old)) {
933
934 # Step 1: Run the step2side algorithm until convergence
935 result <- untangle_step_rotate_2side(dend1, dend2, L = L, max_n_iterations = max_n_iterations, ...)
936 dend1 <- result[[1]]
937 dend2 <- result[[2]]
938
939 entanglement_old <- entanglement_new # Record best entanglement score from last iteration
940 entanglement_new <- entanglement(dend1, dend2, L = L)
941
942 # Step 2: Create new alternative tanglegrams by rotating both dendrograms simultaneously
943 n_leaves <- nleaves(dend1)
944 for (i in 1:(n_leaves - 1)) {
945 for (j in 1:(n_leaves - 1)) {
946 dend1_rotated <- suppressWarnings(rotate(dend1, i))
947 dend2_rotated <- suppressWarnings(rotate(dend2, j))
948 new_entanglement <- entanglement(dend1_rotated, dend2_rotated, L = L)
949
950 if (new_entanglement < entanglement_new) {
951 dend1 <- dend1_rotated
952 dend2 <- dend2_rotated
953 entanglement_new <- new_entanglement
954 }
955
956 }
957 }
958
959 times <- times + 1
960 }
961
962 if (print_times) cat("\nWe ran untangle ", times, " times\n")
963
964 return(dendlist(dend1, dend2))
965 }
966
967
968
969
970
971
972
973
974
975 ##### Other attempts which have not
976 ##### proven themselves as useful...
977
978
979
980
981
982
983 #
984 # untangle.forward.step.rotate.1side <- function(dend1, dend2_fixed) {
985 # # this function gets two dendgrams, and goes over each k splits of the first dend1, and checks if the flip at level k of splitting imporves the entanglement between dend1 and dend2 (Which is fixed)
986 # leaves_order <- order.dendrogram(dend1)
987 # best_dend <- dend1
988 #
989 # k_visited <- rep(F, length(leaves_order))
990 # k_visited[1] <- T # I don't need the first one
991 # k <- 1
992 #
993 # while(!all(k_visited)) {
994 # # create all of the rotations with k+-1:
995 # dend1_k_p1_rotated <- all_couple_rotations_at_k(best_dend, k+1)
996 # dend1_k_m1_rotated <- all_couple_rotations_at_k(best_dend, k-1)
997 # # find the enteglement for all of them:
998 # dend1_cut_k_p1_entanglements <- lapply(dend1_k_p1_rotated, entanglement, dend2 = dend2_fixed)
999 # dend1_cut_k_m1_entanglements <- lapply(dend1_k_m1_rotated, entanglement, dend2 = dend2_fixed)
1000 # # what is best, forward or backward?
1001 # if(min(dend1_cut_k_p1_entanglements) > min(dend1_cut_k_m1_entanglements)) {
1002 #
1003 # }
1004 # k <- k + 1
1005 # ss_best_dend <- which.min(dend1_cut_k_entanglements)
1006 # best_dend <- dend1_k_rotated[[ss_best_dend]]
1007 #
1008 # all_couple_rotations_at_k(best_dend, -1)
1009 # }
1010 #
1011 # return(best_dend)
1012 # }
1013
1014
1015 # dend12s_1_better <- untangle_step_rotate_1side(dend1, dend2)
1016 # cutree(dend1, 10)
1017
1018
1019
1020
1021 # evolution algorithm
1022 untangle_intercourse <- function(brother_1_dend1, brother_1_dend2,
1023 sister_2_dend1, sister_2_dend2, L = 1) {
1024 # Gets two pairs of dend, and returns two childrens (inside a list)
1025 children_1 <- untangle_step_rotate_2side(brother_1_dend1, brother_1_dend2, L = L)
1026 children_2 <- untangle_step_rotate_2side(sister_2_dend1, sister_2_dend2, L = L)
1027
1028 dendlist(children_1, children_2)
1029 }
1030
1031 entanglement_return_best_brother <- function(brother_1_dend1, brother_1_dend2,
1032 brother_2_dend1, brother_2_dend2, L = 1) {
1033 # Gets two pairs of dend, and returns the pair with the best (minimal) entanglement
1034
1035 if (entanglement(brother_1_dend1, brother_1_dend2, L = L) <
1036 entanglement(brother_2_dend1, brother_2_dend2, L = L)) {
1037 return(dendlist(brother_1_dend1, brother_1_dend2))
1038 } else {
1039 return(dendlist(brother_2_dend1, brother_2_dend2))
1040 }
1041 }
1042
1043 untangle_intercourse_evolution <- function(intercourse, L = 1) {
1044 # intercourse is a list with two elements. Each element has two dends
1045 entanglement_return_best_brother(intercourse[[1]], intercourse[[2]],
1046 intercourse[[3]], intercourse[[4]],
1047 L = L
1048 )
1049 }
1050
1051
1052 untangle_evolution <- function(brother_1_dend1, brother_1_dend2,
1053 sister_2_dend1, sister_2_dend2, L = 1) {
1054 intercourse <- untangle_intercourse(brother_1_dend1, brother_1_dend2,
1055 sister_2_dend1, sister_2_dend2,
1056 L = L
1057 ) # creates a list with two pairs of dends
1058 untangle_intercourse_evolution(intercourse, L = L) # returns the best child
1059 }
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070 ####
1071 # A new approuch - I will go through every possible flip on one side, and find the one that gives the best improvement.
1072 # I will do the same on each tree, back and forth, until no better flip is found.
1073
1074 untangle_best_k_to_rotate_by_1side <- function(dend1, dend2_fixed, L = 1) {
1075 # this function gets two dendgrams, and goes over each k splits of the first dend1, and checks if the flip at level k of splitting imporves the entanglement between dend1 and dend2 (Which is fixed)
1076 leaves_order <- order.dendrogram(dend1)
1077 best_dend <- dend1
1078 dend1_k_rotated <- NULL
1079
1080 best_dend_heights_per_k <- heights_per_k.dendrogram(best_dend) # since this function takes a looong time, I'm running it here so it will need to run only once!
1081 # this makes the function about twice as fast...
1082
1083 for (k in 2:length(leaves_order)) {
1084 dend1_k_rotated <- c(
1085 dend1_k_rotated,
1086 all_couple_rotations_at_k(best_dend, k,
1087 dend_heights_per_k = best_dend_heights_per_k
1088 )
1089 )
1090 }
1091
1092 dend1_cut_k_entanglements <- lapply(dend1_k_rotated, entanglement, dend2 = dend2_fixed, L = L)
1093 ss_best_dend <- which.min(dend1_cut_k_entanglements)
1094 best_dend <- dend1_k_rotated[[ss_best_dend]]
1095 return(best_dend)
1096 }
1097
1098
1099
1100 flip_1_and_2 <- function(x) {
1101 ifelse(x == 1, 2, 1)
1102 }
1103
1104 untangle_best_k_to_rotate_by_2side_backNforth <- function(dend1, dend2, times_to_stop = 2, print_times = T, L = 1) {
1105 # this function gets two dendgrams, and orders dend1 and then 2 and then 1 again - back and forth -until a best entengelment is reached.
1106
1107 was_improved <- T # e.g: we can improve it further
1108 counter <- 1
1109
1110 while (was_improved) {
1111 entanglement_old <- entanglement(dend1, dend2, L = L)
1112 dend1 <- untangle_best_k_to_rotate_by_1side(dend1, dend2, L = L)
1113 dend2 <- untangle_best_k_to_rotate_by_1side(dend2, dend1, L = L)
1114 entanglement_new <- entanglement(dend1, dend2, L = L)
1115 was_improved <- identical(entanglement_old, entanglement_new)
1116 counter <- counter + 1
1117 }
1118 # identical(1,1+.00000000000000000000000001) # T
1119 if (print_times) cat("We ran untangle_best_k_to_rotate_by_2side_backNforth ", counter, " times")
1120
1121 return(dendlist(dend1, dend2))
1122 }
1123
1124
1125
1126 #
1127 #
1128 # untangle_OLO <- function(dend1, dend2, ...) {
1129 #
1130 # if(is.dendlist(dend1)) {
1131 # dend2 <- dend1[[2]]
1132 # dend1 <- dend1[[1]]
1133 # }
1134 #
1135 # # hmap(sqrt(d2), Colv = "none", trace = "none", col = viridis(200))
1136 # # Error in (function (x, Rowv = TRUE, Colv = if (symm) "Rowv" else TRUE, :
1137 # # formal argument "Colv" matched by multiple actual arguments
1138 # # d <- cophenetic(dend2) # doesn't work so great
1139 #
1140 # vec <- cbind(order.dendrogram(dend1), order.dendrogram(dend2))
1141 # rownames(vec) <- labels(dend1)[order.dendrogram(dend1)]
1142 # d <- dist(vec)
1143 # o <- seriate(d, method = "OLO", control = list(hclust = as.hclust(dend1)) )
1144 # dend1 <- rotate(dend1, order = rev(labels(d)[get_order(o)]))
1145 # # library(dendextend)
1146 # # o <- seriate(d, method = "OLO", control = list(hclust = as.hclust(dend2)) )
1147 # # dend2 <- rotate(dend2, order = labels(d)[get_order(o)])
1148 # return(dendlist(dend1, dend2))
1149 # }
1150 #
1151 #
1152 #
1153 # if(F) {
1154 # ## Not run:
1155 # require(dendextend)
1156 # set.seed(23235)
1157 # ss <- sample(1:150, 10 )
1158 # dend1 <- iris[ss,-5] %>% dist %>% hclust("com") %>% as.dendrogram
1159 # dend2 <- iris[ss,-5] %>% dist %>% hclust("sin") %>% as.dendrogram
1160 # dend12 <- dendlist(dend1, sort(dend2, type = "nodes", decreasing= T))
1161 # # dend12 <- dendlist(dend1, sort(dend1))
1162 # dend12 %>% tanglegram
1163 # dend12_OLO <- untangle_OLO(dend12)
1164 # dend12_OLO %>% tanglegram
1165 # dend12_OLO %>% sort(type = "nodes") %>% tanglegram
1166 #
1167 # }
1168
1169
1170 #
1171 # if(F) {
1172 # # example
1173 # dist_DATA <- dist(USArrests[1:20,])
1174 # # First two dummy clusters (since you didn't provide with some...)
1175 # hc1 <- hclust(dist_DATA , "single")
1176 # hc2 <- hclust(dist_DATA , "complete")
1177 # dend1 <- as.dendrogram(hc1)
1178 # dend2 <- as.dendrogram(hc2)
1179 # entanglement(dend1, dend2)
1180 #
1181 # system.time(dend12_best_01 <- untangle_step_rotate_2side(dend1, dend2, L = 2)) # 0.47 sec
1182 # system.time(dend12_best_02 <- untangle_best_k_to_rotate_by_2side_backNforth(dend1, dend2, L = 2)) # 0.44 sec
1183 # tanglegram(dend1, dend2)
1184 # tanglegram(dend12_best_01[[1]], dend12_best_01[[2]])
1185 # tanglegram(dend12_best_02[[1]], dend12_best_02[[2]])
1186 # }
1187 #
1188 #
1189 #
1190 #
1191 #
1192 #
1193 #
1194 #
1195 # richrach <- function(x) {
1196 # # move back and forth between the beginning and the end of a vector
1197 # c(t(cbind(x, rev(x))))[1:length(x)]
1198 # # example:
1199 # # richrach(1:6)
1200 # # from this: 1 2 3 4 5 6
1201 # # to this: 1 6 2 5 3 4
1202 # }
1203 #
1204 # richrach_xy <- function(x,y) {
1205 # # move back and forth between the beginning and the end of a vector
1206 # c(t(cbind(x, y)))[1:length(x)]
1207 # # example:
1208 # # richrach(1:6)
1209 # # from this: 1 2 3 4 5 6
1210 # # to this: 1 6 2 5 3 4
1211 # }
1212 #
1213 #
1214 # odd_locations <- function(x) {
1215 # x[seq(1, length(x), by = 2)]
1216 # }
1217 # # odd_locations(1:6)
1218 #
1219 # #
1220 # #
1221 # # if(FALSE) {
1222 # #
1223 # # dist_DATA <- dist(USArrests[1:30,])
1224 # # dist_DATA <- dist(USArrests[1:10,])
1225 # # # First two dummy clusters (since you didn't provide with some...)
1226 # # hc1 <- hclust(dist_DATA , "single")
1227 # # hc2 <- hclust(dist_DATA , "complete")
1228 # # dend1 <- as.dendrogram(hc1)
1229 # # dend2 <- as.dendrogram(hc2)
1230 # #
1231 # # tanglegram(dend1, dend2)
1232 # # entanglement(dend1, dend2) # 0.8
1233 # #
1234 # # # after sorting we get a better measure of entanglement and also a better looking plot
1235 # # tanglegram(sort(dend1), sort(dend2))
1236 # # entanglement(sort(dend1), sort(dend2)) # 0.1818
1237 # #
1238 # # # let's cause some shuffle... (e.g: mix the dendrogram, and see how that effects the outcome)
1239 # # set.seed(134)
1240 # # s_dend1 <- shuffle(dend1)
1241 # # s_dend2 <- shuffle(dend2)
1242 # # tanglegram(s_dend1, s_dend2)
1243 # # entanglement(s_dend1, s_dend2) # 0.7515
1244 # #
1245 # #
1246 # # set.seed(1234)
1247 # # dend12s <- untangle.random.search(dend1, dend2, R = 10)
1248 # # entanglement(dend12s[[1]], dend12s[[2]]) # 0.042
1249 # # tanglegram(dend12s[[1]], dend12s[[2]]) #
1250 # # # this is a case where it is CLEAR that the simplest heuristic would improve this to 0 entanglement...
1251 # #
1252 # # # let's see if we can reach a good solution using a greedy forward selection algorithm
1253 # # dend12s_1_better <- untangle_step_rotate_1side(dend12s[[1]], dend12s[[2]])
1254 # # entanglement(dend12s_1_better, dend12s[[2]]) # from 0.042 to 0.006 !!
1255 # # tanglegram(dend12s_1_better, dend12s[[2]]) #
1256 # #
1257 # # # let's see from the beginning
1258 # # entanglement(dend1, dend2) # 0.6
1259 # # tanglegram(dend1, dend2) # 0.6
1260 # # dend12s_1_better <- untangle_step_rotate_1side(dend1, dend2)
1261 # # entanglement(dend12s_1_better, dend2) # from 0.6 to 0.036
1262 # # tanglegram(dend12s_1_better, dend2) #
1263 # # # let's try the other side:
1264 # # dend12s_2_better <- untangle_step_rotate_1side(dend2, dend12s_1_better)
1265 # # entanglement(dend12s_1_better, dend12s_2_better) # no improvment
1266 # #
1267 # #
1268 # #
1269 # # dend2_01 <- untangle_step_rotate_1side(dend2, dend1)
1270 # # dend2_02 <- untangle.backward.rotate.1side(dend2, dend1)
1271 # # dend2_03 <- untangle.backward.rotate.1side(dend2_01, dend1)
1272 # # dend2_04 <- untangle_step_rotate_1side(dend2_02, dend1)
1273 # # dend2_05 <- untangle_evolution(dend1, dend2 , dend1, dend2_01 )
1274 # # entanglement(dend1, dend2)
1275 # # entanglement(dend1, dend2_01)
1276 # #
1277 # # entanglement(dend1, dend2_02)
1278 # # entanglement(dend1, dend2_03)
1279 # # entanglement(dend1, dend2_04)
1280 # # entanglement(dend2_05[[1]], dend2_05[[2]])
1281 # # tanglegram(dend1, dend2)
1282 # # tanglegram(dend1, dend2_01)
1283 # # tanglegram(dend1, dend2_02)
1284 # # tanglegram(dend1, dend2_03)
1285 # # tanglegram(dend1, dend2_04)
1286 # # tanglegram(dend2_05[[1]], dend2_05[[2]])
1287 # #
1288 # #
1289 # #
1290 # # entanglement(dend1, dend2)
1291 # # tanglegram(dend1, dend2)
1292 # # dend2_01 <- untangle_step_rotate_1side(dend2, dend1)
1293 # # dend2_01 <- untangle.backward.rotate.1side(dend2, dend1)
1294 # # tanglegram(dend1, dend2_01)
1295 # #
1296 # #
1297 # #
1298 # # #
1299 # # dist_DATA <- dist(USArrests[1:10,])
1300 # # # First two dummy clusters (since you didn't provide with some...)
1301 # # hc1 <- hclust(dist_DATA , "single")
1302 # # hc2 <- hclust(dist_DATA , "complete")
1303 # # dend1 <- as.dendrogram(hc1)
1304 # # dend2 <- as.dendrogram(hc2)
1305 # # dend1_01 <- untangle_step_rotate_1side(dend1, dend2)
1306 # # entanglement(dend1, dend2)
1307 # # entanglement(dend1_01, dend2)
1308 # # tanglegram(dend1, dend2)
1309 # # tanglegram(dend1_01, dend2)
1310 # #
1311 # # system.time(dend1_01 <- untangle_step_rotate_1side(dend1, dend2)) # 0.47 sec
1312 # # system.time(dend1_01 <- untangle.best.k.to.rotate.by(dend1, dend2)) # 0.44 sec
1313 # # tanglegram(dend1, dend2)
1314 # # tanglegram(dend1_01, dend2)
1315 # #
1316 # #
1317 # #
1318 # #
1319 # # #### profiling
1320 # # library(profr)
1321 # # slow_dude <- profr(untangle_step_rotate_1side(dend2, dend1))
1322 # # head(slow_dude)
1323 # # summary(slow_dude)
1324 # # plot(slow_dude)
1325 # #
1326 # # library(reshape)
1327 # # a <- cast(slow_dude, f~., value="time", fun.aggregate=c(length, sum))
1328 # # a[order(a[,3]),]
1329 # # ## End(Not run)
1330 # # slow_dude[slow_dude$time > .079991, ]
1331 # #
1332 # #
1333 # # # this also helped:
1334 # # # install.packages("microbenchmark")
1335 # # library(microbenchmark)
1336 # #
1337 # # system.time(entanglement(dend1, dend2) ) # 0.01
1338 # # microbenchmark( entanglement(dend1, dend2) , times = 10 )# so this is 10 times faster (the medians)
1339 # # # betweem 0.011 to 0.038
1340 # #
1341 # # }
1342 # #
1343 # #
1344 # #
1345 # #
1346 # #
1347 # #
1348 # # if(FALSE){
1349 # #
1350 # # # Finding the BEST tree by going through many random seeds and looking for a good solution :)
1351 # #
1352 # # entanglement_history <- c()
1353 # #
1354 # #
1355 # # get.seed <- function(max_lengh = 10e7) round(runif(1)*max_lengh)
1356 # #
1357 # # best_seed <- 28754448 # 55639690 # 5462457 # 75173309 # 20295644
1358 # # set.seed(best_seed)
1359 # # times_a_better_seed_was_found <- 0
1360 # # random_dendros <- untangle.random.search(yoavs_tree, Dan_arc_tree, R = 1, L = 1.5)
1361 # # rotated_dendros <- untangle_step_rotate_2side(random_dendros[[1]], random_dendros[[2]], L = 1.5)
1362 # # best_entanglement <- entanglement(rotated_dendros[[1]], rotated_dendros[[2]], L = 1.5)
1363 # # # tanglegram(rotated_dendros[[1]], rotated_dendros[[2]])
1364 # #
1365 # #
1366 # # for(i in 1:100000) {
1367 # # print(i)
1368 # # current_seed <- get.seed()
1369 # # set.seed(current_seed)
1370 # # random_dendros <- untangle.random.search(yoavs_tree, Dan_arc_tree, R = 10, L = 1.5)
1371 # # rotated_dendros <- untangle_step_rotate_2side(random_dendros[[1]], random_dendros[[2]], L = 1.5)
1372 # # new_entanglement <- entanglement(rotated_dendros[[1]], rotated_dendros[[2]], L = 1.5)
1373 # #
1374 # # entanglement_history <- c(entanglement_history, new_entanglement)
1375 # #
1376 # # if(new_entanglement < best_entanglement ){
1377 # # times_a_better_seed_was_found <- times_a_better_seed_was_found + 1
1378 # # best_seed <- current_seed
1379 # # print(best_seed)
1380 # # print(new_entanglement)
1381 # # best_entanglement <- new_entanglement
1382 # # tanglegram(rotated_dendros[[1]], rotated_dendros[[2]])
1383 # # }
1384 # # flush.console()
1385 # # }
1386 # #
1387 # #
1388 # # hist(entanglement_history)
1389 # #
1390 # # }
1391 # #
1392 # #
1393 # #
1394 # #
1395 # #
1396 #
1397 #
1398 #
1399 #
1400 #
1401 #
1402 # # this function is from the combinat package
1403 # # permn <- function (x, fun = NULL, ...)
1404 # # {
1405 # # if (is.numeric(x) && length(x) == 1 && x > 0 && trunc(x) ==
1406 # # x)
1407 # # x <- seq(x)
1408 # # n <- length(x)
1409 # # nofun <- is.null(fun)
1410 # # out <- vector("list", gamma(n + 1))
1411 # # p <- ip <- seqn <- 1:n
1412 # # d <- rep(-1, n)
1413 # # d[1] <- 0
1414 # # m <- n + 1
1415 # # p <- c(m, p, m)
1416 # # i <- 1
1417 # # use <- -c(1, n + 2)
1418 # # while (m != 1) {
1419 # # out[[i]] <- if (nofun)
1420 # # x[p[use]]
1421 # # else fun(x[p[use]], ...)
1422 # # i <- i + 1
1423 # # m <- n
1424 # # chk <- (p[ip + d + 1] > seqn)
1425 # # m <- max(seqn[!chk])
1426 # # if (m < n)
1427 # # d[(m + 1):n] <- -d[(m + 1):n]
1428 # # index1 <- ip[m] + 1
1429 # # index2 <- p[index1] <- p[index1 + d[m]]
1430 # # p[index1 + d[m]] <- m
1431 # # tmp <- ip[index2]
1432 # # ip[index2] <- ip[m]
1433 # # ip[m] <- tmp
1434 # # }
1435 # # out
1436 # # }
1437 # #
1438 #
1439 #
1440 # #
1441 # #
1442 # #
1443 # # order.weights.by.cluster.order <- function(weights, cluster_id, new_cluster_order) {
1444 # # # this function gets a vector of weights. The clusters each weight belongs to
1445 # # # and a new order for the clusters
1446 # # # and outputs the new weight vector after ordering the vector by the new order of the cluster (internal order of elements within each cluster is preserved)
1447 # # output <- NULL
1448 # # for(i in seq_along(new_cluster_order)) {
1449 # # output <- c(output, weights[cluster_id == new_cluster_order[i]])
1450 # # }
1451 # # return(output)
1452 # # }
1453 # # if(F){
1454 # # # example:
1455 # # x = c(1,2,3,4,5,6)
1456 # # ord1 = c(1,1,2,2,2,3)
1457 # # ord_of_clusters = c(2,1,3)
1458 # # c(x[ord1 == ord_of_clusters[1]],x[ord1 == ord_of_clusters[2]],x[ord1 == ord_of_clusters[3]])
1459 # # order.weights.by.cluster.order(x, ord1, ord_of_clusters)
1460 # # }
1461 #
1462 #
1463 #
1464 #
1465 #
1466 #