Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions rocketpy/simulation/monte_carlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With batch_size=1, the study can now stop as converged after only two simulations.

The first width is computed at n=2, and a bootstrap interval on two draws is roughly the gap between them. With tolerance=0.5, two flights whose apogee_time lands 0.3 s apart pass width <= tolerance at line 1061, and the loop returns after 2 flights. batch_size=2 already behaved like this, but this PR opens the same path for batch_size=1. Could the tolerance check wait for a minimum number of results (a small floor, separate from the bootstrap minimum of 2), or the docstring at least warn that small batches can stop this early?

continue
Comment thread
Gui-FernandesBR marked this conversation as resolved.
Resolved

ci = self.estimate_confidence_interval(
attribute=target_attribute,
confidence_level=target_confidence,
Expand Down
29 changes: 29 additions & 0 deletions tests/integration/simulation/test_monte_carlo_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Comment thread
Gui-FernandesBR marked this conversation as resolved.
Resolved
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)
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/simulation/test_monte_carlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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
Expand All @@ -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)

Expand All @@ -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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test covers max_simulations=2, the smallest valid budget, so a regression of the check to <= 2 would not fail any test.

Suggested change
assert len(history) == 3
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_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."""
Expand Down
Loading