Skip to content

Faster RMSD matrix with optional preload, same results - #30

Merged
hmcezar merged 5 commits into
masterfrom
perf/faster-distmat-optional-preload
Sep 28, 2026
Merged

hmcezar merged 5 commits into
masterfrom
perf/faster-distmat-optional-preload

Conversation

@hmcezar

@hmcezar hmcezar commented Sep 25, 2026 •

Copy link
Copy Markdown
Owner

Faster RMSD matrix, same results

What this does

Computing the RMSD matrix is the slowest part of clusttraj. This change makes it about 5x faster on the MOx test case, without changing any answers (differences are at the 15th decimal place). It also fixes saved structures lagging behind the matrix, and handles review feedback. All 35 tests pass.

Why it was slow

For each pair of structures, the old code read the whole trajectory file from disk again (about 100 reads for 100 structures), redid the same hydrogen filtering and index math every time, and rebuilt reordered structures with a slow step-by-step insert.

What changed

  • Read the trajectory once by default (--preload). All structures stay in memory and are reused for every pair. For trajectories too big for memory, --no-preload streams from disk as before.
  • Do repeated math once per row. Hydrogen filtering, centering, reorder lists, and solute weights are computed once and reused for all pairs in that row.
  • Direct placement instead of slow insert loops. Same result, one fast step per atom.
  • Weighted Kabsch from rmsd 1.7.0 (which merged Faster math steps, fix complex-dtype crash, optional bench suite charnley/rmsd#133). Requires rmsd>=1.7.0; no Cython, no other new packages.
  • One shared alignment for matrix values and saved structures (see below).
  • Review fixes: unset exclusions (None) no longer crash; streaming tasks go out in small batches so worker runs stay low-memory (this was silently broken — the old call even had a wrong argument name); a warning on systems without fork where each worker copies the trajectory; black formatting (CI lint green).

Timings

MOx methanol case (100 structures, 41 atoms, 4950 pairs), measured back-to-back on the same machine, single worker unless noted:

Case Before (master) After Faster by
Loaded in memory (default) 2.74 s 0.52 s 5.3x
Loaded, 4 workers — 0.20 s ~14x
Streamed (--no-preload) 2.74 s 2.61 s ~1x

Streaming is barely faster because its time goes to reading the file, not math — that is expected. Its value is memory: it holds 2 frames at a time and now works for any trajectory size even with several workers. Test suite (35 tests): ~2 s.

Both sides of this comparison ran with rmsd 1.7.0 installed, so the speedup comes purely from this branch's changes (preloading, hoisting repeated math, direct placement) — none of it from the upstream vectorization, which helped both sides equally.

Are the answers still correct?

Yes:

  • 35/35 tests pass, including the MOx test (cluster sizes, medoid indices, syn/anti purity).
  • New vs old matrix, full MOx case and 9 option combinations: largest difference 1.1e-15 (tests allow 1e-08).
  • Preload, streaming, and 1/2/4 workers all agree.

Saved structures now match the matrix

The files clusttraj writes (members aligned to their medoid) should show exactly the superposition the matrix was computed with, but each side had its own copy of the steps and they had drifted: in several settings (no reordering, no solute split, or plain rotation without the final flag) the matrix included a final rotation the saved files were missing. Both sides now run the same shared steps, so they agree by construction. New tests (test_align_consistency.py) prove it three ways over 9 option combos. Matrix numbers are unchanged.

Side finding: rmsd 1.7.0's weighted rotation returns the rotation paired with the translation of the backwards map, so using them as documented gives a slightly wrong overlay. The shared code rebuilds the exact translation (matches to ~1e-15).

Notes

  • Memory with the default: structures × atoms × 3 × 8 bytes, plus a small overhead. Over ~1 GB a warning is printed; use --no-preload then.
  • On Windows/macOS (no fork) each worker holds its own trajectory copy — prefer --no-preload for large runs there.
  • Speed tests live in benchmarks/ (pip install -e ".[bench]", then pytest benchmarks).

Load the trajectory into memory once by default instead of re-reading
the file for every pair of structures. Add --no-preload to stream from
disk for trajectories too large for RAM.

Also remove per-pair overhead: cache repeated index math, replace slow
insert loops with direct placement, and use vectorized weighted Kabsch
(same approach as charnley/rmsd#133, no new dependencies).

All 30 tests pass; results match the old code to 1e-15.
Copilot AI lite review requested due to automatic review settings September 25, 2026 14:59
@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.05780% with 69 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.56%. Comparing base (037eb35) to head (f4a7d8c).

Files with missing lines Patch % Lines
benchmarks/test_bench.py 10.86% 41 Missing ⚠️
clusttraj/distmat.py 81.25% 21 Missing ⚠️
clusttraj/_fastmath.py 95.93% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #30      +/-   ##
==========================================
+ Coverage   70.21%   78.56%   +8.35%     
==========================================
  Files           7        9       +2     
  Lines         752      905     +153     
==========================================
+ Hits          528      711     +183     
+ Misses        224      194      -30     

☔ 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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Critical issues remain in fallback worker memory usage, unset reorder exclusions, and streaming iterator materialization.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 3 High severity · 2 Low severity

Open (5)
What changed in this PR

This PR accelerates RMSD matrix computation through trajectory preloading, cached processing, optimized reordering, and vectorized weighted Kabsch calculations.

Changes:

  • Adds preload/streaming execution and multiprocessing optimizations.
  • Adds numerical equivalence tests and performance benchmarks.
  • Updates documentation and benchmark configuration.
File Description
test/​test_mox_methanol.py Configures preload behavior for regression tests.
test/​test_distmat.py Tests preload and streaming equivalence.
README.md Documents preload options.
pyproject.toml Adds benchmark dependencies.
clusttraj/​io.py Adds preload configuration and optimized alignment.
clusttraj/​distmat.py Implements preload/streaming matrix computation and worker management.
clusttraj/​_fastmath.py Provides optimized RMSD and reordering helpers.
benchmarks/​test_bench.py Adds optional performance benchmarks.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread clusttraj/distmat.py Resolved
Comment thread clusttraj/distmat.py Resolved
Comment thread clusttraj/distmat.py Resolved
Comment thread benchmarks/test_bench.py Resolved
Comment thread test/test_mox_methanol.py Resolved
rmsd 1.7.0 merged charnley/rmsd#133, so the local kabsch_weighted_fast /
kabsch_weighted_rmsd_fast copies are removed and clusttraj calls
rmsd.kabsch_weighted / rmsd.kabsch_weighted_rmsd directly. Same math,
same speed (MOx full matrix still 0.45 s preloaded).

Bump the floor to rmsd>=1.7.0 in requirements.txt. The remaining
_fastmath helpers (scatter rebuild, weight vector, Hungarian reference
cache) are clusttraj-side savings upstream does not provide.

Verified: 30/30 tests pass; 9 option combos vs original master code
agree to 1.8e-15 on both preload and streaming paths.
distmat (RMSD values) and io.align_mol (structures written to disk) each
had their own copy of the superposition steps, and they had drifted
apart: with weights set but final_kabsch off, or with plain Kabsch and
final_kabsch off, the matrix included a final rotation the saved files
were missing. Both paths now run _fastmath.align_core, so the written
structures carry exactly the matrix superposition by construction.

The kernel also applies the correct weighted final transform. rmsd
1.7.0's kabsch_weighted returns the rotation together with the
translation of the transposed map, so Pr @ R + T does not attain its own
rmsd value; the kernel rebuilds the exact Pr->Q translation from the
weighted centroids (verified to match to ~1e-15).

New test/test_align_consistency.py pins the contract three ways over an
option grid: saved files reproduce matrix entries end to end (no
reorder), written coordinates equal the kernel output, and the kernel
outputs rebuild the entries with plain operations.

Matrix values are unchanged (9 option combos vs original code agree to
1.8e-15); all 33 tests pass.
…ning

- build_distance_matrix normalizes an unset reorder_excl (None) to an
  empty array instead of crashing in np.asarray (ClustOptions defaults
  it to None); align_core guards None the same way.
- streaming multi-worker path now submits tasks in bounded batches:
  pool.starmap turns a len-less iterator into a list first, which held
  every frame's arrays in the parent and defeated the --no-preload
  escape hatch for large trajectories (verified against the pool
  source and a generator probe). Also fixes a latent TypeError: the
  old call passed processes= to _new_pool, which takes n_workers.
- non-fork platforms (Windows/macOS) get a log warning that each
  worker holds its own copy of the preloaded trajectory, pointing at
  --no-preload; README documents it. (Shared-memory transport would
  fix it properly but can't be tested here; CI is Ubuntu-only.)
- reword two stale comments (streaming benchmark label, MOx note).
- tests: unset-exclusions regression + streaming/2-workers agreement.
@hmcezar
hmcezar merged commit 04888cb into master Sep 28, 2026
19 checks passed
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