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
7 changes: 4 additions & 3 deletions rocketpy/simulation/monte_carlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -1557,11 +1557,12 @@ def set_num_of_loaded_sims(self):
"""
fmt = self._detect_file_format(self.output_file)
with open(self.output_file, mode="r", encoding="utf-8") as outputs:
# Blank lines are skipped, as in _read_log_file
if fmt == "jsonl":
self.num_of_loaded_sims = sum(1 for _ in outputs)
self.num_of_loaded_sims = sum(1 for line in outputs if line.strip())
elif fmt == "csv":
# Subtract 1 for the header row
self.num_of_loaded_sims = max(0, sum(1 for _ in outputs) - 1)
# DictReader consumes the header row and skips blank rows
self.num_of_loaded_sims = sum(1 for _ in csv.DictReader(outputs))
elif fmt == "json":
content = outputs.read().strip()
if content:
Expand Down
51 changes: 51 additions & 0 deletions tests/unit/simulation/test_monte_carlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,57 @@ def test_set_num_of_loaded_sims_json(tmp_path):
assert mc.num_of_loaded_sims == 3


@pytest.mark.parametrize(
"extension, content",
[
(
"txt",
'{"index": 0, "apogee": 1.0}\n\n{"index": 1, "apogee": 2.0}\n\n',
),
("csv", "index,apogee\n0,1.0\n\n1,2.0\n\n"),
],
ids=["jsonl", "csv"],
)
def test_set_num_of_loaded_sims_skips_blank_lines(tmp_path, extension, content):
"""Tests that blank lines of an outputs log are not counted as simulations,
so that num_of_loaded_sims matches the rows read into outputs_log."""
mc = MockMonteCarloWithLogs()
filepath = tmp_path / f"outputs.{extension}"
filepath.write_text(content, encoding="utf-8")

mc._output_file = str(filepath)
mc.set_outputs_log()
mc.set_num_of_loaded_sims()

assert len(mc.outputs_log) == 2
assert mc.num_of_loaded_sims == 2


def test_simulate_convergence_runs_after_a_log_with_blank_lines(tmp_path):
"""Tests that blank lines in a loaded outputs log do not use up the
simulation budget of simulate_convergence."""
(tmp_path / "study.outputs.txt").write_text(
'{"index": 0, "apogee": 1.0}\n\n{"index": 1, "apogee": 2.0}\n\n',
encoding="utf-8",
)

def simulate(**kwargs):
raise RuntimeError("simulate called")

mc = MonteCarlo.__new__(MonteCarlo)
mc.filename = tmp_path / "study"
mc.simulate = simulate

with pytest.raises(RuntimeError, match="simulate called"):
mc.simulate_convergence(
target_attribute="apogee",
tolerance=1e-9,
max_simulations=4,
batch_size=2,
)
assert mc.num_of_loaded_sims == 2


# --- Adaptive Monte Carlo convergence (PR #922) ---

_CI = namedtuple("_CI", ["low", "high"])
Expand Down
Loading