1 ## dist.topo.R (2012-12-12)
3 ## Topological Distances, Tree Bipartitions,
4 ## Consensus Trees, and Bootstrapping Phylogenies
6 ## Copyright 2005-2012 Emmanuel Paradis
8 ## This file is part of the R-package `ape'.
9 ## See the file ../COPYING for licensing issues.
11 dist.topo <- function(x, y, method = "PH85")
13 if (method == "score" && (is.null(x$edge.length) || is.null(y$edge.length)))
14 stop("trees must have branch lengths for branch score distance.")
15 nx <- length(x$tip.label)
18 bp1 <- .Call("bipartition", x$edge, nx, x$Nnode, PACKAGE = "ape")
19 bp1 <- lapply(bp1, function(xx) sort(x$tip.label[xx]))
20 ny <- length(y$tip.label) # fix by Otto Cordero
21 ## fix by Tim Wallstrom:
22 bp2.tmp <- .Call("bipartition", y$edge, ny, y$Nnode, PACKAGE = "ape")
23 bp2 <- lapply(bp2.tmp, function(xx) sort(y$tip.label[xx]))
24 bp2.comp <- lapply(bp2.tmp, function(xx) setdiff(1:ny, xx))
25 bp2.comp <- lapply(bp2.comp, function(xx) sort(y$tip.label[xx]))
29 if (method == "PH85") {
33 if (identical(bp1[[i]], bp2[[j]]) | identical(bp1[[i]], bp2.comp[[j]])) {
39 dT <- q1 + q2 - 2 * p # same than:
40 ##dT <- if (q1 == q2) 2*(q1 - p) else 2*(min(q1, q2) - p) + abs(q1 - q2)
42 if (method == "score") {
49 if (identical(bp1[[i]], bp2[[j]]) | identical(bp1[[i]], bp2.comp[[j]])) {
50 dT <- dT + (x$edge.length[which(x$edge[, 2] == nx + i)] -
51 y$edge.length[which(y$edge[, 2] == ny + j)])^2
52 found1 <- found2[j] <- TRUE
56 if (found1) found1 <- FALSE
57 else dT <- dT + (x$edge.length[which(x$edge[, 2] == nx + i)])^2
60 dT <- dT + sum((y$edge.length[y$edge[, 2] %in% (ny + which(!found2))])^2)
66 .compressTipLabel <- function(x)
68 ## 'x' is a list of objects of class "phylo" possibly with no class
69 if (!is.null(attr(x, "TipLabel"))) return(x)
70 ref <- x[[1]]$tip.label
72 if (length(unique(ref)) != n)
73 stop("some tip labels are duplicated in tree no. 1")
75 ## serious improvement by Joseph W. Brown!
76 relabel <- function (y) {
78 if (!identical(label, ref)) {
79 if (length(label) != length(ref))
80 stop(paste("tree ", y, "has a different number of tips"))
81 ilab <- match(label, ref)
83 stop(paste("tree ", y, "has different tip labels"))
84 ie <- match(1:n, y$edge[, 2])
90 x <- lapply(x, relabel)
91 attr(x, "TipLabel") <- ref
92 class(x) <- "multiPhylo"
96 prop.part <- function(..., check.labels = TRUE)
99 if (length(obj) == 1 && class(obj[[1]]) != "phylo")
102 ## class(obj) <- NULL # needed? apparently not, see below (2010-11-18)
105 if (ntree == 1) check.labels <- FALSE
106 if (check.labels) obj <- .compressTipLabel(obj) # fix by Klaus Schliep (2011-02-21)
107 for (i in 1:ntree) storage.mode(obj[[i]]$Nnode) <- "integer"
109 ## The 1st must have tip labels
110 ## Maybe simply pass the number of tips to the C code??
111 obj <- .uncompressTipLabel(obj) # fix a bug (2010-11-18)
113 clades <- .Call("prop_part", obj, ntree, TRUE, PACKAGE = "ape")
114 attr(clades, "number") <- attr(clades, "number")[1:length(clades)]
115 attr(clades, "labels") <- obj[[1]]$tip.label
116 class(clades) <- "prop.part"
120 print.prop.part <- function(x, ...)
122 if (is.null(attr(x, "labels"))) {
123 for (i in 1:length(x)) {
124 cat("==>", attr(x, "number")[i], "time(s):")
125 print(x[[i]], quote = FALSE)
128 for (i in 1:length(attr(x, "labels")))
129 cat(i, ": ", attr(x, "labels")[i], "\n", sep = "")
131 for (i in 1:length(x)) {
132 cat("==>", attr(x, "number")[i], "time(s):")
133 print(x[[i]], quote = FALSE)
138 summary.prop.part <- function(object, ...) attr(object, "number")
140 plot.prop.part <- function(x, barcol = "blue", leftmar = 4, ...)
142 if (is.null(attr(x, "labels")))
143 stop("cannot plot this partition object; see ?prop.part for details.")
145 n <- length(attr(x, "labels"))
146 layout(matrix(1:2, 2, 1), heights = c(1, 3))
147 par(mar = c(0.1, leftmar, 0.1, 0.1))
148 plot(1:L, attr(x, "number"), type = "h", col = barcol, xlim = c(1, L),
149 xlab = "", ylab = "Frequency", xaxt = "n", bty = "n")
150 plot(0, type = "n", xlim = c(1, L), ylim = c(1, n),
151 xlab = "", ylab = "", xaxt = "n", yaxt = "n")
152 for (i in 1:L) points(rep(i, length(x[[i]])), x[[i]], ...)
153 mtext(attr(x, "labels"), side = 2, at = 1:n, las = 1)
156 prop.clades <- function(phy, ..., part = NULL, rooted = FALSE)
160 ## Are we going to keep the '...' way of passing trees?
162 if (length(obj) == 1 && class(obj[[1]]) != "phylo")
163 obj <- unlist(obj, recursive = FALSE)
165 part <- prop.part(obj, check.labels = TRUE)
170 bp <- postprocess.prop.part(bp)
171 part <- postprocess.prop.part(part) # fix by Klaus Schliep
172 ## actually the above line in not needed if called from boot.phylo()
175 n <- numeric(phy$Nnode)
176 for (i in seq_along(bp)) {
177 for (j in seq_along(part)) {
178 ## we rely on the fact the values returned by prop.part are
179 ## sorted and without attributes, so identical can be used:
180 if (identical(bp[[i]], part[[j]])) {
181 n[i] <- attr(part, "number")[j]
190 boot.phylo <- function(phy, x, FUN, B = 100, block = 1,
191 trees = FALSE, quiet = FALSE, rooted = FALSE)
193 if (is.list(x) && !is.data.frame(x)) {
194 if (inherits(x, "DNAbin")) x <- as.matrix(x)
200 x <- matrix(x, n, nL/n, byrow = TRUE)
204 boot.tree <- vector("list", B)
205 if (!quiet) # suggestion by Alastair Potts
206 progbar <- utils::txtProgressBar(style = 3)
209 y <- seq(block, ncol(x), block)
210 boot.i <- sample(y, replace = TRUE)
211 boot.samp <- numeric(ncol(x))
212 boot.samp[y] <- boot.i
213 for (j in 1:(block - 1))
214 boot.samp[y - j] <- boot.i - j
215 } else boot.samp <- sample(ncol(x), replace = TRUE)
216 boot.tree[[i]] <- FUN(x[, boot.samp])
217 if (!quiet) utils::setTxtProgressBar(progbar, i/B)
219 if (!quiet) close(progbar)
220 for (i in 1:B) storage.mode(boot.tree[[i]]$Nnode) <- "integer"
221 storage.mode(phy$Nnode) <- "integer"
223 pp <- prop.part(boot.tree)
224 if (!rooted) pp <- postprocess.prop.part(pp)
225 ans <- prop.clades(phy, part = pp, rooted = rooted)
227 ##ans <- attr(.Call("prop_part", c(list(phy), boot.tree),
228 ## B + 1, FALSE, PACKAGE = "ape"), "number") - 1
230 class(boot.tree) <- "multiPhylo"
231 ans <- list(BP = ans, trees = boot.tree)
236 ### The next function transforms an object of class "prop.part" so
237 ### that the vectors which are identical in terms of split are aggregated.
238 ### For instance if n = 5 tips, 1:2 and 3:5 actually represent the same
239 ### split though they are different clades. The aggregation is done
240 ### arbitrarily. The call to ONEwise() insures that all splits include
242 postprocess.prop.part <- function(x)
246 w <- attr(x, "number")
250 for (i in 2:(N - 1)) {
253 for (j in (i + 1):N) {
256 if (length(A) + length(B) != n) next
267 labels <- attr(x, "labels")
270 attr(x, "number") <- w
271 attr(x, "labels") <- labels
272 class(x) <- "prop.part"
277 ### This function changes an object of class "prop.part" so that they
278 ### all include the first tip. For instance if n = 5 tips, 3:5 is
280 ONEwise <- function(x)
284 for (i in 2:length(x)) {
286 if (y[1] != 1) x[[i]] <- v[-y]
291 consensus <- function(..., p = 1, check.labels = TRUE)
293 foo <- function(ic, node) {
295 ## node: node number in the final tree
298 for (j in (ic + 1):m) {
299 wh <- match(pp[[j]], pool)
300 if (!any(is.na(wh))) {
301 edge[pos, 1] <<- node
303 edge[pos, 2] <<- nextnode <<- nextnode + 1L
311 ind <- pos:(pos + size - 1)
312 edge[ind, 1] <<- node
313 edge[ind, 2] <<- pool
318 if (length(obj) == 1) {
319 ## better than unlist(obj, recursive = FALSE)
320 ## because "[[" keeps the class of 'obj':
322 if (class(obj) == "phylo") return(obj)
324 if (!is.null(attr(obj, "TipLabel")))
325 labels <- attr(obj, "TipLabel")
327 labels <- obj[[1]]$tip.label
328 if (check.labels) obj <- .compressTipLabel(obj)
331 ## Get all observed partitions and their frequencies:
332 pp <- prop.part(obj, check.labels = FALSE)
333 ## Drop the partitions whose frequency is less than 'p':
334 if (p == 0.5) p <- 0.5000001 # avoid incompatible splits
335 pp <- pp[attr(pp, "number") >= p * ntree]
336 ## Get the order of the remaining partitions by decreasing size:
337 ind <- sort(unlist(lapply(pp, length)), decreasing = TRUE,
338 index.return = TRUE)$ix
342 edge <- matrix(0L, n + m - 1, 2)
351 structure(list(edge = edge, tip.label = labels,
352 Nnode = m), class = "phylo")