From 8bc335ae47d0562e0cf9fd7f97173d0a87936f18 Mon Sep 17 00:00:00 2001 From: thc1006 <84045975+thc1006@users.noreply.github.com> Date: Wed, 26 Aug 2026 08:56:32 +0800 Subject: [PATCH 1/6] ENH: let a convergence study be reproduced from one seed 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 <84045975+thc1006@users.noreply.github.com> --- rocketpy/simulation/monte_carlo.py | 8 +++ .../simulation/test_convergence_seeding.py | 70 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 tests/unit/simulation/test_convergence_seeding.py diff --git a/rocketpy/simulation/monte_carlo.py b/rocketpy/simulation/monte_carlo.py index 5166920bd..62db59fc3 100644 --- a/rocketpy/simulation/monte_carlo.py +++ b/rocketpy/simulation/monte_carlo.py @@ -1063,6 +1063,8 @@ def simulate_convergence( batch_size=50, parallel=False, n_workers=None, + *, + random_seed=None, ): """Run Monte Carlo simulations in batches until the confidence interval width converges within the specified tolerance or the maximum number of @@ -1084,6 +1086,11 @@ def simulate_convergence( Whether to run simulations in parallel. Default is False. n_workers : int, optional The number of worker processes to use if running in parallel. Default is None. + random_seed : int, sequence of int or numpy.random.SeedSequence, optional + Fixes the whole study rather than one batch. Every batch continues + the same root, so a given ``max_simulations`` reaches the same set + of samples whatever ``batch_size`` divided it up. Keyword-only. + Default is None, which draws fresh entropy and reproduces nothing. Returns ------- @@ -1126,6 +1133,7 @@ def simulate_convergence( include_function_data=False, parallel=parallel, n_workers=n_workers, + random_seed=random_seed, ) self.import_outputs(self.filename.with_suffix(".outputs.txt")) diff --git a/tests/unit/simulation/test_convergence_seeding.py b/tests/unit/simulation/test_convergence_seeding.py new file mode 100644 index 000000000..a6ea37831 --- /dev/null +++ b/tests/unit/simulation/test_convergence_seeding.py @@ -0,0 +1,70 @@ +import json + +import pytest + +from rocketpy.simulation.monte_carlo import MonteCarlo + + +def _study(tmp_path, stem, models): + environment, rocket, flight = models + return MonteCarlo( + filename=str(tmp_path / stem), + environment=environment, + rocket=rocket, + flight=flight, + ) + + +def _drawn(analysis): + with open(analysis.input_file, "r", encoding="utf-8") as written: + rows = [json.loads(line) for line in written if line.strip()] + return {row["index"]: row.get("mass") for row in rows} + + +@pytest.fixture(name="models") +def _models(stochastic_environment, stochastic_calisto, stochastic_flight): + return stochastic_environment, stochastic_calisto, stochastic_flight + + +def _converge(analysis, batch_size, seed): + return analysis.simulate_convergence( + target_attribute="apogee_time", + tolerance=1e-9, + max_simulations=4, + batch_size=batch_size, + random_seed=seed, + ) + + +def test_a_convergence_study_repeats_from_one_seed(models, tmp_path): + """The same seed gives the study back, which it could not before.""" + first = _study(tmp_path, "first", models) + second = _study(tmp_path, "second", models) + + _converge(first, batch_size=2, seed=42) + _converge(second, batch_size=2, seed=42) + + assert _drawn(first) == _drawn(second) + + +def test_the_batch_size_does_not_reach_the_samples(models, tmp_path): + """Splitting the study differently must not change which samples it takes.""" + # Each batch used to derive a root of its own, so the same + # max_simulations reached a different set of samples per batch size. + in_twos = _study(tmp_path, "twos", models) + in_fours = _study(tmp_path, "fours", models) + + _converge(in_twos, batch_size=2, seed=42) + _converge(in_fours, batch_size=4, seed=42) + + assert _drawn(in_twos) == _drawn(in_fours) + + +def test_a_study_without_a_seed_still_runs(models, tmp_path): + """The control. No seed is still allowed, and still reproduces nothing.""" + analysis = _study(tmp_path, "unseeded", models) + + history = _converge(analysis, batch_size=2, seed=None) + + assert history + assert sorted(_drawn(analysis)) == [0, 1, 2, 3] From 41344c7af454d0e244b915a433ddd6c30fd29a27 Mon Sep 17 00:00:00 2001 From: thc1006 <84045975+thc1006@users.noreply.github.com> Date: Wed, 26 Aug 2026 08:56:32 +0800 Subject: [PATCH 2/6] DOC: give the convergence seed its changelog line Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com> --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13c598421..17266102d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ Attention: The newest changes should be on top --> ### Added +- ENH: Reproduce a convergence study from one seed [#1077](https://github.com/RocketPy-Team/RocketPy/issues/1077) - ENH: Reproducible Monte Carlo seeding, and an append that continues the same study [#1187](https://github.com/RocketPy-Team/RocketPy/pull/1187) [#1053](https://github.com/RocketPy-Team/RocketPy/issues/1053) [#1075](https://github.com/RocketPy-Team/RocketPy/issues/1075) - ENH: 3-DOF single rail button flight phase (tip-off analysis), enabled with the opt-in `Flight(use_udot_rail2=True)`. Between the upper rail button leaving the rail and the lower one following it, the rocket pivots about the lower button under a solved constraint wrench instead of jumping straight to free 6-DOF flight. The window is reported as `between_rails_time`, `between_rails_velocity` and `tip_off_duration`, printed by `Flight.info()` and shaded in the attitude plots. Requires `simulation_mode="6 DOF"` and `equations_of_motion="standard"`. [#920](https://github.com/RocketPy-Team/RocketPy/pull/920) - ENH: Support fixed-time parachute deployment triggers [#1133](https://github.com/RocketPy-Team/RocketPy/pull/1133) [#437](https://github.com/RocketPy-Team/RocketPy/issues/437) From d014ba97176b49f173d97c57e426415b0bfccd26 Mon Sep 17 00:00:00 2001 From: thc1006 <84045975+thc1006@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:29:38 +0800 Subject: [PATCH 3/6] BUG: make a seeded convergence study stop where it stopped before 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 <84045975+thc1006@users.noreply.github.com> --- rocketpy/simulation/monte_carlo.py | 17 +++++++++ .../simulation/test_monte_carlo_release.py | 31 ++++++++++++++++ tests/unit/simulation/test_monte_carlo.py | 36 +++++++++++++++++++ 3 files changed, 84 insertions(+) diff --git a/rocketpy/simulation/monte_carlo.py b/rocketpy/simulation/monte_carlo.py index d7ce21f94..95970cabe 100644 --- a/rocketpy/simulation/monte_carlo.py +++ b/rocketpy/simulation/monte_carlo.py @@ -79,6 +79,12 @@ def _study_seed(random_seed): return int(random_seed) +def _bootstrap_seed(study_seed): + """32-bit seed, as SciPy requires, spawned off the study seed so no + simulation's ``[seed, index]`` stream shares it.""" + return int(np.random.SeedSequence(study_seed, spawn_key=(0,)).generate_state(1)[0]) + + def _checkpoint_rows(path): """Read validated checkpoint metadata without retaining physical results.""" rows = [] @@ -980,6 +986,10 @@ def simulate_convergence( random_seed : int, optional Non-negative study seed passed to every batch. If omitted, an existing study keeps its recorded seed; a new study generates and prints one. + The bootstrap behind each width is seeded from it too, so the same + study run again with the same seed stops after the same batch. Runs + with the same seed draw a common prefix of one stream of samples; + where the study stops can still depend on ``batch_size``. Returns ------- @@ -987,6 +997,9 @@ def simulate_convergence( 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 + and ``random_seed`` is not compared with the seed they record, so + reproducing a study needs a fresh ``filename``. """ # Validate inputs up-front. Without this, a non-positive batch_size makes @@ -1009,6 +1022,9 @@ def simulate_convergence( "'target_confidence' must be between 0 and 1 (exclusive), got " f"{target_confidence!r}." ) + # Here as well as in simulate, which a finished study never reaches. + if random_seed is not None: + _study_seed(random_seed) self.import_outputs(self.filename.with_suffix(".outputs.txt")) confidence_interval_history = [] @@ -1030,6 +1046,7 @@ def simulate_convergence( ci = self.estimate_confidence_interval( attribute=target_attribute, confidence_level=target_confidence, + random_state=_bootstrap_seed(self.__study_seed), ) width = float(ci.high - ci.low) diff --git a/tests/integration/simulation/test_monte_carlo_release.py b/tests/integration/simulation/test_monte_carlo_release.py index bf88fd458..70cee5351 100644 --- a/tests/integration/simulation/test_monte_carlo_release.py +++ b/tests/integration/simulation/test_monte_carlo_release.py @@ -200,6 +200,37 @@ def test_convergence_seed_reproduces_inputs_across_batch_sizes(release_study): assert [row["mass"] for row in _rows(release_study.input_file)] == expected +def _converge_by_threes(study, random_seed=None): + # Stops after the second batch for seed 42: 0.269 at three samples, 0.252 + # at six. Unseeded, the bootstrap puts the second width in 0.236-0.262. + history = study.simulate_convergence( + target_attribute="max_speed", + tolerance=0.26, + max_simulations=12, + batch_size=3, + random_seed=random_seed, + ) + return history, _rows(study.input_file) + + +def test_the_same_seed_gives_back_the_same_study(release_study): + """The same seed draws the same inputs and stops after the same batch.""" + first = _converge_by_threes(release_study, random_seed=42) + release_study.simulate(0, append=False, random_seed=42) + + assert _converge_by_threes(release_study, random_seed=42) == first + assert len(first[0]) < 4 # stopped on the tolerance, not on max_simulations + + +def test_an_unseeded_study_repeats_from_the_seed_it_recorded(release_study): + """The seed a study draws for itself reproduces it, stopping point included.""" + first = _converge_by_threes(release_study) + recorded = first[1][0]["seed"] + release_study.simulate(0, append=False, random_seed=recorded) + + assert _converge_by_threes(release_study, random_seed=recorded) == first + + def test_convergence_reads_the_checkpoint_once(release_study, monkeypatch): """Batches reuse what the study just wrote instead of parsing the logs again.""" reads = [] diff --git a/tests/unit/simulation/test_monte_carlo.py b/tests/unit/simulation/test_monte_carlo.py index 9abcda810..cf9374b68 100644 --- a/tests/unit/simulation/test_monte_carlo.py +++ b/tests/unit/simulation/test_monte_carlo.py @@ -242,6 +242,7 @@ def test_estimate_confidence_interval_raises_type_error_for_invalid_statistic(): ({"tolerance": -1.0}, "tolerance"), ({"target_confidence": 1.5}, "target_confidence"), ({"target_confidence": 0}, "target_confidence"), + ({"random_seed": -1}, "random_seed"), ], ) def test_simulate_convergence_validates_inputs(kwargs, match): @@ -549,6 +550,8 @@ def simulate(self, number_of_simulations, append=True, **kwargs): # pylint: disable=arguments-differ self.simulate_calls += 1 self.num_of_loaded_sims = number_of_simulations + # The real simulate settles the study seed; the bootstrap is seeded from it. + setattr(self, "_MonteCarlo__study_seed", kwargs.get("random_seed") or 0) def estimate_confidence_interval(self, attribute, confidence_level=0.95, **kwargs): # pylint: disable=arguments-differ,unused-argument @@ -575,6 +578,39 @@ def test_simulate_convergence_stops_early_when_tolerance_met(): assert mc.num_of_loaded_sims < 1000 # did not exhaust the simulation budget +@pytest.mark.parametrize( + "random_seed, error", + [ + (-1, ValueError), + (1.5, TypeError), + (True, TypeError), + ("42", TypeError), + (np.random.default_rng(42), TypeError), + ], +) +def test_simulate_convergence_refuses_a_bad_seed_with_nothing_to_run( + random_seed, error +): + """A bad seed is refused even when the logs already hold every simulation.""" + mc = ConvergenceMockMonteCarlo(width_model=lambda n: 10.0) + mc.num_of_loaded_sims = 50 + + with pytest.raises(error, match="random_seed"): + mc.simulate_convergence(max_simulations=50, random_seed=random_seed) + assert mc.simulate_calls == 0 + + +def test_simulate_convergence_runs_nothing_when_the_study_is_complete(): + """A finished study returns no widths, whatever valid seed it is given.""" + mc = ConvergenceMockMonteCarlo(width_model=lambda n: 10.0) + mc.num_of_loaded_sims = 50 + + history = mc.simulate_convergence(max_simulations=50, random_seed=7) + + assert isinstance(history, list) and not history + assert mc.simulate_calls == 0 + + def test_simulate_convergence_runs_until_max_when_not_converging(): """When the CI width never drops below the tolerance, the loop must run until max_simulations and never exceed it.""" From 1176b3ed746571c6258f1d7806cd41ba8c41cc60 Mon Sep 17 00:00:00 2001 From: thc1006 <84045975+thc1006@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:30:04 +0800 Subject: [PATCH 4/6] TST: compare every input field when a convergence study is repeated 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 <84045975+thc1006@users.noreply.github.com> --- .../simulation/test_monte_carlo_release.py | 4 +- .../simulation/test_convergence_seeding.py | 70 ------------------- 2 files changed, 2 insertions(+), 72 deletions(-) delete mode 100644 tests/unit/simulation/test_convergence_seeding.py diff --git a/tests/integration/simulation/test_monte_carlo_release.py b/tests/integration/simulation/test_monte_carlo_release.py index 70cee5351..660325b87 100644 --- a/tests/integration/simulation/test_monte_carlo_release.py +++ b/tests/integration/simulation/test_monte_carlo_release.py @@ -186,7 +186,7 @@ def test_convergence_seed_reproduces_inputs_across_batch_sizes(release_study): batch_size=2, random_seed=42, ) - expected = [row["mass"] for row in _rows(release_study.input_file)] + expected = _rows(release_study.input_file) release_study.simulate(0, append=False, random_seed=42) release_study.simulate_convergence( @@ -197,7 +197,7 @@ def test_convergence_seed_reproduces_inputs_across_batch_sizes(release_study): random_seed=42, ) - assert [row["mass"] for row in _rows(release_study.input_file)] == expected + assert _rows(release_study.input_file) == expected def _converge_by_threes(study, random_seed=None): diff --git a/tests/unit/simulation/test_convergence_seeding.py b/tests/unit/simulation/test_convergence_seeding.py deleted file mode 100644 index a6ea37831..000000000 --- a/tests/unit/simulation/test_convergence_seeding.py +++ /dev/null @@ -1,70 +0,0 @@ -import json - -import pytest - -from rocketpy.simulation.monte_carlo import MonteCarlo - - -def _study(tmp_path, stem, models): - environment, rocket, flight = models - return MonteCarlo( - filename=str(tmp_path / stem), - environment=environment, - rocket=rocket, - flight=flight, - ) - - -def _drawn(analysis): - with open(analysis.input_file, "r", encoding="utf-8") as written: - rows = [json.loads(line) for line in written if line.strip()] - return {row["index"]: row.get("mass") for row in rows} - - -@pytest.fixture(name="models") -def _models(stochastic_environment, stochastic_calisto, stochastic_flight): - return stochastic_environment, stochastic_calisto, stochastic_flight - - -def _converge(analysis, batch_size, seed): - return analysis.simulate_convergence( - target_attribute="apogee_time", - tolerance=1e-9, - max_simulations=4, - batch_size=batch_size, - random_seed=seed, - ) - - -def test_a_convergence_study_repeats_from_one_seed(models, tmp_path): - """The same seed gives the study back, which it could not before.""" - first = _study(tmp_path, "first", models) - second = _study(tmp_path, "second", models) - - _converge(first, batch_size=2, seed=42) - _converge(second, batch_size=2, seed=42) - - assert _drawn(first) == _drawn(second) - - -def test_the_batch_size_does_not_reach_the_samples(models, tmp_path): - """Splitting the study differently must not change which samples it takes.""" - # Each batch used to derive a root of its own, so the same - # max_simulations reached a different set of samples per batch size. - in_twos = _study(tmp_path, "twos", models) - in_fours = _study(tmp_path, "fours", models) - - _converge(in_twos, batch_size=2, seed=42) - _converge(in_fours, batch_size=4, seed=42) - - assert _drawn(in_twos) == _drawn(in_fours) - - -def test_a_study_without_a_seed_still_runs(models, tmp_path): - """The control. No seed is still allowed, and still reproduces nothing.""" - analysis = _study(tmp_path, "unseeded", models) - - history = _converge(analysis, batch_size=2, seed=None) - - assert history - assert sorted(_drawn(analysis)) == [0, 1, 2, 3] From ec44dd05b7ad1638d7e872c7d1833610bd9057d6 Mon Sep 17 00:00:00 2001 From: thc1006 <84045975+thc1006@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:00:29 +0800 Subject: [PATCH 5/6] BUG: give the convergence bootstrap its rows in simulation order 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 <84045975+thc1006@users.noreply.github.com> --- CHANGELOG.md | 2 +- rocketpy/simulation/monte_carlo.py | 18 ++++++++++--- .../simulation/test_monte_carlo_release.py | 25 ++++++++++++++++++- tests/unit/simulation/test_monte_carlo.py | 1 + 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a54c868e0..c88c37f2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,7 @@ Attention: The newest changes should be on top --> ### Added -- ENH: Accept `random_seed` in `MonteCarlo.simulate_convergence`, including across batches. [#1198](https://github.com/RocketPy-Team/RocketPy/pull/1198) [#1209](https://github.com/RocketPy-Team/RocketPy/issues/1209) +- ENH: Accept `random_seed` in `MonteCarlo.simulate_convergence`, including across batches, and seed the bootstrap behind each width from it. [#1198](https://github.com/RocketPy-Team/RocketPy/pull/1198) [#1209](https://github.com/RocketPy-Team/RocketPy/issues/1209) - ENH: Reproducible Monte Carlo seeding, and an append that continues the same study [#1187](https://github.com/RocketPy-Team/RocketPy/pull/1187) [#1053](https://github.com/RocketPy-Team/RocketPy/issues/1053) [#1075](https://github.com/RocketPy-Team/RocketPy/issues/1075) - ENH: 3-DOF single rail button flight phase (tip-off analysis), enabled with the opt-in `Flight(use_udot_rail2=True)`. Between the upper rail button leaving the rail and the lower one following it, the rocket pivots about the lower button under a solved constraint wrench instead of jumping straight to free 6-DOF flight. The window is reported as `between_rails_time`, `between_rails_velocity` and `tip_off_duration`, printed by `Flight.info()` and shaded in the attitude plots. Requires `simulation_mode="6 DOF"` and `equations_of_motion="standard"`. [#920](https://github.com/RocketPy-Team/RocketPy/pull/920) - ENH: Support fixed-time parachute deployment triggers [#1133](https://github.com/RocketPy-Team/RocketPy/pull/1133) [#437](https://github.com/RocketPy-Team/RocketPy/issues/437) diff --git a/rocketpy/simulation/monte_carlo.py b/rocketpy/simulation/monte_carlo.py index 95970cabe..3d8754edd 100644 --- a/rocketpy/simulation/monte_carlo.py +++ b/rocketpy/simulation/monte_carlo.py @@ -987,9 +987,10 @@ def simulate_convergence( Non-negative study seed passed to every batch. If omitted, an existing study keeps its recorded seed; a new study generates and prints one. The bootstrap behind each width is seeded from it too, so the same - study run again with the same seed stops after the same batch. Runs - with the same seed draw a common prefix of one stream of samples; - where the study stops can still depend on ``batch_size``. + study run again with the same seed stops after the same batch, + in parallel or not. Runs with the same seed draw a common prefix of + one stream of samples; where the study stops can still depend on + ``batch_size``. Returns ------- @@ -1041,7 +1042,7 @@ def simulate_convergence( random_seed=random_seed, ) - self.import_outputs(self.filename.with_suffix(".outputs.txt")) + self.__read_outputs_in_simulation_order() ci = self.estimate_confidence_interval( attribute=target_attribute, @@ -1069,6 +1070,15 @@ def simulate_convergence( return confidence_interval_history + def __read_outputs_in_simulation_order(self): + """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")) + for log in (self.inputs_log, self.outputs_log): + log.sort(key=lambda row: row[_SIMULATION_INDEX_KEY]) + self.set_results() + def __evaluate_flight_inputs(self, sim_idx): """Evaluates the inputs of a single flight simulation. diff --git a/tests/integration/simulation/test_monte_carlo_release.py b/tests/integration/simulation/test_monte_carlo_release.py index 660325b87..807d5ac24 100644 --- a/tests/integration/simulation/test_monte_carlo_release.py +++ b/tests/integration/simulation/test_monte_carlo_release.py @@ -200,7 +200,7 @@ def test_convergence_seed_reproduces_inputs_across_batch_sizes(release_study): assert _rows(release_study.input_file) == expected -def _converge_by_threes(study, random_seed=None): +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 # at six. Unseeded, the bootstrap puts the second width in 0.236-0.262. history = study.simulate_convergence( @@ -208,6 +208,7 @@ def _converge_by_threes(study, random_seed=None): tolerance=0.26, max_simulations=12, batch_size=3, + parallel=parallel, random_seed=random_seed, ) return history, _rows(study.input_file) @@ -231,6 +232,28 @@ def test_an_unseeded_study_repeats_from_the_seed_it_recorded(release_study): assert _converge_by_threes(release_study, random_seed=recorded) == first +def test_a_parallel_study_stops_where_a_serial_one_does(release_study): + """Workers finish in any order, and the widths must not follow it.""" + 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) + assert parallel == serial + + +def test_rows_logged_out_of_order_give_the_serial_widths(release_study): + """The same check without depending on which worker finishes first.""" + serial, _ = _converge_by_threes(release_study, random_seed=42) + release_study.simulate(3, append=False, random_seed=42, include_function_data=False) + for log in (release_study.input_file, release_study.output_file): + _write_rows(log, _rows(log)[::-1]) + + assert _converge_by_threes(release_study, random_seed=42)[0] == serial[1:] + assert [row["index"] for row in release_study.inputs_log] == [ + row["index"] for row in release_study.outputs_log + ] + + def test_convergence_reads_the_checkpoint_once(release_study, monkeypatch): """Batches reuse what the study just wrote instead of parsing the logs again.""" reads = [] diff --git a/tests/unit/simulation/test_monte_carlo.py b/tests/unit/simulation/test_monte_carlo.py index cf9374b68..7f7fdc964 100644 --- a/tests/unit/simulation/test_monte_carlo.py +++ b/tests/unit/simulation/test_monte_carlo.py @@ -542,6 +542,7 @@ def __init__(self, width_model): self.filename = pathlib.Path("dummy_mc") self._width_model = width_model self.simulate_calls = 0 + self.inputs_log, self.outputs_log = [], [] def import_outputs(self, *args, **kwargs): # no-op, avoids file I/O pass From 5d214b3751da4db10b3c264a36772f407129ea76 Mon Sep 17 00:00:00 2001 From: thc1006 <84045975+thc1006@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:22:53 +0800 Subject: [PATCH 6/6] BUG: read Monte Carlo logs in simulation order wherever they are loaded 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 <84045975+thc1006@users.noreply.github.com> --- CHANGELOG.md | 2 + rocketpy/simulation/monte_carlo.py | 58 ++++++++++++------- .../simulation/test_monte_carlo_release.py | 52 ++++++++++++----- tests/unit/simulation/test_monte_carlo.py | 34 ++++++++--- 4 files changed, 104 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 438b48dd2..1a630a22f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,8 @@ Attention: The newest changes should be on top --> ### Fixed +- BUG: Seed the `MonteCarlo.simulate_convergence` bootstrap from the study seed and read Monte Carlo logs back in simulation order, so the same seed stops after the same batch, in parallel too. A finished study now warns that nothing was run. [#1198](https://github.com/RocketPy-Team/RocketPy/pull/1198) + ## [v1.14.0] - 2026-11-29 ### Breaking changes diff --git a/rocketpy/simulation/monte_carlo.py b/rocketpy/simulation/monte_carlo.py index 3d8754edd..9247aece5 100644 --- a/rocketpy/simulation/monte_carlo.py +++ b/rocketpy/simulation/monte_carlo.py @@ -79,6 +79,19 @@ def _study_seed(random_seed): return int(random_seed) +def _in_simulation_order(rows): + """``rows`` by simulation index when every row records one: parallel + workers write them as they finish. Otherwise in the order given.""" + if isinstance(rows, list) and all( + isinstance(row, dict) + and isinstance(row.get(_SIMULATION_INDEX_KEY), int) + and not isinstance(row.get(_SIMULATION_INDEX_KEY), bool) + for row in rows + ): + return sorted(rows, key=lambda row: row[_SIMULATION_INDEX_KEY]) + return rows + + def _bootstrap_seed(study_seed): """32-bit seed, as SciPy requires, spawned off the study seed so no simulation's ``[seed, index]`` stream shares it.""" @@ -255,9 +268,11 @@ class MonteCarlo: # pylint: disable=too-many-public-methods A dictionary whose keys are the names of the additional exported variables and the values are callback functions. inputs_log : list - List of dictionaries with the inputs used in each simulation. + List of dictionaries with the inputs used in each simulation, in + simulation order when every row records its index. outputs_log : list - List of dictionaries with the outputs of each simulation. + List of dictionaries with the outputs of each simulation, in + simulation order when every row records its index. errors_log : list List of dictionaries with the errors of each simulation. num_of_loaded_sims : int @@ -285,6 +300,10 @@ class MonteCarlo: # pylint: disable=too-many-public-methods spent waiting for I/O operations or other processes to complete. """ + # Settled by simulate. None until then, so that a class overriding simulate + # can still run simulate_convergence. + __study_seed = None + def __init__( self, filename, @@ -998,9 +1017,10 @@ def simulate_convergence( 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 - and ``random_seed`` is not compared with the seed they record, so - reproducing a study needs a fresh ``filename``. + Empty, with a warning, when the logs already hold at least + ``max_simulations`` rows: nothing runs and ``random_seed`` is not + compared with the seed they record, so reproducing a study needs a + fresh ``filename``. """ # Validate inputs up-front. Without this, a non-positive batch_size makes @@ -1028,6 +1048,13 @@ def simulate_convergence( _study_seed(random_seed) self.import_outputs(self.filename.with_suffix(".outputs.txt")) + if self.num_of_loaded_sims >= max_simulations: + warnings.warn( + f"The logs already hold {self.num_of_loaded_sims} simulations, at " + f"least max_simulations={max_simulations}, so nothing was run and " + "no confidence interval width was computed.", + stacklevel=2, + ) confidence_interval_history = [] while self.num_of_loaded_sims < max_simulations: @@ -1042,8 +1069,6 @@ def simulate_convergence( random_seed=random_seed, ) - self.__read_outputs_in_simulation_order() - ci = self.estimate_confidence_interval( attribute=target_attribute, confidence_level=target_confidence, @@ -1070,15 +1095,6 @@ def simulate_convergence( return confidence_interval_history - def __read_outputs_in_simulation_order(self): - """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")) - for log in (self.inputs_log, self.outputs_log): - log.sort(key=lambda row: row[_SIMULATION_INDEX_KEY]) - self.set_results() - def __evaluate_flight_inputs(self, sim_idx): """Evaluates the inputs of a single flight simulation. @@ -1543,24 +1559,26 @@ def _write_log_to_json(self, log_data, filepath): def set_inputs_log(self): """ Sets inputs_log from a file into an attribute for easy access. - Supports .txt (JSONL), .csv, and .json file formats. + Supports .txt (JSONL), .csv, and .json file formats. When every row + records a simulation index, the rows are sorted by it. Returns ------- None """ - self.inputs_log = self._read_log_file(self.input_file) + self.inputs_log = _in_simulation_order(self._read_log_file(self.input_file)) def set_outputs_log(self): """ Sets outputs_log from a file into an attribute for easy access. - Supports .txt (JSONL), .csv, and .json file formats. + Supports .txt (JSONL), .csv, and .json file formats. When every row + records a simulation index, the rows are sorted by it. Returns ------- None """ - self.outputs_log = self._read_log_file(self.output_file) + self.outputs_log = _in_simulation_order(self._read_log_file(self.output_file)) def set_errors_log(self): """ diff --git a/tests/integration/simulation/test_monte_carlo_release.py b/tests/integration/simulation/test_monte_carlo_release.py index 807d5ac24..69738be7a 100644 --- a/tests/integration/simulation/test_monte_carlo_release.py +++ b/tests/integration/simulation/test_monte_carlo_release.py @@ -200,15 +200,16 @@ def test_convergence_seed_reproduces_inputs_across_batch_sizes(release_study): assert _rows(release_study.input_file) == expected -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 - # at six. Unseeded, the bootstrap puts the second width in 0.236-0.262. +def _converge_by_threes( + study, random_seed=None, parallel=False, tolerance=1e-12, max_simulations=12 +): history = study.simulate_convergence( target_attribute="max_speed", - tolerance=0.26, - max_simulations=12, + tolerance=tolerance, + max_simulations=max_simulations, batch_size=3, parallel=parallel, + n_workers=2 if parallel else None, random_seed=random_seed, ) return history, _rows(study.input_file) @@ -216,15 +217,20 @@ def _converge_by_threes(study, random_seed=None, parallel=False): def test_the_same_seed_gives_back_the_same_study(release_study): """The same seed draws the same inputs and stops after the same batch.""" - first = _converge_by_threes(release_study, random_seed=42) + widths, _ = _converge_by_threes(release_study, random_seed=42) + assert widths[1] < widths[0] # so a tolerance between them stops batch two + tolerance = (widths[0] + widths[1]) / 2 + release_study.simulate(0, append=False, random_seed=42) + first = _converge_by_threes(release_study, random_seed=42, tolerance=tolerance) release_study.simulate(0, append=False, random_seed=42) - assert _converge_by_threes(release_study, random_seed=42) == first - assert len(first[0]) < 4 # stopped on the tolerance, not on max_simulations + again = _converge_by_threes(release_study, random_seed=42, tolerance=tolerance) + assert again == first + assert len(first[0]) == 2 # stopped on the tolerance, not on max_simulations def test_an_unseeded_study_repeats_from_the_seed_it_recorded(release_study): - """The seed a study draws for itself reproduces it, stopping point included.""" + """The seed a study draws for itself reproduces it, widths included.""" first = _converge_by_threes(release_study) recorded = first[1][0]["seed"] release_study.simulate(0, append=False, random_seed=recorded) @@ -234,11 +240,13 @@ def test_an_unseeded_study_repeats_from_the_seed_it_recorded(release_study): def test_a_parallel_study_stops_where_a_serial_one_does(release_study): """Workers finish in any order, and the widths must not follow it.""" - serial, _ = _converge_by_threes(release_study, random_seed=42) + # Two batches, so workers start only twice; the second width already + # depends on the order the rows arrive in. + serial, _ = _converge_by_threes(release_study, 42, max_simulations=6) release_study.simulate(0, append=False, random_seed=42) - parallel, _ = _converge_by_threes(release_study, random_seed=42, parallel=True) - assert parallel == serial + parallel, _ = _converge_by_threes(release_study, 42, True, max_simulations=6) + assert parallel == pytest.approx(serial, rel=1e-9) def test_rows_logged_out_of_order_give_the_serial_widths(release_study): @@ -249,9 +257,23 @@ def test_rows_logged_out_of_order_give_the_serial_widths(release_study): _write_rows(log, _rows(log)[::-1]) assert _converge_by_threes(release_study, random_seed=42)[0] == serial[1:] - assert [row["index"] for row in release_study.inputs_log] == [ - row["index"] for row in release_study.outputs_log - ] + + +def test_logs_written_out_of_order_are_read_back_by_index(release_study): + """Any read of the logs, not only the convergence loop, sees index order.""" + release_study.simulate(4, random_seed=42, include_function_data=False) + expected = release_study.estimate_confidence_interval("max_speed", random_state=1) + for log in (release_study.input_file, release_study.output_file): + _write_rows(log, _rows(log)[::-1]) + + release_study.import_inputs(release_study.input_file) + release_study.import_outputs(release_study.output_file) + assert [row["index"] for row in release_study.inputs_log] == [0, 1, 2, 3] + assert [row["index"] for row in release_study.outputs_log] == [0, 1, 2, 3] + assert ( + release_study.estimate_confidence_interval("max_speed", random_state=1) + == expected + ) def test_convergence_reads_the_checkpoint_once(release_study, monkeypatch): diff --git a/tests/unit/simulation/test_monte_carlo.py b/tests/unit/simulation/test_monte_carlo.py index 7f7fdc964..27fbc2574 100644 --- a/tests/unit/simulation/test_monte_carlo.py +++ b/tests/unit/simulation/test_monte_carlo.py @@ -542,7 +542,6 @@ def __init__(self, width_model): self.filename = pathlib.Path("dummy_mc") self._width_model = width_model self.simulate_calls = 0 - self.inputs_log, self.outputs_log = [], [] def import_outputs(self, *args, **kwargs): # no-op, avoids file I/O pass @@ -551,8 +550,6 @@ def simulate(self, number_of_simulations, append=True, **kwargs): # pylint: disable=arguments-differ self.simulate_calls += 1 self.num_of_loaded_sims = number_of_simulations - # The real simulate settles the study seed; the bootstrap is seeded from it. - setattr(self, "_MonteCarlo__study_seed", kwargs.get("random_seed") or 0) def estimate_confidence_interval(self, attribute, confidence_level=0.95, **kwargs): # pylint: disable=arguments-differ,unused-argument @@ -601,17 +598,40 @@ def test_simulate_convergence_refuses_a_bad_seed_with_nothing_to_run( assert mc.simulate_calls == 0 -def test_simulate_convergence_runs_nothing_when_the_study_is_complete(): - """A finished study returns no widths, whatever valid seed it is given.""" +@pytest.mark.parametrize("loaded", [50, 60]) +def test_simulate_convergence_runs_nothing_when_the_study_is_complete(loaded): + """A finished study warns and returns no widths, whatever valid seed it is given.""" mc = ConvergenceMockMonteCarlo(width_model=lambda n: 10.0) - mc.num_of_loaded_sims = 50 + mc.num_of_loaded_sims = loaded - history = mc.simulate_convergence(max_simulations=50, random_seed=7) + with pytest.warns(UserWarning, match="nothing was run") as caught: + history = mc.simulate_convergence(max_simulations=50, random_seed=7) + assert caught[0].filename == __file__ # names the caller assert isinstance(history, list) and not history assert mc.simulate_calls == 0 +@pytest.mark.parametrize( + "rows, ordered", + [ + ([{"index": 2}, {"index": 0}, {"index": 1}], True), + ([{"index": 2}, {"x": 0}, {"index": 1}], False), + ([{"index": 2}, {"index": True}, {"index": 1}], False), + ([{"index": 2}, {"index": 1.0}, {"index": 1}], False), + ({}, False), + ], +) +def test_logs_are_ordered_only_when_every_row_records_an_index(rows, ordered): + """Rows are sorted by index if all of them carry an integer one.""" + result = mc_module._in_simulation_order(rows) + + if ordered: + assert [row["index"] for row in result] == [0, 1, 2] + else: + assert result is rows + + def test_simulate_convergence_runs_until_max_when_not_converging(): """When the CI width never drops below the tolerance, the loop must run until max_simulations and never exceed it."""