]> git.donarmstrong.com Git - ape.git/blob - R/dist.topo.R
5777482c35a1555a7abe2865f532e361af7b80d0
[ape.git] / R / dist.topo.R
1 ## dist.topo.R (2012-03-13)
2
3 ##      Topological Distances, Tree Bipartitions,
4 ##   Consensus Trees, and Bootstrapping Phylogenies
5
6 ## Copyright 2005-2012 Emmanuel Paradis
7
8 ## This file is part of the R-package `ape'.
9 ## See the file ../COPYING for licensing issues.
10
11 dist.topo <- function(x, y, method = "PH85")
12 {
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)
16     x <- unroot(x)
17     y <- unroot(y)
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]))
26     ## End
27     q1 <- length(bp1)
28     q2 <- length(bp2)
29     if (method == "PH85") {
30         p <- 0
31         for (i in 1:q1) {
32             for (j in 1:q2) {
33                 if (identical(bp1[[i]], bp2[[j]]) | identical(bp1[[i]], bp2.comp[[j]])) {
34                     p <- p + 1
35                     break
36                 }
37             }
38         }
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)
41     }
42     if (method == "score") {
43         dT <- 0
44         found1 <- FALSE
45         found2 <- logical(q2)
46         found2[1] <- TRUE
47         for (i in 2:q1) {
48             for (j in 2:q2) {
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
53                     break
54                 }
55             }
56             if (found1) found1 <- FALSE
57             else dT <- dT + (x$edge.length[which(x$edge[, 2] == nx + i)])^2
58         }
59         if (!all(found2))
60             dT <- dT + sum((y$edge.length[y$edge[, 2] %in% (ny + which(!found2))])^2)
61         dT <- sqrt(dT)
62     }
63     dT
64 }
65
66 .compressTipLabel <- function(x)
67 {
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
71     if (any(table(ref) != 1))
72         stop("some tip labels are duplicated in tree no. 1")
73     n <- length(ref)
74     Ntree <- length(x)
75     if (Ntree > 1) {
76         for (i in 2:Ntree) {
77             label <- x[[i]]$tip.label
78             if (!identical(label, ref)) {
79                 if (length(label) != length(ref))
80                     stop(paste("tree no.", i, "has a different number of tips"))
81                 ilab <- match(label, ref)
82                 ## can use tabulate here because 'ilab' contains integers
83                 if (any(is.na(ilab)))
84                     stop(paste("tree no.", i, "has different tip labels"))
85 ### <FIXME> the test below does not seem useful anymore
86 ###            if (any(tabulate(ilab) > 1))
87 ###                stop(paste("some tip labels are duplicated in tree no.", i))
88 ### </FIXME>
89                 ie <- match(1:n, x[[i]]$edge[, 2])
90                 x[[i]]$edge[ie, 2] <- ilab
91             }
92             x[[i]]$tip.label <- NULL
93         }
94     }
95     x[[1]]$tip.label <- NULL
96     attr(x, "TipLabel") <- ref
97     x
98 }
99
100 prop.part <- function(..., check.labels = TRUE)
101 {
102     obj <- list(...)
103     if (length(obj) == 1 && class(obj[[1]]) != "phylo")
104         obj <- obj[[1]]
105     ## <FIXME>
106     ## class(obj) <- NULL # needed? apparently not, see below (2010-11-18)
107     ## </FIXME>
108     ntree <- length(obj)
109     if (ntree == 1) check.labels <- FALSE
110     if (check.labels) obj <- .compressTipLabel(obj) # fix by Klaus Schliep (2011-02-21)
111     for (i in 1:ntree) storage.mode(obj[[i]]$Nnode) <- "integer"
112     ## <FIXME>
113     ## The 1st must have tip labels
114     ## Maybe simply pass the number of tips to the C code??
115     obj <- .uncompressTipLabel(obj) # fix a bug (2010-11-18)
116     ## </FIXME>
117     clades <- .Call("prop_part", obj, ntree, TRUE, PACKAGE = "ape")
118     attr(clades, "number") <- attr(clades, "number")[1:length(clades)]
119     attr(clades, "labels") <- obj[[1]]$tip.label
120     class(clades) <- "prop.part"
121     clades
122 }
123
124 print.prop.part <- function(x, ...)
125 {
126     if (is.null(attr(x, "labels"))) {
127         for (i in 1:length(x)) {
128             cat("==>", attr(x, "number")[i], "time(s):")
129             print(x[[i]], quote = FALSE)
130         }
131     } else {
132         for (i in 1:length(attr(x, "labels")))
133           cat(i, ": ", attr(x, "labels")[i], "\n", sep = "")
134         cat("\n")
135         for (i in 1:length(x)) {
136             cat("==>", attr(x, "number")[i], "time(s):")
137             print(x[[i]], quote = FALSE)
138         }
139     }
140 }
141
142 summary.prop.part <- function(object, ...) attr(object, "number")
143
144 plot.prop.part <- function(x, barcol = "blue", leftmar = 4, ...)
145 {
146     if (is.null(attr(x, "labels")))
147       stop("cannot plot this partition object; see ?prop.part for details.")
148     L <- length(x)
149     n <- length(attr(x, "labels"))
150     layout(matrix(1:2, 2, 1), heights = c(1, 3))
151     par(mar = c(0.1, leftmar, 0.1, 0.1))
152     plot(1:L, attr(x, "number"), type = "h", col = barcol, xlim = c(1, L),
153          xlab = "", ylab = "Frequency", xaxt = "n", bty = "n")
154     plot(0, type = "n", xlim = c(1, L), ylim = c(1, n),
155          xlab = "", ylab = "", xaxt = "n", yaxt = "n")
156     for (i in 1:L) points(rep(i, length(x[[i]])), x[[i]], ...)
157     mtext(attr(x, "labels"), side = 2, at = 1:n, las = 1)
158 }
159
160 prop.clades <- function(phy, ..., part = NULL, rooted = FALSE)
161 {
162     if (is.null(part)) {
163         ## <FIXME>
164         ## Are we going to keep the '...' way of passing trees?
165         obj <- list(...)
166         if (length(obj) == 1 && class(obj[[1]]) != "phylo")
167             obj <- unlist(obj, recursive = FALSE)
168         ## </FIXME>
169         part <- prop.part(obj, check.labels = TRUE)
170     }
171
172     bp <- prop.part(phy)
173     if (!rooted) {
174         bp <- postprocess.prop.part(bp)
175         part <- postprocess.prop.part(part) # fix by Klaus Schliep
176         ## actually the above line in not needed if called from boot.phylo()
177     }
178
179     n <- numeric(phy$Nnode)
180     for (i in seq_along(bp)) {
181         for (j in seq_along(part)) {
182             ## we rely on the fact the values returned by prop.part are
183             ## sorted and without attributes, so identical can be used:
184             if (identical(bp[[i]], part[[j]])) {
185                 n[i] <- attr(part, "number")[j]
186                 done <-  TRUE
187                 break
188             }
189         }
190     }
191     n
192 }
193
194 boot.phylo <- function(phy, x, FUN, B = 100, block = 1,
195                        trees = FALSE, quiet = FALSE, rooted = FALSE)
196 {
197     if (is.list(x) && !is.data.frame(x)) {
198         if (inherits(x, "DNAbin")) x <- as.matrix(x)
199         else {
200             nm <- names(x)
201             n <- length(x)
202             x <- unlist(x)
203             nL <- length(x)
204             x <- matrix(x, n, nL/n, byrow = TRUE)
205             rownames(x) <- nm
206         }
207     }
208     boot.tree <- vector("list", B)
209     if (!quiet) # suggestion by Alastair Potts
210         progbar <- utils::txtProgressBar(style = 3)
211     for (i in 1:B) {
212         if (block > 1) {
213             y <- seq(block, ncol(x), block)
214             boot.i <- sample(y, replace = TRUE)
215             boot.samp <- numeric(ncol(x))
216             boot.samp[y] <- boot.i
217             for (j in 1:(block - 1))
218                 boot.samp[y - j] <- boot.i - j
219         } else boot.samp <- sample(ncol(x), replace = TRUE)
220         boot.tree[[i]] <- FUN(x[, boot.samp])
221         if (!quiet) utils::setTxtProgressBar(progbar, i/B)
222     }
223     if (!quiet) close(progbar)
224     for (i in 1:B) storage.mode(boot.tree[[i]]$Nnode) <- "integer"
225     storage.mode(phy$Nnode) <- "integer"
226
227     pp <- prop.part(boot.tree)
228     if (!rooted) pp <- postprocess.prop.part(pp)
229     ans <- prop.clades(phy, part = pp, rooted = rooted)
230
231     ##ans <- attr(.Call("prop_part", c(list(phy), boot.tree),
232     ##                  B + 1, FALSE, PACKAGE = "ape"), "number") - 1
233     if (trees) {
234         class(boot.tree) <- "multiPhylo"
235         ans <- list(BP = ans, trees = boot.tree)
236     }
237     ans
238 }
239
240 ### The next function transforms an object of class "prop.part" so
241 ### that the vectors which are identical in terms of split are aggregated.
242 ### For instance if n = 5 tips, 1:2 and 3:5 actually represent the same
243 ### split though they are different clades. The aggregation is done
244 ### arbitrarily. The call to ONEwise() insures that all splits include
245 ### the first tip.
246 postprocess.prop.part <- function(x)
247 {
248     n <- length(x[[1]])
249     N <- length(x)
250     w <- attr(x, "number")
251
252     drop <- logical(N)
253     V <- numeric(n)
254     for (i in 2:(N - 1)) {
255         if (drop[i]) next
256         A <- x[[i]]
257         for (j in (i + 1):N) {
258             if (drop[j]) next
259             B <- x[[j]]
260             if (length(A) + length(B) != n) next
261             V[] <- 0L
262             V[A] <- 1L
263             V[B] <- 1L
264             if (all(V == 1L)) {
265                 drop[j] <- TRUE
266                 w[i] <- w[i] + w[j]
267             }
268         }
269     }
270     if (any(drop)) {
271         labels <- attr(x, "labels")
272         x <- x[!drop]
273         w <- w[!drop]
274         attr(x, "number") <- w
275         attr(x, "labels") <- labels
276         class(x) <- "prop.part"
277     }
278     ONEwise(x)
279 }
280
281 ### This function changes an object of class "prop.part" so that they
282 ### all include the first tip. For instance if n = 5 tips, 3:5 is
283 ### changed to 1:2.
284 ONEwise <- function(x)
285 {
286     n <- length(x[[1L]])
287     v <- 1:n
288     for (i in 2:length(x)) {
289         y <- x[[i]]
290         if (y[1] != 1) x[[i]] <- v[-y]
291     }
292     x
293 }
294
295 consensus <- function(..., p = 1, check.labels = TRUE)
296 {
297     foo <- function(ic, node) {
298         ## ic: index of 'pp'
299         ## node: node number in the final tree
300         pool <- pp[[ic]]
301         if (ic < m) {
302             for (j in (ic + 1):m) {
303                 wh <- match(pp[[j]], pool)
304                 if (!any(is.na(wh))) {
305                     edge[pos, 1] <<- node
306                     pool <- pool[-wh]
307                     edge[pos, 2] <<- nextnode <<- nextnode + 1L
308                     pos <<- pos + 1L
309                     foo(j, nextnode)
310                 }
311             }
312         }
313         size <- length(pool)
314         if (size) {
315             ind <- pos:(pos + size - 1)
316             edge[ind, 1] <<- node
317             edge[ind, 2] <<- pool
318             pos <<- pos + size
319         }
320     }
321     obj <- list(...)
322     if (length(obj) == 1) {
323         ## better than unlist(obj, recursive = FALSE)
324         ## because "[[" keeps the class of 'obj':
325         obj <- obj[[1]]
326         if (class(obj) == "phylo") return(obj)
327     }
328     if (!is.null(attr(obj, "TipLabel")))
329         labels <- attr(obj, "TipLabel")
330     else {
331         labels <- obj[[1]]$tip.label
332         if (check.labels) obj <- .compressTipLabel(obj)
333     }
334     ntree <- length(obj)
335     ## Get all observed partitions and their frequencies:
336     pp <- prop.part(obj, check.labels = FALSE)
337     ## Drop the partitions whose frequency is less than 'p':
338     if (p == 0.5) p <- 0.5000001 # avoid incompatible splits
339     pp <- pp[attr(pp, "number") >= p * ntree]
340     ## Get the order of the remaining partitions by decreasing size:
341     ind <- sort(unlist(lapply(pp, length)), decreasing = TRUE,
342                 index.return = TRUE)$ix
343     pp <- pp[ind]
344     n <- length(labels)
345     m <- length(pp)
346     edge <- matrix(0L, n + m - 1, 2)
347     if (m == 1) {
348         edge[, 1] <- n + 1L
349         edge[, 2] <- 1:n
350     } else {
351         nextnode <- n + 1L
352         pos <- 1L
353         foo(1, nextnode)
354     }
355     structure(list(edge = edge, tip.label = labels,
356               Nnode = m), class = "phylo")
357 }