[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CVKYD7KY7S76MRNJVDYAHJ":3,"skill-same:01M7CVKYD7KY7S76MRNJVDYAHJ":73},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M7CVKYD7KY7S76MRNJVDYAHJ","bio-phylo-distance-calculations",null,"Build model-corrected evolutionary distance matrices and distance trees (NJ, BIONJ, FastME, UPGMA) with Biopython Bio.Phylo plus R ape\u002Fphangorn\u002FFastME. Covers why a distance is a model-corrected estimate of substitutions per site that undercounts raw because of multiple\u002Fback\u002Fparallel hits (saturation); why the matrix discards the per-site information ML keeps; the LogDet\u002Fparalinear fix for compositional heterogeneity; the UPGMA molecular-clock trap; and the Bio.Phylo landmine that DistanceCalculator offers only identity\u002Fmatrix distances, not JC\u002FK80\u002FTN93. Use when computing a distance matrix, building a fast NJ\u002FFastME tree, seeding an ML search, barcoding, or testing substitution saturation before a deep tree. Routes ML and starting-tree work to modern-tree-inference, alignment quality to alignment\u002Falignment-io, and tree I\u002FO to tree-io.","mrsonord2240\u002Fopenscience-specialists","mrsonord2240","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F76487430?v=4","01M7CTEM40S43GSJZ9A3YCCXZK","Samuel Nord","01M7CTEM4K69JD1GBYNHVJ9ZP4",2,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-phylo-distance-calculations\ndescription: Build model-corrected evolutionary distance matrices and distance trees (NJ, BIONJ, FastME, UPGMA) with Biopython Bio.Phylo plus R ape\u002Fphangorn\u002FFastME. Covers why a distance is a model-corrected estimate of substitutions per site that undercounts raw because of multiple\u002Fback\u002Fparallel hits (saturation); why the matrix discards the per-site information ML keeps; the LogDet\u002Fparalinear fix for compositional heterogeneity; the UPGMA molecular-clock trap; and the Bio.Phylo landmine that DistanceCalculator offers only identity\u002Fmatrix distances, not JC\u002FK80\u002FTN93. Use when computing a distance matrix, building a fast NJ\u002FFastME tree, seeding an ML search, barcoding, or testing substitution saturation before a deep tree. Routes ML and starting-tree work to modern-tree-inference, alignment quality to alignment\u002Falignment-io, and tree I\u002FO to tree-io.\ntool_type: mixed\nprimary_tool: Bio.Phylo.TreeConstruction\n---\n\n## Version Compatibility\n\nReference examples tested with: BioPython 1.83+. Model-corrected alternatives: ape 5.8+, phangorn, FastME, scikit-bio.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show biopython` then `help(module.function)` to check signatures\n- R: `packageVersion('ape')` then `?dist.dna` to verify model strings\n- CLI: `fastme --version` then `fastme --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nBio.Phylo `DistanceCalculator` offers only identity \u002F substitution-matrix distances and has NO model-based JC\u002FK80\u002FTN93; for model-corrected DNA distances use ape `dist.dna(model=...)` (introspect its model list and `gamma=` support if the version differs).\n\n# Distance Calculations -- Distance Erases the Information ML Keeps; the Correction Is the Model\n\n**\"Build a tree from my alignment\"** -> Estimate model-corrected pairwise distances, then cluster them into a tree, knowing the correction is where the biology lives and the matrix discards what ML uses.\n- Python: `DistanceCalculator(...).get_distance(aln)` then `DistanceTreeConstructor().nj(dm)` (Bio.Phylo, identity-only)\n- R: `dist.dna(x, model='TN93')` then `fastme.bal(d)` \u002F `nj(d)` (ape, model-corrected)\n\nScope: computing evolutionary distance matrices and building\u002Fbootstrapping distance trees (NJ, BIONJ, FastME, UPGMA), and testing saturation before trusting them. ML inference, model selection, and where NJ seeds an ML search -> modern-tree-inference. Alignment quality and trimming, which gate every distance -> alignment\u002Falignment-io. Reading\u002Fwriting\u002Fconverting the trees these methods emit -> tree-io. Rooting and pruning -> tree-manipulation.\n\n## The Single Most Important Modern Insight\n\nA distance-based phylogeny is built in two lossy steps and both losses are silent. First, a distance is a model-corrected estimate of expected substitutions per site, not the observed proportion of differing sites; second, the matrix collapses each sequence pair to one scalar and discards the site-pattern information that maximum likelihood evaluates. Distance methods are therefore fast but doubly limited -- by how good the correction is, and by what a matrix of scalars can encode -- and they are structurally incapable of using the per-site signal that makes ML the gold standard for hard problems. Three load-bearing facts:\n\n1. **The correction is the whole biological content.** The raw p-distance (proportion of differing sites) systematically UNDERCOUNTS true divergence because every site that mutated twice (back-substitution), in parallel on both lineages, or to a third state (multiple hit) is missed, and the gap grows without bound toward saturation. The algorithm downstream (NJ, FastME) is just arithmetic on the numbers handed to it; feed it p-distances on divergent data and it returns a confidently wrong tree, fast.\n2. **The matrix throws away what ML keeps.** Two completely different alignments can produce the same distance matrix and therefore the same tree. ML never collapses the data, so it cannot be fooled this way; once the matrix exists, which sites drove the divergence, among-site rate heterogeneity, and competing site-pattern signal are gone.\n3. **Consistency is conditional, not a guarantee.** NJ is statistically consistent -- it returns the true tree as sequence length grows -- but only if the input distances are additive and correctly estimated. A consistent algorithm fed biased (saturated, misspecified) distances converges confidently on the WRONG tree. \"I used NJ so it is consistent\" is not a defense; the correction is exactly what most users get wrong.\n\n## Distance Corrections\n\nEvery nucleotide correction inverts the probability that a site differs under a model, so as p approaches the equilibrium difference (0.75 for equal base frequencies under JC) the correction diverges to infinity and its variance explodes -- the mathematical face of saturation.\n\n| Correction | Corrects for | When to use | ape model |\n|---|---|---|---|\n| p-distance (raw \u002F Hamming) | nothing | very shallow \u002F barcoding; saturation plots | `'raw'` (`'N'`, `'TS'`, `'TV'` return COUNTS -- divide by `ncol(aln)`) |\n| Jukes-Cantor (JC69) | multiple hits, one rate | minimal correction, quick sanity tree | `'JC69'` |\n| Kimura 2-param (K80) | + transition\u002Ftransversion bias | default DNA quick distance | `'K80'` (default) |\n| Tamura-Nei (TN93) | + two transition rates + unequal base freqs | mtDNA, richest closed-form | `'TN93'` |\n| LogDet \u002F paralinear | COMPOSITIONAL heterogeneity (non-stationary, general Markov) | GC drift across taxa; compositional attraction suspected | `'logdet'`, `'paralin'` |\n| Gamma-corrected | among-site rate variation (ASRV) | alpha small (\u003C ~1); long branches | `dist.dna(..., gamma=alpha)` |\n| Protein matrix (LG\u002FWAG\u002FJTT\u002FPAM) | amino-acid replacement, multiple hits | protein data (use phangorn `dist.ml`) | n\u002Fa (LG\u002FWAG modern; PAM legacy) |\n\nLogDet \u002F paralinear (Lockhart et al. 1994; Lake 1994) is the non-obvious one: JC\u002FK80\u002FTN93 all assume stationarity (constant base composition across the tree), and when composition drifts (thermophiles, AT-rich insect mtDNA, GC-rich chloroplasts) every stationary correction groups taxa by base composition rather than ancestry -- compositional attraction, a sibling of long-branch attraction that fools NJ and stationary-model ML alike. LogDet is computed from the determinant of the 4x4 pairwise divergence matrix and is consistent under the general Markov model, at the cost of needing long sequences and not easily taking gamma. If a topology flips between JC and LogDet, suspect compositional heterogeneity.\n\n## Algorithm Decision\n\n| Algorithm | Criterion | Clock? | Cost | Use \u002F pitfall |\n|---|---|---|---|---|\n| UPGMA | average-linkage clustering | ASSUMES strict clock (ultrametric) | O(n^2) | avoid for molecular phylo; wrong TOPOLOGY under rate variation; serotyping\u002Fdendrograms only |\n| NJ (Saitou & Nei 1987) | greedy balanced minimum evolution (Q-matrix) | no | O(n^3) | fast default; consistent ONLY if distances correct\u002Fadditive; barcoding, large n |\n| BIONJ (Gascuel 1997) | NJ + variance-weighted reduction | no | O(n^3) | better than NJ on large\u002Fnoisy distances; a common ML starting-tree generator (IQ-TREE2\u002FRAxML-NG default to parsimony starts) |\n| FastME (Lefort et al. 2015) | balanced minimum evolution + NNI\u002FSPR search | no | ~NJ-speed | the modern best distance tree; actively searches, not a single greedy pass |\n\nUPGMA is the key warning: it forces every tip equidistant from the root, which molecular data essentially never satisfies because lineages evolve at different rates. A fast-evolving lineage gets pulled toward the tips and grouped by total divergence rather than true ancestry -- a clustering-by-rate artifact analogous to long-branch attraction. Flat rule: do not use UPGMA for molecular phylogeny unless a clock is independently established. NJ does not assume a clock because its Q-matrix corrects each pairwise distance for that taxon's average divergence to everyone else. NJ\u002FBIONJ\u002FFastME can seed ML searches: some ML programs build a BIONJ or ME starting tree in O(n^3) before likelihood NNI\u002FSPR (though IQ-TREE2 and RAxML-NG default to parsimony starting trees), so this machinery still has a place in an all-ML pipeline.\n\n## Tool Taxonomy\n\n| Tool (lang) | Distance step | Tree step | Note |\n|---|---|---|---|\n| Bio.Phylo.TreeConstruction (Py) | `DistanceCalculator` identity \u002F BLOSUM \u002F PAM matrices ONLY | `DistanceTreeConstructor().nj()` \u002F `.upgma()` | NO JC\u002FK80\u002FTN93; `'identity'` is p-distance only on ungapped alignments (gap-vs-base counts as a mismatch over the full length -- strip gap columns first); named matrices are score distances |\n| ape (R) | `dist.dna(model=, gamma=)` -- full menu incl. LogDet, gamma | `nj()`, `bionj()`, `fastme.bal()`, `fastme.ols()` | the reference engine for real corrections |\n| phangorn (R) | `dist.ml(model=)` -- DNA JC69\u002FF81 only, but all protein matrices | `upgma()`, `NJ()` | the natural choice for protein distances |\n| FastME (CLI) | JC\u002FK2P\u002FF84\u002FTN93\u002FLogDet\u002Fprotein | NJ\u002FBIONJ\u002FBME\u002FOLS-ME + NNI\u002FSPR + bootstrap | standalone for very large n; `-m B` = balanced ME |\n| scikit-bio (Py) | none (requires a pre-corrected matrix) | `skbio.tree.nj(dm)` | pure-Python NJ; `neg_as_zero=` since 0.6.3 |\n\nLoud flag, the second flat rule: Bio.Phylo and scikit-bio do NOT correct for multiple hits -- their built-in distance is p-distance or score-based. Presenting Bio.Phylo's `'identity'` distance as a \"Jukes-Cantor tree\" is a common and wrong shortcut. For a real correction, compute the matrix in ape\u002FFastME (or compute it yourself) and pass it in.\n\n## Build a Model-Corrected Distance Matrix and NJ Tree\n\n**Goal:** Turn an alignment into a tree, contrasting Bio.Phylo's identity-only path against ape's model-corrected path.\n\n**Approach:** In Python use Bio.Phylo for the NJ\u002FUPGMA algorithm and pure-Python I\u002FO, but treat its distance as an uncorrected p-distance; for any divergent data move the distance step to ape `dist.dna`, then cluster with FastME (best) or NJ.\n\n```python\nfrom Bio import AlignIO\nfrom Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor\n\naln = AlignIO.read('alignment.fasta', 'fasta')\ncalc = DistanceCalculator('identity')        # identity-only: this is a p-distance, NOT a JC\u002FK80 correction\ndm = calc.get_distance(aln)                   # multiple\u002Fback\u002Fparallel hits are NOT corrected here\ntree = DistanceTreeConstructor().nj(dm)       # NJ algorithm is correct; the DISTANCES are the limitation\n\n# Model-corrected matrix from R -- write.csv(as.matrix(dist.dna(aln, model = 'K80')), 'k80.csv') -- passed in:\nimport pandas as pd\nfrom Bio.Phylo.TreeConstruction import DistanceMatrix\ndf = pd.read_csv('k80.csv', index_col=0)\nnames = list(df.index)\nlower = [[float(df.iat[i, j]) for j in range(i + 1)] for i in range(len(names))]   # lower triangle incl. diagonal\ntree_k80 = DistanceTreeConstructor().nj(DistanceMatrix(names, lower))\n# scikit-bio: skbio.tree.nj(skbio.DistanceMatrix(df.values, names))\n```\n\n```r\nlibrary(ape)\naln \u003C- read.dna('alignment.fasta', format = 'fasta')\nalpha \u003C- 0.5                                        # gamma shape (alpha \u003C 1 = strong ASRV); estimate it, do not assume\nmethod \u003C- function(x) fastme.bal(dist.dna(x, model = 'TN93', gamma = alpha), nni = TRUE, spr = TRUE)\ntree \u003C- method(aln)                                 # define the method ONCE so the bootstrap reuses it exactly\n# nj() \u002F bionj() are the faster single-pass alternatives; bionj seeds ML searches\n```\n\n## Pre-flight: Test Substitution Saturation\n\n**Goal:** Decide whether the data retain phylogenetic signal before trusting any deep distance tree.\n\n**Approach:** Run the ape proxy below: the fraction of pairs with p > 0.5 and whether transition proportions still rise with a corrected distance. Xia's formal Iss vs Iss.c test (Xia 2003) is implemented only in DAMBE (not ape\u002Fphangorn); run it there as an optional confirmation. Do not wait for `NaN` as the warning -- fully saturated data can return finite JC69\u002FTN93 values.\n\n```r\nlibrary(ape)\nL  \u003C- ncol(aln)\np  \u003C- dist.dna(aln, model = 'raw')          # p-distance\nd  \u003C- dist.dna(aln, model = 'TN93')         # corrected distance\nts \u003C- dist.dna(aln, model = 'TS') \u002F L       # 'TS'\u002F'TV' return COUNTS -> divide by length for proportions\ntv \u003C- dist.dna(aln, model = 'TV') \u002F L\nmean(p > 0.5)                               # fraction of pairs with p > 0.5; any sizeable fraction = red flag\ncoef(lm(as.vector(ts) ~ as.vector(d)))[2]   # slope of transitions vs distance; near 0 = PLATEAU = saturated\nplot(d, ts, col = 'red', ylim = range(c(ts, tv))); points(d, tv, col = 'blue')   # unsaturated = both still rising\n```\n\nOn simulated test data: saturated (83% of pairs p > 0.5) gave a transition slope of 0.04 and a mean ts\u002Ftv of 0.76; a deep but unsaturated set (no pair p > 0.5) gave 0.17 and 1.03. A flat transition curve with many p > 0.5 pairs means do not build a distance tree.\n\n## Bootstrap a Distance Tree\n\n**Goal:** Quantify how reproducible each clade is under resampling -- precision, not accuracy.\n\n**Approach:** Resample alignment columns with replacement, recompute the matrix with the SAME correction, rebuild with the SAME algorithm, and summarize clade frequencies on a majority-rule consensus.\n\n```r\nlibrary(ape)\nset.seed(42)\nboot \u003C- boot.phylo(tree, aln, method, B = 500)   # the SAME method (model + gamma + algorithm) that built the tree\n# 100-1000 replicates standard; support measures SAMPLING stability only -- it cannot detect a bias in the distances\n```\n\nIn Python, do NOT pass unrooted NJ replicates to `bootstrap_consensus(..., majority_consensus)`: `majority_consensus` counts ROOTED clades and each NJ replicate is rooted arbitrarily, so a split's count is shared with its complement (on a 20-taxon barcode set, max support 61-68% where the same replicates rooted give 100%). Root every replicate on a fixed outgroup first (identity distance, same correction caveat), and expect it to be slow for large n (~15 min at n=150, B=100) -- prefer ape `boot.phylo` there:\n\n```python\nimport random\nfrom Bio.Phylo.Consensus import bootstrap_trees, majority_consensus\n\nrandom.seed(42)\nreps = []\nfor rep in bootstrap_trees(aln, 100, DistanceTreeConstructor(calc, 'nj')):\n    rep.root_with_outgroup({'name': 'outgroup_taxon'})   # fixed outgroup for every replicate\n    reps.append(rep)\nconsensus = majority_consensus(reps, cutoff=0.5)          # clade.confidence = % of replicates\n```\n\n## When Distance Is Legitimate vs a Trap\n\nLegitimate or preferred: a quick exploratory \u002F sanity tree before a long ML run; very large n (thousands+ tips) where ML is infeasible (large-scale barcoding, OTU\u002Fpangenome trees); barcoding and population-level shallow data, where saturation is negligible and the per-site information ML keeps adds little (NJ on K2P distances is the literal DNA-barcoding standard); and as the starting tree for ML\u002FBayesian search.\n\nA trap, do not: publication-grade deep phylogeny or formal hypothesis testing (dating, selection, contested deep nodes) -- use ML or Bayesian with model selection; any dataset that fails a saturation test (Xia Iss >= Iss.c), which no algorithm rescues; data with strong compositional heterogeneity unless using LogDet\u002Fparalinear; and mistaking consistency for a guarantee -- NJ is consistent only with correct distances, and saturation\u002Fmisspecification break it exactly as they break ML.\n\n## Per-Method Failure Modes\n\n### Saturation Makes Distances Plateau and Mislead at Depth\n**Trigger:** Deep divergences with many pairwise p-distances above ~0.5; transitions exhausted while transversions still climb.\n**Mechanism:** So many superimposed substitutions accumulate that observed differences approach the random expectation; the correction inflates violently near its singularity and carries no remaining signal about deep splits.\n**Symptom:** Corrected distances explode and become unstable; the saturation plot's transition curve flattens; deep nodes are unstable across models.\n**Fix:** Run the saturation pre-flight (optionally Xia Iss in DAMBE); exclude transitions, third codon positions, or saturated partitions; do not build a deep distance (or ML) tree on saturated data.\n\n### UPGMA Returns the Wrong Topology Under Rate Variation\n**Trigger:** Lineages evolving at different rates analyzed with UPGMA.\n**Mechanism:** UPGMA forces an ultrametric tree (clock), so a fast-evolving lineage is pushed toward the tips and grouped by total divergence, not ancestry.\n**Symptom:** Topology differs from an NJ tree on the same matrix; fast lineages cluster together.\n**Fix:** Use NJ or FastME; never UPGMA for molecular phylogeny without an independently established clock.\n\n### Identity \u002F Uncorrected Distance Model on Divergent Data\n**Trigger:** Bio.Phylo `'identity'` or ape `'raw'` on anything beyond shallow divergence; calling it a \"JC tree\".\n**Mechanism:** No multiple-hit correction, so divergence is undercounted nonlinearly and worst on the longest branches, amplifying long-branch artifacts.\n**Symptom:** Branch lengths and topology shift when a real correction is applied; long-branch taxa attract.\n**Fix:** Use ape `dist.dna(model='TN93')` or a gamma correction; for compositional skew use LogDet; for protein use phangorn `dist.ml(model='LG')`.\n\n### Bootstrap on a Method That Discarded the Per-Site Information\n**Trigger:** High distance-NJ bootstrap on saturated or compositionally biased data.\n**Mechanism:** Resampling removes sampling noise, not a systematic bias baked into the distances, so the wrong split reproduces every replicate.\n**Symptom:** Confident, reproducible support on a clade that moves when the correction or saturated sites change.\n**Fix:** Bootstrap measures precision, not accuracy; fix the distances (model + saturation) first.\n\n## Quantitative Thresholds\n\n| Quantity | Threshold | Source \u002F rationale |\n|---|---|---|\n| p-distance saturation onset | unstable as nucleotide p -> ~0.5-0.6; singularity at 0.75 (equal base freqs) | many pairwise p > ~0.5 = red flag, run a saturation test |\n| Xia substitution-saturation test (DAMBE only; optional) | Iss \u003C Iss.c => usable; Iss >= Iss.c (esp. asymmetric Iss.c, the stricter bar) => do not use | Xia et al. 2003 (DAMBE) |\n| Runnable ape proxy | many pairs p > 0.5 AND transition-proportion slope vs TN93 near 0 => saturated | simulated check: 0.83 \u002F 0.04 saturated vs 0.00 \u002F 0.17 unsaturated |\n| JC\u002Fcorrection singularity | log argument -> 0 as p -> 0.75 | d and its variance diverge to infinity |\n| Gamma shape | alpha \u003C ~1 = strong ASRV, materially changes distances\u002Ftopology | ignoring ASRV inflates long-branch artifacts |\n| ts\u002Ftv ratio | commonly 2-15 (~15 primate mtDNA control region) | large ratios make K80\u002FTN93 over JC matter (Tamura & Nei 1993) |\n| Bootstrap replicates | 100-1000; clades \u003C ~70% conventionally unsupported | precision not truth (Hillis & Bull 1993) |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|---|---|---|\n| NJ tree on `model='identity'` called a Jukes-Cantor tree | DistanceCalculator does NOT do JC\u002FK80\u002FTN93 | compute the corrected matrix in ape\u002FFastME, pass it as a matrix |\n| Corrected distances explode \u002F `NaN` | p near or above 0.75 singularity (saturation) | test saturation; drop saturated sites; do not trust deep distances |\n| `NaN` from K80\u002FTN93 at p ~0.6; `nj()`\u002F`fastme.bal()` stop with \"missing values are not allowed\" | stationary correction on compositionally skewed pairs (or short alignments): the log argument goes negative below 0.75 | report the NaN pairs; switch to `'logdet'`\u002F`'paralin'`, or build with `njs()`\u002F`bionjs()`, which tolerate missing distances |\n| UPGMA tree disagrees with NJ | UPGMA clock assumption violated by rate variation | use NJ\u002FFastME for molecular data |\n| Unrelated GC-rich taxa group together; topology flips JC vs LogDet | non-stationary composition under a stationary correction | use LogDet\u002Fparalinear or a non-stationary ML model |\n| LogDet returns `NaN` \u002F undefined | short sequences drive det(F) \u003C= 0 | use longer alignments or a stationary correction |\n| High bootstrap on a wrong clade | resampling masks a systematic bias in the distances | fix the model\u002Fsaturation; support is precision, not accuracy |\n\n## References\n\nSaitou N, Nei M. 1987. The neighbor-joining method: a new method for reconstructing phylogenetic trees. *Molecular Biology and Evolution* 4(4):406-425.\nGascuel O. 1997. BIONJ: an improved version of the NJ algorithm based on a simple model of sequence data. *Molecular Biology and Evolution* 14(7):685-695.\nLefort V, Desper R, Gascuel O. 2015. FastME 2.0: a comprehensive, accurate, and fast distance-based phylogeny inference program. *Molecular Biology and Evolution* 32(10):2798-2800.\nXia X, Xie Z, Salemi M, Chen L, Wang Y. 2003. An index of substitution saturation and its application. *Molecular Phylogenetics and Evolution* 26(1):1-7.\nLockhart PJ, Steel MA, Hendy MD, Penny D. 1994. Recovering evolutionary trees under a more realistic model of sequence evolution. *Molecular Biology and Evolution* 11(4):605-612.\nLake JA. 1994. Reconstructing evolutionary trees from DNA and protein sequences: paralinear distances. *PNAS* 91(4):1455-1459.\nTamura K, Nei M. 1993. Estimation of the number of nucleotide substitutions in the control region of mitochondrial DNA in humans and chimpanzees. *Molecular Biology and Evolution* 10(3):512-526.\nSchliep KP. 2011. phangorn: phylogenetic analysis in R. *Bioinformatics* 27(4):592-593.\nHillis DM, Bull JJ. 1993. An empirical test of bootstrapping as a method for assessing confidence in phylogenetic analysis. *Systematic Biology* 42(2):182-192.\n\n## Related Skills\n\n- modern-tree-inference - ML inference, model selection, and where a BIONJ\u002FME distance tree seeds the ML search\n- tree-manipulation - rooting and pruning the unrooted trees NJ\u002FFastME emit\n- tree-io - reading, writing, and converting the trees these methods produce\n- alignment\u002Falignment-io - the alignment whose quality gates every distance; filter ambiguous blocks first\n","## Version Compatibility\n\nReference examples tested with: BioPython 1.83+. Model-corrected alternatives: ape 5.8+, phangorn, FastME, scikit-bio.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show biopython` then `help(module.function)` to check signatures\n- R: `packageVersion('ape')` then `?dist.dna` to verify model strings\n- CLI: `fastme --version` then `fastme --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nBio.Phylo `DistanceCalculator` offers only identity \u002F substitution-matrix distances and has NO model-based JC\u002FK80\u002FTN93; for model-corrected DNA distances use ape `dist.dna(model=...)` (introspect its model list and `gamma=` support if the version differs).\n\n# Distance Calculations -- Distance Erases the Information ML Keeps; the Correction Is the Model\n\n**\"Build a tree from my alignment\"** -> Estimate model-corrected pairwise distances, then cluster them into a tree, knowing the correction is where the biology lives and the matrix discards what ML uses.\n- Python: `DistanceCalculator(...).get_distance(aln)` then `DistanceTreeConstructor().nj(dm)` (Bio.Phylo, identity-only)\n- R: `dist.dna(x, model='TN93')` then `fastme.bal(d)` \u002F `nj(d)` (ape, model-corrected)\n\nScope: computing evolutionary distance matrices and building\u002Fbootstrapping distance trees (NJ, BIONJ, FastME, UPGMA), and testing saturation before trusting them. ML inference, model selection, and where NJ seeds an ML search -> modern-tree-inference. Alignment quality and trimming, which gate every distance -> alignment\u002Falignment-io. Reading\u002Fwriting\u002Fconverting the trees these methods emit -> tree-io. Rooting and pruning -> tree-manipulation.\n\n## The Single Most Important Modern Insight\n\nA distance-based phylogeny is built in two lossy steps and both losses are silent. First, a distance is a model-corrected estimate of expected substitutions per site, not the observed proportion of differing sites; second, the matrix collapses each sequence pair to one scalar and discards the site-pattern information that maximum likelihood evaluates. Distance methods are therefore fast but doubly limited -- by how good the correction is, and by what a matrix of scalars can encode -- and they are structurally incapable of using the per-site signal that makes ML the gold standard for hard problems. Three load-bearing facts:\n\n1. **The correction is the whole biological content.** The raw p-distance (proportion of differing sites) systematically UNDERCOUNTS true divergence because every site that mutated twice (back-substitution), in parallel on both lineages, or to a third state (multiple hit) is missed, and the gap grows without bound toward saturation. The algorithm downstream (NJ, FastME) is just arithmetic on the numbers handed to it; feed it p-distances on divergent data and it returns a confidently wrong tree, fast.\n2. **The matrix throws away what ML keeps.** Two completely different alignments can produce the same distance matrix and therefore the same tree. ML never collapses the data, so it cannot be fooled this way; once the matrix exists, which sites drove the divergence, among-site rate heterogeneity, and competing site-pattern signal are gone.\n3. **Consistency is conditional, not a guarantee.** NJ is statistically consistent -- it returns the true tree as sequence length grows -- but only if the input distances are additive and correctly estimated. A consistent algorithm fed biased (saturated, misspecified) distances converges confidently on the WRONG tree. \"I used NJ so it is consistent\" is not a defense; the correction is exactly what most users get wrong.\n\n## Distance Corrections\n\nEvery nucleotide correction inverts the probability that a site differs under a model, so as p approaches the equilibrium difference (0.75 for equal base frequencies under JC) the correction diverges to infinity and its variance explodes -- the mathematical face of saturation.\n\n| Correction | Corrects for | When to use | ape model |\n|---|---|---|---|\n| p-distance (raw \u002F Hamming) | nothing | very shallow \u002F barcoding; saturation plots | `'raw'` (`'N'`, `'TS'`, `'TV'` return COUNTS -- divide by `ncol(aln)`) |\n| Jukes-Cantor (JC69) | multiple hits, one rate | minimal correction, quick sanity tree | `'JC69'` |\n| Kimura 2-param (K80) | + transition\u002Ftransversion bias | default DNA quick distance | `'K80'` (default) |\n| Tamura-Nei (TN93) | + two transition rates + unequal base freqs | mtDNA, richest closed-form | `'TN93'` |\n| LogDet \u002F paralinear | COMPOSITIONAL heterogeneity (non-stationary, general Markov) | GC drift across taxa; compositional attraction suspected | `'logdet'`, `'paralin'` |\n| Gamma-corrected | among-site rate variation (ASRV) | alpha small (\u003C ~1); long branches | `dist.dna(..., gamma=alpha)` |\n| Protein matrix (LG\u002FWAG\u002FJTT\u002FPAM) | amino-acid replacement, multiple hits | protein data (use phangorn `dist.ml`) | n\u002Fa (LG\u002FWAG modern; PAM legacy) |\n\nLogDet \u002F paralinear (Lockhart et al. 1994; Lake 1994) is the non-obvious one: JC\u002FK80\u002FTN93 all assume stationarity (constant base composition across the tree), and when composition drifts (thermophiles, AT-rich insect mtDNA, GC-rich chloroplasts) every stationary correction groups taxa by base composition rather than ancestry -- compositional attraction, a sibling of long-branch attraction that fools NJ and stationary-model ML alike. LogDet is computed from the determinant of the 4x4 pairwise divergence matrix and is consistent under the general Markov model, at the cost of needing long sequences and not easily taking gamma. If a topology flips between JC and LogDet, suspect compositional heterogeneity.\n\n## Algorithm Decision\n\n| Algorithm | Criterion | Clock? | Cost | Use \u002F pitfall |\n|---|---|---|---|---|\n| UPGMA | average-linkage clustering | ASSUMES strict clock (ultrametric) | O(n^2) | avoid for molecular phylo; wrong TOPOLOGY under rate variation; serotyping\u002Fdendrograms only |\n| NJ (Saitou & Nei 1987) | greedy balanced minimum evolution (Q-matrix) | no | O(n^3) | fast default; consistent ONLY if distances correct\u002Fadditive; barcoding, large n |\n| BIONJ (Gascuel 1997) | NJ + variance-weighted reduction | no | O(n^3) | better than NJ on large\u002Fnoisy distances; a common ML starting-tree generator (IQ-TREE2\u002FRAxML-NG default to parsimony starts) |\n| FastME (Lefort et al. 2015) | balanced minimum evolution + NNI\u002FSPR search | no | ~NJ-speed | the modern best distance tree; actively searches, not a single greedy pass |\n\nUPGMA is the key warning: it forces every tip equidistant from the root, which molecular data essentially never satisfies because lineages evolve at different rates. A fast-evolving lineage gets pulled toward the tips and grouped by total divergence rather than true ancestry -- a clustering-by-rate artifact analogous to long-branch attraction. Flat rule: do not use UPGMA for molecular phylogeny unless a clock is independently established. NJ does not assume a clock because its Q-matrix corrects each pairwise distance for that taxon's average divergence to everyone else. NJ\u002FBIONJ\u002FFastME can seed ML searches: some ML programs build a BIONJ or ME starting tree in O(n^3) before likelihood NNI\u002FSPR (though IQ-TREE2 and RAxML-NG default to parsimony starting trees), so this machinery still has a place in an all-ML pipeline.\n\n## Tool Taxonomy\n\n| Tool (lang) | Distance step | Tree step | Note |\n|---|---|---|---|\n| Bio.Phylo.TreeConstruction (Py) | `DistanceCalculator` identity \u002F BLOSUM \u002F PAM matrices ONLY | `DistanceTreeConstructor().nj()` \u002F `.upgma()` | NO JC\u002FK80\u002FTN93; `'identity'` is p-distance only on ungapped alignments (gap-vs-base counts as a mismatch over the full length -- strip gap columns first); named matrices are score distances |\n| ape (R) | `dist.dna(model=, gamma=)` -- full menu incl. LogDet, gamma | `nj()`, `bionj()`, `fastme.bal()`, `fastme.ols()` | the reference engine for real corrections |\n| phangorn (R) | `dist.ml(model=)` -- DNA JC69\u002FF81 only, but all protein matrices | `upgma()`, `NJ()` | the natural choice for protein distances |\n| FastME (CLI) | JC\u002FK2P\u002FF84\u002FTN93\u002FLogDet\u002Fprotein | NJ\u002FBIONJ\u002FBME\u002FOLS-ME + NNI\u002FSPR + bootstrap | standalone for very large n; `-m B` = balanced ME |\n| scikit-bio (Py) | none (requires a pre-corrected matrix) | `skbio.tree.nj(dm)` | pure-Python NJ; `neg_as_zero=` since 0.6.3 |\n\nLoud flag, the second flat rule: Bio.Phylo and scikit-bio do NOT correct for multiple hits -- their built-in distance is p-distance or score-based. Presenting Bio.Phylo's `'identity'` distance as a \"Jukes-Cantor tree\" is a common and wrong shortcut. For a real correction, compute the matrix in ape\u002FFastME (or compute it yourself) and pass it in.\n\n## Build a Model-Corrected Distance Matrix and NJ Tree\n\n**Goal:** Turn an alignment into a tree, contrasting Bio.Phylo's identity-only path against ape's model-corrected path.\n\n**Approach:** In Python use Bio.Phylo for the NJ\u002FUPGMA algorithm and pure-Python I\u002FO, but treat its distance as an uncorrected p-distance; for any divergent data move the distance step to ape `dist.dna`, then cluster with FastME (best) or NJ.\n\n```python\nfrom Bio import AlignIO\nfrom Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor\n\naln = AlignIO.read('alignment.fasta', 'fasta')\ncalc = DistanceCalculator('identity')        # identity-only: this is a p-distance, NOT a JC\u002FK80 correction\ndm = calc.get_distance(aln)                   # multiple\u002Fback\u002Fparallel hits are NOT corrected here\ntree = DistanceTreeConstructor().nj(dm)       # NJ algorithm is correct; the DISTANCES are the limitation\n\n# Model-corrected matrix from R -- write.csv(as.matrix(dist.dna(aln, model = 'K80')), 'k80.csv') -- passed in:\nimport pandas as pd\nfrom Bio.Phylo.TreeConstruction import DistanceMatrix\ndf = pd.read_csv('k80.csv', index_col=0)\nnames = list(df.index)\nlower = [[float(df.iat[i, j]) for j in range(i + 1)] for i in range(len(names))]   # lower triangle incl. diagonal\ntree_k80 = DistanceTreeConstructor().nj(DistanceMatrix(names, lower))\n# scikit-bio: skbio.tree.nj(skbio.DistanceMatrix(df.values, names))\n```\n\n```r\nlibrary(ape)\naln \u003C- read.dna('alignment.fasta', format = 'fasta')\nalpha \u003C- 0.5                                        # gamma shape (alpha \u003C 1 = strong ASRV); estimate it, do not assume\nmethod \u003C- function(x) fastme.bal(dist.dna(x, model = 'TN93', gamma = alpha), nni = TRUE, spr = TRUE)\ntree \u003C- method(aln)                                 # define the method ONCE so the bootstrap reuses it exactly\n# nj() \u002F bionj() are the faster single-pass alternatives; bionj seeds ML searches\n```\n\n## Pre-flight: Test Substitution Saturation\n\n**Goal:** Decide whether the data retain phylogenetic signal before trusting any deep distance tree.\n\n**Approach:** Run the ape proxy below: the fraction of pairs with p > 0.5 and whether transition proportions still rise with a corrected distance. Xia's formal Iss vs Iss.c test (Xia 2003) is implemented only in DAMBE (not ape\u002Fphangorn); run it there as an optional confirmation. Do not wait for `NaN` as the warning -- fully saturated data can return finite JC69\u002FTN93 values.\n\n```r\nlibrary(ape)\nL  \u003C- ncol(aln)\np  \u003C- dist.dna(aln, model = 'raw')          # p-distance\nd  \u003C- dist.dna(aln, model = 'TN93')         # corrected distance\nts \u003C- dist.dna(aln, model = 'TS') \u002F L       # 'TS'\u002F'TV' return COUNTS -> divide by length for proportions\ntv \u003C- dist.dna(aln, model = 'TV') \u002F L\nmean(p > 0.5)                               # fraction of pairs with p > 0.5; any sizeable fraction = red flag\ncoef(lm(as.vector(ts) ~ as.vector(d)))[2]   # slope of transitions vs distance; near 0 = PLATEAU = saturated\nplot(d, ts, col = 'red', ylim = range(c(ts, tv))); points(d, tv, col = 'blue')   # unsaturated = both still rising\n```\n\nOn simulated test data: saturated (83% of pairs p > 0.5) gave a transition slope of 0.04 and a mean ts\u002Ftv of 0.76; a deep but unsaturated set (no pair p > 0.5) gave 0.17 and 1.03. A flat transition curve with many p > 0.5 pairs means do not build a distance tree.\n\n## Bootstrap a Distance Tree\n\n**Goal:** Quantify how reproducible each clade is under resampling -- precision, not accuracy.\n\n**Approach:** Resample alignment columns with replacement, recompute the matrix with the SAME correction, rebuild with the SAME algorithm, and summarize clade frequencies on a majority-rule consensus.\n\n```r\nlibrary(ape)\nset.seed(42)\nboot \u003C- boot.phylo(tree, aln, method, B = 500)   # the SAME method (model + gamma + algorithm) that built the tree\n# 100-1000 replicates standard; support measures SAMPLING stability only -- it cannot detect a bias in the distances\n```\n\nIn Python, do NOT pass unrooted NJ replicates to `bootstrap_consensus(..., majority_consensus)`: `majority_consensus` counts ROOTED clades and each NJ replicate is rooted arbitrarily, so a split's count is shared with its complement (on a 20-taxon barcode set, max support 61-68% where the same replicates rooted give 100%). Root every replicate on a fixed outgroup first (identity distance, same correction caveat), and expect it to be slow for large n (~15 min at n=150, B=100) -- prefer ape `boot.phylo` there:\n\n```python\nimport random\nfrom Bio.Phylo.Consensus import bootstrap_trees, majority_consensus\n\nrandom.seed(42)\nreps = []\nfor rep in bootstrap_trees(aln, 100, DistanceTreeConstructor(calc, 'nj')):\n    rep.root_with_outgroup({'name': 'outgroup_taxon'})   # fixed outgroup for every replicate\n    reps.append(rep)\nconsensus = majority_consensus(reps, cutoff=0.5)          # clade.confidence = % of replicates\n```\n\n## When Distance Is Legitimate vs a Trap\n\nLegitimate or preferred: a quick exploratory \u002F sanity tree before a long ML run; very large n (thousands+ tips) where ML is infeasible (large-scale barcoding, OTU\u002Fpangenome trees); barcoding and population-level shallow data, where saturation is negligible and the per-site information ML keeps adds little (NJ on K2P distances is the literal DNA-barcoding standard); and as the starting tree for ML\u002FBayesian search.\n\nA trap, do not: publication-grade deep phylogeny or formal hypothesis testing (dating, selection, contested deep nodes) -- use ML or Bayesian with model selection; any dataset that fails a saturation test (Xia Iss >= Iss.c), which no algorithm rescues; data with strong compositional heterogeneity unless using LogDet\u002Fparalinear; and mistaking consistency for a guarantee -- NJ is consistent only with correct distances, and saturation\u002Fmisspecification break it exactly as they break ML.\n\n## Per-Method Failure Modes\n\n### Saturation Makes Distances Plateau and Mislead at Depth\n**Trigger:** Deep divergences with many pairwise p-distances above ~0.5; transitions exhausted while transversions still climb.\n**Mechanism:** So many superimposed substitutions accumulate that observed differences approach the random expectation; the correction inflates violently near its singularity and carries no remaining signal about deep splits.\n**Symptom:** Corrected distances explode and become unstable; the saturation plot's transition curve flattens; deep nodes are unstable across models.\n**Fix:** Run the saturation pre-flight (optionally Xia Iss in DAMBE); exclude transitions, third codon positions, or saturated partitions; do not build a deep distance (or ML) tree on saturated data.\n\n### UPGMA Returns the Wrong Topology Under Rate Variation\n**Trigger:** Lineages evolving at different rates analyzed with UPGMA.\n**Mechanism:** UPGMA forces an ultrametric tree (clock), so a fast-evolving lineage is pushed toward the tips and grouped by total divergence, not ancestry.\n**Symptom:** Topology differs from an NJ tree on the same matrix; fast lineages cluster together.\n**Fix:** Use NJ or FastME; never UPGMA for molecular phylogeny without an independently established clock.\n\n### Identity \u002F Uncorrected Distance Model on Divergent Data\n**Trigger:** Bio.Phylo `'identity'` or ape `'raw'` on anything beyond shallow divergence; calling it a \"JC tree\".\n**Mechanism:** No multiple-hit correction, so divergence is undercounted nonlinearly and worst on the longest branches, amplifying long-branch artifacts.\n**Symptom:** Branch lengths and topology shift when a real correction is applied; long-branch taxa attract.\n**Fix:** Use ape `dist.dna(model='TN93')` or a gamma correction; for compositional skew use LogDet; for protein use phangorn `dist.ml(model='LG')`.\n\n### Bootstrap on a Method That Discarded the Per-Site Information\n**Trigger:** High distance-NJ bootstrap on saturated or compositionally biased data.\n**Mechanism:** Resampling removes sampling noise, not a systematic bias baked into the distances, so the wrong split reproduces every replicate.\n**Symptom:** Confident, reproducible support on a clade that moves when the correction or saturated sites change.\n**Fix:** Bootstrap measures precision, not accuracy; fix the distances (model + saturation) first.\n\n## Quantitative Thresholds\n\n| Quantity | Threshold | Source \u002F rationale |\n|---|---|---|\n| p-distance saturation onset | unstable as nucleotide p -> ~0.5-0.6; singularity at 0.75 (equal base freqs) | many pairwise p > ~0.5 = red flag, run a saturation test |\n| Xia substitution-saturation test (DAMBE only; optional) | Iss \u003C Iss.c => usable; Iss >= Iss.c (esp. asymmetric Iss.c, the stricter bar) => do not use | Xia et al. 2003 (DAMBE) |\n| Runnable ape proxy | many pairs p > 0.5 AND transition-proportion slope vs TN93 near 0 => saturated | simulated check: 0.83 \u002F 0.04 saturated vs 0.00 \u002F 0.17 unsaturated |\n| JC\u002Fcorrection singularity | log argument -> 0 as p -> 0.75 | d and its variance diverge to infinity |\n| Gamma shape | alpha \u003C ~1 = strong ASRV, materially changes distances\u002Ftopology | ignoring ASRV inflates long-branch artifacts |\n| ts\u002Ftv ratio | commonly 2-15 (~15 primate mtDNA control region) | large ratios make K80\u002FTN93 over JC matter (Tamura & Nei 1993) |\n| Bootstrap replicates | 100-1000; clades \u003C ~70% conventionally unsupported | precision not truth (Hillis & Bull 1993) |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|---|---|---|\n| NJ tree on `model='identity'` called a Jukes-Cantor tree | DistanceCalculator does NOT do JC\u002FK80\u002FTN93 | compute the corrected matrix in ape\u002FFastME, pass it as a matrix |\n| Corrected distances explode \u002F `NaN` | p near or above 0.75 singularity (saturation) | test saturation; drop saturated sites; do not trust deep distances |\n| `NaN` from K80\u002FTN93 at p ~0.6; `nj()`\u002F`fastme.bal()` stop with \"missing values are not allowed\" | stationary correction on compositionally skewed pairs (or short alignments): the log argument goes negative below 0.75 | report the NaN pairs; switch to `'logdet'`\u002F`'paralin'`, or build with `njs()`\u002F`bionjs()`, which tolerate missing distances |\n| UPGMA tree disagrees with NJ | UPGMA clock assumption violated by rate variation | use NJ\u002FFastME for molecular data |\n| Unrelated GC-rich taxa group together; topology flips JC vs LogDet | non-stationary composition under a stationary correction | use LogDet\u002Fparalinear or a non-stationary ML model |\n| LogDet returns `NaN` \u002F undefined | short sequences drive det(F) \u003C= 0 | use longer alignments or a stationary correction |\n| High bootstrap on a wrong clade | resampling masks a systematic bias in the distances | fix the model\u002Fsaturation; support is precision, not accuracy |\n\n## References\n\nSaitou N, Nei M. 1987. The neighbor-joining method: a new method for reconstructing phylogenetic trees. *Molecular Biology and Evolution* 4(4):406-425.\nGascuel O. 1997. BIONJ: an improved version of the NJ algorithm based on a simple model of sequence data. *Molecular Biology and Evolution* 14(7):685-695.\nLefort V, Desper R, Gascuel O. 2015. FastME 2.0: a comprehensive, accurate, and fast distance-based phylogeny inference program. *Molecular Biology and Evolution* 32(10):2798-2800.\nXia X, Xie Z, Salemi M, Chen L, Wang Y. 2003. An index of substitution saturation and its application. *Molecular Phylogenetics and Evolution* 26(1):1-7.\nLockhart PJ, Steel MA, Hendy MD, Penny D. 1994. Recovering evolutionary trees under a more realistic model of sequence evolution. *Molecular Biology and Evolution* 11(4):605-612.\nLake JA. 1994. Reconstructing evolutionary trees from DNA and protein sequences: paralinear distances. *PNAS* 91(4):1455-1459.\nTamura K, Nei M. 1993. Estimation of the number of nucleotide substitutions in the control region of mitochondrial DNA in humans and chimpanzees. *Molecular Biology and Evolution* 10(3):512-526.\nSchliep KP. 2011. phangorn: phylogenetic analysis in R. *Bioinformatics* 27(4):592-593.\nHillis DM, Bull JJ. 1993. An empirical test of bootstrapping as a method for assessing confidence in phylogenetic analysis. *Systematic Biology* 42(2):182-192.\n\n## Related Skills\n\n- modern-tree-inference - ML inference, model selection, and where a BIONJ\u002FME distance tree seeds the ML search\n- tree-manipulation - rooting and pruning the unrooted trees NJ\u002FFastME emit\n- tree-io - reading, writing, and converting the trees these methods produce\n- alignment\u002Falignment-io - the alignment whose quality gates every distance; filter ambiguous blocks first\n",{"name":5,"tool_type":24,"description":7,"primary_tool":25},"mixed","Bio.Phylo.TreeConstruction","main","e0956dc9606356ab78468936b502e55a365282e2","specialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations",0,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists","https:\u002F\u002Fgithub.com\u002Fmrsonord2240","2026-10-12 03:19:04",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-phylo-distance-calculations",{"tool":39,"command":40},"bunx","bunx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-phylo-distance-calculations",{"tool":42,"command":43},"pnpm","pnpm dlx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-phylo-distance-calculations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations\u002FSKILL.md",true,[47,53,57,63,67],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"examples\u002Fbootstrap_consensus.py","SCRIPT","脚本",2012,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations\u002Fexamples\u002Fbootstrap_consensus.py",{"path":54,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":55,"sourceHtmlUrl":56},"examples\u002Fbuild_nj_tree.py",1365,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations\u002Fexamples\u002Fbuild_nj_tree.py",{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"examples\u002Fmodel_corrected_tree.R","OTHER","其他",1612,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations\u002Fexamples\u002Fmodel_corrected_tree.R",{"path":64,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":65,"sourceHtmlUrl":66},"examples\u002Fpairwise_tree_distances.py",705,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations\u002Fexamples\u002Fpairwise_tree_distances.py",{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"usage-guide.md","REFERENCE","参考文档",4599,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmolecular-phylogenetics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-phylo-distance-calculations\u002Fusage-guide.md",[74,81,88,95,102,109],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7CW36A6QAGWFE2C008M1XPG","bio-workflows-metabolomics-pipeline","Orchestrates the untargeted LC-MS metabolomics pipeline end-to-end (xcms 4.x feature extraction, QC\u002Fdrift\u002Fnormalization, confidence-stratified annotation, permutation-validated statistics, background-aware pathway mapping), naming what each stage decides and where it silently fails. Use when running a full LC-MS metabolomics study from raw mzML to enriched pathways and needing the honest handoffs between stages. Each stage defers to its component skill for parameters and traps; for stable-isotope flux (a separate branch, not this untargeted flow) see metabolomics\u002Fisotope-tracing.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-metabolomics-pipeline\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7CW2Y18623NA2S1Y30FRQW1","bio-metabolomics-xcms-preprocessing","Programmatic untargeted LC-MS feature extraction in R with the modern xcms 4.x MsExperiment\u002FXcmsExperiment API, taking raw mzML to a feature table via CentWave peak detection, retention-time alignment, peak-density correspondence, gap-filling, CAMERA redundancy collapse, and built-in QC feature filtering. Use when converting centroided LC-MS runs into a features-by-samples matrix and deciding centWave\u002Fgrouping\u002Falignment parameters. For drift correction and QC\u002FCV filtering execution see metabolomics\u002Fnormalization-qc; for metabolite identification see metabolomics\u002Fmetabolite-annotation; for the MS-DIAL GUI alternative with MS2Dec deconvolution see metabolomics\u002Fmsdial-preprocessing; for downstream statistics see metabolomics\u002Fstatistical-analysis.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-xcms-preprocessing\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7CW2M364HVWPNQEKE2WP4PP","bio-metabolomics-statistical-analysis","Decision-grade statistical analysis for metabolomics intensity tables. Covers transformation and scaling (Pareto vs unit-variance as a hidden hypothesis), unsupervised structure (PCA\u002FHCA for QC), permutation-validated PLS-DA\u002FOPLS-DA (R2 vs Q2, double CV, VIP as heuristic), univariate testing (Welch\u002FMann-Whitney\u002FANOVA\u002FLMM with covariate adjustment), and dependence-aware multiple testing. Use when testing which metabolites differ, building or validating a discriminant model, choosing a scaling, or correcting many correlated tests. For sample-wise normalization\u002Fdrift correction see metabolomics\u002Fnormalization-qc; for ML classifiers and selection-inside-CV leakage see machine-learning\u002Fbiomarker-discovery and machine-learning\u002Fmodel-validation; for pathway interpretation see metabolomics\u002Fpathway-mapping; for design\u002Fpower\u002Fmultiplicity regime see experimental-design\u002Fmultiple-testing.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-statistical-analysis\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7CW2BCBF851WYE03Z8XPEDQ","bio-metabolomics-pathway-mapping","Maps metabolomics results to biological pathways via over-representation (ORA), metabolite-set enrichment (MSEA\u002FQEA), mummichog\u002FPSEA on raw m\u002Fz peaks, and network-diffusion enrichment (FELLA), with correct background-set construction and honest interpretive ceilings. Use when interpreting differential metabolites or an untargeted LC-MS feature table in pathway context, choosing ORA vs MSEA vs mummichog vs topology, or setting the reference\u002Fbackground set. For annotation confidence levels feeding ORA see metabolomics\u002Fmetabolite-annotation; for gene-set concepts see pathway-analysis\u002Fgo-enrichment and pathway-analysis\u002Fgsea; for joint gene+metabolite pathways see multi-omics-integration\u002Fmofa-integration.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-pathway-mapping\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M7CW21NSZMCPMF7D9CHJM718","bio-metabolomics-normalization-qc","Designs QC, corrects signal drift, removes batch effects, filters features, normalizes samples, and imputes missing values for untargeted LC-MS\u002FGC-MS metabolomics, framing each step as a measurement model that can create or erase biological signal. Use when processing a peak\u002Ffeature table before statistical analysis, choosing a drift-correction or sample-normalization method, deciding QC RSD vs D-ratio filtering, or handling left-censored missing values. The feature table is produced by metabolomics\u002Fxcms-preprocessing or metabolomics\u002Fmsdial-preprocessing; transformation\u002Fscaling for modeling defers to metabolomics\u002Fstatistical-analysis; cross-study design issues link to experimental-design\u002Fbatch-design.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-normalization-qc\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M7CW1SWVM0NYHVE6Q7MA3G7R","bio-metabolomics-msdial-preprocessing","Runs the MS-DIAL preprocessing workflow (peak picking, MS2Dec spectral deconvolution, alignment, gap-filling) and imports the alignment-result table into R or Python with honest filtering. Use when preprocessing LC-MS DDA\u002FDIA (SWATH) or GC-MS raw data with MS-DIAL, deciding MS-DIAL vs XCMS, configuring the MSDIALCUI console run, or parsing an MS-DIAL export into a clean feature matrix. For programmatic R peak detection and the feature-table-as-artifact framing see metabolomics\u002Fxcms-preprocessing; for lipid annotation mode see metabolomics\u002Flipidomics; for MSI-level confidence honesty see metabolomics\u002Fmetabolite-annotation; for drift correction and QC see metabolomics\u002Fnormalization-qc.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-msdial-preprocessing\u002FSKILL.md",[],[]]