feat(ls): least-squares distance scoring for the C++ search kernel#246
Merged
Conversation
Add a least-squares (LS) tree-fitting capability to the optimised C++
search kernel, so the existing NNI/SPR rearrangement engine can find the
tree that best fits a target distance matrix under a least-squares
criterion -- not just minimise parsimony. Built for Lapointe & Cucumel's
(1997) average consensus procedure (a new sibling `Consensus` package),
where an averaged, generally non-additive patristic distance matrix must
be fit by a heuristic topology search.
- src/ts_ls.{h,cpp}: design matrix over the tree's unrooted branches
(splits + pendant edges, 2n-3 columns; root's two edges merged), OLS
(normal equations + Cholesky) and NNLS (Lawson-Hanson) solvers, RSS,
and NNI/SPR LS hill-climbing reusing the TreeState move primitives on a
topology-only tree (never touches the Fitch state arrays).
- ts_ls_fit / ts_ls_search Rcpp entry points (src/ts_rcpp.cpp, registered
in TreeSearch-init.c).
- R/LeastSquares.R: LeastSquaresFit() (fixed topology) and
LeastSquaresTree() (search from NULL/NJ, one tree, or a multiPhylo),
returning unrooted trees with fitted branch lengths and an "RSS" attr.
Supports OLS/NNLS and unit/Fitch-Margoliash/custom weighting.
Validated against phangorn::nnls.tree() and designTree() to machine
precision (tests + dev/ls_validate.R). The existing parsimony API is
unchanged. Singular (rank-deficient / zero-weight) fits fail gracefully
with a warning rather than crashing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Author names introduced in the LeastSquares documentation and bib entry. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Adds a least-squares (LS) distance-fitting capability to the optimised C++ search kernel, so the existing NNI/SPR rearrangement engine can find the tree that best fits a target distance matrix under a least-squares criterion — not just minimise a parsimony score.
Two new exported R functions:
LeastSquaresTree(dist, tree = NULL, method, weight, …)— searches topologies for the LS-best fit todist. Starts from the neighbour-joining tree (default), a single tree, or amultiPhylo(returns the best). Returns an unrooted tree with fittededge.lengthand an"RSS"attribute.LeastSquaresFit(tree, dist, method, weight)— fits branch lengths on a fixed topology; the native-kernel analogue ofphangorn::nnls.tree().Both support
method = "nnls"(non-negative, default) or"ols", andweight = NULL/"fm"(Fitch–Margoliash1/D²) / a custom matrix.Why
This is the topology-search step of Lapointe & Cucumel's (1997, Syst. Biol. 46(2):306–312) average consensus procedure, which a new sibling
Consensuspackage will call viaConsensus::Average(method = "ls"). The averaged patristic matrix is generally non-additive (violates the four-point condition), so the best-fitting topology must be found heuristically — exactly what this engine does. Until this lands,Consensusfalls back to a slow R path (CustomSearch+phangorn::nnls.tree); the key external requirement met here is a clean, documented entry point: "given a distance matrix and starting tree(s), return the LS-best tree with branch lengths."How
src/ts_ls.{h,cpp}— design matrix over the tree's unrooted branches (splits + pendant edges,2n−3columns; the rooted root's two edges merged into one), OLS (normal equations + Cholesky) and NNLS (Lawson–Hanson active set) solvers, weighted RSS, andls_nni_search/ls_spr_searchthat reuse theTreeStateNNI/SPR move primitives on a topology-only tree (total_words == 0) — the parsimony/Fitch state arrays are never touched.ts_ls_fit/ts_ls_searchRcpp entry points insrc/ts_rcpp.cpp, registered insrc/TreeSearch-init.c(check_init.Rpasses).R/LeastSquares.R— the wrappers, with input coercion (dist/matrix, label alignment, rooted-binary coercion, compressedmultiPhylo) and roxygen docs.Validation
tests/testthat/test-LeastSquares.R): additive matrices recover the exact generating topology with RSS ≈ 0 (from NJ, random, and multiPhylo starts); branch lengths/RSS matchphangorn::nnls.tree()and OLS matches a directdesignTreenormal-equation solve, to machine precision; non-additive sanity; weighting; OLS/NNLS agreement; input validation; and graceful handling of rank-deficient fits.dev/ls_validate.R.Reviewer notes
MaximizeParsimonysmoke test and an additive-onlyRcppExportsdiff).(length, 0)so unrooting sums them correctly.ok = falseand warn rather than crashing — this was a heap-OOB blocker caught in an independent expert review and fixed (with a regression test) before this PR.cpp-search; it also carries one trivial pre-existing commit ("line endings", +3 lines to.gitattributes) that is on localcpp-searchbut not yet onorigin/cpp-search.🤖 Generated with Claude Code