]> git.donarmstrong.com Git - ape.git/blob - R/dist.topo.R
added edge.lty to plot.phylo
[ape.git] / R / dist.topo.R
1 ## dist.topo.R (2008-07-18)
2
3 ##      Topological Distances, Tree Bipartitions,
4 ##   Consensus Trees, and Bootstrapping Phylogenies
5
6 ## Copyright 2005-2008 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 == "BHV01" && (is.null(x$edge.length) || is.null(y$edge.length)))
14       stop("trees must have branch lengths for Billera et al.'s distance.")
15     n <- length(x$tip.label)
16     bp1 <- .Call("bipartition", x$edge, n, x$Nnode, PACKAGE = "ape")
17     bp1 <- lapply(bp1, function(xx) sort(x$tip.label[xx]))
18     bp2 <- .Call("bipartition", y$edge, n, y$Nnode, PACKAGE = "ape")
19     bp2 <- lapply(bp2, function(xx) sort(y$tip.label[xx]))
20     q1 <- length(bp1)
21     q2 <- length(bp2)
22     if (method == "PH85") {
23         p <- 0
24         for (i in 1:q1) {
25             for (j in 1:q2) {
26                 if (identical(all.equal(bp1[[i]], bp2[[j]]), TRUE)) {
27                     p <- p + 1
28                     break
29                 }
30             }
31         }
32         dT <- if (q1 == q2) 2*(q1 - p) else 2*(min(q1, q2) - p) + abs(q1 - q2)
33     }
34     if (method == "BHV01") {
35         dT <- 0
36         found1 <- FALSE
37         found2 <- logical(q2)
38         found2[1] <- TRUE
39         for (i in 2:q1) {
40             for (j in 2:q2) {
41                 if (identical(bp1[[i]], bp2[[j]])) {
42                     dT <- dT + abs(x$edge.length[which(x$edge[, 2] == n + i)] -
43                                    y$edge.length[which(y$edge[, 2] == n + j)])
44                     found1 <- found2[j] <- TRUE
45                     break
46                 }
47             }
48             if (found1) found1 <- FALSE
49             else dT <- dT + x$edge.length[which(x$edge[, 2] == n + i)]
50         }
51         if (!all(found2))
52           dT <- dT + sum(y$edge.length[y$edge[, 2] %in% (n + which(!found2))])
53     }
54     dT
55 }
56
57 .compressTipLabel <- function(x)
58 {
59     ## 'x' is a list of objects of class "phylo" possibly with no class
60     if (!is.null(attr(x, "TipLabel"))) return(x)
61     ref <- x[[1]]$tip.label
62     if (any(table(ref) != 1))
63         stop("some tip labels are duplicated in tree no. 1")
64     n <- length(ref)
65     for (i in 2:length(x)) {
66         if (identical(x[[i]]$tip.label, ref)) next
67         ilab <- match(x[[i]]$tip.label, ref)
68         ## can use tabulate here because 'ilab' contains integers
69         if (any(tabulate(ilab) > 1))
70             stop(paste("some tip labels are duplicated in tree no.", i))
71         if (any(is.na(ilab)))
72             stop(paste("tree no.", i, "has different tip labels"))
73         ie <- match(1:n, x[[i]]$edge[, 2])
74         x[[i]]$edge[ie, 2] <- ilab
75     }
76     for (i in 1:length(x)) x[[i]]$tip.label <- NULL
77     attr(x, "TipLabel") <- ref
78     x
79 }
80
81 prop.part <- function(..., check.labels = TRUE)
82 {
83     obj <- list(...)
84     if (length(obj) == 1 && class(obj[[1]]) != "phylo")
85         obj <- obj[[1]]
86     ## <FIXME>
87     ## class(obj) <- NULL # needed?
88     ## </FIXME>
89     ntree <- length(obj)
90     if (ntree == 1) check.labels <- FALSE
91     if (check.labels) obj <- .compressTipLabel(obj)
92     for (i in 1:ntree) storage.mode(obj[[i]]$Nnode) <- "integer"
93     ## <FIXME>
94     ## The 1st must have tip labels
95     ## Maybe simply pass the number of tips to the C code??
96     if (!is.null(attr(obj, "TipLabel")))
97         for (i in 1:ntree) obj[[i]]$tip.label <- attr(obj, "TipLabel")
98     ## </FIXME>
99     clades <- .Call("prop_part", obj, ntree, TRUE, PACKAGE = "ape")
100     attr(clades, "number") <- attr(clades, "number")[1:length(clades)]
101     attr(clades, "labels") <- obj[[1]]$tip.label
102     class(clades) <- "prop.part"
103     clades
104 }
105
106 print.prop.part <- function(x, ...)
107 {
108     if (is.null(attr(x, "labels"))) {
109         for (i in 1:length(x)) {
110             cat("==>", attr(x, "number")[i], "time(s):")
111             print(x[[i]], quote = FALSE)
112         }
113     } else {
114         for (i in 1:length(attr(x, "labels")))
115           cat(i, ": ", attr(x, "labels")[i], "\n", sep = "")
116         cat("\n")
117         for (i in 1:length(x)) {
118             cat("==>", attr(x, "number")[i], "time(s):")
119             print(x[[i]], quote = FALSE)
120         }
121     }
122 }
123
124 summary.prop.part <- function(object, ...) attr(object, "number")
125
126 plot.prop.part <- function(x, barcol = "blue", leftmar = 4, ...)
127 {
128     if (is.null(attr(x, "labels")))
129       stop("cannot plot this partition object; see ?prop.part for details.")
130     L <- length(x)
131     n <- length(attr(x, "labels"))
132     layout(matrix(1:2, 2, 1), heights = c(1, 3))
133     par(mar = c(0.1, leftmar, 0.1, 0.1))
134     plot(1:L, attr(x, "number"), type = "h", col = barcol, xlim = c(1, L),
135          xlab = "", ylab = "Frequency", xaxt = "n", bty = "n")
136     plot(0, type = "n", xlim = c(1, L), ylim = c(1, n),
137          xlab = "", ylab = "", xaxt = "n", yaxt = "n")
138     for (i in 1:L) points(rep(i, length(x[[i]])), x[[i]], ...)
139     mtext(attr(x, "labels"), side = 2, at = 1:n, las = 1)
140 }
141
142 prop.clades <- function(phy, ..., part = NULL)
143 {
144     if (is.null(part)) {
145         obj <- list(...)
146         if (length(obj) == 1 && class(obj[[1]]) != "phylo")
147           obj <- unlist(obj, recursive = FALSE)
148         part <- prop.part(obj, check.labels = TRUE)
149     }
150     bp <- .Call("bipartition", phy$edge, length(phy$tip.label),
151                 phy$Nnode, PACKAGE = "ape")
152     if (!is.null(attr(part, "labels")))
153       for (i in 1:length(part))
154         part[[i]] <- sort(attr(part, "labels")[part[[i]]])
155     bp <- lapply(bp, function(xx) sort(phy$tip.label[xx]))
156     n <- numeric(phy$Nnode)
157     for (i in 1:phy$Nnode) {
158         for (j in 1:length(part)) {
159             if (identical(all.equal(bp[[i]], part[[j]]), TRUE)) {
160                 n[i] <- attr(part, "number")[j]
161                 done <-  TRUE
162                 break
163             }
164         }
165     }
166     n
167 }
168
169 boot.phylo <- function(phy, x, FUN, B = 100, block = 1, trees = FALSE)
170 {
171     if (is.list(x)) {
172         if (class(x) == "DNAbin") x <- as.matrix(x)
173         else {
174             nm <- names(x)
175             n <- length(x)
176             x <- unlist(x)
177             nL <- length(x)
178             x <- matrix(x, n, nL/n, byrow = TRUE)
179             rownames(x) <- nm
180         }
181     }
182     boot.tree <- vector("list", B)
183     for (i in 1:B) {
184         if (block > 1) {
185             y <- seq(block, ncol(x), block)
186             boot.i <- sample(y, replace = TRUE)
187             boot.samp <- numeric(ncol(x))
188             boot.samp[y] <- boot.i
189             for (j in 1:(block - 1))
190               boot.samp[y - j] <- boot.i - j
191         } else boot.samp <- sample(ncol(x), replace = TRUE)
192         boot.tree[[i]] <- FUN(x[, boot.samp])
193     }
194     for (i in 1:B) storage.mode(boot.tree[[i]]$Nnode) <- "integer"
195     storage.mode(phy$Nnode) <- "integer"
196     ans <- attr(.Call("prop_part", c(list(phy), boot.tree),
197                       B + 1, FALSE, PACKAGE = "ape"), "number") - 1
198     if (trees) ans <- list(BP = ans, trees = boot.tree)
199     ans
200 }
201
202 consensus <- function(..., p = 1, check.labels = TRUE)
203 {
204     foo <- function(ic, node) {
205         ## ic: index of 'pp'
206         ## node: node number in the final tree
207         pool <- pp[[ic]]
208         if (ic < m) {
209             for (j in (ic + 1):m) {
210                 wh <- match(pp[[j]], pool)
211                 if (!any(is.na(wh))) {
212                     edge[pos, 1] <<- node
213                     pool <- pool[-wh]
214                     edge[pos, 2] <<- nextnode <<- nextnode + 1L
215                     pos <<- pos + 1L
216                     foo(j, nextnode)
217                 }
218             }
219         }
220         size <- length(pool)
221         if (size) {
222             ind <- pos:(pos + size - 1)
223             edge[ind, 1] <<- node
224             edge[ind, 2] <<- pool
225             pos <<- pos + size
226         }
227     }
228     obj <- list(...)
229     if (length(obj) == 1) {
230         ## better than unlist(obj, recursive = FALSE)
231         ## because "[[" keeps the class of 'obj':
232         obj <- obj[[1]]
233         if (class(obj) == "phylo") return(obj)
234     }
235     if (!is.null(attr(obj, "TipLabel")))
236         labels <- attr(obj, "TipLabel")
237     else {
238         labels <- obj[[1]]$tip.label
239         if (check.labels) obj <- .compressTipLabel(obj)
240     }
241     ntree <- length(obj)
242     ## Get all observed partitions and their frequencies:
243     pp <- prop.part(obj, check.labels = FALSE)
244     ## Drop the partitions whose frequency is less than 'p':
245     pp <- pp[attr(pp, "number") >= p * ntree]
246     ## Get the order of the remaining partitions by decreasing size:
247     ind <- sort(unlist(lapply(pp, length)), decreasing = TRUE,
248                 index.return = TRUE)$ix
249     pp <- pp[ind]
250     n <- length(labels)
251     m <- length(pp)
252     edge <- matrix(0L, n + m - 1, 2)
253     if (m == 1) {
254         edge[, 1] <- n + 1L
255         edge[, 2] <- 1:n
256     } else {
257         nextnode <- n + 1L
258         pos <- 1L
259         foo(1, nextnode)
260     }
261     structure(list(edge = edge, tip.label = labels,
262               Nnode = m), class = "phylo")
263 }