3 ## Ancestral Character Estimation
5 ## Copyright 2005-2010 Emmanuel Paradis and Ben Bolker
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
10 ace <- function(x, phy, type = "continuous", method = "ML", CI = TRUE,
11 model = if (type == "continuous") "BM" else "ER",
12 scaled = TRUE, kappa = 1, corStruct = NULL, ip = 0.1)
14 if (!inherits(phy, "phylo"))
15 stop('object "phy" is not of class "phylo".')
16 if (is.null(phy$edge.length))
17 stop("tree has no branch lengths")
18 type <- match.arg(type, c("continuous", "discrete"))
19 nb.tip <- length(phy$tip.label)
21 if (nb.node != nb.tip - 1)
22 stop('"phy" is not rooted AND fully dichotomous.')
23 if (length(x) != nb.tip)
24 stop("length of phenotypic and of phylogenetic data do not match.")
25 if (!is.null(names(x))) {
26 if(all(names(x) %in% phy$tip.label))
28 else warning("the names of 'x' and the tip labels of the tree do not match: the former were ignored in the analysis.")
31 if (kappa != 1) phy$edge.length <- phy$edge.length^kappa
32 if (type == "continuous") {
33 if (method == "pic") {
35 stop('the "pic" method can be used only with model = "BM".')
36 ## See pic.R for some annotations.
37 phy <- reorder(phy, "pruningwise")
38 phenotype <- numeric(nb.tip + nb.node)
39 phenotype[1:nb.tip] <- if (is.null(names(x))) x else x[phy$tip.label]
40 contr <- var.con <- numeric(nb.node)
41 ans <- .C("pic", as.integer(nb.tip), as.integer(nb.node),
42 as.integer(phy$edge[, 1]), as.integer(phy$edge[, 2]),
43 as.double(phy$edge.length), as.double(phenotype),
44 as.double(contr), as.double(var.con),
45 as.integer(CI), as.integer(scaled),
47 obj$ace <- ans[[6]][-(1:nb.tip)]
48 names(obj$ace) <- (nb.tip + 1):(nb.tip + nb.node)
51 CI95 <- matrix(NA, nb.node, 2)
52 CI95[, 1] <- obj$ace + se * qnorm(0.025)
53 CI95[, 2] <- obj$ace - se * qnorm(0.025)
59 tip <- phy$edge[, 2] <= nb.tip
60 dev.BM <- function(p) {
61 if (p[1] < 0) return(1e100) # in case sigma² is negative
62 x1 <- p[-1][phy$edge[, 1] - nb.tip]
63 x2 <- numeric(length(x1))
64 x2[tip] <- x[phy$edge[tip, 2]]
65 x2[!tip] <- p[-1][phy$edge[!tip, 2] - nb.tip]
66 -2 * (-sum((x1 - x2)^2/phy$edge.length)/(2*p[1]) -
69 out <- nlm(function(p) dev.BM(p),
70 p = c(1, rep(mean(x), nb.node)), hessian = TRUE)
71 obj$loglik <- -out$minimum / 2
72 obj$ace <- out$estimate[-1]
73 names(obj$ace) <- (nb.tip + 1):(nb.tip + nb.node)
74 se <- sqrt(diag(solve(out$hessian)))
75 obj$sigma2 <- c(out$estimate[1], se[1])
78 CI95 <- matrix(NA, nb.node, 2)
79 CI95[, 1] <- obj$ace + se * qt(0.025, nb.node)
80 CI95[, 2] <- obj$ace - se * qt(0.025, nb.node)
85 if (method == "GLS") {
86 if (is.null(corStruct))
87 stop('you must give a correlation structure if method = "GLS".')
88 if (class(corStruct)[1] == "corMartins")
89 M <- corStruct[1] * dist.nodes(phy)
90 if (class(corStruct)[1] == "corGrafen")
91 phy <- compute.brlen(attr(corStruct, "tree"),
93 power = exp(corStruct[1]))
94 if (class(corStruct)[1] %in% c("corBrownian", "corGrafen")) {
95 dis <- dist.nodes(attr(corStruct, "tree"))
96 MRCA <- mrca(attr(corStruct, "tree"), full = TRUE)
97 M <- dis[as.character(nb.tip + 1), MRCA]
98 dim(M) <- rep(sqrt(length(M)), 2)
100 varAY <- M[-(1:nb.tip), 1:nb.tip]
101 varA <- M[-(1:nb.tip), -(1:nb.tip)]
102 V <- corMatrix(Initialize(corStruct, data.frame(x)),
105 o <- gls(x ~ 1, data.frame(x), correlation = corStruct)
107 obj$ace <- drop(varAY %*% invV %*% (x - GM) + GM)
108 names(obj$ace) <- (nb.tip + 1):(nb.tip + nb.node)
110 CI95 <- matrix(NA, nb.node, 2)
111 se <- sqrt((varA - varAY %*% invV %*% t(varAY))[cbind(1:nb.node, 1:nb.node)])
112 CI95[, 1] <- obj$ace + se * qnorm(0.025)
113 CI95[, 2] <- obj$ace - se * qnorm(0.025)
117 } else { # type == "discrete"
119 stop("only ML estimation is possible for discrete characters.")
120 if (!is.factor(x)) x <- factor(x)
124 if (is.character(model)) {
125 rate <- matrix(NA, nl, nl)
126 if (model == "ER") np <- rate[] <- 1
127 if (model == "ARD") {
129 rate[col(rate) != row(rate)] <- 1:np
131 if (model == "SYM") {
132 np <- nl * (nl - 1)/2
133 sel <- col(rate) < row(rate)
139 if (ncol(model) != nrow(model))
140 stop("the matrix given as `model' is not square")
141 if (ncol(model) != nl)
142 stop("the matrix `model' must have as many rows
143 as the number of categories in `x'")
148 tmp <- cbind(1:nl, 1:nl)
149 index.matrix[tmp] <- NA
151 rate[rate == 0] <- np + 1 # to avoid 0's since we will use this as numeric indexing
153 liks <- matrix(0, nb.tip + nb.node, nl)
155 liks[cbind(TIPS, x)] <- 1
156 phy <- reorder(phy, "pruningwise")
158 Q <- matrix(0, nl, nl)
159 dev <- function(p, output.liks = FALSE) {
160 if (any(is.nan(p)) || any(is.infinite(p))) return(1e50)
161 ## from Rich FitzJohn:
162 comp <- numeric(nb.tip + nb.node) # Storage...
164 diag(Q) <- -rowSums(Q)
165 for (i in seq(from = 1, by = 2, length.out = nb.node)) {
167 anc <- phy$edge[i, 1]
168 des1 <- phy$edge[i, 2]
169 des2 <- phy$edge[j, 2]
170 v.l <- matexpo(Q * phy$edge.length[i]) %*% liks[des1, ]
171 v.r <- matexpo(Q * phy$edge.length[j]) %*% liks[des2, ]
174 liks[anc, ] <- v/comp[anc]
176 if (output.liks) return(liks[-TIPS, ])
177 dev <- -2 * sum(log(comp[-TIPS]))
178 if (is.na(dev)) Inf else dev
180 out <- nlminb(rep(ip, length.out = np), function(p) dev(p),
181 lower = rep(0, np), upper = rep(1e50, np))
182 obj$loglik <- -out$objective/2
184 oldwarn <- options("warn")
186 h <- nlm(function(p) dev(p), p = obj$rates, iterlim = 1,
187 stepmax = 0, hessian = TRUE)$hessian
190 warning("The likelihood gradient seems flat in at least one dimension (gradient null):\ncannot compute the standard-errors of the transition rates.\n")
191 else obj$se <- sqrt(diag(solve(h)))
192 obj$index.matrix <- index.matrix
194 obj$lik.anc <- dev(obj$rates, TRUE)
195 colnames(obj$lik.anc) <- lvls
198 obj$call <- match.call()
203 logLik.ace <- function(object, ...) object$loglik
205 deviance.ace <- function(object, ...) -2*object$loglik
207 AIC.ace <- function(object, ..., k = 2)
209 if (is.null(object$loglik)) return(NULL)
210 ## Trivial test of "type"; may need to be improved
211 ## if other models are included in ace(type = "c")
212 np <- if (!is.null(object$sigma2)) 1 else length(object$rates)
213 -2*object$loglik + np*k
217 anova.ace <- function(object, ...)
219 X <- c(list(object), list(...))
220 df <- sapply(lapply(X, "[[", "rates"), length)
221 ll <- sapply(X, "[[", "loglik")
222 ## check if models are in correct order?
223 dev <- c(NA, 2*diff(ll))
224 ddf <- c(NA, diff(df))
225 table <- data.frame(ll, df, ddf, dev,
226 pchisq(dev, ddf, lower.tail = FALSE))
227 dimnames(table) <- list(1:length(X), c("Log lik.", "Df",
228 "Df change", "Resid. Dev",
230 structure(table, heading = "Likelihood Ratio Test Table",
231 class = c("anova", "data.frame"))
234 print.ace <- function(x, digits = 4, ...)
236 cat("\n Ancestral Character Estimation\n\n")
240 if (!is.null(x$loglik))
241 cat(" Log-likelihood:", x$loglik, "\n\n")
242 ratemat <- x$index.matrix
243 if (is.null(ratemat)) { # to be improved
245 x$loglik <- x$call <- NULL
248 dimnames(ratemat)[1:2] <- dimnames(x$lik.anc)[2]
249 cat("Rate index matrix:\n")
250 print(ratemat, na.print = ".")
252 npar <- length(x$rates)
253 estim <- data.frame(1:npar, round(x$rates, digits), round(x$se, digits))
254 cat("Parameter estimates:\n")
255 names(estim) <- c("rate index", "estimate", "std-err")
256 print(estim, row.names = FALSE)
257 cat("\nScaled likelihoods at the root (type '...$lik.anc' to get them for all nodes):\n")
258 print(x$lik.anc[1, ])