Skip to content

DistanceOracle(): one-to-many distances against prepared trees (#229) - #232

Merged
ms609 merged 14 commits into
mainfrom
distance-oracle
Nov 25, 2026
Merged

ms609 merged 14 commits into
mainfrom
distance-oracle

Conversation

@ms609-agent

Copy link
Copy Markdown
Collaborator

Adds DistanceOracle(trees, Func, ...), which prepares a set of trees once and returns function(i) giving Func(trees[[i]], trees, ...). This is the shape Coreset::FarFirst(d = ) accepts. Addresses the remaining cost in #229.

Builds on #230 (one-many-batch). This branch contains #230's commits, so until #230 merges the diff below includes them. The new work is the last three commits.

What it does

  • C++ (src/pairwise_distances.cpp). cpp_oracle_prepare() parses every tree once into an OracleStore behind an external pointer.
    • The store holds compact split rows, in_split, CanonSplits, and per-tree information (clustering entropy, splitwise info or NSplits).
    • Building the canonical forms runs in parallel.
    • cpp_oracle_column() points a few SplitList shells at the stored rows, as PrunedTree already does, and scores the query against every tree in one OpenMP loop. It touches no R objects.
  • Shared scorers. The per-metric dispatch from pruned_pair() is now metric_score(), which both the pruned-pairs path and the oracle call. They use the same scorers as cross_pairs(), and the query is always argument a, so raw scores match the one-to-many kernels exactly.
  • R (R/DistanceOracle.R). Each Func's one-to-many post-processing is reproduced as written: .FloorNumericalNoise(), .InfoToNormalize()/NormalizeInfo() semantics, and names.
  • Supported Funcs: ClusteringInfoDistance, InfoRobinsonFoulds, RobinsonFoulds, MatchingSplitDistance, NyeSimilarity and JaccardRobinsonFoulds, with normalize as FALSE, TRUE, numeric or a function, plus similarity, k, allowConflict and normalizeMax.
    • An unsupported Func, reportMatching = TRUE or an unknown argument is an error.
    • MatchingSplitDistance(normalize = TRUE) errors, as it does today.
    • NyeSimilarity returns a similarity by default; the documentation says so.
  • Rebuild after deserialization. If the pointer is NULL, as after saveRDS()/readRDS(), the oracle rebuilds it on the next call.
  • Fallback. oracle(i) calls Func(trees[[i]], trees, ...) when the trees do not share a set of four or more leaves, or when the estimated store would exceed maxBytes (2 GiB by default; about 11.5 KB per tree at 183 leaves).
  • Vector i returns an N × length(i) matrix.

Equality: across all metrics, every normalize variant and 9, 70, 140 and 330 leaves, the largest |oracle − Func| was exactly 0 (NaN on both sides for normalized star trees). The tests cover 1, 2, 3 and 6 bins (6 exercises the generic canonical-form path), and includes duplicate trees, an unresolved tree, a star tree, permuted leaf order, mc.cores = 2 and an readRDS() round trip.

Benchmark

Release build installed to a per-agent library, R-devel on Windows. Each figure is the mean time for one column (one tree against all), in ms, cycling through random query trees for at least 1 s (so the slowest cells average only 3–4 columns). Repeat runs differ by up to about ±20% (e.g. the 1-thread CID baseline was 147 ms here and 178 ms in the thread study below), so compare within a row. The baseline is Func(sp[[i]], sp) on this branch, with sp a list of Splits, which is what WideSample passes. Leaves: 183.

  • ws = as.phylo(sample.int(1e6, N), 183); pairs differ in only 2 to 7 splits.
  • nni = 15 random NNIs from one tree; pairs differ in about 27 splits, so the LAP does real work.

10 000 trees, 1 thread (one-off preparation 200–250 ms)

Metric ws: now ws: oracle ws: × nni: now nni: oracle nni: ×
CID 147 29.4 5.0 347 258 1.35
IRF 129 15.0 8.6 190 17.8 10.7
RF 129 9.4 13.6 135 13.1 10.3
MSD 139 20.4 6.8 216 105 2.1
Nye 149 24.1 6.2 320 185 1.7
JRF 220 25.1 8.8 430 188 2.3

10 000 trees, 2 threads

Metric ws: now ws: oracle ws: × nni: now nni: oracle nni: ×
CID 139 19.4 7.1 244 103 2.4
IRF 130 8.6 15.0 139 9.5 14.6
RF 136 5.3 25.9 131 6.4 20.4
MSD 137 13.5 10.2 188 54.7 3.4
Nye 137 15.5 8.9 242 112 2.2
JRF 320 17.6 18.2 353 102 3.5

2 000 trees

ws, 1 thread nni, 1 thread ws, 2 threads nni, 2 threads
CID, now → oracle 37.4 → 8.4 (4.5×) 65.6 → 37.0 (1.8×) 29.7 → 3.7 (8.0×) 53.7 → 25.5 (2.1×)
RF, now → oracle 28.6 → 1.8 (15.9×) 29.1 → 2.4 (12.2×) 28.1 → 0.9 (30.7×) 29.7 → 1.3 (22.6×)

The absolute saving per 10k-tree column ranges from about 90 ms (CID on nni trees) to 240 ms (JRF on nni trees). The ratio is largest where scoring is cheap: near-identical trees, and IRF/RF on any trees. On nni trees, CID is dominated by its LAP, so preparation buys only about 1.35×.

Implication for WideSample, estimated from these timings (TreeSearch was not run): 48 CID columns of 10 000 ws trees take about 48 × 147 ms ≈ 7.1 s now, against 0.21 s preparation + 48 × 29.4 ms ≈ 1.6 s with the oracle at 1 thread, or ≈ 1.1 s at 2 threads.

Why 2 threads didn't speed up the existing one-to-many CID call

Timed directly on 10k ws trees:

ms 1 thread 2 threads
ClusteringInfoDistance(sp[[7]], sp) 178 145
cpp_mutual_clustering_cross_pairs, 1 × 10k 157 142
same kernel, 8 × 10k, per column 49 33
parsing alone (cpp_clustering_entropy_batch) 57 54
oracle C++ column 31.5 16.4

OpenMP is active. In cross_pairs(), each 16-tree chunk is first refilled serially on the main thread (Rcpp::as<RawMatrix> + refill_split_list, about 55 ms per 10k trees). Only then does a parallel region build canonical forms and score 16 pairs. The serial parse explains about a third of the cost: it alone predicts about 107 ms at 2 threads, against 142 ms measured. I attribute the rest to the ~625 small fork/join regions with a dynamic, chunk-1 schedule, but did not measure that separately. With 8 queries the scoring share grows, and 2 threads help (49 → 33 ms per column). The oracle parses once, so its single loop scales almost linearly (1.9×).

Proposed TreeSearch change (not made here)

In R/WideSample.R, .WideSampleColumnOracle() could use the oracle when it is available. NyeSimilarity is excluded because it defaults to a similarity.

.WideSampleColumnOracle <- function(dist, trees, nTrees) {
  supported <- list(TreeDist::ClusteringInfoDistance,
                    TreeDist::InfoRobinsonFoulds, TreeDist::RobinsonFoulds,
                    TreeDist::MatchingSplitDistance,
                    TreeDist::JaccardRobinsonFoulds)
  if (exists("DistanceOracle", asNamespace("TreeDist"), inherits = FALSE) &&
      any(vapply(supported, identical, logical(1), dist))) {
    oracle <- TreeDist::DistanceOracle(trees, dist)
    return(function(i) as.numeric(oracle(i)))
  }
  # ... existing probe and closure unchanged
}

Checks

  • New tests: 1060+ expectations with NOT_CRAN=true (396 on CRAN, where only the 9-leaf grid runs), all passing against the release install. The rest of the local suite passed except test-parallel.R:21 (NNIDist through a PSOCK cluster); CI on this PR should settle that.
  • Coverage of the new test file (covr): 100% of new R lines and all new C++ lines. The defensive leaf-count stop() in cpp_oracle_prepare(), which the R layer cannot reach, is marked // #nocov; it still has a direct test.
  • spelling::spell_check_package() finds no errors.
  • R CMD check is left to CI on this PR.

🤖 Generated with Claude Code

ms609-agent and others added 10 commits November 25, 2026 11:36
- `.SplitDistanceOneMany()` and `.FastManyManyPath()` route a single tree
  versus many through the batched cross-pairs kernels; the kernel dispatch
  is shared via `.BatchCrossPairs()`.
- Cross-pairs kernels hold the smaller tree set in memory and stream the
  larger through a reused pool of SplitLists, avoiding a ~520 KB heap
  allocation per tree.

ClusteringInfoDistance(tree, trees), 2000 trees of 183 leaves:
622 -> 144 ms (phylo), 466 -> 73 ms (Splits).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A split's clustering entropy depends only on its size, so compute it once
per size rather than calling log()/log1p() for every split of every tree.
Bit-identical results; 2000 trees of 183 leaves: 24.1 -> 10.2 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Lists of Splits already on the target leaf labels skip TipLabels() and
  as.Splits(), which cost more than scoring the pairs.
- Cross-pairs kernels can return each tree's information content, so
  .FastManyManyPath() no longer parses every tree a second time.
- build_canon() sorts canonical forms directly when a split needs at most
  four bins.

ClusteringInfoDistance(sp[[1]], sp), 10 000 trees of 183 leaves:
258 -> 108 ms. Outputs are bit-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Normalized MutualClusteringInfo(), SharedPhylogeneticInfo(),
  MatchingSplitInfo() and InfoRobinsonFoulds() take each tree's
  information from the kernel that scores it.
- RobinsonFoulds() scores one-to-many and Splits comparisons with a
  batch kernel.
- TransferDist() cross pairs stream through cross_pairs() and reuse
  labelled Splits.
- PathDist() and KendallColijn() score one-to-many in one pass;
  KCVector() finds each pair's MRCA depth in O(1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Parse a tree set once into compact split rows and canonical forms held
behind an external pointer; each column re-aims SplitList shells at the
stored rows and scores with the same scorers as cross_pairs().  Supports
CID, IRF, RF, MSD, Nye and JRF; falls back to Func(trees[[i]], trees)
where trees cannot be prepared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ms609-agent
ms609-agent requested a review from ms609 November 25, 2026 16:26
ms609-agent and others added 4 commits November 25, 2026 16:38
…e-e0fdc0

# Conflicts:
#	tests/testthat/test-pairwise_distances.R
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Performance benchmark results

Call Status Change Time (ms)
ClusteringInfoDistance(sp[[1]], sp) ⚪ NSD -2.91% 14.2, 14.7 →
15.6, 14.3
ClusteringInfoDistance(tr[[1]], tr) ⚪ NSD -2.28% 55, 57.3 →
56.4, 57.3
ClusteringInfoDistance(tr280) ⚪ NSD -1.67% 8.06, 8.16 →
8.24, 8.31
ClusteringInfoDistance(tr50) ⚪ NSD -1.73% 5.5, 5.54 →
5.68, 5.56
LAPJV(test2000) 🟣 ~same 4.81% 137, 138 →
131, 130
LAPJV(test40) ⚪ NSD -1.67% 0.0186, 0.0186 →
0.0191, 0.0186
LAPJV(test400) ⚪ NSD -0.23% 3.53, 3.54 →
3.54, 3.54
MutualClusteringInfo(tr[1:100], tr[1:100 + 500]) ⚪ NSD -4.16% 32.8, 32.4 →
34.4, 33.4
MutualClusteringInfo(tr280) ⚪ NSD 2.36% 11.1, 11 →
10.5, 11.1
MutualClusteringInfo(tr50) ⚪ NSD -0.44% 8.96, 8.55 →
8.39, 8.8
NNIMaxStep(2000, normalize = TRUE) ⚪ NSD 1.56% 0.211, 0.211 →
0.209, 0.207
NNIMaxStep(300, normalize = TRUE) ⚪ NSD -0.07% 0.0307, 0.031 →
0.0306, 0.0311
NNIMaxStep(300) ⚪ NSD -0.22% 0.00896, 0.00923 →
0.00874, 0.00938
PathDist(postTrees) ⚪ NSD 1.32% 1.67, 1.66 →
1.63, 1.65
PhylogeneticInfoDistance(tr180) 🟣 ~same 1.64% 60.8, 60.9 →
60, 59.9
PhylogeneticInfoDistance(tr50) ⚪ NSD 0.37% 40.9, 41.2 →
40.8, 41
RobinsonFoulds(tr280) ⚪ NSD -1.54% 4.79, 4.76 →
4.87, 4.83
RobinsonFoulds(tr280) ⚪ NSD 0.05% 4.61, 4.59 →
4.63, 4.58
RobinsonFoulds(tr50) ⚪ NSD 0.66% 4.73, 4.62 →
4.69, 4.63

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.83%. Comparing base (d7d47a0) to head (e307822).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #232      +/-   ##
==========================================
+ Coverage   97.77%   97.83%   +0.06%     
==========================================
  Files          60       61       +1     
  Lines        6832     7033     +201     
==========================================
+ Hits         6680     6881     +201     
  Misses        152      152              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ms609
ms609 merged commit c9298b1 into main Nov 25, 2026
21 checks passed
@ms609
ms609 deleted the distance-oracle branch November 25, 2026 18:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants