diff --git a/rocketpy/simulation/monte_carlo.py b/rocketpy/simulation/monte_carlo.py index d7ce21f94..77fb92e4d 100644 --- a/rocketpy/simulation/monte_carlo.py +++ b/rocketpy/simulation/monte_carlo.py @@ -970,7 +970,9 @@ def simulate_convergence( tolerance : float, optional The desired width of the confidence interval in seconds, meters, or other units. 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. Default is 1000. batch_size : int, optional The number of simulations to run in each batch. Default is 50. parallel : bool, optional @@ -984,9 +986,12 @@ 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. 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 +1000,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 +1032,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, 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..8bdd9632e 100644 --- a/tests/unit/simulation/test_monte_carlo.py +++ b/tests/unit/simulation/test_monte_carlo.py @@ -238,6 +238,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 +542,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 +554,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 +578,26 @@ 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_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."""