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 d7ce21f94..3d8754edd 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,11 @@ 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, + 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 ------- @@ -987,6 +998,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 +1023,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 = [] @@ -1025,11 +1042,12 @@ 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, confidence_level=target_confidence, + random_state=_bootstrap_seed(self.__study_seed), ) width = float(ci.high - ci.low) @@ -1052,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 bf88fd458..807d5ac24 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,61 @@ 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, 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( + target_attribute="max_speed", + tolerance=0.26, + max_simulations=12, + batch_size=3, + parallel=parallel, + 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_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): diff --git a/tests/unit/simulation/test_monte_carlo.py b/tests/unit/simulation/test_monte_carlo.py index 9abcda810..7f7fdc964 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): @@ -541,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 @@ -549,6 +551,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 +579,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."""