]> git.donarmstrong.com Git - ape.git/blob - R/dist.topo.R
new image.DNAbin()
[ape.git] / R / dist.topo.R
1 ## dist.topo.R (2011-02-21)
2
3 ##      Topological Distances, Tree Bipartitions,
4 ##   Consensus Trees, and Bootstrapping Phylogenies
5
6 ## Copyright 2005-2011 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     for (i in 2:length(x)) {
75         label <- x[[i]]$tip.label
76         if (!identical(label, ref)) {
77             if (length(label) != length(ref))
78                 stop(paste("tree no.", i, "has a different number of tips"))
79             ilab <- match(label, ref)
80             ## can use tabulate here because 'ilab' contains integers
81             if (any(is.na(ilab)))
82                 stop(paste("tree no.", i, "has different tip labels"))
83 ### <FIXME> the test below does not seem useful anymore
84 ###            if (any(tabulate(ilab) > 1))
85 ###                stop(paste("some tip labels are duplicated in tree no.", i))
86 ### </FIXME>
87             ie <- match(1:n, x[[i]]$edge[, 2])
88             x[[i]]$edge[ie, 2] <- ilab
89         }
90         x[[i]]$tip.label <- NULL
91     }
92     x[[1]]$tip.label <- NULL
93     attr(x, "TipLabel") <- ref
94     x
95 }
96
97 prop.part <- function(..., check.labels = TRUE)
98 {
99     obj <- list(...)
100     if (length(obj) == 1 && class(obj[[1]]) != "phylo")
101         obj <- obj[[1]]
102     ## <FIXME>
103     ## class(obj) <- NULL # needed? apparently not, see below (2010-11-18)
104     ## </FIXME>
105     ntree <- length(obj)
106     if (ntree == 1) check.labels <- FALSE
107     if (check.labels) obj <- .compressTipLabel(obj) # fix by Klaus Schliep (2011-02-21)
108     for (i in 1:ntree) storage.mode(obj[[i]]$Nnode) <- "integer"
109     ## <FIXME>
110     ## The 1st must have tip labels
111     ## Maybe simply pass the number of tips to the C code??
112     obj <- .uncompressTipLabel(obj) # fix a bug (2010-11-18)
113     ## </FIXME>
114     clades <- .Call("prop_part", obj, ntree, TRUE, PACKAGE = "ape")
115     attr(clades, "number") <- attr(clades, "number")[1:length(clades)]
116     attr(clades, "labels") <- obj[[1]]$tip.label
117     class(clades) <- "prop.part"
118     clades
119 }
120
121 print.prop.part <- function(x, ...)
122 {
123     if (is.null(attr(x, "labels"))) {
124         for (i in 1:length(x)) {
125             cat("==>", attr(x, "number")[i], "time(s):")
126             print(x[[i]], quote = FALSE)
127         }
128     } else {
129         for (i in 1:length(attr(x, "labels")))
130           cat(i, ": ", attr(x, "labels")[i], "\n", sep = "")
131         cat("\n")
132         for (i in 1:length(x)) {
133             cat("==>", attr(x, "number")[i], "time(s):")
134             print(x[[i]], quote = FALSE)
135         }
136     }
137 }
138
139 summary.prop.part <- function(object, ...) attr(object, "number")
140
141 plot.prop.part <- function(x, barcol = "blue", leftmar = 4, ...)
142 {
143     if (is.null(attr(x, "labels")))
144       stop("cannot plot this partition object; see ?prop.part for details.")
145     L <- length(x)
146     n <- length(attr(x, "labels"))
147     layout(matrix(1:2, 2, 1), heights = c(1, 3))
148     par(mar = c(0.1, leftmar, 0.1, 0.1))
149     plot(1:L, attr(x, "number"), type = "h", col = barcol, xlim = c(1, L),
150          xlab = "", ylab = "Frequency", xaxt = "n", bty = "n")
151     plot(0, type = "n", xlim = c(1, L), ylim = c(1, n),
152          xlab = "", ylab = "", xaxt = "n", yaxt = "n")
153     for (i in 1:L) points(rep(i, length(x[[i]])), x[[i]], ...)
154     mtext(attr(x, "labels"), side = 2, at = 1:n, las = 1)
155 }
156
157 prop.clades <- function(phy, ..., part = NULL)
158 {
159     if (is.null(part)) {
160         obj <- list(...)
161         if (length(obj) == 1 && class(obj[[1]]) != "phylo")
162           obj <- unlist(obj, recursive = FALSE)
163         part <- prop.part(obj, check.labels = TRUE)
164     }
165     bp <- .Call("bipartition", phy$edge, length(phy$tip.label),
166                 phy$Nnode, PACKAGE = "ape")
167     if (!is.null(attr(part, "labels")))
168       for (i in 1:length(part))
169         part[[i]] <- sort(attr(part, "labels")[part[[i]]])
170     bp <- lapply(bp, function(xx) sort(phy$tip.label[xx]))
171     n <- numeric(phy$Nnode)
172     for (i in 1:phy$Nnode) {
173         for (j in 1:length(part)) {
174             if (identical(all.equal(bp[[i]], part[[j]]), TRUE)) {
175                 n[i] <- attr(part, "number")[j]
176                 done <-  TRUE
177                 break
178             }
179         }
180     }
181     n
182 }
183
184 boot.phylo <- function(phy, x, FUN, B = 100, block = 1, trees = FALSE)
185 {
186     if (is.list(x) && !is.data.frame(x)) {
187         if (inherits(x, "DNAbin")) x <- as.matrix(x)
188         else {
189             nm <- names(x)
190             n <- length(x)
191             x <- unlist(x)
192             nL <- length(x)
193             x <- matrix(x, n, nL/n, byrow = TRUE)
194             rownames(x) <- nm
195         }
196     }
197     boot.tree <- vector("list", B)
198     for (i in 1:B) {
199         if (block > 1) {
200             y <- seq(block, ncol(x), block)
201             boot.i <- sample(y, replace = TRUE)
202             boot.samp <- numeric(ncol(x))
203             boot.samp[y] <- boot.i
204             for (j in 1:(block - 1))
205               boot.samp[y - j] <- boot.i - j
206         } else boot.samp <- sample(ncol(x), replace = TRUE)
207         boot.tree[[i]] <- FUN(x[, boot.samp])
208     }
209     for (i in 1:B) storage.mode(boot.tree[[i]]$Nnode) <- "integer"
210     storage.mode(phy$Nnode) <- "integer"
211     ans <- attr(.Call("prop_part", c(list(phy), boot.tree),
212                       B + 1, FALSE, PACKAGE = "ape"), "number") - 1
213     if (trees) {
214         class(boot.tree) <- "multiPhylo"
215         ans <- list(BP = ans, trees = boot.tree)
216     }
217     ans
218 }
219
220 consensus <- function(..., p = 1, check.labels = TRUE)
221 {
222     foo <- function(ic, node) {
223         ## ic: index of 'pp'
224         ## node: node number in the final tree
225         pool <- pp[[ic]]
226         if (ic < m) {
227             for (j in (ic + 1):m) {
228                 wh <- match(pp[[j]], pool)
229                 if (!any(is.na(wh))) {
230                     edge[pos, 1] <<- node
231                     pool <- pool[-wh]
232                     edge[pos, 2] <<- nextnode <<- nextnode + 1L
233                     pos <<- pos + 1L
234                     foo(j, nextnode)
235                 }
236             }
237         }
238         size <- length(pool)
239         if (size) {
240             ind <- pos:(pos + size - 1)
241             edge[ind, 1] <<- node
242             edge[ind, 2] <<- pool
243             pos <<- pos + size
244         }
245     }
246     obj <- list(...)
247     if (length(obj) == 1) {
248         ## better than unlist(obj, recursive = FALSE)
249         ## because "[[" keeps the class of 'obj':
250         obj <- obj[[1]]
251         if (class(obj) == "phylo") return(obj)
252     }
253     if (!is.null(attr(obj, "TipLabel")))
254         labels <- attr(obj, "TipLabel")
255     else {
256         labels <- obj[[1]]$tip.label
257         if (check.labels) obj <- .compressTipLabel(obj)
258     }
259     ntree <- length(obj)
260     ## Get all observed partitions and their frequencies:
261     pp <- prop.part(obj, check.labels = FALSE)
262     ## Drop the partitions whose frequency is less than 'p':
263     pp <- pp[attr(pp, "number") >= p * ntree]
264     ## Get the order of the remaining partitions by decreasing size:
265     ind <- sort(unlist(lapply(pp, length)), decreasing = TRUE,
266                 index.return = TRUE)$ix
267     pp <- pp[ind]
268     n <- length(labels)
269     m <- length(pp)
270     edge <- matrix(0L, n + m - 1, 2)
271     if (m == 1) {
272         edge[, 1] <- n + 1L
273         edge[, 2] <- 1:n
274     } else {
275         nextnode <- n + 1L
276         pos <- 1L
277         foo(1, nextnode)
278     }
279     structure(list(edge = edge, tip.label = labels,
280               Nnode = m), class = "phylo")
281 }