DDD: diversity-dependent diversification models, likelihoods and optimization

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5
)
# Results of the time-consuming analyses in this vignette were computed
# beforehand with the script data-raw/vignette_results.R in the source
# repository of DDD (https://github.com/rsetienne/DDD), and are loaded here.
results <- readRDS("vignette_results.rds")
options(knitr.kable.NA = "-")
show_fit <- function(x, digits = 4) {
  x <- as.data.frame(x)
  num <- vapply(x, is.numeric, logical(1))
  x[num] <- lapply(x[num], signif, digits = digits)
  rownames(x) <- NULL
  x
}
# a number in scientific notation, for use inside $...$
sci <- function(x, digits = 2) {
  e <- floor(log10(abs(x)))
  paste0(signif(x / 10^e, digits), " \\times 10^{", e, "}")
}

1. Introduction

The R package DDD computes the likelihood of a phylogeny (or rather, of its branching times) under birth-death models of diversification, and finds the parameters that maximize this likelihood. Its name refers to its main feature: models in which the speciation rate and/or the extinction rate depend on the number of species in the clade, i.e. diversity-dependent diversification (Etienne et al. 2012). The likelihood of such models cannot be written down in closed form. DDD computes it by solving the master equation for the probability distribution of the number of species that are not visible in the reconstructed phylogeny (extinct lineages, and species that are extant but missing from the tree), along the branching times of the phylogeny (Etienne et al. 2012).

Besides the diversity-dependent models, DDD contains:

This vignette explains the models, shows how to compute likelihoods and how to estimate parameters by maximum likelihood for each model, and describes the optimization methods in detail. The table below lists the main functions.

| Model | Likelihood | Maximum likelihood | Simulation | |:------|:-----------|:-------------------|:-----------| | Constant-rate and time-dependent | bd_loglik | bd_ML | dd_sim (with K = Inf), td_sim | | Diversity-dependent | dd_loglik | dd_ML | dd_sim | | Rate shift in the whole clade | dd_SR_loglik | dd_SR_ML | dd_SR_sim | | Key innovation (decoupled subclade) | dd_KI_loglik | dd_KI_ML | dd_KI_sim | | Macroevolutionary shift (coupled subclade) | dd_MS_loglik | dd_MS_ML | dd_MS_sim | | Test of diversity dependence | | dd_LR | |

The optimization routines are optimizer and optimizer_lhs.

library(DDD)

2. Data: branching times

All likelihood functions in DDD take the branching times of an ultrametric phylogeny as input, rather than the phylogeny itself. Branching times are positive numbers measured from the present backwards: the largest branching time is the crown age (the age of the first split) and the smallest is the age of the most recent split. If the phylogeny has a stem, the stem age can be added as the largest value; we then tell DDD that the first value is a stem age with soc = 1 (the default, soc = 2, means crown age).

Throughout this vignette we use a phylogeny simulated under the linear diversity-dependent model with speciation rate $\lambda_0 = 0.8$, extinction rate $\mu = 0.1$ and carrying capacity $K = 30$, for 10 million years:

set.seed(1)
sim <- dd_sim(pars = c(0.8, 0.1, 30), age = 10)
names(sim)

The first element, tes, is the reconstructed tree of extant species, the second, tas, the complete tree including extinct species, the third, L, a table with the birth time, parent, identity and extinction time of every species that ever lived, and the fourth, brts, the branching times of the reconstructed tree.

oldpar <- par(mfrow = c(1, 2), mar = c(1, 1, 2, 1))
plot(sim$tes, show.tip.label = FALSE, main = "Reconstructed tree")
plot(sim$tas, show.tip.label = FALSE, main = "Complete tree")
par(oldpar)

For a phylogeny of class phylo that is read from a file (e.g. with ape::read.tree or ape::read.nexus), the branching times are obtained with ape::branching.times:

brts <- ape::branching.times(sim$tes)
all.equal(sort(as.numeric(brts)), sort(sim$brts))
brts <- sim$brts
length(brts) + 1 # number of species in the phylogeny
max(brts) # crown age

The lineages-through-time plot shows the typical slowdown of diversification in a diversity-dependent model:

ape::ltt.plot(sim$tes, log = "y", xlab = "Time (before present)",
              ylab = "Number of lineages")

Two other aspects of the data enter the likelihood:

The functions L2phylo, L2brts and phylo2L convert between the event table L produced by the simulation functions, phylogenies and branching times.

3. The models

3.1 Constant-rate and time-dependent models

The functions bd_loglik and bd_ML deal with models in which the rates do not depend on diversity. There are four parameters, identified by number in the maximum likelihood functions:

  1. $\lambda_0$, the speciation rate;
  2. $\mu_0$, the extinction rate;
  3. $\lambda_1$, the rate of decline in the speciation rate, or the carrying capacity $K$ for the models with tdmodel 2 to 4;
  4. $\mu_1$, the rate of decline in the extinction rate.

The argument tdmodel selects the model:

3.2 Diversity-dependent models

In the diversity-dependent models, the speciation rate $\lambda_N$ and/or the extinction rate $\mu_N$ depend on the number of species $N$ in the clade. This number includes the species that are not visible in the reconstructed phylogeny. There are three parameters, $\lambda_0$, $\mu_0$ and $K$ (identified by 1, 2 and 3), and a fourth one, $r$, for ddmodel = 5. The argument ddmodel selects the form of the dependence:

| ddmodel | Speciation rate $\lambda_N$ | Extinction rate $\mu_N$ | Meaning of the third parameter | |:---|:---|:---|:---| | 1 | $\max(0, \lambda_0 - (\lambda_0 - \mu_0) N/K)$ | $\mu_0$ | $K$: diversity at which $\lambda_N = \mu_N$ | | 1.3 | $\max(0, \lambda_0 (1 - N/K'))$ | $\mu_0$ | $K'$: diversity at which $\lambda_N = 0$ | | 1.4 | $\lambda_0 N/(N + K')$ | $\mu_0$ | $K'$: diversity at which $\lambda_N = \lambda_0/2$ (positive diversity dependence) | | 1.5 | $\max(0, \lambda_0 (N/K') (1 - N/K'))$ | $\mu_0$ | $K'$: diversity at which $\lambda_N = 0$ (positive, then negative diversity dependence) | | 2 | $\lambda_0 (N + 1)^{-x}$ | $\mu_0$ | $K$, with $x = \log(\lambda_0/\mu_0)/\log(K + 1)$ so that $\lambda_K = \mu_0$ | | 2.1 | $\lambda_0 N^{-x}$ | $\mu_0$ | $K$, with $x = \log(\lambda_0/\mu_0)/\log(K)$ | | 2.2 | $\lambda_0 / N$ | $\mu_0$ | not used | | 2.3 | $\lambda_0 N^{-x}$ | $\mu_0$ | the exponent $x$ itself | | 3 | $\lambda_0$ | $\mu_0 + (\lambda_0 - \mu_0) N/K$ | $K$: diversity at which $\lambda_N = \mu_N$ | | 4 | $\lambda_0$ | $\mu_0 (N + 1)^{x}$ | $K$, with $x = \log(\lambda_0/\mu_0)/\log(K + 1)$ | | 4.1 | $\lambda_0$ | $\mu_0 N^{x}$ | $K$, with $x = \log(\lambda_0/\mu_0)/\log(K)$ | | 4.2 | $\lambda_0$ | $\mu_0 N$ | not used | | 5 | $\max(0, \lambda_0 - \frac{1}{r+1} (\lambda_0 - \mu_0) N/K)$ | $\mu_0 + \frac{r}{r+1} (\lambda_0 - \mu_0) N/K$ | $K$; $r$ is the ratio of the slopes of the extinction and speciation rates |

The default, ddmodel = 1, is linear diversity dependence in the speciation rate. The parameter $K$ is the clade-level carrying capacity: the diversity at which speciation and extinction balance. With $K = \infty$ the model reduces to the constant-rate birth-death model.

3.3 Conditioning and other settings

The likelihood can be conditioned on aspects of the data, set by cond:

Etienne et al. (2016) discuss the effect of the conditioning on parameter estimates. Further settings are:

3.4 Models with shifts

Rate shift (SR). In the model of dd_SR_loglik and dd_SR_ML the whole clade experiences a shift in its parameters at time $t_{shift}$. There are seven parameters: $\lambda_0$, $\mu_0$ and $K$ before the shift (ids 1 to 3), $\lambda_0$, $\mu_0$ and $K$ after the shift (ids 4 to 6), and $t_{shift}$ (id 7). With idparsnoshift one specifies which parameters do not shift, so that they take the same value before and after the shift. The default is a shift in $K$ only.

Key innovation (KI). In the model of dd_KI_loglik and dd_KI_ML (Etienne & Haegeman 2012) one lineage acquires a key innovation (or enters a new environment) at time $t_d$. From then on, the subclade descending from this lineage has its own speciation rate, extinction rate and carrying capacity, and its diversity dynamics are decoupled from those of the main clade: the subclade does not feel the diversity of the main clade and vice versa. The data consist of the branching times of the main clade (brtsM) and of the subclade (brtsS), and the time at which the lineage leading to the subclade branched off from the main clade (tsplit). The decoupling time $t_d$ lies between tsplit and the crown age of the subclade. There are seven parameters: $\lambda_M$, $\mu_M$ and $K_M$ of the main clade (ids 1 to 3), $\lambda_S$, $\mu_S$ and $K_S$ of the subclade (ids 4 to 6) and $t_d$ (id 7). The argument correction = TRUE (the default) applies the correction to the likelihood of a shift that is placed on a particular branch, described by Laudanno et al. (2021).

Macroevolutionary shift (MS). The model of dd_MS_loglik and dd_MS_ML also lets a subclade acquire a different speciation and extinction rate at time $t_d$, but here the subclade remains coupled to the main clade: both experience the total diversity of the clade and share one carrying capacity. There are six parameters: $\lambda_M$, $\mu_M$, the shared carrying capacity (ids 1 to 3), $\lambda_S$, $\mu_S$ (ids 4 and 5) and $t_d$ (id 6). The default diversity dependence is ddmodel = 1.3, with the carrying capacity $K'$ at which speciation stops.

3.5 Simulation

Each model has a simulation function: dd_sim, dd_SR_sim, dd_KI_sim and dd_MS_sim, and td_sim for the time-dependent model that matches the expected diversity of a diversity-dependent model. They all take a vector of parameters, the crown age and the model, and return the reconstructed and complete trees and the event table L. The functions dd_KI_sim and dd_MS_sim also return the trees of the subclade. Simulations are useful for checking how well parameters can be recovered, and for parametric bootstrapping, as in dd_LR.

4. Computing the likelihood

The likelihood functions take the parameters (pars1), the model settings (pars2), the branching times and the number of missing species. For dd_loglik, pars2 contains, in this order: res, ddmodel, cond, btorph, the verbose level and soc. The loglikelihood of our phylogeny at the parameters used to simulate it, with the defaults of dd_ML, is:

pars2 <- c(res = 10 * (1 + length(brts)), ddmodel = 1, cond = 1, btorph = 1,
           verbose = 0, soc = 2)
dd_loglik(pars1 = c(0.8, 0.1, 30), pars2 = pars2, brts = brts, missnumspec = 0)

The value is the same, up to the accuracy of the integration, when the master equation is solved numerically:

dd_loglik(pars1 = c(0.8, 0.1, 30), pars2 = pars2, brts = brts, missnumspec = 0,
          methode = 'odeint::runge_kutta_cash_karp54')

and for the constant-rate model:

bd_loglik(pars1 = c(0.3, 0.1), pars2 = c(0, 1, 1, 0, 2), brts = brts,
          missnumspec = 0)

For bd_loglik the elements of pars2 are tdmodel, cond, btorph, the verbose level and soc. Parameter values that are not allowed, such as negative rates, give a loglikelihood of -Inf.

5. Maximum likelihood estimation

5.1 The common interface

All maximum likelihood functions (bd_ML, dd_ML, dd_SR_ML, dd_KI_ML and dd_MS_ML) share the same set-up:

The output is a data frame with the estimated (and fixed) parameters, the maximum loglikelihood (loglik), the number of estimated parameters (df) and a convergence code (conv; 0 means that the optimization converged). The functions also print the results. If the initial parameter values have a likelihood of zero, the function reports this and returns -1 for all values; other initial values should then be tried.

5.2 Constant-rate and time-dependent models

The constant-rate birth-death model estimates $\lambda_0$ and $\mu_0$:

fit_cr <- bd_ML(brts = brts)
fit_cr

The estimated extinction rate is zero, at the boundary of the parameter space, a common finding for phylogenies whose diversification slows down. For the model with an exponential decline in the speciation rate we estimate $\lambda_0$, $\mu_0$ and $\lambda_1$, and fix $\mu_1 = 0$:

fit_td1 <- bd_ML(brts = brts, tdmodel = 1, initparsopt = c(0.5, 0.1, 0.1),
                 idparsopt = 1:3, idparsfix = 4, parsfix = 0)
fit_td1

The time-dependent model that matches the expected diversity of the diversity-dependent model (tdmodel = 4) takes longer to fit:

fit_td4 <- bd_ML(brts = brts, tdmodel = 4, initparsopt = c(0.5, 0.1, 40),
                 idparsopt = 1:3, idparsfix = 4, parsfix = 0)
show_fit(results$td_fits$td4$value)

5.3 Diversity-dependent models

A quick way to fit the linear diversity-dependent model is to fix the extinction rate at 0 and estimate only $\lambda_0$ and $K$:

fit_dd_mu0 <- dd_ML(brts = brts, initparsopt = c(0.5, 30), idparsopt = c(1, 3),
                    idparsfix = 2, parsfix = 0)
fit_dd_mu0

Estimating all three parameters (with the default initial values $\lambda_0 = 0.2$, $\mu_0 = 0.1$ and $K = 2 \times$ the number of species) takes longer; the result below took r round(results$dd_fits$seconds[results$dd_fits$ddmodel == 1]) seconds:

fit_dd <- dd_ML(brts = brts)
show_fit(results$dd_fits[results$dd_fits$ddmodel == 1,
                         c("lambda", "mu", "K", "loglik", "df", "conv")])

The estimates are close to the values used in the simulation ($\lambda_0 = 0.8$, $\mu = 0.1$, $K = 30$); speciation and extinction rates are notoriously hard to estimate precisely from a single phylogeny of this size, but $K$ is well estimated here.

Other forms of diversity dependence are fitted by changing ddmodel. For ddmodel = 5 the default initial value of $r$ is 0.01. The table below compares all models fitted to our phylogeny, using Akaike's information criterion, $\mathrm{AIC} = 2\,\mathrm{df} - 2 \log L$, and its version corrected for small samples, $\mathrm{AIC_c}$, with the number of branching times as sample size:

for(ddmodel in c(1, 1.3, 2, 2.1, 2.3, 3, 4, 5)) {
  print(dd_ML(brts = brts, ddmodel = ddmodel))
}
dd <- results$dd_fits
tab <- data.frame(model = c("bd_ML, tdmodel = 0",
                            "bd_ML, tdmodel = 1",
                            "bd_ML, tdmodel = 4",
                            paste0("dd_ML, ddmodel = ", dd$ddmodel)),
                  loglik = c(fit_cr$loglik, fit_td1$loglik,
                             results$td_fits$td4$value$loglik, dd$loglik),
                  df = c(fit_cr$df, fit_td1$df,
                         results$td_fits$td4$value$df, dd$df),
                  conv = c(fit_cr$conv, fit_td1$conv,
                           results$td_fits$td4$value$conv, dd$conv))
n <- length(brts)
tab$AIC <- 2 * tab$df - 2 * tab$loglik
tab$AICc <- tab$AIC + 2 * tab$df * (tab$df + 1) / (n - tab$df - 1)
tab$delta_AICc <- tab$AICc - min(tab$AICc)
tab <- tab[order(tab$AICc), ]
rownames(tab) <- NULL
knitr::kable(tab, digits = 2)

A few things stand out in this table. Models with ddmodel = 1 and ddmodel = 1.3 have the same maximum: they are the same model with a different parameter for the carrying capacity ($K' = \lambda_0 K/(\lambda_0 - \mu_0)$). The models with diversity dependence in the extinction rate (ddmodel 3 and 4) fit no better than the constant-rate model: the estimated extinction rate is practically zero, so there is no extinction for diversity to act on.

Models with ddmodel = 2.1 and ddmodel = 2.3 also have the same maximum, for the same reason: both have the speciation rate $\lambda_0 N^{-x}$, with $x = \log(\lambda_0/\mu_0)/\log K$ in ddmodel = 2.1 and $x$ as a parameter in ddmodel = 2.3. For this phylogeny the maximum is at $\mu_0 = 0$, with $x =$ r round(results$dd_fits$K[results$dd_fits$ddmodel == 2.3], 3). In the parameters of ddmodel = 2.1, $\mu_0 = 0$ means $K = \infty$, so its loglikelihood keeps increasing along a ridge towards $\mu_0 = 0$ and $K = \infty$ on which $x$ hardly changes. The simplex method follows such a ridge only very slowly and, with the default tolerances, does not stop on it, because a parameter that keeps shrinking towards 0 cannot meet the relative tolerance in the parameters (tol[1]). dd_ML therefore optimizes ddmodel = 2.1 as ddmodel = 2.3, with $x$ in place of $K$, and converts the estimate back to $K = (\lambda_0/\mu_0)^{1/x}$; the estimate of $x$ is shown in the printed output. For our phylogeny this took r round(results$dd_fits$seconds[results$dd_fits$ddmodel == 2.1]) seconds and gave $\mu_0 = r sci(results$dd_fits$mu[results$dd_fits$ddmodel == 2.1])$ and $K = r sci(results$dd_fits$K[results$dd_fits$ddmodel == 2.1])$: such a small $\mu_0$ with such a large $K$ means that the maximum is at $\mu_0 = 0$ and $K = \infty$. $K$ is not reported as Inf, as dd_ML does for other models when $K > 10^7$, because together with $\mu_0$ it still gives the right $x$, and hence the maximum loglikelihood.

We left out ddmodel = 4.1, because its optimization does not finish. Its extinction rate $\mu_0 N^x$, with $x = \log(\lambda_0/\mu_0)/\log K$, can be written as $\mu_N = \lambda_0 (N/K)^x$. When $\mu_0$ goes to 0, $x$ goes to infinity, so the extinction rate goes to 0 for $N < K$ and to infinity for $N > K$: the model becomes a pure-birth model with a hard ceiling at $K$ species. For our phylogeny the loglikelihood keeps increasing on the way to this limit, so its maximum is not at any $\mu_0 > 0$. The limit is approached extremely slowly, because $\mu_0$ only enters through $x$, i.e. through $\log \mu_0$. In a run with res = 100, the optimization had reached $\lambda_0 = 0.20$, $\mu_0 = 2.4 \times 10^{-16}$ and $K = 33.4$ after 18 minutes, which gives $x = 9.8$, and an extinction rate at $N = 33$ that is still $0.89\lambda_0$; at $\mu_0 = 10^{-300}$, close to the smallest positive number a computer can represent, it would still be $0.1\lambda_0$. The loglikelihood was still increasing by about 0.03 for every fourfold decrease of $\mu_0$, whereas convergence requires the loglikelihoods at all points of the simplex to lie within tol[2] $\times$ 78 $\approx 0.008$ of each other. The relative tolerance in the parameters (tol[1]) cannot be met either by a $\mu_0$ that keeps shrinking. Meanwhile every likelihood evaluation becomes slower, because the extinction rates at large $N$ grow without bound (at $N = 100$ it was already $46\,000 \lambda_0$), which makes the master equation stiff: an evaluation took one to one and a half minutes at the end. The loglikelihood on this path (about $-78.2$) stays well below that of the linear diversity-dependent model.

More importantly, ddmodel = 5 contains ddmodel = 1 as the special case $r = 0$, so its maximum loglikelihood must be at least as high. Yet the optimization ended at r round(results$dd_fits$loglik[results$dd_fits$ddmodel == 5], 3), lower than the r round(results$dd_fits$loglik[results$dd_fits$ddmodel == 1], 3) of ddmodel = 1: the simplex stopped before reaching the maximum. Restarting the optimization from the result until it no longer changes (Section 6.2) solves this here:

fit_dd5 <- dd_ML(brts = brts, ddmodel = 5, num_cycles = Inf)
show_fit(results$dd5_cycles$value)

Comparing nested models in this way is a cheap check on the optimization: a model can never have a lower maximum likelihood than a model it contains.

Information criteria should be interpreted with care here. Pannetier et al. (2021) found that standard model selection criteria favoured diversity dependence even for phylogenies simulated under the time-dependent model with tdmodel = 4, and that after a bootstrap correction neither model was decisively supported. Moreover, the conditioning and the size of the phylogeny affect the power to detect diversity dependence (Etienne et al. 2016). The bootstrap likelihood ratio test of Section 5.6 accounts for this.

5.4 Rate-shift model

By default, dd_SR_ML estimates $\lambda_0$, $\mu_0$, $K$ before the shift, $K$ after the shift and the time of the shift (idparsopt = c(1:3, 6:7)), with $\lambda_0$ and $\mu_0$ not shifting (idparsnoshift = c(4, 5)):

fit_sr <- dd_SR_ML(brts = brts)
show_fit(results$sr_fit$value)

The rate-shift model contains the diversity-dependent model as the special case in which $K$ does not shift, so its maximum loglikelihood must be at least r round(results$dd_fits$loglik[results$dd_fits$ddmodel == 1], 3), the maximum found by dd_ML. The optimization from the default initial values ended at r round(results$sr_fit$value$loglik, 3), so it got stuck in a local optimum. Multi-start optimization (Section 6.6), with ranges for all seven parameters of which the five optimized ones are used, finds a higher maximum, at the cost of a much longer computation (r round(results$sr_lhs_fit$seconds / 60) minutes here):

fit_sr_lhs <- dd_SR_ML(
  brts = brts,
  optimmethod = list(lower = c(0.05, 0, 25, 0.05, 0, 25, 0.5),
                     upper = c(3, 1.5, 500, 3, 1.5, 500, 9.5),
                     sampling_scale = c('transformed', 'transformed', 'log',
                                        'transformed', 'transformed', 'log',
                                        'original'),
                     strategy = 'screen',
                     num_samples = 500,
                     num_best = 5))
show_fit(results$sr_lhs_fit$value)

The improvement over the diversity-dependent model without a shift is small for a model with two more parameters, so there is no support for a shift here; but the comparison would have been misleading had we relied on the first fit.

The likelihood surface of this model is often rugged in the direction of the shift time, with local optima near branching times. With allbp = TRUE, the likelihood is also optimized with the shift time fixed just before and just after each branching time; this is slow but helps to find the global optimum. Multi-start optimization (Section 6.6) is an alternative.

5.5 Key innovation and macroevolutionary shift models

For the subclade models we use the small artificial data set of the help pages, with the main clade, the subclade, and the split between them at time 5:

brtsM <- 4:10
brtsS <- seq(0.1, 3.5, 0.7)
tsplit <- 5

In the key innovation model we estimate $\lambda_M$, $\mu_M$, $K_M$, $K_S$ and $t_d$, and let the subclade have the same speciation and extinction rate as the main clade (idparsnoshift = c(4, 5)):

fit_ki <- dd_KI_ML(brtsM = brtsM, brtsS = brtsS, tsplit = tsplit,
                   idparsopt = c(1:3, 6, 7), initparsopt = c(0.9, 0.05, 7, 7, 4),
                   idparsfix = NULL, parsfix = NULL, idparsnoshift = c(4, 5),
                   cond = 0)
show_fit(results$ki_fit$value)

The estimated decoupling time equals the most recent branching time of the main clade (4). With the estimated carrying capacity of the main clade, a more recent decoupling gives a likelihood of zero, and the likelihood decreases for earlier decoupling times, so the maximum lies on this boundary.

In the macroevolutionary shift model the subclade shares the carrying capacity with the main clade; here we estimate $\lambda_M$, $\mu_M$, $K'$ and $t_d$. Note that with ddmodel = 1.3 speciation stops when the clade has $K'$ species, so the initial value of $K'$ must be larger than the total number of species (here 14); otherwise the initial likelihood is zero:

fit_ms <- dd_MS_ML(brtsM = brtsM, brtsS = brtsS, tsplit = tsplit,
                   idparsopt = c(1:3, 6), initparsopt = c(0.9, 0.05, 20, 4),
                   idparsfix = NULL, parsfix = NULL, idparsnoshift = c(4, 5),
                   cond = 0)
show_fit(results$ms_fit$value)

5.6 Bootstrap likelihood ratio test of diversity dependence

dd_LR tests the diversity-dependent model against the constant-rate model (Etienne et al. 2016). It fits both models to the data, simulates endmc phylogenies under each fitted model, refits both models to every simulated phylogeny, and uses the distribution of the likelihood ratio under the constant-rate model to compute a p-value, and its distribution under the diversity-dependent model to compute the power of the test. Because the diversity-dependent model is fitted from two sets of initial values for each simulated tree, this takes a long time; the default of 1000 bootstrap replicates is recommended for real analyses:

lr <- dd_LR(brts = brts, initparsoptDD = c(0.5, 0.1, 40),
            initparsoptCR = c(0.2, 0.05), missnumspec = 0, endmc = 1000)
lr$pvalue
lr$poweroftest

6. Optimization

6.1 What happens inside the maximum likelihood functions

Every maximum likelihood function in DDD follows the same steps:

  1. The initial values of the parameters are transformed with $x \mapsto x/(1 + x)$, which maps the parameter range $[0, \infty)$ onto $[0, 1)$, with $\infty$ mapped onto 1. This transformation is available as transform_pars, its inverse as untransform_pars.
  2. A function is built that takes the transformed parameters to be optimized, inserts the fixed parameters, checks whether the values are allowed, transforms them back and computes the loglikelihood. Values that are not allowed, and numerical problems, give -Inf.
  3. This function is maximized by optimizer, using the method set by optimmethod, starting from the transformed initial values.
  4. The optimized parameters are transformed back and returned.
transform_pars(c(0, 0.1, 1, 30, 1000, Inf))
untransform_pars(c(0, 0.5, 0.99))

The transformation has several advantages. The search space is bounded, which is needed by the global optimization methods. Parameters on very different scales, such as rates around 0.1 and carrying capacities in the hundreds, are brought to a comparable scale. And a carrying capacity of infinity, which reduces the diversity-dependent model to the constant-rate model, corresponds to the finite value 1, so the optimizer can approach it (dd_ML reports a $K$ larger than $10^7$ as Inf). A consequence is that the tolerances of the optimization (Section 6.2) apply to the transformed parameters.

The function optimizer can also be called directly, with any function that takes the transformed parameters as an argument called trparsopt:

loglik_bd <- function(trparsopt, brts) {
  pars <- untransform_pars(trparsopt)
  bd_loglik(pars1 = pars, pars2 = c(0, 1, 1, 0, 2), brts = brts, missnumspec = 0)
}
out <- optimizer(optimmethod = 'simplex',
                 optimpars = c(1E-4, 1E-4, 1E-6, 1000, 0),
                 fun = loglik_bd,
                 trparsopt = transform_pars(c(0.2, 0.05)),
                 brts = brts)
out$fvalues
untransform_pars(out$par)

It returns a list with the optimized (transformed) parameters par, the maximum fvalues and the convergence code conv. Additional arguments, here brts, are passed on to the function being optimized. The same holds for the likelihood of the diversity-dependent model, which we use below to compare optimization methods:

loglik_dd <- function(trparsopt, brts) {
  # the same checks as in the likelihood wrapper inside dd_ML: no negative
  # values, no infinite speciation or extinction rate, and lambda0 > mu0
  if(any(trparsopt < 0) || any(trparsopt > 1) || any(trparsopt[1:2] == 1) ||
     trparsopt[1] <= trparsopt[2]) return(-Inf)
  pars <- untransform_pars(trparsopt)
  loglik <- dd_loglik(pars1 = pars,
                      pars2 = c(10 * (1 + length(brts)), 1, 1, 1, 0, 2),
                      brts = brts, missnumspec = 0)
  if(!is.finite(loglik)) loglik <- -Inf # NaN, NA or Inf: numerical problems
  loglik
}

6.2 Tolerances, iterations and convergence

The settings of the optimization are passed to optimizer as optimpars, a vector of five elements. The maximum likelihood functions compose it from their arguments as c(tol, maxiter, verbose):

  1. tol[1], the relative tolerance in the parameters (default 1E-3 in the ML functions);
  2. tol[2], the relative tolerance in the loglikelihood (default 1E-4);
  3. tol[3], the absolute tolerance in the parameters (default 1E-6);
  4. maxiter, the maximum number of iterations (default $1000 \times \mathrm{round}(1.25^d)$ for $d$ estimated parameters);
  5. the verbose level: with 1 or more, optimizer shows the trajectory of the optimization and the result.

How these settings are used depends on the method:

| optimmethod | Stopping rule | maxiter counts | |:---|:---|:---| | 'simplex' | all three tolerances must be met (see Section 6.3) | iterations | | 'subplex' | relative change in the parameters below tol[1] | function evaluations | | 'optim::...' | relative change in the loglikelihood below tol[2] (reltol of optim); 'optim::Brent': tol[3] in the parameter; 'optim::L-BFGS-B': its own criteria (factr and pgtol of optim) | iterations (maxit) | | 'DEoptim' | no relative improvement larger than tol[2] in 100 generations | generations | | 'pso' | no improvement larger than tol[2] (relatively) plus tol[3] in 100 iterations | iterations | | 'cmaes' | default stopping conditions of cmaesr, then as 'subplex' | function evaluations of subplex |

The convergence code is 0 when the optimization ended because the stopping rule was met, and nonzero when, for instance, maxiter was reached. With changeloglikifnoconv = TRUE the ML functions report a loglikelihood of -Inf for an optimization that did not converge, which is convenient when many fits are run in batch, e.g. on simulated data.

Cycles. With num_cycles larger than 1, the optimization is restarted from the optimum found in the previous cycle until the maximum loglikelihood changes by less than tol[3] between cycles, or num_cycles cycles have been done; num_cycles = Inf means at most 10 cycles. Restarting helps local methods such as the simplex method, which can stop prematurely when the simplex has collapsed along a ridge of the likelihood surface; the new simplex is built afresh around the current best point. For our phylogeny:

fit_cycles <- dd_ML(brts = brts, num_cycles = Inf)
show_fit(results$cycles_fit$value)

6.3 Local methods

Local methods move uphill from the initial values and find the nearest maximum, which is not necessarily the global one.

'simplex' (the default) is DDD's own implementation of the Nelder-Mead simplex algorithm. It starts with a simplex of $d + 1$ points: the initial values and $d$ points in which one parameter is increased by (at most) 5%, or set to 0.00025 on the transformed scale if it is 0. In every iteration the worst point is reflected through the centroid of the other points; depending on the loglikelihood at the reflected point the step is expanded (factor 2), accepted, or contracted (factor 0.5), and if none of these improves the simplex, the whole simplex shrinks towards the best point (factor 0.5). The algorithm stops when the loglikelihoods of all points differ from the best one by less than tol[2] times its absolute value, and all parameters differ from those of the best point by less than tol[1] times their value and by less than tol[3]. With verbose level 1 or higher every iteration is shown with its parameters (on the original scale), its loglikelihood and the type of step. The method needs no derivatives, copes well with -Inf values, and is robust, but it can be slow for many parameters.

'subplex' uses the subplex algorithm of Rowan (1990), implemented in the package subplex. It applies the Nelder-Mead method to a sequence of low-dimensional subspaces, which makes it more efficient than the simplex method when there are many parameters. The argument jitter of optimizer (recommended value 1E-5 when used) is only relevant for subplex: it shifts initial transformed values that are exactly 0.5, i.e. parameter values of 1, by this small amount. The ML functions do not pass jitter; there, the same is achieved by an initial value slightly different from 1.

'optim::...' uses one of the methods of stats::optim: e.g. 'optim::Nelder-Mead' (another implementation of the simplex method), 'optim::BFGS' and 'optim::CG' (quasi-Newton and conjugate-gradient methods that use numerical derivatives), 'optim::L-BFGS-B' (BFGS with limited memory and bounds on the parameters), 'optim::SANN' (simulated annealing, which always uses maxiter function evaluations and does not converge to a precise optimum) and 'optim::Brent' (for a single parameter only). Methods that use derivatives can be fast on smooth likelihood surfaces, but their finite-difference steps can land on parameter values with a loglikelihood of -Inf, such as $\mu_0 < 0$ or $\lambda_0 \leq \mu_0$. For 'optim::BFGS', 'optim::CG' and 'optim::L-BFGS-B', optimizer therefore replaces such values by a large finite penalty. 'optim::L-BFGS-B' and 'optim::Brent' search within bounds on the transformed scale: $[0, 1]$ for parameters with a non-negative initial value (the entire range of non-negative parameters) and $[-1, 1]$ for parameters with a negative initial value. This makes 'optim::L-BFGS-B' the best choice among the gradient-based methods when the maximum may lie on the boundary, e.g. at $\mu_0 = 0$. All methods except 'simplex' minimize minus the loglikelihood; values of NaN or NA returned by the likelihood function are treated as a likelihood of zero.

6.4 Global methods

Global methods search the entire parameter space for the global maximum. Their packages are not installed together with DDD (they are listed under Suggests); a message tells you to install them when needed. They all search the transformed parameters within the bounds described above for 'optim::L-BFGS-B': $[0, 1]$, i.e. the entire range of non-negative parameters, or $[-1, 1]$ for parameters with a negative initial value.

'DEoptim' uses differential evolution (package DEoptim; Mullen et al. 2011): a population of $10d$ parameter sets evolves by mutation, crossover and selection. The initial values are not used, and num_cycles is set to 1 because restarting is of no use. The search stops after maxiter generations or when the best value has not improved by more than tol[2] (relatively) in 100 generations. Differential evolution is robust but needs many likelihood evaluations.

'pso' uses particle swarm optimization (package pso, standard PSO 2007 with a swarm of $\lfloor 10 + 2\sqrt{d} \rfloor$ particles). The initial values are the starting position of the first particle. The search stops, like that of DEoptim, when the best value has not improved by more than tol[2] times its absolute value plus tol[3] during 100 iterations (convergence code 0), or after maxiter iterations (convergence code 1).

'cmaes' uses the covariance matrix adaptation evolution strategy (package cmaesr, which also needs smoof and ParamHelpers), starting from the initial values with an initial step size of 0.05 on the transformed scale. Because CMA-ES is good at locating the region of the global optimum but slow to pin down its exact position, its result is refined with subplex.

6.5 Comparing the methods

The table below shows the result of each method for the linear diversity-dependent model and our phylogeny, all started from $\lambda_0 = 0.2$, $\mu_0 = 0.1$ and $K = 60$, with optimpars = c(1E-4, 1E-4, 1E-6, maxiter, 0). For DEoptim and pso maxiter was set to 200 to keep the running time acceptable. The number of likelihood evaluations was counted with a wrapper around loglik_dd; the running times depend on the computer:

compare <- function(method, maxiter = 1000) {
  n_eval <- 0
  counted <- function(trparsopt, brts) {
    n_eval <<- n_eval + 1
    loglik_dd(trparsopt, brts)
  }
  out <- optimizer(optimmethod = method,
                   optimpars = c(1E-4, 1E-4, 1E-6, maxiter, 0),
                   fun = counted,
                   trparsopt = transform_pars(c(0.2, 0.1, 60)),
                   brts = brts)
  c(untransform_pars(out$par), loglik = out$fvalues, conv = out$conv,
    evaluations = n_eval)
}
compare('simplex')
compare('subplex')
compare('optim::Nelder-Mead')
compare('optim::BFGS')
compare('optim::L-BFGS-B')
compare('optim::SANN')
compare('DEoptim', maxiter = 200)
compare('pso', maxiter = 200)
compare('cmaes')
mc <- results$method_comparison
mc <- mc[, c("method", "lambda", "mu", "K", "loglik", "conv",
             "evaluations", "seconds")]
knitr::kable(mc, digits = c(0, 3, 4, 2, 4, 0, 0, 0), row.names = FALSE)
mcr <- function(m, col) results$method_comparison[results$method_comparison$method == m, col]

On this likelihood surface, which has a single maximum, all methods except 'optim::SANN' end at the maximum. The simplex method needed r mcr('simplex', 'evaluations') evaluations of the likelihood and subplex r mcr('subplex', 'evaluations'). The Nelder-Mead and BFGS methods of optim used somewhat fewer evaluations, but stopped slightly below the maximum; they stop on the relative change in the loglikelihood only. L-BFGS-B, which searches within the bounds, needed r mcr('optim::L-BFGS-B', 'evaluations') evaluations. Simulated annealing used all r mcr('optim::SANN', 'maxiter') evaluations it was allowed and ended far from the maximum (r round(mcr('optim::SANN', 'loglik'), 2)). The global methods found the same maximum as the simplex method, but needed r mcr('pso', 'evaluations') (particle swarm), r mcr('cmaes', 'evaluations') (CMA-ES) and r mcr('DEoptim', 'evaluations') (differential evolution) evaluations; particle swarm optimization stopped because the best value no longer improved, well before maxiter. Global methods are worth their cost when the likelihood surface has several maxima; for a well-behaved surface, a local method from a few starting points is much cheaper.

6.6 Multi-start optimization with Latin hypercube sampling

A practical way to reduce the risk of ending in a local optimum, while keeping the precision of a local method, is to start the local optimization from several points spread over the parameter space. The function optimizer_lhs does this with starting points obtained by Latin hypercube sampling: the range of each parameter is divided into $n$ strata of equal width and every stratum is sampled exactly once, so that every parameter range is covered evenly by $n$ points. You specify the range of each parameter with lower and upper (on the original scale), and the scale on which the strata have equal width with sampling_scale: 'transformed' (the scale of the optimization; allows bounds of 0 and Inf), 'original' or 'log' (useful for parameters that span orders of magnitude, such as $K$). The function lhs_sample draws such a sample:

set.seed(42)
trpars <- lhs_sample(n = 5,
                     lower = c(lambda = 0.05, mu = 0, K = 25),
                     upper = c(lambda = 3, mu = 1.5, K = 500),
                     sampling_scale = c('transformed', 'transformed', 'log'))
untransform_pars(trpars)

There are three strategies (argument strategy):

The points with the highest likelihood tend to lie close together, in the basin of attraction of the same maximum. Optimizing from all of them would mostly repeat the same optimization, and agreement among them would say little about whether the global maximum has been found. Therefore, in 'screen' and 'agree', a point is skipped when it lies within min_dist (default 0.1, i.e. 10% of each parameter range on its sampling scale) of a starting point that has already been used, in every parameter. When no points remain that are far enough from all starting points, min_dist is halved. The initial guess (trparsopt) is added to the candidates as well. Each optimization uses optimmethod (default 'simplex') with optimpars and num_cycles.

For a likelihood that is fast to compute, such as that of the constant-rate model, this takes little time:

set.seed(3)
out_lhs <- optimizer_lhs(fun = loglik_bd,
                         lower = c(lambda = 0.01, mu = 0),
                         upper = c(lambda = 2, mu = 2),
                         strategy = 'agree',
                         num_samples = 200,
                         num_agree = 3,
                         lhs_verbose = 0,
                         brts = brts)
out_lhs$runs

The output contains the same elements as that of optimizer (par, fvalues, conv), so it can be used in its place, and in addition a table runs with one row per optimization (the starting point, the value of min_dist when it was chosen, the initial and final loglikelihood, the convergence code, whether the result agrees with the best one, and the initial and final parameters on the original scale), the table samples with all candidate starting points and their loglikelihoods, and the number of optimizations that agree with the best result.

To see what screening and the minimum distance do, consider the loglikelihood of the diversity-dependent model as a function of $\lambda_0$ and $K$ only, with $\mu_0$ fixed at r results$surface$mu (close to its estimate). We screen 200 Latin hypercube samples and optimize from the 6 best ones that are at least min_dist = 0.1 apart:

loglik_dd_lambda_K <- function(trparsopt, brts) {
  loglik_dd(c(trparsopt[1], transform_pars(0.12), trparsopt[2]), brts)
}
set.seed(2)
lhs_surface <- optimizer_lhs(fun = loglik_dd_lambda_K,
                             lower = c(lambda = 0.05, K = 25),
                             upper = c(lambda = 3, K = 500),
                             sampling_scale = c('transformed', 'log'),
                             strategy = 'screen', num_samples = 200,
                             num_best = 6, min_dist = 0.1,
                             lhs_verbose = 0, brts = brts)
srf <- results$surface
z <- srf$loglik
z[!is.finite(z)] <- NA
zz <- srf$zoom_loglik
zz[!is.finite(zz)] <- NA
zmax <- max(c(z, zz), na.rm = TRUE)
smp <- srf$lhs$samples
runs <- srf$lhs$runs
oldpar <- par(mfrow = c(1, 2), mar = c(4.5, 4.5, 2, 1))
# left: the whole parameter range
plot(smp$lambda, log10(smp$K), pch = 16, cex = 0.5, col = "grey60",
     xlim = range(srf$lambda), ylim = log10(range(srf$K)), yaxt = "n",
     xlab = expression(lambda[0]), ylab = "K", main = "Latin hypercube samples")
axis(2, at = log10(c(25, 50, 100, 200, 500)), labels = c(25, 50, 100, 200, 500))
contour(srf$lambda, log10(srf$K), z, levels = zmax - c(2, 8, 32),
        drawlabels = FALSE, add = TRUE, col = "steelblue")
rect(min(srf$zoom_lambda), log10(min(srf$zoom_K)), max(srf$zoom_lambda),
     log10(max(srf$zoom_K)), border = "firebrick", lty = 2)
points(runs$lambda_init, log10(runs$K_init), pch = 16, col = "firebrick", cex = 0.8)
# right: zoomed in on the ridge
lev <- c(0.5, 1, 2, 4, 8)
contour(srf$zoom_lambda, srf$zoom_K, zz, levels = zmax - lev,
        labels = paste0("max - ", lev), col = "steelblue", labcex = 0.6,
        xlab = expression(lambda[0]), ylab = "K", main = "Starting points and results")
in_zoom <- smp$K >= min(srf$zoom_K) & smp$K <= max(srf$zoom_K)
points(smp$lambda[in_zoom], smp$K[in_zoom], pch = 16, cex = 0.5, col = "grey60")
arrows(runs$lambda_init, runs$K_init, runs$lambda, runs$K, length = 0.08,
       col = "firebrick")
points(runs$lambda_init, runs$K_init, pch = 21, bg = "white", col = "firebrick",
       cex = 2)
text(runs$lambda_init, runs$K_init, seq_len(nrow(runs)), cex = 0.65,
     col = "firebrick")
points(runs$lambda, runs$K, pch = 4, cex = 1.5, lwd = 2)
par(oldpar)

The left panel shows the Latin hypercube samples (grey), which cover every part of the parameter ranges, and contours of the loglikelihood 2, 8 and 32 units below its maximum. The loglikelihood is high only in a narrow band of $K$ values; the right panel zooms in on this band (dashed rectangle). Within it, the loglikelihood forms a ridge along which $\lambda_0$ is poorly determined. The six starting points (numbered in the order in which they were chosen) are the best samples that are at least 10% of the ranges apart, so they are spread along the ridge instead of being clustered around the single best sample. All six optimizations (arrows) end at the same maximum (crosses), with loglikelihood r round(srf$lhs$fvalues, 4), which suggests that this surface has a single maximum.

For the full diversity-dependent model, with ranges for $\lambda_0$, $\mu_0$ and $K$:

lower <- c(lambda = 0.05, mu = 0, K = 25)
upper <- c(lambda = 3, mu = 1.5, K = 500)
scales <- c('transformed', 'transformed', 'log')
optimpars <- c(1E-4, 1E-4, 1E-6, 1000, 0)
set.seed(1)
lhs_starts <- optimizer_lhs(fun = loglik_dd, lower = lower, upper = upper,
                            sampling_scale = scales, strategy = 'starts',
                            num_starts = 10, optimpars = optimpars,
                            brts = brts)
set.seed(1)
lhs_screen <- optimizer_lhs(fun = loglik_dd, lower = lower, upper = upper,
                            sampling_scale = scales, strategy = 'screen',
                            num_samples = 300, num_best = 5,
                            optimpars = optimpars, brts = brts)
set.seed(1)
lhs_agree <- optimizer_lhs(fun = loglik_dd, lower = lower, upper = upper,
                           sampling_scale = scales, strategy = 'agree',
                           num_samples = 300, num_agree = 3,
                           optimpars = optimpars, brts = brts)

The runs of the three strategies were:

lhs_table <- function(x, strategy) {
  runs <- x$value$runs
  runs <- runs[, c("sample", "init_fvalue", "fvalue", "conv", "agrees",
                   "lambda", "mu", "K")]
  knitr::kable(runs, digits = c(0, 2, 4, 0, 0, 3, 4, 2), row.names = FALSE,
               caption = paste0("Strategy '", strategy, "'"))
}
lhs_table(results$lhs_starts, "starts")
lhs_table(results$lhs_screen, "screen")
lhs_table(results$lhs_agree, "agree")
lhs_s <- results$lhs_starts$value

All optimizations of all three strategies end at the same maximum, which is also the maximum found by dd_ML from its default initial values: the likelihood surface of the linear diversity-dependent model has a single maximum for this phylogeny. In 'starts', only r sum(is.finite(lhs_s$samples$fvalue)) of the 10 samples had a nonzero likelihood (in the others $\mu_0 > \lambda_0$, which is not allowed in this model), so r nrow(lhs_s$runs) optimizations were run, from starting points that were spread over the whole parameter space. 'screen' ran 5 optimizations from the best samples, and 'agree' stopped after r nrow(results$lhs_agree$value$runs), because they agreed. The value of multi-start optimization shows in models with local optima, such as the rate-shift model of Section 5.4.

Using multi-start optimization in the ML functions. All maximum likelihood functions accept a list instead of a method name as optimmethod. optimizer then calls optimizer_lhs with the settings in the list. The list must contain lower and upper, and can contain any other argument of optimizer_lhs; its element optimmethod (default 'simplex') sets the method used from each starting point:

fit_lhs <- dd_ML(brts = brts,
                 optimmethod = list(lower = c(lambda = 0.05, mu = 0, K = 25),
                                    upper = c(lambda = 3, mu = 1.5, K = 500),
                                    sampling_scale = c('transformed',
                                                       'transformed', 'log'),
                                    strategy = 'agree',
                                    num_samples = 300,
                                    num_agree = 3))
show_fit(results$lhs_dd_ML$value)

The ranges can be given for the parameters that are optimized, or for all parameters of the model; in the latter case the ranges of the optimized parameters are selected with idparsopt. The second option allows the same list to be used for different submodels, e.g. in dd_LR, where $K$ is fixed at infinity in the constant-rate model. The initial values initparsopt are added as a candidate starting point (add trparsopt = NULL to the list to leave them out). The ML functions report only their usual output; to see the individual runs, call optimizer_lhs directly as above.

Parallel computing. The likelihood of the samples and the optimizations from different starting points are independent of each other, so they can be computed in parallel. With num_cores larger than 1, optimizer_lhs starts that many R processes and divides the work over them; parallel_phase selects whether the screening ('screening'), the optimizations ('optimizations') or both ('both', the default) are done in parallel:

set.seed(1)
lhs_agree_par <- optimizer_lhs(fun = loglik_dd, lower = lower, upper = upper,
                               sampling_scale = scales, strategy = 'agree',
                               num_samples = 300, num_agree = 3,
                               optimpars = optimpars, num_cores = 2,
                               brts = brts)
t_par <- results$lhs_agree_parallel$seconds
t_seq <- results$lhs_agree_sequential$seconds
n_par <- nrow(results$lhs_agree_parallel$value$runs)
n_seq <- nrow(results$lhs_agree_sequential$value$runs)

On the computer used for this vignette, with two cores, this took r round(t_par) seconds, against r round(t_seq) seconds without parallel computing, and both found the same maximum (r round(results$lhs_agree_parallel$value$fvalues, 5) and r round(results$lhs_agree_sequential$value$fvalues, 5)). The Latin hypercube sample, and hence the order of the candidate starting points, is the same with and without parallel computing. Strategies 'starts' and 'screen' then run exactly the same optimizations, divided over the workers: a worker starts the next optimization as soon as it has finished one. Strategy 'agree' does the same when the package future is installed: it starts a new optimization whenever a worker is free, checks agreement after each finished optimization, and stops as soon as enough optimizations agree. Optimizations that are still running at that moment are abandoned (or, with a cluster supplied as cl, finished, so that the cluster can be used again). The number of optimizations can therefore differ a little from that without parallel computing: here r n_par, against r n_seq. Without the package future, strategy 'agree' runs the optimizations in batches of as many as there are workers, which leaves workers idle while the slowest optimization of a batch finishes. Each optimization on a worker gets its own random number seed, so optimization methods that use random numbers give the same results whichever worker runs them.

The workers are separate R processes (a PSOCK cluster, which also works on Windows), not forked copies of the R session. A likelihood function that is itself parallelized therefore keeps working within each worker; for example, a likelihood that uses several threads, with their number set by an argument that is passed through ..., uses that many threads in every worker, so the total number of cores used is num_cores times the number of threads. The function to be optimized and the other arguments are sent to the workers once. DDD is attached on the workers; a function of your own that calls functions from other packages without :: needs these packages in packages, and a function that uses other objects from your workspace needs a cluster that you set up yourself (with parallel::makeCluster and parallel::clusterExport) and pass as cl, which is also the way to reuse a cluster or to use several machines. Parallel computing is also available in the ML functions, by adding num_cores (or cl) to the list given as optimmethod, e.g. dd_ML(brts, optimmethod = list(lower = ..., upper = ..., num_cores = 4)).

6.7 Multi-start optimization on a computer cluster

On a computer cluster, there are two ways to run the optimizations from many starting points in parallel.

One job with several cores. optimizer_lhs (or an ML function with a list as optimmethod) runs on one node, with num_cores workers. With SLURM, ask for one task with several CPUs, and take the number of workers from the environment variable SLURM_CPUS_PER_TASK (not from parallel::detectCores(), which counts all cores of the node, also those allocated to other jobs):

```{bash slurm_single, eval = FALSE}

!/bin/bash

SBATCH --job-name=ddd_ml

SBATCH --nodes=1

SBATCH --ntasks=1

SBATCH --cpus-per-task=16

SBATCH --mem=32G

SBATCH --time=24:00:00

module load R Rscript run_ml.R

with `run_ml.R`:

```r
library(DDD)
brts <- ... # the branching times
num_cores <- as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1"))
fit <- dd_ML(brts = brts,
             optimmethod = list(lower = c(0.05, 0, 25), upper = c(3, 1.5, 500),
                                sampling_scale = c('transformed', 'transformed', 'log'),
                                strategy = 'agree', num_agree = 5,
                                num_cores = num_cores))
saveRDS(fit, "fit.rds")

Every worker is a separate R process with its own copy of the data, so memory use grows with the number of workers. If the likelihood function uses several threads itself, ask for num_cores times that number of CPUs.

A job array of single-core jobs. A job that asks for many cores on one node may have to wait in the queue until such a node is free, whereas the jobs of a job array start as soon as single cores are free. To combine this with screening, optimizer_lhs can save the chosen starting points to a file (starts_file) and stop there (run_optimizations = FALSE); every job of the array then optimizes from one of them, and afterwards the best result is taken. Here is the whole workflow on a small scale, for the constant-rate model, with a loop instead of a job array:

starts_file <- tempfile(fileext = ".rds")
set.seed(5)
screen_only <- bd_ML(brts = brts,
                     optimmethod = list(lower = c(lambda = 0.01, mu = 0),
                                        upper = c(lambda = 2, mu = 2),
                                        strategy = 'screen', num_samples = 200,
                                        num_best = 4, starts_file = starts_file,
                                        run_optimizations = FALSE,
                                        lhs_verbose = 0))
saved <- readRDS(starts_file)
saved$starts

With run_optimizations = FALSE the ML function returns no estimates (all values are -1, and conv is -99); the result is the file. It contains the starting points on the original scale (saved$pars, one row per starting point, in the order in which 'screen' would optimize them), the same on the transformed scale (saved$trpars), the table above, all screened samples and the settings. Each job optimizes from one row:

fits <- lapply(seq_len(nrow(saved$pars)), function(id) {
  bd_ML(brts = brts, initparsopt = saved$pars[id, ])
})
fits <- do.call(rbind, fits)
fits
fits[which.max(fits$loglik), ]

On a SLURM cluster, the screening is one job (which can use several cores through num_cores), and the optimizations are a job array that starts when the screening has finished:

# screen.R: choose 50 starting points and save them
library(DDD)
brts <- ... # the branching times
set.seed(1)
dd_ML(brts = brts,
      optimmethod = list(lower = c(0.05, 0, 25), upper = c(3, 1.5, 500),
                         sampling_scale = c('transformed', 'transformed', 'log'),
                         strategy = 'screen', num_samples = 1000, num_best = 50,
                         starts_file = "starts.rds", run_optimizations = FALSE,
                         num_cores = as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1"))))

# optimize_one.R: optimize from starting point number id
library(DDD)
brts <- ... # the branching times
id <- as.integer(commandArgs(trailingOnly = TRUE)[1])
saved <- readRDS("starts.rds")
fit <- dd_ML(brts = brts, initparsopt = saved$pars[id, ])
saveRDS(fit, sprintf("fit_%03d.rds", id))

# collect.R: the best results
files <- list.files(pattern = "^fit_[0-9]+\\.rds$")
fits <- do.call(rbind, lapply(files, readRDS))
fits <- fits[order(fits$loglik, decreasing = TRUE), ]
head(fits)
# how many optimizations found (practically) the same maximum
sum(fits$loglik > fits$loglik[1] - 1E-3)

```{bash slurm_array, eval = FALSE}

screen.sh

!/bin/bash

SBATCH --job-name=ddd_screen

SBATCH --nodes=1

SBATCH --ntasks=1

SBATCH --cpus-per-task=8

SBATCH --time=02:00:00

module load R Rscript screen.R

optimize.sh

!/bin/bash

SBATCH --job-name=ddd_optimize

SBATCH --ntasks=1

SBATCH --cpus-per-task=1

SBATCH --array=1-50

SBATCH --time=12:00:00

module load R Rscript optimize_one.R $SLURM_ARRAY_TASK_ID

submit both; the job array starts when the screening has finished

jid=$(sbatch --parsable screen.sh) sbatch --dependency=afterok:$jid optimize.sh ```

Strategy 'agree' cannot stop a job array early, but the last lines of collect.R show how many optimizations found the best maximum.

6.8 Recommendations

References



Try the DDD package in your browser

Any scripts or data that you put into this service are public.

DDD documentation built on Dec. 6, 2026, 1:08 a.m.