Bayesian General Mixed Yule-Coalescent Model for Species Delimitation

Implements a Bayesian version of the general mixed Yule-coalescent (GMYC) model for species delimitation from single-locus data (Reid & Carstens 2012, BMC Evolutionary Biology 12:196). Markov Chain Monte Carlo sampling evaluates the posterior distribution of species boundaries under flexible uniform priors, with branching rates profiled at their maximum likelihood estimates. Supports pooling over multiple posterior trees to propagate phylogenetic uncertainty into marginal probabilities of conspecificity, convergence diagnostics (split-Rhat, ESS, prior-vs-posterior contraction), and interactive heatmap visualization of the resulting matrices.


bGMYC4

Reid's Bayesian species delimitation, made reproducible and accessible

bGMYC4 logo

License: GPL v3

CRAN status

Total downloads

Lifecycle: stable

Bayesian General Mixed Yule-Coalescent (GMYC) model for species delimitation in R β‰₯ 4.0


🌍 Overview

bGMYC4 implements the Bayesian GMYC model of Reid & Carstens (2012): MCMC sampling of the threshold between Yule (speciation) and coalescent (within-species) branching on ultrametric trees. Pooling samples over a posterior sample of trees propagates phylogenetic uncertainty into marginal posterior probabilities of species limits and pairwise conspecificity.


What's new in 4.3.1

  • Fast post-processing. spec.probmat() and bgmyc.spec() exploit the fact that the species partition is a deterministic function of (tree, threshold): tip descendants are computed once per tree, samples are tabulated by threshold, and clusters are built once per unique threshold and weighted by its frequency. Internal benchmark (215 tips, 2000 retained samples): spec.probmat() ~10 s β†’ ~0.006 s; bgmyc.spec() ~9.5 s β†’ ~0.04 s. Output is numerically equivalent to the previous per-sample implementation (max difference < 1e-14).
  • fix_ultrametric() is now an exported function (it used to live only inside the helper script). It repairs rounding-level noise from BEAST exports and refuses genuinely non-clock trees instead of silently stretching branches.
  • Input validation. bgmyc.gibbs() checks proposal widths and prior bounds, and warns when py2/pc2 exceed interpretable values, when the threshold prior is truncated by Nnode, when the chain is too short, or when burn-in eats almost the whole chain.
  • Honest pooling. If trees contributed unequal numbers of samples, spec.probmat() and bgmyc.spec() warn that trees are then weighted by sample count rather than equally.
  • cmatrix validation in bgmyc.spec(): row names must cover all tip labels, so species-by-locality matrices can no longer be silently filled with the wrong rows.
  • Diagnostics: bgmyc.chains(), bgmyc.convergence(), bgmyc.pool(), hpd_discrete(); summary() reports the pooled marginal threshold summary plus per-tree diagnostics.
  • Documentation is fully generated by roxygen2; NAMESPACE is rebuilt from @export tags.
  • Bug fixes: HPD type error in summary.multibgmyc(); a dead loop in bgmyc.point(); numerical guards (0^0, degenerate rates, stable log-density) in gmyc.5parameter.lik(); explicit root handling in bgmyc.dataprep(); graphics-device protection and removal of unused arguments in plot.interactive.probmat().

✨ Key Features

Feature Description
🌲 Single & multi-tree analysis Run GMYC on one tree, or pool over a posterior sample of trees
⚑ Parallel multi-tree runs bgmyc.multiphylo(..., cores = k) uses a parallel cluster; cores = 1 (default) runs sequentially
🎲 Reproducible RNG bgmyc.multiphylo(..., seed = 42) assigns independent L'Ecuyer-CMRG substreams per tree
πŸ“Š Interactive diagnostics Trace plots, acceptance rates, ESS (optional mcmcse), split-RΜ‚ via bgmyc.convergence()
🌑️ Heatmap visualisation Conspecificity matrices ordered by tree topology; static and interactive (plotly)
🧬 BEAST-friendly workflow The helper script in inst/scripts/ reads BEAST trees via treeio, prunes outgroups and checks ultrametricity
πŸ‡ Pure-R post-processing Threshold-aggregated, vectorised; no external sort/uniq dependencies
πŸ“– Interactive vignette vignette("bGMYC4-interactive", package = "bGMYC4")

πŸ“¦ Installation

πŸ”Ή From CRAN (recommended)

install.packages("bGMYC4")

πŸ”Ή From GitHub (latest version)

if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
remotes::install_github("DmitryKarabanov/bGMYC4", build_vignettes = TRUE)

πŸ”Ή From source archive

install.packages("path/to/bGMYC4.tar.gz", repos = NULL, type = "source")
# To build vignettes locally:
# install.packages("path/to/bGMYC4.tar.gz", repos = NULL, type = "source", build_vignettes = TRUE)

πŸ”Ή System requirements

  • R β‰₯ 4.0.0 (as declared in DESCRIPTION; tested on R 4.5.x)
  • Required (Imports): ape (β‰₯ 5.0), parallel (ships with R)
  • Optional (Suggests):
    • mcmcse β€” effective sample size and convergence statistics
    • plotly, base64enc, htmlwidgets β€” interactive heatmaps and HTML export
    • knitr, rmarkdown β€” vignettes
    • treeio, ggtree, dplyr β€” BEAST annotation handling in the helper script

πŸš€ Quick Start

library(bGMYC4)
data(east10)          # 10 posterior trees, 215 tips

## one tree (short chain for a smoke test)
result <- bgmyc.singlephy(
  phylo = east10[[1]],
  mcmc = 1000, burnin = 200, thinning = 10,
  py1 = 0, py2 = 1.5, pc1 = 0, pc2 = 2,
  t1 = 2, t2 = 35,
  scale = c(20, 10, 5), start = c(1, 0.5, 10)
)

plot(result)          # trace plots
summary(result)       # threshold mean + 95% HPD

## conspecificity matrix
prob_mat <- spec.probmat(result)
plot(prob_mat, east10[[1]])

## point estimate of species clusters
out <- bgmyc.point(prob_mat, ppcutoff = 0.5)
cat("Delimited clusters:", length(out), "\n")

For a publication-grade analysis, run many trees with long chains, e.g.

res <- bgmyc.multiphylo(east10, mcmc = 10000, burnin = 1000, thinning = 100,
                        cores = 4, seed = 42)
pm  <- spec.probmat(res)
summary(res)

πŸ“š Documentation

Resource Command Description
Package help ?bGMYC4 Function reference
Interactive tutorial browseVignettes("bGMYC4") Step-by-step workflow with diagnostics
Function details ?bgmyc.multiphylo, ?spec.probmat Parameter explanations
Built-in data ?east10 Simulated dataset for testing
Performance tips vignette("bGMYC4-interactive", package = "bGMYC4") Section "Performance & Export"
Example inst/scripts/bGMYC.R Simple interactive script

Workflow

  1. Preprocess trees. Ultrametric, fully bifurcating, no zero-length terminal branches. Use fix_ultrametric() if BEAST export produced rounding-level noise.
  2. Tune on one tree. bgmyc.singlephy() β†’ plot() β†’ acceptance rates and ESS.
  3. Run the posterior sample. bgmyc.multiphylo() with the tuned settings.
  4. Summarise. spec.probmat() β†’ heatmap; bgmyc.point() for a point estimate; bgmyc.spec() for the full posterior of species partitions (optionally as species-by-locality matrices via cmatrix, for downstream community analyses).

Parameters

Parameter Role Typical values Notes
mcmc Chain length 10 000 (test), 50 000+ (final) Reid & Carstens (2012) used 10 000 per tree over 100 trees
burnin Burn-in 10–30 % of mcmc The original study discarded 1 000 of 10 000
thinning Sampling interval 10–100 Reduces autocorrelation and RAM
py1, py2 Yule rate-change prior 0, 0.5–1.5 Ξ» ∝ n^py; values above ~1.5 blur the Yule/coalescent boundary
pc1, pc2 Coalescent rate-change prior 0, 1.0–2.0 < 1 β†’ decline, > 1 β†’ growth
t1, t2 Threshold prior (number of species) 2, min(Nnode, …) t2 above Nnode = ntips βˆ’ 1 is unreachable; the prior is truncated and a warning is issued
scale Proposal widths (py, pc, t) c(20, 10, 5) Tune via acceptance rates; aim for ~0.2–0.4 on long chains
ppcutoff Threshold for lumping tips into species in bgmyc.point() 0.05 (value used in the original bGMYC documentation), 0.01 Single linkage; see "Choosing ppcutoff" below. Do not round the matrix before calling bgmyc.point()

Choosing ppcutoff

spec.probmat() returns the marginal posterior probability that two tips were placed in the same species, pooled over all retained thresholds and (for multibgmyc) over all trees. It is therefore not comparable to a clade posterior probability. A well-supported biological species can show pairwise values well below 0.5 simply because the threshold posterior is broad or because trees disagree, whereas pairs from different species usually sit close to 0. The informative gap is near zero β€” which is why the original bGMYC documentation uses 0.05.

bgmyc.point() is a single-linkage procedure: tips join when P > cutoff and clusters merge transitively. A species is therefore held together by its weakest link. Even when most pairs inside a real species have P = 1, a single uncertain pair bridging two intraspecific lineages (e.g. populations from different river basins) may be their only connection. Raising the cutoff removes such bridges and fragments real species into phylogeographic subgroups, whereas pairs from different species usually have P near 0 and remain separated even at very low cutoffs. On empirical data the stability plateau is typically found at low values (0.001-0.05); the original bGMYC documentation uses 0.05.

Choose the value from your own data:

pm <- spec.probmat(res)          # do NOT round before bgmyc.point()
sw <- c(0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.9)
data.frame(cutoff = sw,
           clusters = vapply(sw, function(p) length(bgmyc.point(pm, p)), integer(1)))

Look for a plateau β€” a range of cutoffs where the number of clusters is stable β€” and check it against independent evidence (morphology, geography, nuclear markers). Report the chosen cutoff and the plateau in your methods section.

Performance and parallelism

## limit the number of workers used by the package
res <- bgmyc.multiphylo(trees, mcmc = 10000, burnin = 1000, thinning = 100,
                        cores = 8, seed = 42)

bgmyc.multiphylo() uses parallel::makeCluster(). Use the cores argument.

Post-processing cost depends on the number of distinct thresholds, not on the number of retained samples, which is why long chains and large tree sets remain fast.

Convergence diagnostics

  • Acceptance rates are reported per chain (target β‰ˆ 0.2–0.4 for long chains).
  • ESS via mcmcse when installed (target > 200).
  • Split-RΜ‚: run several independent chains with bgmyc.chains() and summarise them with bgmyc.convergence() (target RΜ‚ < 1.05).

⚠️ RΜ‚ is not computed across different trees. Each posterior tree defines its own conditional posterior, so a cross-tree RΜ‚ is not a valid convergence statistic. summary() therefore reports per-tree diagnostics alongside the pooled marginal summary.

Troubleshooting

Issue Solution
Your input tree is not ultrametric Try fix_ultrametric(tr); if it still fails, the tree is genuinely non-clock β€” re-export from BEAST or check the clock model
All trees must share the same tip label set Prune/rename tips so every tree has the same labels before bgmyc.multiphylo()
'scale' must be three positive numbers Proposal widths must all be > 0
Prior bounds must satisfy py1 < py2 … Lower bound must be strictly below the upper bound
cmatrix must have rownames covering all tree tip labels Set rownames(cmatrix) to the tip labels
Trees contributed unequal numbers of samples Use identical mcmc/burnin/thinning for equal-weight model averaging
Interactive heatmap not saved Install plotly, base64enc, htmlwidgets

Citation

If you use bGMYC4, please cite:

@Manual{bGMYC4,
  title  = {bGMYC4: Bayesian General Mixed Yule-Coalescent Model for Species Delimitation},
  author = {Karabanov, Dmitry},
  year   = {2026},
  note   = {R package version 4.3.1},
  url    = {https://github.com/DmitryKarabanov/bGMYC4}
}

Foundational work:

  • Pons J, Barraclough TG, Gomez-Zurita J, et al. (2006) Sequence-based species delimitation for the DNA taxonomy of undescribed insects. Systematic Biology 55(4):595–609. doi:10.1080/10635150600852011
  • Reid NM, Carstens BC (2012) BMC Evolutionary Biology 12:196. doi:10.1186/1471-2148-12-196

citation("bGMYC4") prints both entries.

License

GPL (β‰₯ 3). See the DESCRIPTION file.

Author

Dmitry Karabanov β€” dk[at]ibiw.ru Institute for Biology of Inland Waters, RAS ORCID: 0000-0001-6008-7441

Original bGMYC implementation: Noah Reid.

Acknowledgements

This package was developed with assistance from the Qwen AI assistant (Alibaba Cloud), which provided code review, debugging support and documentation drafting. All scientific decisions, parameter choices and biological interpretations were made by the author.


bGMYC4 – Bayesian species delimitation, made simple, reproducible, and biologist‑friendly πŸŒΏπŸ”¬

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.

install.packages("bGMYC4")

4.3.1 by Dmitry Karabanov, 9 days ago


https://github.com/DmitryKarabanov/bGMYC4


Report a bug at https://github.com/DmitryKarabanov/bGMYC4/issues


Browse source code at https://github.com/cran/bGMYC4


Authors: Noah Reid [ctb, cph] (Original author of bGMYC) , Dmitry Karabanov [aut, cre] (ORCID:


Documentation:   PDF Manual  


GPL (>= 3) license


Imports ape, parallel

Suggests mcmcse, plotly, base64enc, testthat, knitr, rmarkdown, htmlwidgets, treeio, ggtree, dplyr


See at CRAN