diff --git a/rocketpy/rocket/parachute.py b/rocketpy/rocket/parachute.py index bef27a6a5..6fe3c498f 100644 --- a/rocketpy/rocket/parachute.py +++ b/rocketpy/rocket/parachute.py @@ -167,7 +167,6 @@ def __init__( height=None, porosity=0.0432, drag_coefficient=1.4, - seed=None, ): """Initializes Parachute class. @@ -224,7 +223,9 @@ def __init__( List in the format (mean, standard deviation, time-correlation). The values are used to add noise to the pressure signal which is passed to the trigger function. Default value is ``(0, 0, 0)``. - Units are in Pa. + Units are in Pa. The noise is reproducible only through the seed a + ``MonteCarlo`` run records, or with ``from_dict`` on a dict that + carries one; ``numpy.random.seed`` does not affect it. radius : float, optional Length of the non-unique semi-axis (radius) of the inflated hemispheroid parachute. If not provided, it is estimated from @@ -253,12 +254,6 @@ def __init__( - **1.5** — extended-skirt canopy Has no effect when ``radius`` is explicitly provided. - seed : int, array_like, SeedSequence, BitGenerator, Generator or None, optional - Seed for the per-instance NumPy Generator used by pressure noise. - A fixed seed makes the noise reproducible and independent of the - process-global NumPy RNG (and therefore usable under Monte Carlo). - ``None`` keeps the noise random but still drawn from this instance's - generator. Default is ``None``. """ # Save arguments as attributes @@ -273,8 +268,8 @@ def __init__( # Per-instance RNG: pressure noise must not draw from the process-global # NumPy RNG, or Monte Carlo cannot reproduce deployment (see #1091). - self._seed = seed - self._rng = np.random.default_rng(seed) + self._seed = None + self._rng = np.random.default_rng() # Initialize derived attributes self.radius = self.__resolve_radius(radius, cd_s, drag_coefficient) @@ -314,11 +309,11 @@ def __init_noise(self, noise): noise : tuple, list List in the format (mean, standard deviation, time-correlation). """ - self.noise_signal = [[-1e-6, self._rng.normal(noise[0], noise[1])]] self.noisy_pressure_signal = [] self.clean_pressure_signal = [] self.noise_bias = noise[0] self.noise_deviation = noise[1] + self.__draw_initial_noise() self.noise_corr = (noise[2], (1 - noise[2] ** 2) ** 0.5) self.clean_pressure_signal_function = Function(0) self.noisy_pressure_signal_function = Function(0) @@ -332,6 +327,19 @@ def __init_noise(self, noise): + beta * self._rng.normal(noise[0], noise[1]) ) + def __draw_initial_noise(self): + """Starts the noise signal with one sample from the current RNG.""" + self.noise_signal = [ + [-1e-6, self._rng.normal(self.noise_bias, self.noise_deviation)] + ] + + def _set_noise_seed(self, seed): + """Reseeds the noise and redraws the unseeded first sample, before any + Flight. Used by ``StochasticParachute`` and ``from_dict``.""" + self._seed = seed + self._rng = np.random.default_rng(seed) + self.__draw_initial_noise() + def __evaluate_trigger_function(self, trigger): # pylint: disable=too-many-statements """This is used to set the triggerfunc attribute that will be used to interact with the Flight class. @@ -559,7 +567,9 @@ def from_dict(cls, data): drag_coefficient=data.get("drag_coefficient", 1.4), height=data.get("height", None), porosity=data.get("porosity", 0.0432), - seed=data.get("seed", None), ) + # Dicts written before the seed was recorded have none. + if data.get("seed") is not None: + parachute._set_noise_seed(data["seed"]) return parachute diff --git a/rocketpy/stochastic/stochastic_parachute.py b/rocketpy/stochastic/stochastic_parachute.py index 6ff3775be..c654e799d 100644 --- a/rocketpy/stochastic/stochastic_parachute.py +++ b/rocketpy/stochastic/stochastic_parachute.py @@ -207,11 +207,17 @@ def create_object(self): # Tie pressure noise into the Monte Carlo seed tree when one is set. # Key by parachute name so drogue and main on the same rocket do not # share one noise stream. + noise_seed = None if self._seed is not None: - generated_dict["seed"] = _sampler_seed( + # Cut to 63 bits: the seed is recorded in the inputs, and pandas + # reads JSON integers as int64. + noise_seed = _sampler_seed( self._seed, ("pressure_noise", generated_dict["name"]) - ) - # Recorded after the seed is in, or the inputs describe a parachute - # with noise nobody can reproduce. - self._record_draw(generated_dict) - return Parachute(**generated_dict) + ) & (2**63 - 1) + # Recorded with the seed, or the inputs describe a parachute with + # noise nobody can reproduce. Rebuild it with Parachute.from_dict. + self._record_draw({**generated_dict, "seed": noise_seed}) + parachute = Parachute(**generated_dict) + if noise_seed is not None: + parachute._set_noise_seed(noise_seed) + return parachute diff --git a/tests/unit/rocket/test_parachute_noise_seed.py b/tests/unit/rocket/test_parachute_noise_seed.py index 1cd702eaf..0e051d6e8 100644 --- a/tests/unit/rocket/test_parachute_noise_seed.py +++ b/tests/unit/rocket/test_parachute_noise_seed.py @@ -1,25 +1,28 @@ """Determinism tests for seeded parachute pressure noise (#1091). -Pressure noise is drawn from a per-instance ``numpy.random.Generator`` created -from the ``seed`` argument, instead of the process-global ``numpy.random``. -A seed makes the noise reproducible and independent of the global RNG state. +Pressure noise is drawn from a per-instance ``numpy.random.Generator`` instead +of the process-global ``numpy.random``. The seed is private: only +``StochasticParachute`` and ``from_dict`` set it, after construction. """ import numpy as np +import pytest from rocketpy import Parachute from rocketpy.stochastic import StochasticParachute -def _parachute(seed, noise=(0, 8.3, 0.5)): - return Parachute( - name="main", +def _parachute(seed, noise=(0, 8.3, 0.5), name="main"): + parachute = Parachute( + name=name, cd_s=10.0, trigger="apogee", sampling_rate=100, noise=noise, - seed=seed, ) + if seed is not None: + parachute._set_noise_seed(seed) + return parachute def _noise_sequence(parachute, n=16): @@ -80,7 +83,27 @@ def test_seed_survives_serialization_round_trip(): def test_from_dict_defaults_seed_to_none_when_absent(): data = _parachute(11).to_dict() del data["seed"] - assert Parachute.from_dict(data).to_dict()["seed"] is None + restored = Parachute.from_dict(data) + assert restored.to_dict()["seed"] is None + assert any(sample != 0.0 for sample in _noise_sequence(restored)) + + +def test_seed_is_not_a_constructor_argument(): + with pytest.raises(TypeError, match="seed"): + Parachute( # pylint: disable=unexpected-keyword-arg + name="main", + cd_s=10.0, + trigger="apogee", + sampling_rate=100, + seed=1, + ) + + +def test_set_noise_seed_redraws_the_initial_noise_sample(): + """The sample taken at construction came from an unseeded generator.""" + seeded = _parachute(5) + assert seeded.noise_signal[0][1] == _parachute(5).noise_signal[0][1] + assert len(seeded.noise_signal) == 1 def test_stochastic_parachute_threads_seed_into_created_object(): @@ -98,3 +121,41 @@ def test_stochastic_parachute_threads_seed_into_created_object(): other = stochastic.create_object() assert other._seed != first._seed assert _noise_sequence(other) != _noise_sequence(first) + + +# Noise seeds a StochasticParachute seeded with 123 derives, pinned so a change +# to the derivation shows up here. +_PINNED_SEEDS = {"main": 6639568465033922193, "drogue": 6152077226054995121} + + +def _expected_noise(seed, mean, deviation, correlation, n): + """The AR(1) chain from a fresh generator, independent of NumPy's stream.""" + rng = np.random.default_rng(seed) + samples = [rng.normal(mean, deviation)] + for _ in range(n): + samples.append( + correlation * samples[-1] + + (1 - correlation**2) ** 0.5 * rng.normal(mean, deviation) + ) + return samples + + +@pytest.mark.parametrize("name", ["main", "drogue"]) +def test_stochastic_parachute_noise_follows_the_pinned_seed(name): + stochastic = StochasticParachute( + Parachute( + name=name, + cd_s=10.0, + trigger="apogee", + sampling_rate=100, + noise=(0, 8.3, 0.5), + ) + ) + stochastic._set_stochastic(seed=123) + + built = stochastic.create_object() + + assert built._seed == _PINNED_SEEDS[name] + assert _noise_sequence(built, n=6) == pytest.approx( + _expected_noise(_PINNED_SEEDS[name], 0, 8.3, 0.5, n=6), rel=1e-12 + ) diff --git a/tests/unit/simulation/test_monte_carlo_seeding.py b/tests/unit/simulation/test_monte_carlo_seeding.py index 798eaaa98..11a2054cc 100644 --- a/tests/unit/simulation/test_monte_carlo_seeding.py +++ b/tests/unit/simulation/test_monte_carlo_seeding.py @@ -1,4 +1,3 @@ -import io import json import os from time import time @@ -96,17 +95,16 @@ def test_study_seed_rejects_negative_values(): _study_seed(-1) -def test_a_generated_study_seed_lets_pandas_read_the_logs(): - """Every row carries the seed, and pandas reads JSON integers as int64.""" +def test_pandas_reads_the_inputs_of_an_unseeded_run(models, tmp_path): + """Rows carry the study seed and each parachute's noise seed, and pandas + reads JSON integers as int64.""" pandas = pytest.importorskip("pandas") - rows = "".join( - json.dumps({"index": index, "seed": _study_seed(None)}) + "\n" - for index in range(20) - ) + analysis = _a_run(tmp_path, "study", models, count=2) - logs = pandas.read_json(io.StringIO(rows), lines=True) + logs = pandas.read_json(analysis.input_file, lines=True) - assert len(logs) == 20 + assert len(logs) == 2 + assert all("seed" in parachute for parachute in logs["parachutes"][0]) @pytest.mark.slow