This tutorial is maintained on GitHub — view the repository ↗
Contents
- Introduction
- Data and Files
- 1. Inputs And Output Settings
- 2. Core Model Constants
- 3. MCMC Settings
- 4. Initialization, Input Parsing, And Tree Setup
- 5. HiSSE-Like Diversification Layer
- 6. Trait Transition Process And Hidden-State Q
- 7. Population Tree Likelihood
- 8. Augmented Trait Histories
- 9. Speciation Completion Rates
- 10. Derived Descriptors
- 11. Protracted Speciation Histories
- 12. Monitors
- 13. Run MCMC
- 14. Post-Processing And Summaries
- Expected Output Files
- Parameter Correspondence Table
- Plot Results
- 1) Descriptor distributions
- 2) Diversification and transition rates
- 3) Reversible-jump model indicators
- 4) Tree-based summaries
- References
Author: Guilherme H. F. Azevedo
Introduction
Trait-Dependent Rates Protracted Speciation (Traderpros) is a Bayesian model that links trait evolution, lineage diversification, and protracted speciation in a single framework, as presented in Azevedo & Hedin 2026 (submitted). The model combines:
- a hidden-state SSE (Beaulieu and O’Meara 2016) component (HiSSE-like) for population formation, extinction, and trait transition rates;
- a protracted speciation (Rosindell et al. 2010) component that models speciation-completion events along branches as a Poisson process;
- data augmentation for latent trait histories (May and Moore 2020) and branch-level speciation-completion histories.
In this framework (Fig. 1), species-level and population-level processes can be estimated jointly from:
- a dated population tree,
- a discrete trait matrix,
- and population-to-species assignments.

Fig. 1: Conceptual overview of Traderpros
This tutorial follows the full model (Fig. 2), as implemented in the Traderpros program by Azevedo & Hedin 2026 (submitted).
Fig. 2: Full DAG used in the model
Conceptually, the protracted component models branch-level completion events as a Poisson process with branch-specific rates derived from trait history:
$$ \eta_i \sim \text{Poisson}(σ_i \cdot t_i) $$
where $\eta_i$ is the number of completion events on branch $i$, $t_i$ is branch duration, and $σ_i$ is the branch-specific completion rate obtained from time spent in each state along that branch.
This implementation combines ideas from protracted-speciation approaches (for example, DELINEATE-style branch-event logic; Sukumaran et al. 2021) with data augmentation of character histories in RevBayes (see this tutorial for an example).
Data and Files
This tutorial uses the files in docs/TutorialRev/data:
example.treexample_trait.nexusexample.SpeciesMatrix.txt
Because this tutorial file is in docs/TutorialRev, paths below are set to ./data/....
The species matrix is read as natural-number states. In practice, known species should be encoded as positive integers, and uncertain assignments can be represented as missing (?).
1. Inputs And Output Settings
Set reproducibility, output naming, file paths, and TensorPhylo options.
SEED_NUMBER = 0
OUT_PREFIX = "tutorial_output"
OUT_DIR = "./tutorial_output" + "/"
TREE_PATH = "./data/example.tre"
TRAIT_PATH = "./data/example_trait.nexus"
SP_MATRIX = "./data/example.SpeciesMatrix.txt"
USE_TENSOR = "no"
TENSOR_PATH = "None"
SEED_NUMBER = 0 keeps stochastic behavior between runs. Set a non-zero seed to reproduce a run exactly.
USE_TENSOR can be set to “yes” if you want to use TensorPhylo. Make sure it is installed and that the correct path is set with TENSOR_PATH.
2. Core Model Constants
Define known sampling context and prior hyperparameters.
TRANS_PRIOR_PARAM <- 10
STRUCTURE_PRIOR_PARAM <- 1
SPECIATION_PRIOR_PARAM <- 1
NUM_HIDDEN = 2
MEAN_HIDDEN_HYPERPRIOR = 0.587405
NUM_TOTAL_POPULATIONS = 457
MAX_NUM_SPECIES <- 24
ROOT_PRIOR <- [1,1,1,1]
CHAR_MOVE_INTESITY = 0.5
NUM_PROC = 4
These parameters define the rate parameter ($1/\text{mean}$) of the exponential priors for trait transitions (TRANS_PRIOR_PARAM), net population formation (STRUCTURE_PRIOR_PARAM), and speciation completion (SPECIATION_PRIOR_PARAM).
NUM_HIDDEN sets the number of hidden states used to capture unmeasured rate heterogeneity. MEAN_HIDDEN_HYPERPRIOR sets the mean of the exponential prior on the standard deviation of the lognormal hidden-rate variation used in discretization. The same prior mean is used for population formation, extinction, and speciation completion, but each rate’s hidden variation is sampled independently.
NUM_TOTAL_POPULATIONS should be a user-provided approximation of the total number of populations. Because this value is often uncertain, it is useful to test multiple values and assess sensitivity. Alternatively, the script can be modified so this quantity is sampled from a prior and marginalized across possible values (see this example).
MAX_NUM_SPECIES is the maximum possible number of species represented in the tree, including potentially new species among populations with unknown assignments. For example, with 20 known species and 6 unassigned populations that could each be distinct, MAX_NUM_SPECIES is 26. If all tips are already assigned, use the known number of species. Do not include unsampled species. Larger values increase runtime. This setting may have limited effect on rate estimates, but its impact on species delimitation may be greater.
ROOT_PRIOR specifies root-state probabilities across all root states. With 2 observed and 2 hidden states, the order is: Observed 0 Hidden A, Observed 1 Hidden A, Observed 0 Hidden B, Observed 1 Hidden B. Values can sum to 1 or be provided as relative simplex weights. For example, [1,0,1,0] corresponds to 0.5, 0.0, 0.5, 0.0.
CHAR_MOVE_INTESITY controls the intensity of augmented-history trait moves and should be between 0 and 1. Lower values update fewer branches and are faster, but may mix less efficiently. On large trees, a value of 1 can be computationally expensive, so testing a few values is recommended.
NUM_PROC sets the number of processors used by TensorPhylo. It has no effect if the TensorPhylo plugin is not being used.
3. MCMC Settings
Choose run length and logging intervals.
N_GEN = 1000
N_PRINT_SCREEN = 10
N_PRINT_LOG = 10
N_PRINT_TREE = 10
N_RUNS = 1
N_CHECK_INTERVAL = 10
BURN_IN = 0.1
For real analyses, increase N_GEN substantially and check convergence diagnostics.
4. Initialization, Input Parsing, And Tree Setup
Create move/monitor containers, optionally set the seed, and load the plugin.
moves = VectorMoves()
monitors = VectorMonitors()
if (SEED_NUMBER!=0){
seed(SEED_NUMBER)
}
printSeed()
if (USE_TENSOR == "yes"){
loadPlugin("TensorPhylo", TENSOR_PATH)
}
Parse core input data and create helper variables.
tree <- readTrees(TREE_PATH)[1]
writeNexus(tree, filename= OUT_DIR + OUT_PREFIX +"_indexed.tree.nex")
n_nodes <- tree.nnodes()
n_branches <- n_nodes -1
taxa <- tree.taxa()
tree_length <- tree.treeLength()
root <- tree.rootAge()
data <- readDiscreteCharacterData(TRAIT_PATH)
num_states <- data.getStateDescriptions().size()
data_exp <- data.expandCharacters( NUM_HIDDEN )
num_rates <- num_states * NUM_HIDDEN
speciesData = readDelimitedCharacterData(file= SP_MATRIX , stateLabels=MAX_NUM_SPECIES )
The indexed tree file helps inspect branch identities, which is useful for debugging branch-level speciation-event summaries.
5. HiSSE-Like Diversification Layer
This block defines population formation/extinction rates with observed-state and hidden-state variation. The code here has the same logic as in the HiSSE Tutorial.
We begin by defining global net population formation and global turnover. From these two quantities, the script derives global population formation and global extinction.
global_net_pop_formation ~ dnExponential(STRUCTURE_PRIOR_PARAM)
global_net_pop_formation.setValue( (NUM_TOTAL_POPULATIONS-2) / tree_length )
moves.append( mvScale(global_net_pop_formation,weight=1.0) )
global_pop_turnover ~ dnBeta(1.0, 1.0)
moves.append( mvSlide(global_pop_turnover, delta=1.0, tune=true, weight=1.0) )
denom := abs(1.0 - global_pop_turnover)
global_pop_formation := global_net_pop_formation / denom
global_extinction := (global_pop_turnover * global_net_pop_formation) / denom
Next, observed-state relative weights (proportions) are sampled with reversible-jump priors, then converted into observed-state-specific formation and extinction rates.
pop_formation_relative ~ dnReversibleJumpMixture( simplex(rep(1, num_states)), dnDirichlet(rep(1, num_states)), p=0.5 )
extinction_relative ~ dnReversibleJumpMixture( simplex(rep(1, num_states)), dnDirichlet(rep(1, num_states)), p=0.5 )
moves.append( mvRJSwitch(pop_formation_relative , weight=1.0) )
moves.append( mvRJSwitch(extinction_relative , weight=1.0) )
moves.append( mvDirichletSimplex( pop_formation_relative, weight=1 ) )
moves.append( mvDirichletSimplex( extinction_relative, weight=1 ) )
pop_formation_observed := pop_formation_relative * global_pop_formation
extinction_observed := extinction_relative * global_extinction
The hidden-state multipliers are then modeled through discretized lognormal mixtures and normalized so they behave as proportional modifiers across hidden regimes (similar to the Branch Specific Diversification tutorial).
ln_pop_formation_hidden_mean <- ln(1.0)
pop_formation_hidden_sd ~ dnReversibleJumpMixture( 0.0, dnExponential( 1.0 / MEAN_HIDDEN_HYPERPRIOR ), p=0.5 )
moves.append( mvScale(pop_formation_hidden_sd, lambda=1, tune=true, weight=1.0) )
moves.append( mvRJSwitch(pop_formation_hidden_sd , weight=1.0) )
pop_formation_hidden_unormalized := fnDiscretizeDistribution( dnLognormal(ln_pop_formation_hidden_mean, pop_formation_hidden_sd), NUM_HIDDEN )
pop_formation_hidden := pop_formation_hidden_unormalized / sum(pop_formation_hidden_unormalized)
ln_extinction_hidden_mean <- ln(1.0)
extinction_hidden_sd ~ dnReversibleJumpMixture( 0.0, dnExponential( 1.0 / MEAN_HIDDEN_HYPERPRIOR ), p=0.5 )
moves.append( mvScale(extinction_hidden_sd, lambda=1, tune=true, weight=1.0) )
moves.append( mvRJSwitch(extinction_hidden_sd , weight=1.0) )
extinction_hidden_unormalized := fnDiscretizeDistribution( dnLognormal(ln_extinction_hidden_mean, extinction_hidden_sd), NUM_HIDDEN )
extinction_hidden := extinction_hidden_unormalized / sum(extinction_hidden_unormalized)
We track model-indicator variables, and the reversible-jump components let the chain estimate whether rates are effectively equal or state-dependent.
is_pop_formation_state_dependent := ifelse( pop_formation_relative == simplex(rep(1,num_states)), 0.0, 1.0)
is_extinction_state_dependent := ifelse( extinction_relative == simplex(rep(1,num_states)), 0.0, 1.0)
is_bd_state_dependent := ifelse( (extinction_relative == simplex(rep(1,num_states)) & pop_formation_relative == simplex(rep(1,num_states))), 0.0, 1.0)
is_extinction_hidden := ifelse( pop_formation_hidden_sd == 0, 0.0, 1.0)
is_pop_formation_hidden := ifelse( extinction_hidden_sd == 0, 0.0, 1.0)
Finally, we combine observed-state and hidden-state components into full state-specific rates.
for (j in 1:NUM_HIDDEN) {
for (i in 1:num_states) {
index = i+(j*num_states)-num_states
pop_formation[index] := pop_formation_observed[i] * pop_formation_hidden[j]
extinction[index] := extinction_observed[i] * extinction_hidden[j]
}
}
net_pop_formation_rate_observed := pop_formation_observed - extinction_observed
net_pop_formation_rate := pop_formation - extinction
6. Trait Transition Process And Hidden-State Q
Define observed-state transitions, test reversibility, then combine with hidden-state transitions.
Start by defining the global transition-rate scale and the number of observed-state transitions.
global_trans_rate ~ dnExp(TRANS_PRIOR_PARAM)
moves.append( mvScale( global_trans_rate, weight=1 ) )
n_obs_transitions = num_states * (num_states - 1)
Next, sample the free upper-triangle transition weights that parameterize the irreversible model.
irreversible_free ~ dnDirichlet(rep(1, n_obs_transitions / 2))
if (irreversible_free.size() > 1){
moves.append( mvDirichletSimplex( irreversible_free, weight=1 ) )
}
Then map those free parameters into the full off-diagonal transition vector. Forward directions get free values, reverse directions are set to zero in the irreversible model.
free_idx = 1
flat_idx = 1
for (i in 1:num_states) {
for (j in 1:num_states) {
if (i != j) {
if (j > i) {
irreversible[flat_idx] := irreversible_free[free_idx]
free_idx += 1
} else {
irreversible[flat_idx] <- 0.0
}
flat_idx += 1
}
}
}
Use reversible-jump to compare the irreversible model against a fully free transition simplex, then convert relative weights into absolute transition rates.
relative_transition ~ dnReversibleJumpMixture( simplex(irreversible), dnDirichlet(rep(1, n_obs_transitions)), p=0.5 )
moves.append( mvRJSwitch(relative_transition , weight=1.0) )
moves.append( mvDirichletSimplex( relative_transition, weight=1 ) )
is_reversible := ifelse( relative_transition == simplex(irreversible), 0.0, 1.0)
transition_rates := relative_transition * global_trans_rate
is_reversible is monitored later to summarize support for irreversible vs. reversible observed-state transitions.
Now define hidden-state switching rates and build the full hidden-state rate matrix used by the character process.
transition_hidden ~ dnExponential(TRANS_PRIOR_PARAM)
moves.append( mvScale(transition_hidden,lambda=0.5,tune=true,weight=1) )
for (i in 1:(NUM_HIDDEN * (NUM_HIDDEN - 1))) {
R[i] := transition_hidden
}
rate_matrix := fnHiddenStateRateMatrix(transition_rates, R, rescaled=FALSE)
Finally, place a prior on root frequencies for the expanded observed-plus-hidden state space.
root_prior ~ dnDirichlet( ROOT_PRIOR )
moves.append( mvDirichletSimplex(root_prior,tune=true,weight=1) )
7. Population Tree Likelihood
Create the character-dependent birth-death process on the population tree.
rho <- tree.ntips()/NUM_TOTAL_POPULATIONS
if (USE_TENSOR == "yes"){
timetree ~ dnGLHBDSP(
rootAge = root,
lambda = pop_formation,
mu = extinction,
rho = rho,
eta = rate_matrix,
pi = root_prior,
condition = "time",
taxa = taxa,
nStates = num_rates,
nProc = NUM_PROC
)
} else {
timetree ~ dnCDBDP(
rootAge = root,
speciationRates = pop_formation,
extinctionRates = extinction,
Q = rate_matrix,
condition = "time",
pi = root_prior,
rho = rho )
}
timetree.clamp(tree)
timetree.clampCharData(data_exp)
The tree and expanded character data are clamped as observations, so we get the likelihood of the HiSSE-like layer of the process.
If you are using TensorPhylo, make sure it is installed and configured for RevBayes, and that the correct path is provided.
8. Augmented Trait Histories
Simulate latent (hidden) trait histories on branches so we can connect them to branch-wise speciation completion (see section 11. Protracted Speciation Histories).
The data-augmentation step samples augmented trait histories (where and when state changes occur on branches). Those histories are then used to compute branch-specific completion rates by weighting state-specific rates by relative time in each state (as done in the State-Dependent Brownian Rate Tutorial).
The latent trait process is also constrained so that each sampled history remains compatible with the observed tip states. In practice, this is what lets the model reconstruct branch histories while still honoring the data you observed at the tips.
First, define the augmented trait-history process on the fixed tree and hidden-state rate matrix.
trait_evol ~ dnPhyloCTMCDASiteIID(tree=tree,
Q=rate_matrix,
branchRates=1,
type="NaturalNumbers",
nSites=1,
rootFrequencies=root_prior,
treatAmbiguousAsGap=TRUE)
To ensure compatibility with observed tip states, the script creates a helper missing-state reference and enforces per-tip consistency through Bernoulli clamps.
This is done because
dnPhyloCTMCDASiteIID()cannot clamp missing data or ambiguous states when hidden characters are included. In practice, the trait process is clamped to the expanded hidden-plus-observed matrix (data_exp) while enforcing consistency only for the observed state.
helper_data <- data
helper_data.addMissingTaxa("Fictional")
for (i in 1:trait_evol.ntaxa()) {
if (!(data[data.taxonIndex(trait_evol.taxa()[i].getName())][1] == helper_data[helper_data.taxonIndex("Fictional")][1])){
obs_state := 1*data[data.taxonIndex(trait_evol.taxa()[i].getName())][1]
evol_state := 1*trait_evol[i][1]
success[i] := ifelse( (evol_state % num_states) == obs_state , 1 , 0 )
trait_evol_success[i] ~ dnBernoulli(Probability(success[i]))
trait_evol_success[i].clamp(1)
}else{
success[i] <- 1
trait_evol_success[i] ~ dnBernoulli(Probability(success[i]))
trait_evol_success[i].clamp(1)
}
}
9. Speciation Completion Rates
Define the global speciation-completion rate and an observed-state reversible-jump mixture of relative weights. This follows the same strategy used for population-formation and extinction rates.
global_spCompletion ~ dnExponential(SPECIATION_PRIOR_PARAM)
moves.append(mvScale(global_spCompletion, weight=1))
spCompletion_relative ~ dnReversibleJumpMixture( simplex(rep(1, num_states)), dnDirichlet(rep(1, num_states)), p=0.5 )
moves.append( mvRJSwitch(spCompletion_relative, weight=1.0) )
moves.append(mvSimplex(spCompletion_relative, weight=1))
spCompletion_observed := spCompletion_relative * global_spCompletion
Then model hidden-regime multipliers for completion with a discretized lognormal mixture and normalize them to proportional weights.
ln_completion_hidden_mean <- ln(1.0)
spCompletion_hidden_sd ~ dnReversibleJumpMixture( 0.0, dnExponential( 1.0 / MEAN_HIDDEN_HYPERPRIOR ), p=0.5 )
moves.append( mvScale(spCompletion_hidden_sd, lambda=1, tune=true, weight=1.0) )
moves.append( mvRJSwitch(spCompletion_hidden_sd, weight=1.0) )
spCompletion_hidden_unormalized := fnDiscretizeDistribution( dnLognormal(ln_completion_hidden_mean, spCompletion_hidden_sd), NUM_HIDDEN )
spCompletion_hidden := spCompletion_hidden_unormalized / sum(spCompletion_hidden_unormalized)
Finally, compute RJ indicator summaries and combine observed-state and hidden-state components into full state-specific completion rates.
is_spCompletion_state_dependent := ifelse( spCompletion_relative == simplex(rep(1, num_states)), 0.0, 1.0)
is_spCompletion_hidden := ifelse( spCompletion_hidden_sd == 0, 0.0, 1.0)
for (j in 1:NUM_HIDDEN) {
for (i in 1:num_states) {
index = i+(j*num_states)-num_states
spCompletion[index] := spCompletion_observed[i] *spCompletion_hidden[j]
}
}
The speciation-completion rates are state-dependent through both observed and hidden regimes.
10. Derived Descriptors
Compute turnover, evolvability, speciation success, and ephemerality directly from sampled model parameters.
Note
These are not model parameters, but they are derived from model rates and can be used to explore aspects of diversification processes. See Azevedo & Hedin (submitted) for details.
First, derive turnover at state-specific and observed-state levels.
pop_turnover := extinction / pop_formation
pop_turnover_observed := extinction_observed / pop_formation_observed
Next, compute rates of leaving each state from the diagonal of the hidden-state rate matrix, then combine them with formation, completion, and extinction to obtain state-specific evolvability.
index=1
for (i in 1:rate_matrix.size() ){
for (j in 1:rate_matrix.size() ){
if (i==j){
rate_of_leaving_state[index] := -1*rate_matrix[i][j]
index = index+1
}
}
}
evolvability := pop_formation +
spCompletion +
rate_of_leaving_state -
extinction
Then repeat this calculation for observed states only and also compute the global evolvability summary.
Q_observed := fnFreeK(transition_rates, rescaled=FALSE)
index=1
for (i in 1:Q_observed.size() ){
for (j in 1:Q_observed.size() ){
if (i==j){
rate_of_leaving_state_observed[index] := -1*Q_observed[i][j]
index = index+1
}
}
}
evolvability_observed := pop_formation_observed +
spCompletion_observed +
rate_of_leaving_state_observed -
extinction_observed
global_evolvability := global_pop_formation +
global_spCompletion +
global_trans_rate -
global_extinction
Now calculate speciation success, interpreted as the proportion of surviving populations that is expected to complete speciation.
speciation_success := spCompletion / (pop_formation - extinction)
speciation_success_observed := spCompletion_observed / (pop_formation_observed - extinction_observed)
global_speciation_success := global_spCompletion / (global_pop_formation - global_extinction)
Finally, derive ephemerality as turnover relative to speciation success.
ephemerality := pop_turnover / speciation_success
ephemerality_observed := pop_turnover_observed / speciation_success_observed
global_ephemerality := global_pop_turnover / global_speciation_success
These descriptors are later summarized from posterior samples.
11. Protracted Speciation Histories
Here we sample the number of speciation events on each branch and ensure that they match the population-to-species assignments.
The next step is the key protracted-speciation component. We first summarize the trait-dependent completion rate on each branch and then use the population-to-species mapping to decide which branches can be clamped to zero completion events (observed no-speciation events) and which branches must retain uncertainty (speciation events need to be estimated). This creates the augmented and observed speciation history.
The species annotation at internal nodes uses a Fitch-style optimization over species labels. For each internal node, the script combines the labels of the two daughter clades, removes duplicates, and sorts the result. If both daughters belong to a single known species, the corresponding daughter branches are forced to have zero completion events because no speciation completion should be observed within a conspecific split. If the node connects different species, the two daughter branches remain stochastic and are initialized with a positive value so MCMC can explore them.
First, turn state-specific completion rates into branch-specific rates.
for(i in 1:n_branches) {
branch_spCompletion[i] := sum(trait_evol.relativeTimeInStates(i,1) * spCompletion)
}
Annotate internal nodes with descendant species labels using a Fitch-style algorithm.
for (i in 1:n_nodes){
if (! tree.isInternal(i)){
node_sp[i] <- [speciesData[speciesData.taxonIndex(tree.nodeName(i))][1]]
} else {
node_sp[i] <- append(node_sp[tree.child(i, 1)],
node_sp[tree.child(i, 2)]
)
node_sp[i].unique()
node_sp[i].sort()
}
}
Once descendant species are known, the next block decides whether each pair of daughter branches should be clamped to zero completion events (observed no speciation) or kept free for MCMC. Conspecific daughter branches are fixed to zero (first part of the if statement), while heterospecific branches are initialized at one event so the chain can explore them. The assigned MCMC moves then sample the augmented speciation history.
Note
Because states are natural numbers, unknown
?assignments are represented as0in thenode_spcontainer. For this reason, the species matrix must not use state0as a valid species label.
for (i in (taxa.size()+1):(n_nodes)){
if (node_sp[i].size() == 1 & !node_sp[i].contains(0)){
branch_speciation_events[tree.child(i, 1)] ~ dnPoisson(branch_spCompletion[tree.child(i, 1)]*tree.branchLength(tree.child(i, 1)))
branch_speciation_events[tree.child(i, 1)].clamp(0)
branch_speciation_events[tree.child(i, 2)] ~ dnPoisson(branch_spCompletion[tree.child(i, 2)]*tree.branchLength(tree.child(i, 2)))
branch_speciation_events[tree.child(i, 2)].clamp(0)
}else{
branch_speciation_events[tree.child(i, 1)] ~ dnPoisson(branch_spCompletion[tree.child(i, 1)]*tree.branchLength(tree.child(i, 1)))
moves.append(mvRandomNaturalWalk(branch_speciation_events[tree.child(i, 1)], weight=10))
branch_speciation_events[tree.child(i, 1)].setValue(1)
branch_speciation_events[tree.child(i, 2)] ~ dnPoisson(branch_spCompletion[tree.child(i, 2)]*tree.branchLength(tree.child(i, 2)))
moves.append(mvRandomNaturalWalk(branch_speciation_events[tree.child(i, 2)], weight=10))
branch_speciation_events[tree.child(i, 2)].setValue(1)
}
}
Here we store the likelihood of the augmented speciation history.
for (i in 1:branch_speciation_events.size()){
br_lnLikelihood[i] := branch_speciation_events[i].lnProbability()
}
tree_protracted_lnLikelihood := sum(br_lnLikelihood)
Track whether at least one speciation occurred and the corresponding branch-level probabilities of at least one speciation event and no-speciation.
for (i in 1:(n_branches)){
speciation_binary[i] := ifelse(branch_speciation_events[i] == 0, 0, 1)
p_no_speciation[i] := ifelse(branch_speciation_events[i] == 0,
branch_speciation_events[i].probability(),
dpoisson(0, branch_spCompletion[i]*tree.branchLength(i), FALSE))
p_speciation[i] := 1-p_no_speciation[i]
}
Save a trace with the number of speciation events on each branch, including the root branch. This is later used to summarize event counts on a time tree.
for (i in 1:(n_branches+1)){
if(i==n_branches+1){
end[i] <- 0
}else{
end[i] := branch_speciation_events[i]
}
}
The last block assembles the speciation-event tree, sets the species-assignment likelihood, and registers the model object used by MCMC. In this tree, branch lengths represent numbers of speciation events from the augmented speciation history. After assembly, the model evaluates a simple likelihood of the observed species matrix on this event tree, ensuring that sampled speciation histories remain compatible with observed species assignments. That is, populations of different species are required to be separated by at least one branch with length greater than zero.
topologyPopNames <- readBranchLengthTrees(TREE_PATH)[1]
topologyPopNames.renumberNodes(tree)
SpeciationBranchTreePopNames := fnTreeAssembly(topologyPopNames, branch_speciation_events)
Qs <- fnFreeK(rep(1, MAX_NUM_SPECIES^2), rescale=FALSE)
speciation ~ dnPhyloCTMC(tree=SpeciationBranchTreePopNames, Q=Qs, type="NaturalNumbers")
speciation.clamp(speciesData)
mymodel = model(branch_speciation_events)
Key logic:
- conspecific internal splits are clamped to zero completion events;
- heterospecific paths must contain sampled completion events;
- species assignments are clamped through
dnPhyloCTMCon the event-weighted tree.
Interpretation notes:
- Populations with uncertain species identity are not hard constrained to a single species path, so their connecting branches can retain posterior uncertainty in completion events.
- The speciation-event tree and the summary files can therefore be used not only for rate inference, but also to inspect branch-level support relevant for species delimitation.
This is also why the branch-event summaries are useful even when your goal is primarily species delimitation: they let you inspect where the posterior places speciation completion events, and where it prefers to keep the branches unspeciated.
12. Monitors
Set output traces for parameters, descriptors, model-choice indicators, trees, and branch event summaries.
Start with a screen monitor for run progress and a full model log for all sampled parameters.
monitors.append( mnScreen(printgen= N_PRINT_SCREEN) )
monitors.append( mnModel(file= OUT_DIR + OUT_PREFIX + ".model.log",
printgen=N_PRINT_LOG) )
Next, write the main diversification and speciation-completion rate parameters to a dedicated rates log to facilitate inspection of target parameters.
monitors.append( mnFile(pop_formation_hidden,
extinction_hidden,
pop_formation_observed,
extinction_observed,
global_pop_formation,
global_extinction,
net_pop_formation_rate,
net_pop_formation_rate_observed,
global_net_pop_formation,
pop_formation,
extinction,
global_trans_rate,
transition_rates,
R,
global_spCompletion,
spCompletion_relative,
spCompletion,
spCompletion_observed,
spCompletion_hidden,
filename= OUT_DIR + OUT_PREFIX +".Rates.log",
printgen= N_PRINT_LOG) )
Then log derived descriptors to summarize biological interpretation across samples.
monitors.append( mnFile(net_pop_formation_rate,
net_pop_formation_rate_observed,
global_net_pop_formation,
pop_turnover,
pop_turnover_observed,
global_pop_turnover,
evolvability,
evolvability_observed,
global_evolvability,
speciation_success,
speciation_success_observed,
global_speciation_success,
ephemerality,
ephemerality_observed,
global_ephemerality,
filename= OUT_DIR + OUT_PREFIX +".Descriptors.log",
printgen= N_PRINT_LOG) )
Track branch-specific birth-death rates inferred on the clamped population tree.
monitors.append( mnStochasticBranchRate(glhbdsp = timetree,
printgen = N_PRINT_TREE,
filename = OUT_DIR + OUT_PREFIX + ".BirthDeathBrRates.log") )
Record reversible-jump indicator variables to evaluate support for equal-versus-dependent model components.
monitors.append( mnFile(is_pop_formation_state_dependent,
is_extinction_state_dependent,
is_bd_state_dependent,
is_reversible,
is_spCompletion_state_dependent,
is_spCompletion_hidden,
is_extinction_hidden,
is_pop_formation_hidden,
filename= OUT_DIR + OUT_PREFIX +".RJ.log",
printgen= N_PRINT_LOG) )
Save joint conditional ancestral-state reconstructions (including hidden states) for downstream character-history summaries.
monitors.append( mnJointConditionalAncestralState(tree = tree,
glhbdsp = timetree,
type = "NaturalNumbers",
printgen = N_PRINT_TREE,
withTips = TRUE,
withStartStates = FALSE,
filename = OUT_DIR + OUT_PREFIX + ".traits.log") )
Store branch-level speciation-event counts in a compact trace that is easy to summarize and map.
monitors.append( mnFile(end,
filename= OUT_DIR + OUT_PREFIX + ".SpEvents.log",
printgen= N_PRINT_LOG) )
Export an extended Newick tree with branch-wise protracted outputs: no-speciation probability, speciation probability, and completion rate.
monitors.append( mnExtNewick(
filename = OUT_DIR + OUT_PREFIX + ".Protracted.trees",
isNodeParameter=TRUE,
printgen=N_PRINT_TREE,
separator=TAB,
tree=tree,
p_no_speciation,
p_speciation,
branch_spCompletion
) )
Finally, log the speciation-event tree (speciation events as branch lengths) as a diagnostic view of branch-event behavior.
monitors.append( mnFile(SpeciationBranchTreePopNames,
filename = OUT_DIR + OUT_PREFIX +".SpEventsBrLen.trees",
printgen = N_PRINT_TREE) )
13. Run MCMC
mymcmc = mcmc(mymodel, monitors, moves, nruns = N_RUNS, combine="mixed")
mymcmc.run(N_GEN,
checkpointFile = OUT_DIR + OUT_PREFIX + ".checkpoint",
checkpointInterval= N_CHECK_INTERVAL )
For practical analyses, run longer chains and verify ESS and convergence across runs.
14. Post-Processing And Summaries
Create summary trees and MAP ancestral reconstructions.
First, clean the branch-event trace formatting so it can be parsed reliably, then read it as an ancestral-state trace object.
This calls Python from the RevBayes front-end terminal to modify the file. Python must be installed.
file_to_edit = OUT_DIR + OUT_PREFIX + ".SpEvents.log"
command_process = "python3 -c 'p=\"" + file_to_edit + "\"; s=open(p).read().replace(\"[\",\"_\").replace(\"]\",\"\"); open(p,\"w\").write(s)'"
system(command_process)
sp_events_trace = readAncestralStateTrace(OUT_DIR + OUT_PREFIX + ".SpEvents.log")
Next, summarize branch-level speciation events as a marginal MAP reconstruction.
ancestralStateTree(tree=tree,
ancestral_state_trace_vector=sp_events_trace,
file=OUT_DIR + OUT_PREFIX + ".SpEvents.MAP.tre",
summary_statistic="MAP",
reconstruction="marginal",
site=1,
nStates=1,
burnin= BURN_IN)
Then rename the default annotation label in the output tree so it is explicit in downstream interpretation.
Again, Python is called from the RevBayes front-end terminal to modify the file. Python must be installed.
file_to_edit = OUT_DIR + OUT_PREFIX + ".SpEvents.MAP.tre"
command_sed = "python3 -c 'p=\"" + file_to_edit + "\"; s=open(p).read().replace(\"anc_state_1\",\"branch_speciation_events\"); open(p,\"w\").write(s)'"
system(command_sed)
Now summarize the protracted-tree outputs that include branch-wise rates and speciation probabilities.
treeTrace_sprates = readTreeTrace(OUT_DIR + OUT_PREFIX + ".Protracted.trees",
burnin = BURN_IN )
mapTree(treeTrace_sprates,
file = OUT_DIR + OUT_PREFIX + ".Protracted.MAP.tre")
Also summarize the tree where branch lengths represent inferred speciation-event counts.
Note
The number of events is summarized as the median number of events per branch across sampled trees, not as a maximum a posteriori estimate.
treeTrace_speventsbr = readTreeTrace(OUT_DIR + OUT_PREFIX +".SpEventsBrLen.trees",
burnin= BURN_IN )
mapTree(treeTrace_speventsbr,
file= OUT_DIR + OUT_PREFIX + ".SpEventsBrLen.MAP.tre",
ccAges=FALSE,
ccp=FALSE,
conditionalAges=FALSE,
mean=FALSE,
sampledAncestors=FALSE,
positiveBranchLengths=FALSE)
Finally, summarize ancestral trait states under both conditional and marginal reconstructions, then print the seed and exit.
anc_states_trace = readAncestralStateTrace(OUT_DIR + OUT_PREFIX + ".traits.log")
anc_tree_cond = ancestralStateTree(tree = tree,
ancestral_state_trace_vector = anc_states_trace,
include_start_states = FALSE,
file = OUT_DIR + OUT_PREFIX + ".traits.MAP.cond.tree",
reconstruction="conditional",
burnin = BURN_IN,
summary_statistic = "MAP",
site=1)
anc_tree_marg = ancestralStateTree(tree = tree,
ancestral_state_trace_vector = anc_states_trace,
include_start_states = FALSE,
file = OUT_DIR + OUT_PREFIX + ".traits.MAP.marg.tree",
reconstruction = "marginal",
burnin = BURN_IN,
summary_statistic = "MAP",
site=1)
printSeed()
quit()
Expected Output Files
With the example settings, outputs are written under ./tutorial_output/ and include:
tutorial_output.model.log: inspect this for convergence and MCMC diagnostics. It contains all model parameters, but it is long. For convenience, key parameters are separated into the files below.tutorial_output.Rates.log: likely the main target file, with posterior distributions for transition, population formation, extinction, and speciation-completion rates.tutorial_output.Descriptors.log: posterior distributions of derived diversification descriptors, such as ephemerality and evolvability.tutorial_output.RJ.log: posterior probabilities for reversible-jump model indicators. You can assess whether trait transitions are irreversible, whether observed-state rates differ, and whether hidden-rate heterogeneity is supported.tutorial_output.Protracted.trees: posterior distribution of trees with branch-level speciation probabilities and a binary indicator of whether speciation occurred.tutorial_output.SpEvents.log: posterior distribution of the number of speciation events on each branch.tutorial_output.SpEvents.MAP.tre: maximum a posteriori (MAP) tree with the number of speciation events as branch annotations.tutorial_output.SpEventsBrLen.trees: posterior distribution of event trees in which branch lengths correspond to numbers of speciation events.tutorial_output.SpEventsBrLen.MAP.tre: MAP event tree.tutorial_output.Protracted.MAP.tre: MAP summary fromtutorial_output.Protracted.trees.tutorial_output.traits.log: posterior distribution of augmented trait histories (simmaps).tutorial_output.traits.MAP.cond.tree: node ancestral-state reconstruction summarized as MAP based on conditional probabilities.tutorial_output.traits.MAP.marg.tree: node ancestral-state reconstruction summarized as MAP based on marginal probabilities.
Parameter Correspondence Table
The table below maps model notation to output/script parameter names.
| Parameter | Meaning | Name on Output |
|---|---|---|
| σS0A | State-dependent speciation-completion rate in observed state 0 and hidden state A | spCompletion[1] |
| σS1A | State-dependent speciation-completion rate in observed state 1 and hidden state A | spCompletion[2] |
| σS0B | State-dependent speciation-completion rate in observed state 0 and hidden state B | spCompletion[3] |
| σS1B | State-dependent speciation-completion rate in observed state 1 and hidden state B | spCompletion[4] |
| wσ0 | Proportional weight for observed speciation completion rate in observed state 0 | spCompletion_relative[1] |
| wσ1 | Proportional weight for observed speciation completion rate in observed state 1 | spCompletion_relative[2] |
| σO0 | Total speciation completion rate for the observed state 0 | spCompletion_observed[1] |
| σO1 | Total speciation completion rate for the observed state 1 | spCompletion_observed[2] |
| σhA | Speciation-completion-rate proportional multiplier in slower hidden regime A | spCompletion_hidden[1] |
| σhB | Speciation-completion-rate proportional multiplier in slower hidden regime B | spCompletion_hidden[2] |
| σg | Global speciation completion rate | global_spCompletion |
| μs0A | State-dependent population extinction rate in observed state 0 and hidden state A | extinction[1] |
| μs1A | State-dependent population extinction rate in observed state 1 and hidden state A | extinction[2] |
| μs0B | State-dependent population extinction rate in observed state 0 and hidden state B | extinction[3] |
| μs1B | State-dependent population extinction rate in observed state 1 and hidden state B | extinction[4] |
| wμ0 | Proportional weight for observed population extinction rate in observed state 0 | extinction_relative[1] |
| wμ1 | Proportional weight for observed population extinction rate in observed state 1 | extinction_relative[2] |
| μO0 | Total population extinction rate for the observed state 0 | extinction_observed[1] |
| μO1 | Total population extinction rate for the observed state 1 | extinction_observed[2] |
| μhA | Population extinction-rate proportional multiplier in slower hidden regime A | extinction_hidden[1] |
| μhB | Population extinction-rate proportional multiplier in slower hidden regime B | extinction_hidden[2] |
| μg | Global population extinction rate | global_extinction |
| λs0A | State-dependent population-formation rate in observed state 0 and hidden state A | pop_formation[1] |
| λs1A | State-dependent population-formation rate in observed state 1 and hidden state A | pop_formation[2] |
| λs0B | State-dependent population-formation rate in observed state 0 and hidden state B | pop_formation[3] |
| λs1B | State-dependent population-formation rate in observed state 1 and hidden state B | pop_formation[4] |
| wλ0 | Proportional weight for observed population formation rate in observed state 0 | pop_formation_relative[1] |
| wλ1 | Proportional weight for observed population formation rate in observed state 1 | pop_formation_relative[2] |
| λO0 | Total population formation rate for the observed state 0 | pop_formation_observed[1] |
| λO1 | Total population formation rate for the observed state 1 | pop_formation_observed[2] |
| λhA | Population-formation-rate proportional multiplier in slower hidden regime A | pop_formation_hidden[1] |
| λhB | Population-formation-rate proportional multiplier in slower hidden regime B | pop_formation_hidden[2] |
| λg | Global population formation rate | global_pop_formation |
| rg | Global population turnover rate | global_pop_turnover |
| dg | Global net population formation rate | global_net_pop_formation |
Plot Results
You can use the custom R functions below to plot the example results stored in docs/TutorialRev/tutorial_output.
First, load the plotting script:
source("docs/TutorialRev/scripts/traderpros_plotting.R")
1) Descriptor distributions
plot_descriptors(
input = "docs/TutorialRev/tutorial_output",
output = "docs/TutorialRev/tutorial_output/plots",
graph = "violin",
burn_in = 0.10,
force = "yes",
out_images_format = "both"
)

This figure summarizes posterior distributions of ephemerality, evolvability, net population formation, and turnover across states. Wider violins indicate higher posterior uncertainty.
2) Diversification and transition rates
plot_rates(
input = "docs/TutorialRev/tutorial_output",
output = "docs/TutorialRev/tutorial_output/plots",
graph = "violin",
burn_in = 0.10,
force = "yes",
out_images_format = "both"
)

This panel compares transition, speciation-completion, population-formation, and extinction rates. Differences in central tendency among violins reflect support for state-dependent dynamics.
3) Reversible-jump model indicators
plot_rj(
input = "docs/TutorialRev/tutorial_output",
output = "docs/TutorialRev/tutorial_output/plots",
burn_in = 0.10,
force = "yes",
out_images_format = "both"
)

Each bar plot shows posterior probabilities for indicator states (No/Yes), helping assess support for model components such as state dependence, hidden effects, and reversibility.
4) Tree-based summaries
plot_trees(
input = "docs/TutorialRev/tutorial_output",
output = "docs/TutorialRev/tutorial_output/plots",
prefix_used_in_traderpros = "tutorial_output",
burn_in = 0.10,
force = "yes",
out_images_format = "both"
)

This tree maps branch-specific speciation-completion rates. Warmer colors indicate branches with higher inferred completion rates.

This tree shows posterior branch-level probability of at least one completion event, highlighting where speciation is most strongly supported.

This plot summarizes MAP branch event counts, giving a direct view of where completion events are concentrated.

This ancestral-state reconstruction displays the most probable hidden-observed state combinations through time under the conditional MAP summary.
This tree maps branch-specific population formation rates. Warmer colors indicate branches with higher inferred population formation rates.
This tree maps branch-specific population extinction rates. Warmer colors indicate branches with higher inferred population extinction rates.
References
Azevedo, GHF & Hedin, M (2026) Trait-dependent protracted speciation illuminates the penumbra between micro- and macroevolution: insights from cave spider diversification (submitted)
Sukumaran J, Holder MT, Knowles LL (2021) Incorporating the speciation process into species delimitation. PLoS Comput Biol 17(5): e1008924. https://doi.org/10.1371/journal.pcbi.1008924
Rosindell, J., Cornell, S.J., Hubbell, S.P. and Etienne, R.S. (2010), Protracted speciation revitalizes the neutral theory of biodiversity. Ecology Letters, 13: 716-727. https://doi.org/10.1111/j.1461-0248.2010.01463.x
May, Michael & Brian R Moore (2020) A Bayesian Approach for Inferring the Impact of a Discrete Character on Rates of Continuous-Character Evolution in the Presence of Background-Rate Variation, Systematic Biology, Volume 69, Issue 3, Pages 530–544, https://doi.org/10.1093/sysbio/syz069
Beaulieu, Jeremy M. & Brian C. O’Meara (2016) Detecting Hidden Diversification Shifts in Models of Trait-Dependent Speciation and Extinction, Systematic Biology, Volume 65, Issue 4, July 2016, Pages 583–601. https://doi.org/10.1093/sysbio/syw022