diff --git a/CHANGELOG.md b/CHANGELOG.md index b773fbf2c..b6b70753e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ 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) - BUG: fetch Windy forecasts from the official Point Forecast API, which requires an API key [#1254](https://github.com/RocketPy-Team/RocketPy/pull/1254) - BUG: Fix inverted and wrong factors in the units conversion table. Results computed with `ft/s^2`, `atm`, `mg`, `g`, `deg` and `grad` change, and those with `lb`, `mmHg` and `inHg` change by at most about 3 parts per million. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199) - BUG: Use one height unit throughout `EnvironmentAnalysis`. With the imperial unit system, the pressures at 1000, 10000 and 30000 ft change, since they were evaluated at the wrong height. `original_pressure_level_data` now keeps the units of the file. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199) diff --git a/rocketpy/simulation/monte_carlo.py b/rocketpy/simulation/monte_carlo.py index d7ce21f94..9247aece5 100644 --- a/rocketpy/simulation/monte_carlo.py +++ b/rocketpy/simulation/monte_carlo.py @@ -79,6 +79,25 @@ 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.""" + 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 = [] @@ -249,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 @@ -279,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, @@ -980,6 +1005,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 +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, 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 @@ -1009,8 +1043,18 @@ 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")) + 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: @@ -1025,11 +1069,10 @@ def simulate_convergence( random_seed=random_seed, ) - self.import_outputs(self.filename.with_suffix(".outputs.txt")) - 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) @@ -1516,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 bf88fd458..69738be7a 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,83 @@ 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, tolerance=1e-12, max_simulations=12 +): + history = study.simulate_convergence( + target_attribute="max_speed", + 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) + + +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.""" + 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) + + 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, widths 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.""" + # 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, 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): + """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:] + + +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 9abcda810..27fbc2574 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): @@ -575,6 +576,62 @@ 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 + + +@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 = loaded + + 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."""