diff --git a/rocketpy/simulation/monte_carlo.py b/rocketpy/simulation/monte_carlo.py index d7ce21f94..3c938af97 100644 --- a/rocketpy/simulation/monte_carlo.py +++ b/rocketpy/simulation/monte_carlo.py @@ -64,6 +64,14 @@ # Written by the study on every row, so not a result and not a collector name. _ROW_METADATA = frozenset((_SIMULATION_INDEX_KEY, _SIMULATION_SEED_KEY)) +# A confidence interval on a handful of results is sampling noise, not +# convergence: with batch_size=1 the first width is computed at two results and +# is roughly the gap between them, so a loose tolerance can accept two flights +# whose values happened to land close together (#1233). A study may only stop +# early once it holds this many results. Kept below the default batch_size, so a +# default study still stops as soon as its first batch meets the tolerance. +MIN_RESULTS_FOR_CONVERGENCE = 30 + def _study_seed(random_seed): """Validate a study seed before opening or truncating any logs.""" @@ -968,9 +976,17 @@ def simulate_convergence( target_confidence : float, optional The confidence level for the interval (between 0 and 1). Default is 0.95. tolerance : float, optional - The desired width of the confidence interval in seconds, meters, or other units. Default is 0.5. + The desired width of the confidence interval in seconds, meters, or other units. + The width is only accepted once the study holds at least + ``MIN_RESULTS_FOR_CONVERGENCE`` results, so a small batch cannot stop + the study on a pair of values that happen to land close together. + Default is 0.5. max_simulations : int, optional - The maximum number of simulations to run to avoid infinite loops. Default is 1000. + The maximum number of simulations to run to avoid infinite loops. Must + be at least 2, since a confidence interval cannot be estimated from a + single observation. A budget below ``MIN_RESULTS_FOR_CONVERGENCE`` + never meets the tolerance, so such a study always runs its full + budget. Default is 1000. batch_size : int, optional The number of simulations to run in each batch. Default is 50. parallel : bool, optional @@ -984,9 +1000,14 @@ def simulate_convergence( Returns ------- confidence_interval_history : list of float - 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. + History of confidence interval widths, one value per batch that leaves + two or more results. A confidence interval cannot be estimated from a + single observation, so a fresh study with ``batch_size=1`` has one + entry fewer than batches run. A study stops early only after at least + ``MIN_RESULTS_FOR_CONVERGENCE`` results, so a shorter budget produces + one entry per batch that leaves two or more results. The last element + corresponds to the width when the simulation stopped for either + meeting the tolerance or reaching the maximum number of simulations. """ # Validate inputs up-front. Without this, a non-positive batch_size makes @@ -995,10 +1016,10 @@ def simulate_convergence( raise ValueError( f"'batch_size' must be a positive integer, got {batch_size!r}." ) - if not isinstance(max_simulations, (int, np.integer)) or max_simulations <= 0: + if not isinstance(max_simulations, (int, np.integer)) or max_simulations < 2: raise ValueError( - f"'max_simulations' must be a positive integer, got " - f"{max_simulations!r}." + "'max_simulations' must be an integer of at least 2 to estimate " + f"a confidence interval, got {max_simulations!r}." ) if not isinstance(tolerance, (int, float)) or tolerance <= 0: raise ValueError( @@ -1027,6 +1048,12 @@ def simulate_convergence( self.import_outputs(self.filename.with_suffix(".outputs.txt")) + # scipy.stats.bootstrap needs two or more observations, so the first + # batch of a fresh study with batch_size=1 cannot be summarised yet. + # Keep simulating until the logs hold two rows. + if self.num_of_loaded_sims < 2: + continue + ci = self.estimate_confidence_interval( attribute=target_attribute, confidence_level=target_confidence, @@ -1047,7 +1074,13 @@ def simulate_convergence( ) break - if width <= tolerance: + # The tolerance is only meaningful once the study holds enough results: + # a width computed from a handful of them is noise that a loose + # tolerance would read as convergence (#1233). + if ( + width <= tolerance + and self.num_of_loaded_sims >= MIN_RESULTS_FOR_CONVERGENCE + ): break return confidence_interval_history diff --git a/tests/integration/simulation/test_monte_carlo_release.py b/tests/integration/simulation/test_monte_carlo_release.py index bf88fd458..db989f080 100644 --- a/tests/integration/simulation/test_monte_carlo_release.py +++ b/tests/integration/simulation/test_monte_carlo_release.py @@ -225,6 +225,35 @@ def test_convergence_reads_the_checkpoint_once(release_study, monkeypatch): ] +def test_convergence_with_a_batch_size_of_one_waits_for_a_second_result( + release_study, +): + """A fresh study with ``batch_size=1`` must not bootstrap a lone result. + + The first batch leaves a single row, and ``scipy.stats.bootstrap`` needs at + least two, so the study has to keep running instead of raising on its very + first batch. + """ + history = release_study.simulate_convergence( + target_attribute="max_speed", + tolerance=1e-12, + max_simulations=4, + batch_size=1, + random_seed=1, + ) + + assert release_study.num_of_loaded_sims == 4 + # One width per batch that had two results to bootstrap: the batches that + # ended at 2, 3 and 4 rows. + assert len(history) == 3 + assert sorted(row["index"] for row in _rows(release_study.input_file)) == [ + 0, + 1, + 2, + 3, + ] + + def test_a_log_changed_after_the_run_is_read_again(release_study): """The shortcut only holds while the logs are what the study wrote.""" release_study.simulate(2, random_seed=42, include_function_data=False) diff --git a/tests/unit/simulation/test_monte_carlo.py b/tests/unit/simulation/test_monte_carlo.py index 9abcda810..ba3c3012a 100644 --- a/tests/unit/simulation/test_monte_carlo.py +++ b/tests/unit/simulation/test_monte_carlo.py @@ -15,6 +15,7 @@ from rocketpy.simulation import monte_carlo as mc_module from rocketpy.stochastic import StochasticFlight from rocketpy.simulation.monte_carlo import ( + MIN_RESULTS_FOR_CONVERGENCE, _refuse_logs_this_run_cannot_write, ) @@ -238,6 +239,7 @@ def test_estimate_confidence_interval_raises_type_error_for_invalid_statistic(): ({"batch_size": 0}, "batch_size"), ({"batch_size": -5}, "batch_size"), ({"max_simulations": 0}, "max_simulations"), + ({"max_simulations": 1}, "max_simulations"), ({"tolerance": 0}, "tolerance"), ({"tolerance": -1.0}, "tolerance"), ({"target_confidence": 1.5}, "target_confidence"), @@ -541,6 +543,7 @@ def __init__(self, width_model): self.filename = pathlib.Path("dummy_mc") self._width_model = width_model self.simulate_calls = 0 + self.estimate_calls = [] def import_outputs(self, *args, **kwargs): # no-op, avoids file I/O pass @@ -552,6 +555,7 @@ def simulate(self, number_of_simulations, append=True, **kwargs): def estimate_confidence_interval(self, attribute, confidence_level=0.95, **kwargs): # pylint: disable=arguments-differ,unused-argument + self.estimate_calls.append(self.num_of_loaded_sims) width = self._width_model(self.num_of_loaded_sims) return _CI(low=0.0, high=width) @@ -575,6 +579,80 @@ def test_simulate_convergence_stops_early_when_tolerance_met(): assert mc.num_of_loaded_sims < 1000 # did not exhaust the simulation budget +def test_simulate_convergence_never_estimates_from_a_single_result(): + """A fresh study with batch_size=1 must wait for its second result. + + ``scipy.stats.bootstrap`` needs two or more observations, so the first + batch of a one-row-per-batch study could not be summarised (#1229). + """ + mc = ConvergenceMockMonteCarlo(width_model=lambda n: 10.0) + + history = mc.simulate_convergence( + target_attribute="apogee_time", + tolerance=0.5, + max_simulations=4, + batch_size=1, + ) + + assert mc.simulate_calls == 4 + assert mc.estimate_calls == [2, 3, 4] # never a lone observation + assert len(history) == 3 + + +def test_simulate_convergence_accepts_the_smallest_budget(): + """max_simulations=2 is the smallest budget that yields one width.""" + mc = ConvergenceMockMonteCarlo(width_model=lambda n: 10.0) + + history = mc.simulate_convergence( + target_attribute="apogee_time", + tolerance=0.5, + max_simulations=2, + batch_size=1, + ) + + assert mc.simulate_calls == 2 + assert mc.estimate_calls == [2] + assert len(history) == 1 + + +def test_simulate_convergence_waits_for_the_minimum_number_of_results(): + """A loose tolerance must not accept the width of a lucky pair of results. + + The first width is computed at two results, and a bootstrap interval on two + draws is roughly the gap between them, so two flights that happen to land + close together would look converged (#1233). The tolerance is only accepted + once the study holds ``MIN_RESULTS_FOR_CONVERGENCE`` results. + """ + mc = ConvergenceMockMonteCarlo(width_model=lambda n: 0.1) # always inside tolerance + + history = mc.simulate_convergence( + target_attribute="apogee_time", + tolerance=0.5, + max_simulations=MIN_RESULTS_FOR_CONVERGENCE, + batch_size=1, + ) + + assert mc.num_of_loaded_sims == MIN_RESULTS_FOR_CONVERGENCE + assert mc.estimate_calls == list(range(2, MIN_RESULTS_FOR_CONVERGENCE + 1)) + assert history == [0.1] * (MIN_RESULTS_FOR_CONVERGENCE - 1) + + +def test_simulate_convergence_stops_at_the_floor_of_a_single_batch(): + """A batch that meets the floor exactly must be allowed to stop the study.""" + mc = ConvergenceMockMonteCarlo(width_model=lambda n: 0.1) + + history = mc.simulate_convergence( + target_attribute="apogee_time", + tolerance=0.5, + max_simulations=2 * MIN_RESULTS_FOR_CONVERGENCE, + batch_size=MIN_RESULTS_FOR_CONVERGENCE, + ) + + assert mc.simulate_calls == 1 + assert mc.num_of_loaded_sims == MIN_RESULTS_FOR_CONVERGENCE + assert history == [0.1] + + 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."""