Skip to content
Merged
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
34 changes: 22 additions & 12 deletions rocketpy/rocket/parachute.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,6 @@ def __init__(
height=None,
porosity=0.0432,
drag_coefficient=1.4,
seed=None,
):
"""Initializes Parachute class.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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
18 changes: 12 additions & 6 deletions rocketpy/stochastic/stochastic_parachute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
77 changes: 69 additions & 8 deletions tests/unit/rocket/test_parachute_noise_seed.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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():
Expand All @@ -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
)
16 changes: 7 additions & 9 deletions tests/unit/simulation/test_monte_carlo_seeding.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import io
import json
import os
from time import time
Expand Down Expand Up @@ -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
Expand Down
Loading