Skip to content

Faster math steps, fix complex-dtype crash, optional bench suite - #133

Merged
charnley merged 6 commits into
charnley:masterfrom
hmcezar:perf/benchmark-and-optimize
Sep 26, 2026
Merged

charnley merged 6 commits into
charnley:masterfrom
hmcezar:perf/benchmark-and-optimize

Conversation

@hmcezar

@hmcezar hmcezar commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

What this does

This makes parts of the program faster, fixes a crash, and adds speed tests. Nothing about how you use the program changes: same commands, same options, same function names. All existing tests pass without any changes to them.

1. Fixes a crash

With new versions of NumPy, any run with the default reordering method crashed with this error:

ValueError: Unsupported dtype complex128

That happened because the code used np.linalg.eig on a symmetric 3x3 table, and new NumPy answers that with complex numbers, which the next step (cdist) refuses. Switching to np.linalg.eigh (the right tool for symmetric tables) fixes the crash and is also a little faster (1.4x on that step). Before this fix, 9 of the existing tests failed; now all 52 pass.

2. Makes the slow math steps faster

Three steps did their work item-by-item in slow Python loops. They now do the same math with fast array operations (NumPy only, no new required packages):

  • kabsch_weighted: the triple loop is gone.
  • quaternion_rotate: building one small table per atom in a loop is gone.
  • get_inertia_tensor: a per-atom loop that was never even used (dead code) is gone, and the mass table is no longer built as a big NxN block.
  • get_cm: weight look-up is now a single array step.
  • check_reflections: no more extra copies of the data on each of the 48 tries.

3. Adds speed tests (optional)

pip install -e ".[bench]" then pytest benchmarks runs timing tests for small (8 atoms), medium (60 atoms) and large (200–1064 atoms) cases. Normal users never need to install this.

Timings

Measured with pytest-benchmark (best of several runs). One note first: unmodified master crashes on every reorder run in this setup (see crash section above — that is also why 9 tests failed before the fix), so pure master has no timing at all. To keep the speed comparison fair, every "Before" number below was measured with master plus only the crash fix.

Single steps, medium molecule (60 atoms, ChEMBL 3039407):

Step Before After Faster by
Inertia table 202 µs 32 µs 6x
Weighted Kabsch 378 µs 45 µs 8x
Quaternion rotation 497 µs 50 µs 10x

Single steps, large molecule (1000 atoms):

Step Before After Faster by
Inertia table 5.89 ms 0.07 ms 86x
Weighted Kabsch 5.86 ms 0.10 ms 57x
Quaternion rotation 7.99 ms 0.20 ms 40x
Center of mass 0.17 ms 0.04 ms 5x

Full default run (--reorder), which is what most users run:

Case Before After Faster by
60 atoms 1.73 ms 1.21 ms 1.4x
1064 atoms 285 ms 224 ms 1.3x
Lysozyme, 1960 atoms, hydrogens mixed up, turned 110 degrees (real-life test, correct answer 0) 1.11 s (unmodified master crashes here — see note above) 1.09 s 1.02x for speed; crash fixed

Answers are unchanged everywhere: same atom matching, same RMSD values (equal to 13–16 digits).

Honest conclusions

  • The slow single steps are much faster (up to 140x), and anyone using them directly as library functions will feel it.
  • But the full default run is only a little faster (1.0–1.4x). The reason is simple: most of its time goes to the Hungarian matching step, which was already fast compiled code and is intentionally untouched, since changing it could change answers.
  • For small molecules run from the command line, users will notice nothing at all: starting Python and loading the packages alone takes about 0.35 s, which is far more than the math itself.
  • The most visible change for users is therefore the crash fix, not speed: the default method works again on new NumPy.
  • Cython was considered but deliberately not added: there is nothing left that it would speed up, and it would make installing the package harder. Dependencies stay as they were (numpy + scipy).

…bench suite

- kabsch_weighted: replace triple Python loop with vectorized covariance
- get_cm/get_inertia_tensor: indexed weight lookup, drop dead loop,
  avoid NxN mass matrix
- quaternion_rotate: vectorized (N,4,4) stacks + einsum, keep
  makeW/makeQ API unchanged
- inertia paths: eigh instead of eig (real output, fixes complex128
  cdist crash on NumPy>=2)
- check_reflections: skip redundant copies and diag matmul
- benchmarks: pytest-benchmark suite behind rmsd[bench] extra
Copilot AI lite review requested due to automatic review settings September 25, 2026 09:45

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

Unresolved correctness, input-isolation, validation, and optional-test integration issues remain.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 High severity · 1 Medium severity

Open (3)
What changed in this PR

Improves RMSD performance, fixes complex-eigenvalue handling, and adds optional benchmarks.

Changes:

  • Vectorizes several numerical routines.
  • Uses eigh for symmetric matrices.
  • Adds optional pytest-benchmark support.
File Changes
rmsd/​calculate_rmsd.py Numerical optimizations and eigenvalue handling
pyproject.toml Optional benchmark dependency
benchmarks/​test_bench.py Performance benchmark suite

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

Comment thread benchmarks/test_bench.py Resolved
Comment thread rmsd/calculate_rmsd.py
Comment on lines +1458 to 1461
# Symmetric tensor: eigh is correct (real) and faster; indexing kept
eigval, eigvec = np.linalg.eigh(inertia)

principal_axis: ndarray = eigvec[np.argmax(eigval)]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Leaving this one open on purpose: the row indexing predates this PR (only eig->eigh changed here, which was required to fix the complex128 crash), no test covers this helper, and changing it would alter return values for existing callers. Proposing it as a separate follow-up instead.

Comment thread rmsd/calculate_rmsd.py Resolved
- benchmarks/test_bench.py: skip module when pytest-benchmark
  is not installed so plain pytest stays green
- check_reflections: cheap q_atoms.copy() keeps isolation from
  custom reorder callables while still skipping the coordinate
  deepcopy
@hmcezar

hmcezar commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review — addressed two findings in fd2b6f3, replying to all three below.

1. Benchmark tests breaking pytest discovery (fixed). You were right: plain pytest from the repo root collects benchmarks/test_bench.py, and without the optional pytest-benchmark install the benchmark fixture is missing and the suite errors. The module now starts with pytest.importorskip("pytest_benchmark"), so it skips cleanly unless the rmsd[bench] extra is installed.

2. Principal eigenvector row vs column (kept as-is, on purpose). The eigvec[np.argmax(eigval)] indexing is pre-existing behavior in get_principal_axis — this PR only changed eig to eigh (needed: eig returns complex output on current NumPy, which crashes the reorder path). No test covers this helper, and changing row to column indexing would change what the function returns for existing callers. Since this PR promises identical behavior, I left the indexing untouched. Happy to fix it as a separate change if you want.

3. q_atoms isolation in check_reflections (fixed). Fair point about custom reorder callables. It is now tmp_atoms = q_atoms.copy() — a cheap copy of a small int array that keeps the old isolation, while the expensive coordinate deepcopy stays removed (q_coord[:, swap] already makes a fresh array).

On the failing CI: I checked, and it is not caused by this PR. Every CI job fails in the make format step on a mypy internal error (mypy crashing on itself, version 2.3.1, with zero type errors reported). I ran mypy 2.3.1 locally on all 21 Python files in the repo — individually, in batches, and all together — and everything passes. And this failure is pre-existing: the fork's CI on unmodified master failed the same way back in May (make test green, make format red), while upstream master last went green in March, before mypy 2.x existed (requirements.txt does not pin mypy, so CI now pulls the crashing version). The right fix is on the maintainer side (pin mypy or wait for a mypy fix) — nothing in this diff triggers it, so I left requirements.txt alone.

@charnley

charnley commented Sep 25, 2026 •

Copy link
Copy Markdown
Owner

Overall looks good (however very wordy). I need some extra time to validate these two sections

  • quaternionen rewrite
  • intertia rewrite

@charnley

Copy link
Copy Markdown
Owner

Build / Format has been fixed, and simplified requirements. Please merge with master and your tests should run through

@charnley

Copy link
Copy Markdown
Owner

I added the fixes to make the PR build. Since I want to address the inertia index you found, I will just merge. Thanks for the clean-up PR.

@charnley
charnley merged commit 43a424a into charnley:master Sep 26, 2026
3 checks passed
hmcezar added a commit to hmcezar/clusttraj that referenced this pull request Sep 28, 2026
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.
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.

3 participants