Benchmark for PSV family functions
psv
library(phyr)
# simulate data
nspp = 500
nsite = 100
tree_sim = ape::rtree(n = nspp)
comm_sim = matrix(rbinom(nspp * nsite, size = 1, prob = 0.6),
nrow = nsite, ncol = nspp)
row.names(comm_sim) = paste0("site_", 1:nsite)
colnames(comm_sim) = paste0("t", 1:nspp)
comm_sim = comm_sim[, tree_sim$tip.label]
# about 40 times faster
rbenchmark::benchmark(
"picante" = {picante::psv(comm_sim, tree_sim)},
"phyr R" = {phyr::psv(comm_sim, tree_sim, cpp = FALSE)},
"phyr c++" = {phyr::psv(comm_sim, tree_sim, cpp = TRUE)},
replications = 10,
columns = c("test", "replications", "elapsed",
"relative", "user.self", "sys.self"))
#> test replications elapsed relative user.self sys.self
#> 3 phyr c++ 10 0.339 1.000 0.298 0.030
#> 2 phyr R 10 3.287 9.696 2.907 0.303
#> 1 picante 10 16.265 47.979 14.824 0.795
pse
comm_sim = matrix(rpois(nspp * nsite, 3), nrow = nsite, ncol = nspp)
row.names(comm_sim) = paste0("site_", 1:nsite)
colnames(comm_sim) = paste0("t", 1:nspp)
comm_sim = comm_sim[, tree_sim$tip.label]
# about 2-3 times faster
rbenchmark::benchmark(
"picante" = {picante::pse(comm_sim, tree_sim)},
"phyr R" = {phyr::pse(comm_sim, tree_sim, cpp = FALSE)},
"phyr c++" = {phyr::pse(comm_sim, tree_sim, cpp = TRUE)},
replications = 20,
columns = c("test", "replications", "elapsed",
"relative", "user.self", "sys.self"))
#> test replications elapsed relative user.self sys.self
#> 3 phyr c++ 20 1.456 1.000 1.329 0.105
#> 2 phyr R 20 4.233 2.907 3.453 0.555
#> 1 picante 20 3.858 2.650 3.319 0.475
pcd
# pcd is about 20 times faster
rbenchmark::benchmark(
"phyr" = {phyr::pcd(comm = comm_a, tree = phylotree, reps = 1000, verbose = FALSE)},
"picante" = {picante::pcd(comm = comm_a, tree = phylotree, reps = 1000)},
replications = 10,
columns = c("test", "replications", "elapsed",
"relative", "user.self", "sys.self"))
#> test replications elapsed relative user.self sys.self
#> 1 phyr 10 0.214 1.000 0.192 0.012
#> 2 picante 10 4.516 21.103 4.043 0.074Benchmark for pglmm()
The benchmarks below were run on a MacBook Pro (Apple M1 Pro, 32 GB of memory) with R 4.6.0 and Apple’s Accelerate BLAS library, with phyr 1.4.0, lme4 2.0.1, glmmTMB 1.1.15.2 and Matrix 1.7.5; the times and memory of phyr were measured again with phyr 1.9.1 (and Matrix 1.7.6), whose fits are faster with the same estimates. Each model was fitted once, in a new R session; times are elapsed seconds, and memory is the peak memory of the R session (which uses about 0.3 GB with the packages loaded).
This vignette is about speed. For why phylogenetic random terms matter (without them, tests of the effects of traits on community composition reject a true null hypothesis far too often), see Li, D. & Ives, A. R. (2017) The statistical need to include phylogeny in trait-based analyses of community composition. Methods in Ecology and Evolution, 8, 1192–1199, doi:10.1111/2041-210X.12767.
Simulated data
Community data: nsp species (with a coalescent tree) at
20 sites, with 80% of the combinations of species and sites observed, a
covariate x, and phylogenetic and non-phylogenetic
variation among species, variation among sites, and phylogenetic
variation of species within sites. The phylogenetic effects are
simulated along the tree (Brownian motion), so that large trees do not
need the covariance matrix of the species.
sim_data <- function(nsp, nsite = 20, seed = 1) {
set.seed(seed)
phy <- ape::rcoal(nsp, tip.label = paste0("sp", 1:nsp))
h <- max(ape::node.depth.edgelength(phy))
bm <- function(sd) ape::rTraitCont(phy, sigma = sd / sqrt(h))[phy$tip.label]
d <- expand.grid(sp = phy$tip.label, site = paste0("s", 1:nsite), stringsAsFactors = FALSE)
d <- d[sort(sample(nrow(d), round(0.8 * nrow(d)))), ]
i <- match(d$sp, phy$tip.label)
j <- match(d$site, paste0("s", 1:nsite))
u_phy <- bm(0.5)
u_sp <- rnorm(nsp, sd = 0.3)
u_site <- rnorm(nsite, sd = 0.5)
u_nested <- sapply(1:nsite, function(k) bm(0.3)) # one column per site
d$x <- rnorm(nrow(d))
eta <- 0.3 * d$x + u_phy[i] + u_sp[i] + u_site[j] + u_nested[cbind(i, j)]
d$y <- eta + rnorm(nrow(d))
d$pa <- rbinom(nrow(d), 1, plogis(eta - 0.5))
d$count <- rpois(nrow(d), exp(eta - 0.5))
list(d = d, phy = phy)
}Comparison with lme4 and glmmTMB
Models without phylogeny, (1 | sp) + (1 | site), fitted
by maximum likelihood with pglmm(),
lme4::lmer() and lme4::glmer(), and
glmmTMB():
s <- sim_data(5000)
d <- s$d
pglmm(pa ~ x + (1 | sp) + (1 | site), data = d, family = "binomial", REML = FALSE,
add.obs.re = FALSE)
lme4::glmer(pa ~ x + (1 | sp) + (1 | site), data = d, family = "binomial")
glmmTMB::glmmTMB(pa ~ x + (1 | sp) + (1 | site), data = d, family = "binomial")| Species | Observations | Family | phyr | lme4 | glmmTMB |
|---|---|---|---|---|---|
| 1000 | 16,000 | gaussian | 0.11 | 0.62 | 1.71 |
| 1000 | 16,000 | binomial | 0.48 | 1.68 | 1.79 |
| 1000 | 16,000 | poisson | 0.39 | 1.60 | 1.63 |
| 2000 | 32,000 | gaussian | 0.13 | 0.72 | 2.39 |
| 2000 | 32,000 | binomial | 0.73 | 3.33 | 2.58 |
| 2000 | 32,000 | poisson | 0.73 | 2.77 | 2.22 |
| 5000 | 80,000 | gaussian | 0.38 | 1.16 | 4.94 |
| 5000 | 80,000 | binomial | 1.97 | 8.44 | 5.04 |
| 5000 | 80,000 | poisson | 1.99 | 9.43 | 5.04 |
Time (seconds). With 5000 species, the R sessions used 0.6 to 0.8 GB of memory with phyr and lme4, and 1.0 to 1.2 GB with glmmTMB. The three packages give the same estimates: the log-likelihoods of phyr and glmmTMB agree to 1e-7, their slopes to 1e-6 and the standard errors of the slopes to 2e-5 (relative); lme4 stops slightly earlier for binomial and poisson models (log-likelihoods lower by up to 1e-3), and its standard errors of the slopes of these models are up to 1.6% smaller (they are computed differently).
Models with a phylogenetic term, (1 | sp__) + (1 | site)
in phyr, which is
(1 | sp) + propto(0 + sp | g, C) + (1 | site) in glmmTMB
(with g a factor with one level and C the
phylogenetic covariance matrix); lme4 cannot fit phylogenetic terms:
s <- sim_data(5000)
d <- s$d
pglmm(pa ~ x + (1 | sp__) + (1 | site), data = d, family = "binomial",
cov_ranef = list(sp = s$phy), REML = FALSE, add.obs.re = FALSE)
d$spf <- factor(d$sp, levels = s$phy$tip.label)
d$g <- factor(1)
C <- ape::vcv(s$phy)
glmmTMB::glmmTMB(pa ~ x + (1 | spf) + propto(0 + spf | g, C) + (1 | site),
data = d, family = "binomial")| Species | Observations | Family | phyr | glmmTMB | phyr memory (GB) | glmmTMB memory (GB) |
|---|---|---|---|---|---|---|
| 300 | 4,800 | gaussian | 0.09 | 1.87 | 0.4 | 0.6 |
| 300 | 4,800 | binomial | 0.29 | 2.06 | 0.4 | 0.5 |
| 300 | 4,800 | poisson | 0.31 | 1.77 | 0.4 | 0.6 |
| 1000 | 16,000 | gaussian | 0.21 | 12.2 | 0.4 | 2.1 |
| 1000 | 16,000 | binomial | 1.18 | 11.3 | 0.4 | 2.1 |
| 1000 | 16,000 | poisson | 1.07 | 12.0 | 0.4 | 2.1 |
| 2000 | 32,000 | gaussian | 0.32 | 73.8 | 0.4 | 7.4 |
| 2000 | 32,000 | binomial | 2.49 | 66.2 | 0.5 | 7.1 |
| 2000 | 32,000 | poisson | 2.60 | 63.0 | 0.5 | 7.2 |
| 5000 | 80,000 | gaussian | 0.98 | 703 | 0.7 | 13.0 |
| 5000 | 80,000 | binomial | 6.14 | 671 | 0.8 | 12.5 |
| 5000 | 80,000 | poisson | 6.02 | 708 | 0.8 | 11.7 |
Time (seconds) and memory. glmmTMB works with the dense covariance
matrix of the species, so its time and memory grow much faster than the
number of species, while phyr uses the sparse precision matrix of the
phylogeny (sparse = TRUE, the default): with 5000 species,
phyr is 110 to 720 times faster, with less than a tenth of the memory.
The estimates are the same: log-likelihoods within 4e-7, slopes within
3e-6, and standard errors within 5e-5 (relative).
Large phylogenies
The full model of the simulated data,
y ~ x + (1 | sp__) + (1 | site) + (1 | sp__@site), with the
defaults of pglmm() (REML, the Laplace approximation for
binomial and poisson models, and the sparse code):
s <- sim_data(10000)
pglmm(pa ~ x + (1 | sp__) + (1 | site) + (1 | sp__@site), data = s$d,
family = "binomial", cov_ranef = list(sp = s$phy))| Species | Observations | gaussian | binomial | poisson | Memory (GB) |
|---|---|---|---|---|---|
| 1000 | 16,000 | 4.6 | 8.6 | 9.7 | 0.5 to 0.6 |
| 2000 | 32,000 | 5.3 | 15.4 | 25.3 | 0.7 to 0.9 |
| 5000 | 80,000 | 12.8 | 48.9 | 61.7 | 1.4 to 1.7 |
| 10000 | 160,000 | 28.1 | 74.6 | 140.7 | 2.1 to 2.7 |
Time (seconds) and memory: time and memory grow about linearly with
the number of species. The nested term (1 | sp__@site) (the
phylogeny of the species within each site) is the most costly: without
it, the models with 5000 species of the previous section took 1 to 6
seconds (fitted by maximum likelihood).
Dense and sparse code, and earlier versions of phyr
The same full model, fitted with the sparse code (the default), with
the dense code (sparse = FALSE, the covariance matrices of
the species), and with phyr 1.1.3 (the dense code, and penalized
quasi-likelihood for binomial models):
| Species | Observations | gaussian, 1.1.3 | gaussian, dense | gaussian, sparse | binomial PQL, 1.1.3 | binomial PQL, sparse | binomial Laplace, sparse |
|---|---|---|---|---|---|---|---|
| 50 | 800 | 16.6 | 0.36 | 0.11 | 30.2 | 0.16 | 0.20 |
| 100 | 1,600 | 139 | 2.2 | 0.37 | 313 | 0.35 | 0.41 |
| 200 | 3,200 | > 900 | 16.3 | 0.63 | > 900 | 1.0 | 1.3 |
| 400 | 6,400 | 100 | 1.6 | 2.6 | 3.9 | ||
| 1000 | 16,000 | 742 | 4.6 | 4.1 | 8.6 |
Time (seconds; phyr 1.1.3 was stopped after 900 seconds). The dense code needed 3.3 GB of memory with 400 species and 9.3 GB with 1000 species, the sparse code 0.4 to 0.5 and 0.5 to 0.6 GB. With up to 400 species, the estimates of phyr 1.1.3 and 1.4.0, and of the dense and sparse code, are the same within the tolerances of the optimizers (variances within 0.006, slopes within 2e-4). With 1000 species, the optimizer of the dense code (L-BFGS) failed after one iteration, with a warning, and the dense fit is 668 units of log-likelihood below the sparse one: use the sparse code (the default) for large models.
Benchmark for phylo_signal()
phylo_signal() estimates Pagel’s lambda or Blomberg’s K
of a trait, optionally with known standard errors of the species means.
It is compared here with phytools::phylosig(),
geiger::fitContinuous(),
phylosignal::phyloSignal(),
picante::phylosignal(), phylolm::phylolm(),
caper::pgls() and nlme::gls() with
ape::corPagel(). Only phytools and geiger also fit lambda
with known standard errors
(phylolm(..., measurement_error = TRUE) estimates an
unknown error variance instead, a different model), and only phytools
fits K with them.
The benchmarks were run on the same computer as those of
pglmm() (Apple M1 Pro, 32 GB, R 4.6.0 with Accelerate
BLAS), with phytools 2.5.2, geiger 2.0.12, phylosignal 1.3.1, picante
1.8.4, phylolm 2.6.5, caper 1.0.4 and nlme 3.1.172, on one core.
Simulated data
A coalescent tree, a trait that evolved by Brownian motion along the tree with its branches transformed by Pagel’s lambda, and, for the fits with measurement error, standard errors between 0.05 and 0.6 with the corresponding noise added to the trait:
sim_trait <- function(n, lambda, se = TRUE, seed = 1) {
set.seed(seed)
phy <- ape::rcoal(n)
tl <- phylolm::transf.branch.lengths(phy, "lambda", parameters = list(lambda = lambda))$tree
x <- ape::rTraitCont(tl, sigma = 1)[phy$tip.label]
s <- NULL
if (se) {
s <- setNames(runif(n, 0.05, 0.6), phy$tip.label)
x <- x + rnorm(n, 0, s)
}
list(phy = phy, x = x, se = s,
data = data.frame(sp = phy$tip.label, x = unname(x), row.names = phy$tip.label))
}
d <- sim_trait(1000, lambda = 0.6)Pagel’s lambda
The same model fitted with each package (without se for
the packages that do not take it):
phylo_signal(x, d$phy, se = se, data = cbind(d$data, se = d$se), species = sp)
phytools::phylosig(d$phy, d$x, method = "lambda", se = d$se)
geiger::fitContinuous(d$phy, d$x, SE = d$se, model = "lambda")
phylosignal::phyloSignal(phylobase::phylo4d(d$phy, tip.data = d$data["x"]), methods = "Lambda")
phylolm::phylolm(x ~ 1, data = d$data, phy = d$phy, model = "lambda")
caper::pgls(x ~ 1, caper::comparative.data(d$phy, d$data, "sp"), lambda = "ML")
nlme::gls(x ~ 1, data = d$data, method = "ML",
correlation = ape::corPagel(0.5, d$phy, form = ~sp, fixed = FALSE))| Species | phyr | phyr, se
|
geiger | geiger, se
|
phylolm | phylosignal | nlme | phytools | phytools, se
|
caper |
|---|---|---|---|---|---|---|---|---|---|---|
| 1000 | < 0.01 | 0.03 | 1.5 | 1.1 | 0.07 | 1.5 | 4.7 | 5.2 | 113 | 63 |
| 2000 | < 0.01 | 0.05 | 2.2 | 1.7 | 0.14 | 10.5 | 36 | 34 | 533 | 241 |
| 5000 | 0.01 | 0.11 | 4.5 | 4.2 | 0.41 | 273 | 683 | 342 | ||
| 20000 | 0.02 | 0.36 | 15.9 | 15.2 | 1.39 |
Time (seconds) for one fit, without tests; empty cells were not run, as the previous size took more than two minutes. phyr, geiger and phylolm compute the likelihood in time linear in the number of species (without the covariance matrix of the species); the other packages use the dense covariance matrix, and their time grows with its cube.
To compare the estimates, the lambda of each package is scored on the same profile log-likelihood (the likelihood of the model maximized over the variance and the mean, at that lambda), the one all packages maximize:
prof_loglik <- function(lambda, x, phy, se = NULL) {
C <- ape::vcv(phy)[names(x), names(x)]
Cl <- lambda * C + (1 - lambda) * diag(diag(C))
M <- if (is.null(se)) 0 else diag(se[names(x)]^2)
ll <- function(log_sig2) {
V <- exp(log_sig2) * Cl + M
iV <- solve(V)
a <- sum(iV %*% x) / sum(iV)
r <- x - a
-0.5 * (sum(r * (iV %*% r)) + determinant(V)$modulus + length(x) * log(2 * pi))
}
optimise(ll, c(-20, 10), maximum = TRUE)$objective
}Across 80 simulated data sets (lambda of 0, 0.3, 0.7 and 1, 10 data sets each, with 100 and 300 species), the number of data sets where the estimate of each package is below the maximum (the log-likelihood of phyr’s estimate) by more than 0.001 and by more than 1:
| Without measurement error | phyr | geiger | phylolm | caper | phytools | phylosignal | nlme |
|---|---|---|---|---|---|---|---|
| Failed | 0 | 0 | 0 | 0 | 0 | 0 | 13 |
| Below by > 0.001 | 0 | 12 | 21 | 21 | 32 | 33 | 4 |
| Below by > 1 | 0 | 3 | 3 | 3 | 10 | 10 | 4 |
| Largest difference | 0 | 3.1 | 3.1 | 3.1 | 5.9 | 5.6 | |
| Median time, 300 species (s) | 0.001 | 0.88 | 0.02 | 3.5 | 0.36 | 0.09 | 0.45 |
The estimates agree on average, and most differences are in data sets
with lambda = 1, where the maximum can be slightly above 1: lambda can
be as large as the height of the tree over the height of its deepest
internal node (for these trees, about 1.00002), and without measurement
error the likelihood rises steeply in that narrow interval. geiger,
phylolm and caper keep lambda below 1; phytools and phylosignal search
up to the maximum with one call to optimize(), whose
precision (about 1e-4) is coarser than the interval. phylolm and caper
also stopped at their lower bound (lambda of 1e-7) in one data set whose
estimate is 0.16. nlme did not converge in 13 data sets, and does not
bound lambda: it returned values below 0 or above the maximum in 4
others (where the covariance matrix is not valid).
| With measurement error | phyr | geiger | phytools |
|---|---|---|---|
| Below by > 0.001 | 0 | 5 | 7 |
| Below by > 1 | 0 | 0 | 7 |
| Largest difference | 0 | 0.04 | 101 |
| Mean lambda, true lambda 0 (300 species) | 0.001 | 0.001 | 0.100 |
| Mean lambda, true lambda 0.3 (300 species) | 0.265 | 0.265 | 0.470 |
| Median time, 300 species (s) | 0.012 | 0.76 | 10 |
With measurement error, phytools stopped at a local maximum near
lambda = 1 in 7 of the 80 data sets (37 to 101 units of log-likelihood
below the maximum), which also changes its test of lambda = 0 from P of
about 1 to P of about 0, and biases its mean estimate upwards. The small
differences of geiger are data sets whose maximum is above 1.
phylo_signal() evaluates the profile likelihood on a grid
of lambda between 0 and the maximum before refining the best value, so
it does not depend on starting values.
Blomberg’s K
d <- sim_trait(2000, lambda = 0.8, se = FALSE)
phylo_signal(d$x, d$phy, method = "K", nsim = 999)
phytools::phylosig(d$phy, d$x, method = "K", test = TRUE, nsim = 999)
picante::phylosignal(d$x[d$phy$tip.label], d$phy, reps = 999)
phylosignal::phyloSignal(phylobase::phylo4d(d$phy, tip.data = d$data["x"]),
methods = "K", reps = 999)| Species | phyr | phylosignal | picante | phytools |
|---|---|---|---|---|
| 500 | 0.03 | 0.18 | 0.39 | 1.1 |
| 1000 | 0.06 | 0.75 | 1.9 | 4.3 |
| 2000 | 0.11 | 4.5 | 14.8 | 18.5 |
Time (seconds) for K and its randomization test with 999
randomizations, without measurement error. The four packages give the
same K (to 8 significant digits), and P-values that agree within the
error of the randomizations. With measurement error (se), K
and its test took 0.19 seconds with phyr and 36 seconds with phytools
for 300 species (the same K), and 0.43 and 2.2 seconds with phyr for
1000 and 5000 species.
Benchmark for cor_phylo()
library(ape)
# Set up parameter values for simulating data
n <- 50
phy <- rcoal(n, tip.label = 1:n)
trt_names <- paste0("par", 1:2)
R <- matrix(c(1, 0.7, 0.7, 1), nrow = 2, ncol = 2)
d <- c(0.3, 0.95)
B2 <- 1
Se <- c(0.2, 1)
M <- matrix(Se, nrow = n, ncol = 2, byrow = TRUE)
colnames(M) <- trt_names
# Set up needed matrices for the simulations
p <- length(d)
star <- stree(n)
star$edge.length <- array(1, dim = c(n, 1))
star$tip.label <- phy$tip.label
Vphy <- vcv(phy)
Vphy <- Vphy/max(Vphy)
Vphy <- Vphy/exp(determinant(Vphy)$modulus[1]/n)
tau <- matrix(1, nrow = n, ncol = 1) %*% diag(Vphy) - Vphy
C <- matrix(0, nrow = p * n, ncol = p * n)
for (i in 1:p) for (j in 1:p) {
Cd <- (d[i]^tau * (d[j]^t(tau)) * (1 - (d[i] * d[j])^Vphy))/(1 - d[i] * d[j])
C[(n * (i - 1) + 1):(i * n), (n * (j - 1) + 1):(j * n)] <- R[i, j] * Cd
}
MM <- matrix(M^2, ncol = 1)
V <- C + diag(as.numeric(MM))
iD <- t(chol(V))
XX <- iD %*% rnorm(2 * n)
X <- matrix(XX, n, p)
colnames(X) <- trt_names
rownames(X) <- phy$tip.label
rownames(M) <- phy$tip.label
U <- list(cbind(rnorm(n, mean = 2, sd = 10)))
names(U) <- trt_names[2]
X[,2] <- X[,2] + B2[1] * U[[1]][,1] - B2[1] * mean(U[[1]][,1])
z <- cor_phylo(variates = X,
covariates = U,
meas_errors = M,
phy = phy,
species = phy$tip.label)
U2 <- list(NULL, matrix(rnorm(n, mean = 2, sd = 10), nrow = n, ncol = 1))
rownames(U2[[2]]) <- phy$tip.label
colnames(U2[[2]]) <- "par2"
X2 = X
X2[,2] <- X2[,2] + B2[1] * U2[[2]][,1] - B2[1] * mean(U2[[2]][,1])
z_r <- corphylo(X = X2, SeM = M, U = U2, phy = phy, method = "Nelder-Mead")
rbenchmark::benchmark(
"cor_phylo" = {cor_phylo(variates = X, covariates = U, meas_errors = M,
phy = phy, species = phy$tip.label)},
"corphylo" = {corphylo(X = X2, SeM = M, U = U2, phy = phy, method = "Nelder-Mead")},
replications = 5,
columns = c("test", "replications", "elapsed",
"relative", "user.self", "sys.self")
)
#> test replications elapsed relative user.self sys.self
#> 1 cor_phylo 5 4.511 1.000 4.329 0.062
#> 2 corphylo 5 16.190 3.589 13.863 1.369