Skip to content

Fix PersistenceLength normalization for sliced run (Issue #5453) - #5459

Open
srikarjy wants to merge 8 commits into
MDAnalysis:developfrom
srikarjy:fix-persistencelength-normalization-5453
Open

srikarjy wants to merge 8 commits into
MDAnalysis:developfrom
srikarjy:fix-persistencelength-normalization-5453

Conversation

@srikarjy

@srikarjy srikarjy commented Aug 15, 2026 •

Copy link
Copy Markdown

Fixes #5453

Changes made in this Pull Request:

  • PersistenceLength._conclude() normalized bond_autocorrelation by the total number of trajectory frames instead of the number of frames analyzed, which gave wrong results when run() was called with start, stop, step or frames. It now uses self.n_frames.
  • run() now raises a clear ValueError if zero frames are analyzed, instead of failing later inside the fit.
  • Documented the ValueError in the class docstring and added a versionchanged 2.12.0 note.
  • Added a regression test that asserts precalculated values for a sliced run, and a test for the zero frames error.

LLM / AI generated code disclosure

LLMs or other AI-powered tools (beyond simple IDE use cases) were used in this contribution: yes. I used Claude (Anthropic) to write code for this PR, including the fix, the tests and the docstring, and to help draft my commit messages and review replies. I reviewed and tested the changes.

PR Checklist

  • Issue raised/referenced?
  • Tests updated/added?
  • Documentation updated/added?
  • package/CHANGELOG file updated?
  • Is your name in package/AUTHORS?
  • I have read and understand the current AI Policy
  • LLM/AI disclosure was updated.

…5453)

PersistenceLength._conclude() normalized bond_autocorrelation using
the total number of frames in the trajectory instead of the number
of frames actually analyzed. This gave wrong results whenever run()
was called with start, stop, or step. Now uses self.n_frames, which
AnalysisBase already tracks for this purpose. Added a regression
test comparing full trajectory and sliced runs against manually
computed normalization values.
@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.93%. Comparing base (f4ffee3) to head (b6fad5c).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #5459   +/-   ##
========================================
  Coverage    93.93%   93.93%           
========================================
  Files          184      184           
  Lines        22679    22681    +2     
  Branches      3228     3229    +1     
========================================
+ Hits         21303    21305    +2     
  Misses         916      916           
  Partials       460      460           

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

Comment thread package/CHANGELOG Outdated
* 0.7.5.1

Fixes
* `PersistenceLength._conclude()` now normalizes `results.bond_autocorrelation` using the number of frames actually analyzed instead of the total trajectory frame count, fixing incorrect results when `run()` is called with `start`/`stop`/`step` (Issue #5453).

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.

Why has this CHANGELOG entry been duplicated across so many old versions? Did you see any previous examples where we did this? Did you read your diff carefully?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You are right, and I apologize. I did not review my diff carefully enough before submitting it, which is how the duplication slipped through. I removed the duplicate entries. The entry now appears only once, under the current unreleased 2.11.0 section, consistent with the rest of the file.

norm *= len(chains) * n_sliced_frames
expected = p.results.raw_bond_autocorr / norm

assert_almost_equal(p.results.bond_autocorrelation, expected, decimal=6)

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.

Here and above -- I don't like that your expected value is derived from the actual class/function under test. That can be a recipe for suppression of breaking changes if both the actual and expected values are mutated in a similar way.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed. Reworked this so expected is computed independently, directly from atom positions and trajectory frames, without calling into PersistenceLength or touching any of its results. Also extended the test to cover step=, start/stop/step, and frames=[...], since the original only exercised stop=.

* Remove the CHANGELOG entry that was accidentally duplicated across
  about 25 historical release sections. It now appears only once,
  under the current unreleased 2.11.0 header.
* Replace the tautological regression test, where the expected value
  was derived from the class under test, with an independent reference
  implementation that recomputes the normalized bond autocorrelation
  directly from atom positions, without touching PersistenceLength or
  its results.
* Extend test coverage to step=, start/stop/step, frames=[...], and
  the multiprocessing backend, beyond the original stop= only case.
* Add a guard in _conclude() that raises a clear ValueError when a run
  selects zero frames, instead of silently returning a fabricated all
  zero curve before this fix, or crashing with an opaque scipy NaN
  error after this fix, found while testing the above.
* Document, without fixing since it is out of scope for this issue,
  two existing unrelated edge cases found during testing: a one atom
  chain crashing identically before and after this fix, and a numpy
  boolean frames= mask being misread by AnalysisBase computation
  grouping, pinned as xfail for visibility.
@srikarjy

Copy link
Copy Markdown
Author

Thanks again for the review. While reworking the test above, I also found and fixed something not covered by either of your original comments. An empty frame selection, for example run(start=2, stop=2), used to silently return a fabricated all zero curve. It now raises a clear ValueError instead of crashing later inside scipy.optimize.curve_fit with an opaque NaN error. I also extended the regression test to cover step=, start/stop/step, frames=[...], and the multiprocessing backend, since the original test only exercised stop=.

While testing further I found two more things that already exist and are unrelated to this normalization bug, so I documented them with tests rather than fixing them here: a one atom chain crashes identically before and after this fix, and a numpy boolean frames= mask gets misread by AnalysisBase computation grouping logic. I pinned the second one as an xfail test so it stays visible. Happy to open separate issues for either if that is useful.

Thanks again for catching both of the original issues.

…ength-normalization-5453

# Conflicts:
#	package/CHANGELOG
@orbeckst orbeckst added the AI-assisted Generated with AI/LLM assistance label Sep 4, 2026
@sici17

sici17 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

Hi @srikarjy, I found your issue while I was looking for some issues related to parallelization. Specifically I am interested in your comment on the boolean mask problem. I have been able to locally reproduce the behavior you are talking about with a minimal example on MDAnalysis 2.10.0. As I understand it the NumPy boolean arrays pass through _setup_computation_groups() without being recognized as made of booleans and are for this reason converted to integer frame indices. Are you planning to open a separate issue or work on this yourself? If not I would be interested in working on it. I wanted to check with you first to avoid duplicating your work. Thanks for identifying and documenting the problem.

@srikarjy

Copy link
Copy Markdown
Author

Hi @sici17, thanks for checking in and for reproducing the issue! I'm a bit swamped at the moment and won't be able to work on this myself, so please go ahead I'd be happy to see you take it. Let me know if you need any clarification on the original problem description. Good luck with the PR!

assert p.n_frames == n_sliced_frames
assert p.n_frames != u.trajectory.n_frames

expected, n_frames = _reference_bond_autocorrelation(

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.

pre calculate and assert values

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done. test_sliced_run_normalization now asserts precalculated values.

Comment on lines +261 to +265
# atol/rtol (looser than a plain decimal=6 comparison) account for
# PersistenceLength accumulating raw_bond_autocorr in float32 while
# this reference accumulates in float64; their rounding drift is
# a couple of float32 ULPs at this trajectory's frame/chain count,
# not a sign of disagreement.

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.

reduce the LLM commentary to the essentials

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done.

chains, range(u.trajectory.n_frames)
)
assert n_frames == u.trajectory.n_frames
# atol/rtol (looser than a plain decimal=6 comparison) account for

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.

reduce the LLM commentary to the essentials

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done.

Comment thread package/MDAnalysis/analysis/polymer.py Resolved
Address review feedback from orbeckst on PR MDAnalysis#5459 (Issue MDAnalysis#5453).

Tests:
* Replace the helper that recomputed the expected values with a test
  that asserts precalculated values for a sliced run (stop=3). The
  values were computed with plain numpy from the TRZ positions.
* Remove the full trajectory test, which the bug did not affect and
  which existing tests already cover.
* Remove the xfail test for numpy boolean masks, since Issue MDAnalysis#5472
  is fixed.
* Remove the other frame selection, parallel and single atom chain
  tests.
* Reduce the comments to the essentials.

Docs:
* Document the ValueError raised for unequal chain lengths and for
  zero analyzed frames.
* Add a versionchanged 2.12.0 note describing the normalization fix.

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

Thanks for the updates. Can you please look at my comments and add an additional test where you check that it works with step=2, too?

Comment thread package/MDAnalysis/analysis/polymer.py Resolved
Comment thread package/MDAnalysis/analysis/polymer.py Resolved
* Add a step=2 case to the sliced run regression test.
* Move the 2.12.0 note into the Raises section as versionadded and
  remove the versionchanged entry.
* Shorten the test comment.
@srikarjy

Copy link
Copy Markdown
Author

Thanks for the review. I added a step=2 case to the sliced run test in 32492fd and addressed your other comments in 32492fd and 8d00e09.

@orbeckst

Copy link
Copy Markdown
Member

There's a multiprocessing RMSD analysis test that appears to be timing out repeatedly on the Python 3.11 runners. I am not sure why; I am restarting the runners and we'll see if they pass again.

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

With all tests passing cleanly, looks good.

@orbeckst orbeckst self-assigned this Nov 20, 2026
@srikarjy

Copy link
Copy Markdown
Author

@orbeckst Thank you for the approval. Is there anything else you need from me before this can be merged?

@orbeckst

Copy link
Copy Markdown
Member

@tylerjereddy do you have a few minutes to check if your comments have been addressed? It looks ok from my end. Thanks!

@srikarjy it's going to be Thanksgiving in the US, which many people take off for a few days, so please be patient if it takes a bit longer over the next few days.

@srikarjy

Copy link
Copy Markdown
Author

@orbeckst Thank you, no problem at all. Happy Thanksgiving!

…ength-normalization-5453

# Conflicts:
#	package/AUTHORS
#	package/CHANGELOG

This branch has not been deployed

No deployments
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PersistenceLength.run(start=, stop=) rescales entire results.bond_autocorrelation array by n_frames_processed / n_frames_total_trajectory

4 participants