Debian Codegraph @

R/entanglement.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
25
26
27
28
29 #' @title Adjust the order of one dendrogram based on another (using labels)
30 #' @export
31 #' @description
32 #' Takes one dendrogram and adjusts its order leaves valeus based on the order
33 #' of another dendrogram. The values are matached based on the labels of the
34 #' two dendrograms.
35 #'
36 #' This allows for faster \link{entanglement} running time, since we can be
37 #' sure that the leaves order is just as using their labels.
38 #'
39 #' @param dend_change tree object (dendrogram)
40 #' @param dend_template tree object (dendrogram)
41 #' @param check_that_labels_match logical (TRUE). If to check that the labels
42 #' in the two dendrogram match. (if they do not, the function aborts)
43 #' @return Returns dend_change after adjusting its order values to
44 #' be like dend_template.
45 #' @seealso \link{entanglement} , \link{tanglegram}
46 #' @examples
47 #' \dontrun{
48 #'
49 #' dend <- USArrests[1:4, ] %>%
50 #' dist() %>%
51 #' hclust() %>%
52 #' as.dendrogram()
53 #' order.dendrogram(dend) # c(4L, 3L, 1L, 2L)
54 #'
55 #' dend_changed <- dend
56 #' order.dendrogram(dend_changed) <- 1:4
57 #' order.dendrogram(dend_changed) # c(1:4)
58 #'
59 #' # now let's fix the order of the new object to be as it was:
60 #' dend_changed <- match_order_by_labels(dend_changed, dend)
61 #' # these two are now the same:
62 #' order.dendrogram(dend_changed)
63 #' order.dendrogram(dend)
64 #' }
65 match_order_by_labels <- function(dend_change, dend_template, check_that_labels_match = TRUE) {
66
67 # let's put the leaves' numbers and labels in two data.frames
68 # tree_to_change_labels_order <- data.frame(labels = labels(dend_change), values = order.dendrogram(dend_change))
69 # tree_template_labels_order <- data.frame(labels = labels(dend_template), values = order.dendrogram(dend_template))
70 tree_to_change_labels <- labels(dend_change)
71 tree_template_labels <- labels(dend_template)
72
73 if (check_that_labels_match) {
74 if (!identical(sort(tree_to_change_labels), sort(tree_template_labels))) {
75 stop("labels do not match in both trees. Please make sure to fix the labels names!
76 (make sure also that the labels of BOTH trees are 'character')")
77 }
78 }
79
80 tree_template_order <- order.dendrogram(dend_template)
81
82 # this gives us how to order y so it would be in the order of x.
83 # y_to_order_like_x <- c(2,3,1,4)
84 # y_to_order_like_x[match(c(1:4), y_to_order_like_x)]
85 # I want to order the numbers in yoav_tree so that they would match the needed order in dans_tree
86
87 ss_order_change_leaf_numbers_to_match_template <- match(x = tree_to_change_labels, table = tree_template_labels)
88 tree_new_leaf_numbers <- tree_template_order[ss_order_change_leaf_numbers_to_match_template]
89 order.dendrogram(dend_change) <- tree_new_leaf_numbers
90
91 return(dend_change)
92 }
93
94
95
96
97
98
99 #' @title Adjust the order of one dendrogram based on another (using order)
100 #' @export
101 #' @description
102 #' Takes one dendrogram and adjusts its order leaves valeus based on the order
103 #' of another dendrogram. The values are matached based on the order of the
104 #' two dendrograms.
105 #'
106 #' This allows for faster \link{entanglement} running time, since we can be
107 #' sure that the leaves order is just as using their labels.
108 #'
109 #' This is a function is FASTER than \link{match_order_by_labels}, but it
110 #' assumes that the order and the labels of the two trees are matching!!
111 #'
112 #' This will allow for a faster calculation of \link{entanglement}.
113 #'
114 #' @param dend_change tree object (dendrogram)
115 #' @param dend_template tree object (dendrogram)
116 #' @param dend_change_old_order a numeric vector with the order of leaves in
117 #' dend_change (at least before it was changes for some reason).
118 #' This is the vector based on which we adjust the new values of dend_change.
119 #' @param check_that_labels_match logical (FALSE). If to check that the labels
120 #' in the two dendrogram match. (if they do not, the function aborts)
121 #' @param check_that_leaves_order_match logical (FALSE). If to check that
122 #' the order in the two dendrogram match. (if they do not, the function aborts)
123 #'
124 #' @return Returns dend_change after adjusting its order values to
125 #' be like dend_template.
126 #' @seealso \link{entanglement} , \link{tanglegram},
127 #' \link{match_order_by_labels}
128 #' @examples
129 #' \dontrun{
130 #'
131 #' dend <- USArrests[1:4, ] %>%
132 #' dist() %>%
133 #' hclust() %>%
134 #' as.dendrogram()
135 #' order.dendrogram(dend) # c(4L, 3L, 1L, 2L)
136 #'
137 #'
138 #' # Watch this!
139 #' dend_changed <- dend
140 #' dend_changed <- rev(dend_changed)
141 #' expect_false(identical(order.dendrogram(dend_changed), order.dendrogram(dend)))
142 #' # we keep the order of dend_change, so that the leaves order are synced
143 #' # with their labels JUST LIKE dend:
144 #' old_dend_changed_order <- order.dendrogram(dend_changed)
145 #' # now we change dend_changed leaves order values:
146 #' order.dendrogram(dend_changed) <- 1:4
147 #' # and we can fix them again, based on their old kept leaves order:
148 #' dend_changed <- match_order_dendrogram_by_old_order(
149 #' dend_changed, dend,
150 #' old_dend_changed_order
151 #' )
152 #' expect_identical(order.dendrogram(dend_changed), order.dendrogram(dend))
153 #' }
154 match_order_dendrogram_by_old_order <- function(dend_change, dend_template,
155 dend_change_old_order,
156 check_that_labels_match = FALSE,
157 check_that_leaves_order_match = FALSE) {
158
159 # this function was made to help make entanglement.dendrogram faster.
160 # But it relies on some important assumptions (otherwise, its results will be nonsense!)
161
162 if (check_that_labels_match) { # I am turning this check to FALSE since it takes 0.03 sec from the function (which is a long time when running this function a lot)
163 if (any(sort(labels(dend_change)) != sort(labels(dend_template)))) stop("labels do not match in both trees. Please make sure to fix the labels names!")
164 }
165 if (check_that_leaves_order_match) { # I am turning this check to FALSE since it takes 0.03 sec from the function (which is a long time when running this function a lot)
166 if (any(sort(order.dendrogram(dend_change)) != sort(order.dendrogram(dend_template)))) stop("order.dendrogram do not match in both trees. Please make sure to fix the labels names!")
167 }
168
169 # if(print_NOTE) cat("NOTE:
170 # Make sure that the values in dend_change_old_order match the labels of dend1 in the same way
171 # as the values and labels of the dend_change!
172 # ")
173
174
175 # let's put the leaves' numbers and labels in two data.frames
176 # tree_to_change_labels_order <- data.frame(labels = labels(dend_change), values = order.dendrogram(dend_change))
177 # tree_template_labels_order <- data.frame(labels = labels(dend_template), values = order.dendrogram(dend_template))
178 tree_to_change_order <- order.dendrogram(dend_change)
179 tree_template_order <- order.dendrogram(dend_template) # these should be values after some change was done outside the function (and dend_change_old_order are the values before the change)
180
181 # this gives us how to order y so it would be in the order of x.
182 # y_to_order_like_x <- c(2,3,1,4)
183 # y_to_order_like_x[match(c(1:4), y_to_order_like_x)]
184 # I want to order the numbers in yoav_tree so that they would match the needed order in dans_tree
185
186 ss_order_change_leaf_numbers_to_match_template <- match(x = tree_to_change_order, table = dend_change_old_order)
187 # ss_order_change_leaf_numbers_to_match_template <- match(x= tree_template_order, table= dend_change_old_order)
188 # ss_order_change_leaf_numbers_to_match_template <- match(tree_to_change_order, dend_change_old_order)
189
190 new_leaves_order <- tree_template_order[ss_order_change_leaf_numbers_to_match_template]
191 order.dendrogram(dend_change) <- new_leaves_order
192
193 return(dend_change)
194 }
195
196
197
198
199
200
201
202
203
204
205
206
207
208 # untangle.dendrogram # A function to take two dendrograms and rotate them so to minimize some penalty on entanglement
209
210 # entanglement
211
212
213 #' @title Measures entanglement between two trees
214 #' @rdname entanglement
215 #' @export
216 #' @description
217 #' Measures the entanglement between two trees.
218 #' Entanglement is a measure between 1 (full entanglement) and 0
219 #' (no entanglement). The exact behavior of the number depends on the L norm
220 #' which is chosen.
221 #'
222 #'
223 #'
224 #'
225 #' @param dend1 a tree object (of class dendrogram/hclust/phylo).
226 #' @param dend2 a tree object (of class dendrogram/hclust/phylo).
227 #' @param which an integer vector of length 2, indicating
228 #' which of the trees in a dendlist object should have
229 #' their entanglement calculated
230 #' @param L the distance norm to use for measuring the distance between the
231 #' two trees. It can be any positive number, often one will want to
232 #' use 0, 1, 1.5, 2 (see 'details' for more).
233 #' @param leaves_matching_method a character scalar, either "order"
234 #' or "labels" (default) . If using "labels", then we use the labels for
235 #' matching the leaves order value (safer).
236 #'
237 #' And if "order" then we use the old leaves order value for matching the
238 #' leaves order value.
239 #'
240 #' Using "order" is faster, but "labels" is safer. "order" will assume that
241 #' the original two trees had their labels and order values MATCHED.
242 #'
243 #' Hence, it is best to make sure that the trees used here have the same labels
244 #' and the SAME values matched to these values - and then use "order" (for
245 #' fastest results).
246 #'
247 #' @param ... not used
248 #'
249 #' @details
250 #'
251 #' Entanglement is measured by giving the left tree's labels the values of
252 #' 1 till tree size, and than match these numbers with the right tree.
253 #' Now, entanglement is the L norm distance between these two vectors.
254 #' That is, we take the sum of the absolute difference (each one in the power
255 #' of L). e.g: \code{sum(abs(x-y)^L)}.
256 #' And this is devided by the "worst case" entanglement level (e.g:
257 #' when the right tree is the complete reverse of the left tree).
258 #'
259 #' L tells us which panelty level we are at (L0, L1, L2, partial L's etc).
260 #' L>1 means that we give a big panelty for sharp angles.
261 #' While L->0 means that any time something is not a streight horizontal line,
262 #' it gets a large penalty
263 #' If L=0.1 it means that we much prefer streight lines over non streight lines
264 #'
265 #' @return The number of leaves in the tree
266 #' @seealso \link{tanglegram}, \link{match_order_by_labels}.
267 #' @examples
268 #'
269 #' \dontrun{
270 #' dend1 <- iris[, -5] %>%
271 #' dist() %>%
272 #' hclust("com") %>%
273 #' as.dendrogram()
274 #' dend2 <- iris[, -5] %>%
275 #' dist() %>%
276 #' hclust("sin") %>%
277 #' as.dendrogram()
278 #' dend12 <- dendlist(dend1, dend2)
279 #' tanglegram(dend12)
280 #'
281 #' entanglement(dend12)
282 #' entanglement(dend12, L = 0)
283 #' entanglement(dend12, L = 0.25)
284 #' entanglement(dend1, dend2, L = 0) # 1
285 #' entanglement(dend1, dend2, L = 0.25) # 0.97
286 #' entanglement(dend1, dend2, L = 1) # 0.93
287 #' entanglement(dend1, dend2, L = 2) # 0.88
288 #'
289 #' # a somewhat better tanglegram
290 #' tanglegram(sort(dend1), sort(dend2))
291 #' # and alos a MUCH better entanglement
292 #' entanglement(sort(dend1), sort(dend2), L = 1.5) # 0.0811
293 #' # but not that much, for L=0.25
294 #' entanglement(sort(dend1), sort(dend2), L = .25) # 0.579
295 #'
296 #'
297 #'
298 #' ##################
299 #' ##################
300 #' ##################
301 #' # massing up the order of leaves is dangerous:
302 #' entanglement(dend1, dend2, 1.5, "order") # 0.91
303 #' order.dendrogram(dend2) <- seq_len(nleaves(dend2))
304 #' # this 0.95 number is NO LONGER correct!!
305 #' entanglement(dend1, dend2, 1.5, "order") # 0.95
306 #' # but if we use the "labels" method - we still get the correct number:
307 #' entanglement(dend1, dend2, 1.5, "labels") # 0.91
308 #'
309 #' # however, we can fix our dend2, as follows:
310 #' dend2 <- match_order_by_labels(dend2, dend1)
311 #' # Now that labels and order are matched - entanglement is back at working fine:
312 #' entanglement(dend1, dend2, 1.5, "order") # 0.91
313 #' }
314 entanglement <- function(dend1, ...) {
315 UseMethod("entanglement")
316 }
317
318
319 #' @export
320 entanglement.default <- function(dend1, dend2, ...) {
321 stop("no default function for entanglement")
322 }
323
324
325 #' @export
326 #' @rdname entanglement
327 entanglement.hclust <- function(dend1, dend2, ...) {
328 dend1 <- as.dendrogram(dend1)
329 dend2 <- as.dendrogram(dend2)
330 entanglement(dend1, dend2, ...)
331 }
332
333 #' @export
334 #' @rdname entanglement
335 entanglement.phylo <- function(dend1, dend2, ...) {
336 dend1 <- as.dendrogram(dend1)
337 dend2 <- as.dendrogram(dend2)
338 entanglement(dend1, dend2, ...)
339 }
340
341
342 #' @export
343 #' @rdname entanglement
344 entanglement.dendlist <- function(dend1, which = c(1L, 2L), ...) {
345 # many things can go wrong here (which we might wish to fix):
346 # we could get a dendlist with a length of 1 - in which case, we can't plot
347 if (length(dend1) == 1) stop("Your dendlist has only 1 dendrogram - entanglement can not be calculated")
348 # we could get a dendlist with a length of >2 - in which case, should we only plot the first two items?
349 if (all(which %in% seq_len(length(dend1)))) {
350 entanglement.dendrogram(dend1[[which[1]]], dend1[[which[2]]], ...)
351 } else {
352 stop("You are trying to calculate the entanglement for trees which are outside the range of trees in your dendlist")
353 }
354 }
355
356
357 #' @export
358 #' @rdname entanglement
359 entanglement.dendrogram <- function(dend1, dend2, L = 1.5, leaves_matching_method = c("labels", "order"), ...) {
360 # One day, one might think of other measures of entanglement.
361 # But for now, we have only one method ("cor.spearman"). Which is the 1-absolute value of the tanks of the values in the two dendrograms.
362 # A level close to 1 is bad (very entangled). A number close to 0 is good (low entanglement)
363 # leaves(dend1),leaves(dend2)
364 # L tells us which panelty level we are at (L0, L1, L2, partial L's etc). L>1 means that we give a big panelty for sharp angles. While L->0 means that any time something is not a streight horizontal line, it gets a large penalty
365 # If L=0.1 it means that we much prefer streight lines over non streight lines
366
367 if (L == 0) L <- L + 1e-50 # this is in order to make sure L is not ==0. Because that would just create nonsical meaning.
368
369
370 n_leaves <- nleaves(dend1) # how many leaves do we have? (number of leaves)
371 one_to_n_leaves <- seq_len(n_leaves)
372
373 leaves_matching_method <- match.arg(leaves_matching_method)
374 if (leaves_matching_method == "order") {
375 dend1_old_order <- order.dendrogram(dend1)
376 order.dendrogram(dend1) <- one_to_n_leaves # change the leaves of dend1 to be 1:n
377 dend2 <- match_order_dendrogram_by_old_order(dend2, dend1, dend1_old_order)
378 # make sure that the numbers if the
379 } else { # "labels" - this method is "safer" (since we can easily see if the labels on the two trees match or not
380 # however, this is twice as slow (which adds up quite a bit with the functions that rely on this)
381 # Hence, it is best to make sure that the trees used here have the same labels and the SAME values matched to these values
382 order.dendrogram(dend1) <- one_to_n_leaves # change the leaves of dend1 to be 1:n
383 dend2 <- match_order_by_labels(dend2, dend1) # This one is "slow"
384 }
385
386 sum_abs_diff_L <- function(x, y, L) {
387 sum(abs(x - y)^L)
388 }
389
390 entanglement_result <- sum_abs_diff_L(order.dendrogram(dend1), order.dendrogram(dend2), L)
391 worse_entanglement_result <- sum_abs_diff_L(one_to_n_leaves, rev(one_to_n_leaves), L)
392 normalized_entanglement_result <- entanglement_result / worse_entanglement_result # should range between 0 (no etnaglement) and 1 (max entangelment
393
394 return(normalized_entanglement_result)
395 }
396
397
398
399
400
401
402
403
404
405
406 # ### OLD entanglement concept.
407 # entanglement.dendrogram <- function(dend1,dend2 , method = c("absolute.rank.sum", "cor.spearman") )
408 # {
409 # # One day, one might think of other measures of entanglement. But for now, we have only one method ("cor.spearman"). Which is the 1-absolute value of the tanks of the values in the two dendrograms.
410 # # A level close to 1 is bad (very entangled). A number close to 0 is good (low entanglement)
411 # # leaves(dend1),leaves(dend2)
412 #
413 # n_leaves <- nleaves(dend1) # how many leaves do we have? (number of leaves)
414 # order.dendrogram(dend1) <- seq_len(n_leaves) # change the leaves of dend1 to be 1:n
415 # dend2 <- match_order_by_labels(dend2 , dend1) # make sure that the numbers if the
416 #
417 # if(method[1] == "cor.spearman") {
418 # order_cor <- cor(order.dendrogram(dend1),order.dendrogram(dend2), method = "spearman")
419 # entanglement_result <- (1-order_cor)/2 # cor=1 is best (0 entanglement), cor = 0 is bad (0.5 entanglement), cor = -1 is worst (1 entanglament)
420 # }
421 # if(method[1] == "absolute.rank.sum") {
422 # entanglement_result <- sum(abs(order.dendrogram(dend1)-order.dendrogram(dend2)))
423 # }
424 #
425 # entanglement_result
426 # }
427
428
429
430
431
432
433 #
434 # # OLD and SLOW
435 # entanglement.dendrogram <- function(dend1,dend2, L = 1.5)
436 # {
437 # # One day, one might think of other measures of entanglement. But for now, we have only one method ("cor.spearman"). Which is the 1-absolute value of the tanks of the values in the two dendrograms.
438 # # A level close to 1 is bad (very entangled). A number close to 0 is good (low entanglement)
439 # # leaves(dend1),leaves(dend2)
440 # # L tells us which panelty level we are at (L0, L1, L2, partial L's etc). L>1 means that we give a big panelty for sharp angles. While L->0 means that any time something is not a streight horizontal line, it gets a large penalty
441 # # If L=0.1 it means that we much prefer streight lines over non streight lines
442 #
443 # if(L==0) L <- L + 1e-50 # this is in order to make sure L is not ==0. Because that would just create nonsical meaning.
444 #
445 #
446 # n_leaves <- nleaves(dend1) # how many leaves do we have? (number of leaves)
447 # one_to_n_leaves <- seq_len(n_leaves)
448 # order.dendrogram(dend1) <- one_to_n_leaves # change the leaves of dend1 to be 1:n
449 # dend2 <- match_order_by_labels(dend2 , dend1) # make sure that the numbers if the
450 #
451 # sum_abs_diff_L <- function(x,y,L) {sum(abs(x-y)^L)}
452 #
453 # entanglement_result <- sum_abs_diff_L(order.dendrogram(dend1), order.dendrogram(dend2), L)
454 # worse_entanglement_result <- sum_abs_diff_L(one_to_n_leaves, rev(one_to_n_leaves), L)
455 # normalized_entanglement_result <- entanglement_result/worse_entanglement_result # should range between 0 (no etnaglement) and 1 (max entangelment
456 #
457 # normalized_entanglement_result
458 # }
459 #
460 #
461 #
462 #
463 #
464 #