Skip to content

Speed up FastNS neighbor searches with contiguous cell storage - #5547

Closed
gregm711 wants to merge 2 commits into
MDAnalysis:developfrom
gregm711:perf/nsgrid-contiguous-cells
Closed

gregm711 wants to merge 2 commits into
MDAnalysis:developfrom
gregm711:perf/nsgrid-contiguous-cells

Conversation

@gregm711

@gregm711 gregm711 commented Nov 12, 2026 •

Copy link
Copy Markdown

FastNS spends substantial time traversing linked lists, evaluating periodic images, and converting C++ result vectors through Python lists. This change stores cell contents contiguously in the existing traversal order, copies results directly into NumPy arrays, and uses a guarded triclinic distance fast path with the existing 27-image calculation as fallback.

AI disclosure and contribution policy

LLMs or other AI-powered tools (beyond simple IDE use cases) were used in this contribution: yes.

Submitted from Greg Miller's account at his explicit request. The original optimization was generated with Claude. OpenAI Codex inspected the patch, reran validation, added regression tests, and prepared this submission and its description. This is not presented as solely human-written code.

We recognize that the current AI policy does not permit fully AI-generated contributions. This PR is submitted transparently for your decision on whether to consider an exception; no exception has been granted. We understand if you close it under the current policy.

Changes

  • Preserve pair visitation order while using contiguous cell indices and coordinates.
  • Use the triclinic fast path only when the cutoff is at most 0.4999 times the smallest perpendicular box width; otherwise retain the existing image search.
  • Convert result vectors directly to NumPy storage.
  • Add eight regression cases covering both sides of the fast-path cutoff, two skewed boxes, and both search modes, checked against the independent distance-array implementation.
  • Update AUTHORS and CHANGELOG.

Evidence and limits

Recorded local measurements against upstream bd5aa9101f1ff7f7d9df535c963ec320c9614432, on one Apple M1 Max under concurrent load:

Workload Original Patched Ratio
capped_distance, 10,000 x 10,000, triclinic, 5 A cutoff 0.126 s 0.038 s 3.3x
same, 10 A 1.075 s 0.254 s 4.2x
same, 15 A 4.331 s 0.879 s 4.9x
self_capped_distance, 47,681 atoms, triclinic, 15 A 21.905 s 7.350 s 3.0x
capped_distance, synthetic orthogonal box, 15 A 1.257 s 0.265 s 4.7x
InterRDF, 75 bins, range 0-15, 10,000 water oxygens, 10 frames 45.16 s 9.41 s 4.8x

These are exploratory best-of-5 measurements (best-of-3 for self-search and RDF), not controlled cross-platform benchmarks. The RDF workload uses the parameters from SimpleRdfBench; the local harness includes object construction. No Linux/x86 or production-workload measurements have been made. This submission pass checked the saved timing files but did not repeat the timing runs.

The original experiment saved outputs for 88 search/self-search cases across six box shapes, multiple cutoffs and sizes, and periodic/nonperiodic inputs: 7,142,368 pairs. A fresh comparison against that saved baseline passed, including byte-for-byte comparison of pair and distance arrays. That establishes equivalence for these cases on arm64, not a universal guarantee.

Fresh validation for this submission:

  • Existing nsgrid, distances and RDF tests: 3,860 passed, 1 skipped.
  • nsgrid tests after adding the eight regression cases: 41 passed, 1 skipped.
  • Byte-for-byte comparison against all 88 saved baseline cases: passed.
  • Black 24 formatting and git diff --check: passed.
python -m pytest testsuite/MDAnalysisTests/lib/test_nsgrid.py \
  testsuite/MDAnalysisTests/lib/test_distances.py \
  testsuite/MDAnalysisTests/analysis/test_rdf.py -q

The contiguous representation currently coexists with the original linked-list allocation, so this trades additional memory and setup work for faster traversal. Peak memory and small-workload regressions have not been measured.

Standalone timing reproduction (run on original and patched builds)
"""Timing for the neighbour search and the RDF analysis that depends on it (best of 5)."""
import time, warnings
import numpy as np
import MDAnalysis as mda
from MDAnalysisTests.datafiles import TPR, XTC
from MDAnalysis.lib import distances
from MDAnalysis.analysis.rdf import InterRDF
warnings.simplefilter("ignore")

def best(f, n=5):
    return min((lambda t: (f(), time.perf_counter() - t)[1])(time.perf_counter()) for _ in range(n))

u = mda.Universe(TPR, XTC)
ow = u.select_atoms("name OW")
p = ow.positions[:10000]
print(f"system: {len(u.atoms)} atoms, box {u.dimensions}, {len(u.trajectory)} frames")
for cut in (5.0, 10.0, 15.0):
    t = best(lambda: distances.capped_distance(p, p, cut, box=u.dimensions, method="nsgrid"))
    print(f"capped_distance   10000x10000 cutoff {cut:4.1f}: {t:7.3f}s")
for cut in (5.0, 10.0, 15.0):
    t = best(lambda: distances.self_capped_distance(u.atoms.positions, cut, box=u.dimensions, method="nsgrid"), 3)
    print(f"self_capped_distance all 47681 cutoff {cut:4.1f}: {t:7.3f}s")
ob = np.array([80, 80, 80, 90, 90, 90], dtype=np.float32)  # same atoms, rectangular box (synthetic)
for cut in (5.0, 10.0, 15.0):
    t = best(lambda: distances.capped_distance(p, p, cut, box=ob, method="nsgrid"))
    print(f"capped_distance   rectangular box  cutoff {cut:4.1f}: {t:7.3f}s")
s = ow[:10000]
t = best(lambda: InterRDF(s, s, nbins=75, range=[0, 15]).run(), 3)
print(f"InterRDF asv case (75 bins, range 0-15, 10000 atoms, 10 frames): {t:7.2f}s")

PR checklist

Preserve cell traversal order, avoid Python-list result conversion, and add a guarded triclinic minimum-image fast path. Add regression coverage around the fast-path cutoff.

AI disclosure: original optimization generated with Claude; validation, regression tests and submission prepared with OpenAI Codex at the contributor request.
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 MDAnalysis | 🛠️ Build #35852056 | 📁 Comparing 13af385 against latest (bd5aa91)

  🔍 Preview build  

2 files changed
± index.html
± documentation_pages/analysis/wbridge_analysis.html

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.92%. Comparing base (bd5aa91) to head (13af385).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #5547      +/-   ##
===========================================
- Coverage    93.93%   93.92%   -0.01%     
===========================================
  Files          184      184              
  Lines        22662    22662              
  Branches      3223     3223              
===========================================
- Hits         21287    21286       -1     
  Misses         915      915              
- Partials       460      461       +1     

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

@orbeckst orbeckst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

  1. Have you read the AI policy?
  2. Please open an issue first, documenting the problem that you're trying to solve.

@orbeckst orbeckst added AI-assisted Generated with AI/LLM assistance more information needed Please reply to requests for information or the issue will be closed. labels Nov 13, 2026
@orbeckst

Copy link
Copy Markdown
Member

I am not reviewing large PRs with math/algorithmic changes without a proper issue and explanation of the approach.

@IAlibay

IAlibay commented Nov 23, 2026

Copy link
Copy Markdown
Member

I'm closing this PR as stale, due to lack of author input. Please re-open as needed.

@IAlibay IAlibay closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI-assisted Generated with AI/LLM assistance more information needed Please reply to requests for information or the issue will be closed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants