Skip to content

ENH: let a convergence study be reproduced from one seed - #1198

Open
thc1006 wants to merge 8 commits into
RocketPy-Team:developfrom
thc1006:enh/a-convergence-study-from-one-seed-v2
Open

thc1006 wants to merge 8 commits into
RocketPy-Team:developfrom
thc1006:enh/a-convergence-study-from-one-seed-v2

Conversation

@thc1006

@thc1006 thc1006 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Addresses #1077.

While this was open, #1213, for the release blockers in #1209, put the seed pass-through and its changelog entry on develop (9e3cc63). I merged develop and took its side of both conflicts, so what this PR adds now is the follow-up from review.

Pull request type

  • Code changes (bugfix, features)

Checklist

  • Tests for the changes have been added (if needed)
  • Docs have been reviewed and added / updated
  • Lint (ruff check / ruff format --check, pylint) has passed locally
  • All tests have passed locally
  • CHANGELOG.md: a line under Unreleased. The changelog workflow skips a PR that already has one.

Current behavior

simulate_convergence passes random_seed to every batch but bootstraps each confidence interval from SciPy's global generator. Two runs with the same seed can return different widths and, near the tolerance, stop after a different number of batches. A bad random_seed fails only inside the first batch, and not at all if the logs already hold max_simulations rows or more.

New behavior

The bootstrap is seeded from the study's seed, and set_inputs_log and set_outputs_log return the rows in simulation order when each row records its index. So a study run again with the same seed stops after the same batch, in parallel or not. That includes a study that drew its own seed, run again with the one it printed. random_seed is checked with the other inputs, before any log is read, and the docstring says what the seed does not fix: where the study stops can depend on batch_size, and a finished study runs nothing. That case now warns.

Breaking change

  • No

Additional information

The integration tests sit in test_monte_carlo_release.py, beside the convergence tests develop added, and the cross-batch one there now compares whole input rows. Taking out the bootstrap seed, seeding it from the argument instead of the study, reading the logs in the order workers wrote them, or dropping the up-front check or the warning each makes one of them fail.

Merged with develop at v1.14.0, the unit, integration, doctest and acceptance tests pass on Python 3.10 and 3.14 with .[all], and so do the slow Monte Carlo tests. ruff 0.17.6 and pylint 4.1.4 are clean.

Two things I found along the way are filed separately as #1229 and #1230.

Each batch derived a root of its own, so a study could not be repeated and
the same max_simulations reached different samples per batch size.

Signed-off-by: thc1006 <[email protected]>
@thc1006
thc1006 requested a review from a team as a code owner September 16, 2026 20:54
@codecov

codecov Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.04%. Comparing base (488e086) to head (5d214b3).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #1198   +/-   ##
========================================
  Coverage    87.03%   87.04%           
========================================
  Files          130      130           
  Lines        18096    18105    +9     
========================================
+ Hits         15750    15759    +9     
  Misses        2346     2346           

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

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

Nine findings inline. The one on random_seed=random_seed affects what the feature promises; the rest are smaller.

Comment thread rocketpy/simulation/monte_carlo.py Resolved
Comment thread rocketpy/simulation/monte_carlo.py Resolved
Comment thread rocketpy/simulation/monte_carlo.py Resolved
Comment thread rocketpy/simulation/monte_carlo.py Resolved
Comment thread CHANGELOG.md Resolved
develop now carries the seed pass-through and its changelog entry
(9e3cc63, RocketPy-Team#1209), so both conflicts take develop's side.

Signed-off-by: thc1006 <[email protected]>
simulate_convergence handed its seed to every batch but bootstrapped each
confidence interval from SciPy's global generator, so the same seed gave a
different confidence_interval_history and, near the tolerance, a different
stopping batch. The bootstrap now takes a 32-bit seed spawned off the study
seed. That also covers a study that drew its own seed and is run again with
the one it recorded.

A random_seed of the wrong type or sign is now refused with the other inputs,
before the logs are read, including when they already hold every simulation
and nothing would run. The docstring says what the seed does not fix: where
the study stops can depend on batch_size, and a finished study runs nothing
whatever seed it is given.

Signed-off-by: thc1006 <[email protected]>
The cross-batch test compared mass alone, which comes from the rocket's
stream, so a change in the environment or flight draws would still pass. It
now compares each input row in full and in order.

The three tests this branch added ran twenty Calisto flights, keyed the rows
they compared by index, and copied their helpers from other files. What they
checked is now covered next to the convergence tests develop already has, on
its light release_study fixture, so the file is gone.

Signed-off-by: thc1006 <[email protected]>
@thc1006
thc1006 force-pushed the enh/a-convergence-study-from-one-seed-v2 branch from 3f7b767 to 1176b3e Compare November 20, 2026 11:09

@Gui-FernandesBR Gui-FernandesBR 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 thorough round. One finding left, inline: with parallel=True the seeded bootstrap can still give a different stopping batch.

Comment thread rocketpy/simulation/monte_carlo.py Resolved
Parallel workers append rows as they finish, so two runs with the same seed
could hand the seeded bootstrap the same values in a different order and get
different widths, which near the tolerance means a different stopping batch.
Each batch now reads the outputs, sorts both logs by index and rebuilds
results before the bootstrap. Sorting the inputs as well keeps each input
row next to its output.

The changelog entry for this pull request now mentions the seeded bootstrap.

Signed-off-by: thc1006 <[email protected]>
Comment thread rocketpy/simulation/monte_carlo.py Outdated
History of confidence interval widths, one value per batch of simulations.
The last element corresponds to the width when the simulation stopped for
either meeting the tolerance or reaching the maximum number of simulations.
Empty when the logs already hold ``max_simulations`` rows: nothing runs

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-existing (not from this change, not blocking): when the log already holds max_simulations rows, simulate_convergence returns [] without computing a width, and a random_seed that differs from the recorded one is accepted silently.

This PR now documents and tests that, but the first Returns paragraph still says the last element is the width where the study stopped, so a caller following it gets IndexError on history[-1]. The guard is <, so the same happens with more than max_simulations rows ("hold max_simulations rows" should be "at least"). Fix: warn when nothing runs, or return one width over the loaded rows, and fix the wording.

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.

Fixed in 5d214b3. A finished study now warns that nothing was run. The check is >=, Returns says "at least", and the unit test runs 50 and 60 loaded rows against max_simulations=50.

I went with the warning instead of a width over the loaded rows. That width would need the study seed read back from the logs, and comparing it with random_seed there is #1236.

Comment thread rocketpy/simulation/monte_carlo.py Outdated

return confidence_interval_history

def __read_outputs_in_simulation_order(self):

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.

Nit (optional): the order fix only exists inside simulate_convergence. After it returns, results, inputs_log and outputs_log are sorted in memory while the files keep arrival order, and the next simulate or import_outputs reloads them unsorted.

So estimate_confidence_interval(..., random_state=s) called by a user on a parallel study still depends on which worker finished first, and gives different numbers before and after a reload. Fix: sort once where the logs are read (set_outputs_log / set_inputs_log) so every path sees index order.

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.

Done in 5d214b3. set_inputs_log and set_outputs_log now sort the rows by index when every row has an integer one, and keep the file order otherwise, as in the old example.outputs.txt fixture. test_logs_written_out_of_order_are_read_back_by_index reverses both logs, reloads them, and checks the order and that a seeded estimate_confidence_interval gives the same interval as before.

Comment thread rocketpy/simulation/monte_carlo.py Outdated
"""Reads the outputs log, then sorts both logs by simulation index and
rebuilds ``results``. Parallel workers append rows as they finish, and
the seeded bootstrap must see the same sequence every time."""
self.import_outputs(self.filename.with_suffix(".outputs.txt"))

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.

Nit (optional): __terminate_simulation has just parsed the outputs log through the output_file setter, so this import_outputs parses the whole file a second time on every batch, and set_results() below rebuilds what the setter already built.

processed_results is also left computed from the unsorted rows while results is rebuilt from the sorted ones. Fix: sort self.outputs_log and self.inputs_log as __terminate_simulation leaves them, then call set_results() and set_processed_results() once.

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.

With the sort in the readers, the loop no longer calls import_outputs or set_results. It uses what __terminate_simulation loaded, so processed_results comes from the same sorted rows.

ci = self.estimate_confidence_interval(
attribute=target_attribute,
confidence_level=target_confidence,
random_state=_bootstrap_seed(self.__study_seed),

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.

Nit (optional): simulate_convergence now needs self.__study_seed, which only simulate() sets (it is not initialised in __init__). A subclass or test double that overrides simulate raises AttributeError: _MonteCarlo__study_seed here, which is why ConvergenceMockMonteCarlo had to setattr the mangled name.

Fix: initialise self.__study_seed = None in __init__, or read the seed through a small public accessor that simulate fills.

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.

__study_seed = None is a class attribute now. ConvergenceMockMonteCarlo skips MonteCarlo.__init__, so a default set there would not reach it; the class attribute does, and the mock no longer sets the mangled name.

A class that overrides simulate and never sets the seed gets an unseeded bootstrap this way, since SeedSequence(None) draws fresh entropy.



def _converge_by_threes(study, random_seed=None, parallel=False):
# Stops after the second batch for seed 42: 0.269 at three samples, 0.252

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.

Nit (optional): the tests hard-code that seed 42 gives 0.269 then 0.252 against a 0.26 tolerance, a margin of about 3%. That ties them to the exact flight output and to SciPy's bootstrap stream, so a physics fix or a SciPy change fails them without any seeding regression.

The "Unseeded ... 0.236-0.262" remark is also misleading now: an unseeded study draws a new study seed, so the samples change as well, not only the bootstrap. Fix: derive the tolerance from the first run's own widths (for example halfway between the first and second width), and drop the numbers from the comment.

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.

The same-seed test now runs once with a negligible tolerance, checks that the second width is below the first, and stops the next two runs halfway between them. The other convergence tests use the negligible tolerance, so they run to max_simulations and compare every width. The comment with the numbers is gone.

serial, _ = _converge_by_threes(release_study, random_seed=42)
release_study.simulate(0, append=False, random_seed=42)

parallel, _ = _converge_by_threes(release_study, random_seed=42, parallel=True)

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.

Nit (optional): parallel=True without n_workers starts os.cpu_count() processes for a 3-simulation batch, twice. The other parallel tests in this file pass n_workers=2.

Fix: pass n_workers=2 through _converge_by_threes.

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.

Done, _converge_by_threes passes n_workers=2 when parallel is set, and the parallel test stops after two batches.

release_study.simulate(0, append=False, random_seed=42)

parallel, _ = _converge_by_threes(release_study, random_seed=42, parallel=True)
assert parallel == serial

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.

Nit (optional): parallel == serial compares widths with exact float equality across worker processes. It holds only if each flight is bit-identical in a spawned worker and in the parent, so a platform or library difference at the 1e-12 level would fail the test with no ordering bug.

Fix: compare with pytest.approx(serial, rel=1e-9); a wrong bootstrap seed moves the widths by far more than that, so it still fails without the fix.

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.

Done. Dropping the bootstrap seed still fails it.

…study-from-one-seed-v2

Signed-off-by: thc1006 <[email protected]>

# Conflicts:
#	CHANGELOG.md
Sorting by index only inside simulate_convergence left results, and any
seeded estimate_confidence_interval a user ran, in arrival order after the
next reload. set_inputs_log and set_outputs_log now sort when every row
records an integer index, so the convergence loop no longer parses the
outputs a second time per batch or rebuilds results next to a stale
processed_results.

A finished study now warns that nothing was run, also when the logs hold
more than max_simulations rows, and the Returns section says so. The study
seed defaults to None on the class, so a class overriding simulate no
longer has to set the mangled name.

The convergence tests derive their tolerance from the run's own widths,
run the parallel case on two workers for two batches, and compare its
widths with pytest.approx. Since v1.14.0 has shipped, the changelog gets a
new entry under Unreleased.

Signed-off-by: thc1006 <[email protected]>
@thc1006

thc1006 commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Merged develop. v1.14.0 shipped with the earlier changelog line, so the seeded bootstrap, the log order and the warning have a new entry under Unreleased.

simulate_convergence is at 25 statements, pylint's limit. Merged with #1233 as it stands, it comes to 27, so whichever of the two lands second still needs the extraction I mentioned.

One docs example now warns. In monte_carlo_class_usage.ipynb, the simulate_convergence cell runs on the study the cell above filled to 1000 simulations, with max_simulations=1000, so it already ran nothing. A study of its own would leave untracked logs next to the tracked ones in monte_carlo_analysis_outputs/ each time someone runs the notebook, so I have left it for you to decide. I can change it here or separately.

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