From 94abad4578aa3cbeaac724cea977677decab9610 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 28 Nov 2026 20:14:46 -0300 Subject: [PATCH 1/6] MNT: drop the deprecated static_margin setter The static margin is computed from the rocket, and assigning it was never documented. Assigning it raises AttributeError again. Co-Authored-By: Claude Opus 5.5 --- rocketpy/rocket/rocket.py | 18 ------------ tests/unit/rocket/test_rocket.py | 49 ++------------------------------ 2 files changed, 3 insertions(+), 64 deletions(-) diff --git a/rocketpy/rocket/rocket.py b/rocketpy/rocket/rocket.py index a7e790813..702c238be 100644 --- a/rocketpy/rocket/rocket.py +++ b/rocketpy/rocket/rocket.py @@ -763,19 +763,6 @@ def static_margin(self): self.evaluate_static_margin() return self._static_margin - @static_margin.setter - @deprecated( - reason=( - "Assigning `static_margin` is deprecated and will be removed in a " - "future version, because the static margin is computed from the " - "rocket's geometry" - ) - ) - def static_margin(self, value): - # Kept until the next geometry/mass/surface change marks it dirty. - self._static_margin = value - self._static_margin_dirty = False - def evaluate_static_margin(self): """Calculates the static margin of the rocket as a function of time. @@ -786,11 +773,6 @@ def evaluate_static_margin(self): Static margin is defined as the distance between the center of pressure and the center of mass, divided by the rocket's diameter. """ - # An assigned non-Function value (e.g. a float) cannot be updated in place. - if not isinstance(self._static_margin, Function): - self._static_margin = Function( - lambda time: 0, inputs="Time (s)", outputs="Static Margin (c)" - ) # Calculate static margin; fold _csys into the source so we do not # rebind a property when multiplying. self._static_margin.set_source( diff --git a/tests/unit/rocket/test_rocket.py b/tests/unit/rocket/test_rocket.py index b14d086e3..832022504 100644 --- a/tests/unit/rocket/test_rocket.py +++ b/tests/unit/rocket/test_rocket.py @@ -92,54 +92,11 @@ def test_static_margin_rebuilds_after_adding_surface(calisto): assert margin_after != pytest.approx(margin_before, abs=1e-6) -def test_static_margin_assignment_warns_and_is_returned(calisto): - """Assigning static_margin warns at the caller's line and sticks.""" - with pytest.warns(DeprecationWarning, match="static_margin") as record: +def test_static_margin_cannot_be_assigned(calisto): + """The static margin is computed from the rocket, so it cannot be set.""" + with pytest.raises(AttributeError): calisto.static_margin = 2.0 - assert len(record) == 1 - assert record[0].filename == __file__ - assert "will be removed in a future version" in str(record[0].message) - assert calisto.static_margin == 2.0 - - -def test_static_margin_assignment_is_recomputed_after_geometry_change(calisto): - """A later surface change discards an assigned value, as evaluate does.""" - with pytest.warns(DeprecationWarning): - calisto.static_margin = 2.0 - - calisto.add_nose(length=0.55829, kind="ogive", position=1.160) - - margin = calisto.static_margin - assert isinstance(margin, Function) - assert margin(0) != pytest.approx(2.0, abs=1e-6) - - -def test_evaluate_static_margin_overwrites_assigned_value(calisto): - """Explicit evaluate_static_margin replaces an assigned float.""" - expected = calisto.static_margin(0) - with pytest.warns(DeprecationWarning): - calisto.static_margin = 2.0 - - calisto.evaluate_static_margin() - - assert calisto.static_margin(0) == pytest.approx(expected, abs=1e-8) - - -def test_static_margin_internal_use_does_not_warn(calisto_motorless): - """Building and updating a rocket never triggers the assignment warning.""" - rocket = calisto_motorless - with warnings.catch_warnings(): - warnings.simplefilter("error", DeprecationWarning) - rocket.add_nose(length=0.55829, kind="ogive", position=1.160) - rocket.add_trapezoidal_fins( - 4, span=0.100, root_chord=0.120, tip_chord=0.040, position=-1.04956 - ) - _ = rocket.static_margin(0) - rocket.evaluate_static_margin() - rocket.static_margin.get_value_opt(0) - rocket.to_dict() - @pytest.mark.parametrize( "k, type_", From 3b4c7ad1620d7cf1f31d19b238bc0ac5edd5db72 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 28 Nov 2026 20:14:46 -0300 Subject: [PATCH 2/6] MNT: simplify the sensor seed check Replace the seed type alias, its two helpers and the type hints with one check that rejects random generator objects, and shorten the comments, the error message and the seed docstrings. NumPy rejects any other invalid seed. Co-Authored-By: Claude Opus 5.5 --- rocketpy/sensors/accelerometer.py | 16 +-- rocketpy/sensors/barometer.py | 16 +-- rocketpy/sensors/gnss_receiver.py | 16 +-- rocketpy/sensors/gyroscope.py | 16 +-- rocketpy/sensors/sensor.py | 139 ++++--------------- tests/unit/sensors/test_sensor_validation.py | 30 +--- 6 files changed, 60 insertions(+), 173 deletions(-) diff --git a/rocketpy/sensors/accelerometer.py b/rocketpy/sensors/accelerometer.py index 88b641a74..d60737272 100644 --- a/rocketpy/sensors/accelerometer.py +++ b/rocketpy/sensors/accelerometer.py @@ -2,7 +2,7 @@ from ..mathutils.vector_matrix import Matrix, Vector from ..prints.sensors_prints import _InertialSensorPrints -from ..sensors.sensor import InertialSensor, SeedLike +from ..sensors.sensor import InertialSensor # pylint: disable=too-many-arguments @@ -79,7 +79,7 @@ def __init__( cross_axis_sensitivity=0, consider_gravity=False, name="Accelerometer", - seed: SeedLike | None = None, + seed=None, ): """ Initialize the accelerometer sensor @@ -174,14 +174,12 @@ def __init__( which is zero at rest. Default is False. name : str, optional The name of the sensor. Default is "Accelerometer". - seed : int, array_like of ints, numpy.random.SeedSequence, optional + seed : int, list of ints or numpy.random.SeedSequence, optional Seed for the random number generator that draws the measurement - noise. If given, the noise becomes reproducible and independent of - the process-global NumPy RNG. Only seeds that describe a stream are - taken: live ``Generator``, ``BitGenerator`` and ``RandomState`` - objects are rejected, because their state advances as noise is - drawn and so cannot be represented in ``to_dict()``. Default is - None, meaning the noise is seeded from fresh entropy per instance. + noise. If given, the noise is reproducible. Random generator + objects (``numpy.random.Generator``, ``BitGenerator`` or + ``RandomState``) are not accepted, because they cannot be saved. + Default is None, meaning the noise is drawn from a new random seed. Returns ------- diff --git a/rocketpy/sensors/barometer.py b/rocketpy/sensors/barometer.py index 593be2fc9..1d8b7526d 100644 --- a/rocketpy/sensors/barometer.py +++ b/rocketpy/sensors/barometer.py @@ -2,7 +2,7 @@ from ..mathutils.vector_matrix import Matrix from ..prints.sensors_prints import _SensorPrints -from ..sensors.sensor import ScalarSensor, SeedLike +from ..sensors.sensor import ScalarSensor class Barometer(ScalarSensor): @@ -62,7 +62,7 @@ def __init__( temperature_bias=0, temperature_scale_factor=0, name="Barometer", - seed: SeedLike | None = None, + seed=None, ): """ Initialize the barometer sensor @@ -111,14 +111,12 @@ def __init__( meaning no temperature scale factor is applied. name : str, optional The name of the sensor. Default is "Barometer". - seed : int, array_like of ints, numpy.random.SeedSequence, optional + seed : int, list of ints or numpy.random.SeedSequence, optional Seed for the random number generator that draws the measurement - noise. If given, the noise becomes reproducible and independent of - the process-global NumPy RNG. Only seeds that describe a stream are - taken: live ``Generator``, ``BitGenerator`` and ``RandomState`` - objects are rejected, because their state advances as noise is - drawn and so cannot be represented in ``to_dict()``. Default is - None, meaning the noise is seeded from fresh entropy per instance. + noise. If given, the noise is reproducible. Random generator + objects (``numpy.random.Generator``, ``BitGenerator`` or + ``RandomState``) are not accepted, because they cannot be saved. + Default is None, meaning the noise is drawn from a new random seed. Returns ------- diff --git a/rocketpy/sensors/gnss_receiver.py b/rocketpy/sensors/gnss_receiver.py index d7978280d..db76e9524 100644 --- a/rocketpy/sensors/gnss_receiver.py +++ b/rocketpy/sensors/gnss_receiver.py @@ -4,7 +4,7 @@ from ..mathutils.vector_matrix import Matrix, Vector from ..prints.sensors_prints import _GnssReceiverPrints -from .sensor import ScalarSensor, SeedLike +from .sensor import ScalarSensor class GnssReceiver(ScalarSensor): @@ -38,7 +38,7 @@ def __init__( position_accuracy=0, altitude_accuracy=0, name="GnssReceiver", - seed: SeedLike | None = None, + seed=None, ): """Initialize the Gnss Receiver sensor. @@ -54,14 +54,12 @@ def __init__( position in meters. Default is 0. name : str The name of the sensor. Default is "GnssReceiver". - seed : int, array_like of ints, numpy.random.SeedSequence, optional + seed : int, list of ints or numpy.random.SeedSequence, optional Seed for the random number generator that draws the measurement - noise. If given, the noise becomes reproducible and independent of - the process-global NumPy RNG. Only seeds that describe a stream are - taken: live ``Generator``, ``BitGenerator`` and ``RandomState`` - objects are rejected, because their state advances as noise is - drawn and so cannot be represented in ``to_dict()``. Default is - None, meaning the noise is seeded from fresh entropy per instance. + noise. If given, the noise is reproducible. Random generator + objects (``numpy.random.Generator``, ``BitGenerator`` or + ``RandomState``) are not accepted, because they cannot be saved. + Default is None, meaning the noise is drawn from a new random seed. """ super().__init__(sampling_rate=sampling_rate, name=name, seed=seed) self.position_accuracy = position_accuracy diff --git a/rocketpy/sensors/gyroscope.py b/rocketpy/sensors/gyroscope.py index 579c9f6da..1f933ef84 100644 --- a/rocketpy/sensors/gyroscope.py +++ b/rocketpy/sensors/gyroscope.py @@ -2,7 +2,7 @@ from ..mathutils.vector_matrix import Vector from ..prints.sensors_prints import _GyroscopePrints -from ..sensors.sensor import InertialSensor, SeedLike +from ..sensors.sensor import InertialSensor # pylint: disable=too-many-arguments @@ -78,7 +78,7 @@ def __init__( cross_axis_sensitivity=0, acceleration_sensitivity=0, name="Gyroscope", - seed: SeedLike | None = None, + seed=None, ): """ Initialize the gyroscope sensor @@ -172,14 +172,12 @@ def __init__( length 3. name : str, optional The name of the sensor. Default is "Gyroscope". - seed : int, array_like of ints, numpy.random.SeedSequence, optional + seed : int, list of ints or numpy.random.SeedSequence, optional Seed for the random number generator that draws the measurement - noise. If given, the noise becomes reproducible and independent of - the process-global NumPy RNG. Only seeds that describe a stream are - taken: live ``Generator``, ``BitGenerator`` and ``RandomState`` - objects are rejected, because their state advances as noise is - drawn and so cannot be represented in ``to_dict()``. Default is - None, meaning the noise is seeded from fresh entropy per instance. + noise. If given, the noise is reproducible. Random generator + objects (``numpy.random.Generator``, ``BitGenerator`` or + ``RandomState``) are not accepted, because they cannot be saved. + Default is None, meaning the noise is drawn from a new random seed. Returns ------- diff --git a/rocketpy/sensors/sensor.py b/rocketpy/sensors/sensor.py index 4e83ff9d8..31e8f9fce 100644 --- a/rocketpy/sensors/sensor.py +++ b/rocketpy/sensors/sensor.py @@ -2,7 +2,6 @@ import logging import warnings from abc import ABC, abstractmethod -from collections.abc import Sequence import numpy as np @@ -10,47 +9,6 @@ logger = logging.getLogger(__name__) -# The seed kinds that describe a stream, and so survive a to_dict() round trip. -# Named once because every concrete sensor repeats it in its signature; it is a -# union, so help() and inspect.signature() still show the members in full. -SeedLike = int | np.integer | Sequence[int] | np.ndarray | np.random.SeedSequence - - -def _is_int_array_like(value): - """Whether ``value`` is an int or a flat sequence of ints. - - This is the half of ``numpy.random.default_rng``'s seed contract that - ``RocketPyEncoder`` can write out: integers keep their value across a JSON - round trip, so a seed read back names the same stream it named before. - - Flat, because that is all ``SeedSequence`` takes as entropy: a nested - sequence raises ``TypeError`` and a multi-dimensional array ``ValueError``, - neither of them naming the seed. Older NumPy let some of those through, - and RocketPy pins no upper bound, so they are refused here to keep one - answer across versions. - """ - if isinstance(value, (int, np.integer)): - return True - if isinstance(value, np.ndarray): - return np.issubdtype(value.dtype, np.integer) and value.ndim <= 1 - if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): - return all(isinstance(item, (int, np.integer)) for item in value) - return False - - -def _is_seed_descriptor(seed): - """Whether ``seed`` describes a random stream rather than being one. - - ``SeedSequence`` counts because it is defined by its entropy and spawn key, - and #1124 taught ``RocketPyEncoder`` to serialize it, so it still names the - same stream after a round trip. - """ - return ( - seed is None - or isinstance(seed, np.random.SeedSequence) - or _is_int_array_like(seed) - ) - # pylint: disable=too-many-statements class Sensor(ABC): @@ -104,7 +62,7 @@ def __init__( temperature_bias=0, temperature_scale_factor=0, name="Sensor", - seed: SeedLike | None = None, + seed=None, ): """ Initialize the accelerometer sensor @@ -154,17 +112,12 @@ def __init__( meaning no temperature scale factor is applied. name : str, optional The name of the sensor. Default is "Sensor". - seed : int, array_like of ints, numpy.random.SeedSequence, optional + seed : int, list of ints or numpy.random.SeedSequence, optional Seed for the random number generator that draws the measurement - noise. If given, the noise becomes reproducible and independent of - the process-global NumPy RNG. A ``numpy.random.SeedSequence`` is - also accepted and round trips through ``RocketPyEncoder``. Only - seeds that describe a stream are taken: the live ``Generator``, - ``BitGenerator`` and ``RandomState`` objects that - ``numpy.random.default_rng`` also accepts are rejected here, - because their state advances as noise is drawn and so cannot be - represented in the dictionary returned by ``to_dict()``. Default is - None, meaning the noise is seeded from fresh entropy per instance. + noise. If given, the noise is reproducible. Random generator + objects (``numpy.random.Generator``, ``BitGenerator`` or + ``RandomState``) are not accepted, because they cannot be saved. + Default is None, meaning the noise is drawn from a new random seed. Returns ------- @@ -173,14 +126,20 @@ def __init__( Raises ------ TypeError - If ``seed`` is not an int, an array_like of ints, a - ``SeedSequence`` or None -- in particular if it is a live - ``Generator``, ``BitGenerator`` or ``RandomState``. + If ``seed`` is a random generator object. See Also -------- TODO link to documentation on noise model """ + if isinstance( + seed, (np.random.Generator, np.random.BitGenerator, np.random.RandomState) + ): + raise TypeError( + "A sensor seed must be an int, a list of ints or a numpy " + "SeedSequence. Random generator objects are not accepted because " + "they cannot be saved." + ) warnings.warn( "The Sensor class (and all its subclasses) is still under " "experimental development. Some features may be changed in future " @@ -206,45 +165,7 @@ def __init__( self._random_walk_drift = 0 self.normal_vector = Vector([0, 0, 0]) - # default_rng() takes two different kinds of argument. One describes a - # stream -- an int, an array_like of ints, a SeedSequence -- and can be - # written down and read back. The other is a stream already in - # progress: Generator, BitGenerator, and, since NumPy 2.2, RandomState. - # Their state advances on every draw, so what to_dict() writes is a - # snapshot of the moment it ran rather than the stream the sensor used. - # #1124 taught RocketPyEncoder to serialize a SeedSequence, which stays - # reproducible because it is defined by its entropy and spawn key; a - # live generator has no such description to write. - # - # The check names the descriptors instead of the live types because the - # descriptors are the stable half of that contract: a seed kind numpy - # starts accepting later is refused here rather than reaching - # json.dumps(). Without it the sensor builds fine and only fails at - # serialization, far from the call that caused it. - if isinstance( - seed, - (np.random.Generator, np.random.BitGenerator, np.random.RandomState), - ): - raise TypeError( - f"Invalid seed type '{type(seed).__name__}'. The seed must be " - "an int, an array_like of ints, a numpy.random.SeedSequence or " - "None. numpy.random.default_rng also accepts Generator, " - "BitGenerator and RandomState objects, but their state advances " - "as noise is drawn, so they cannot be represented in the " - "dictionary to_dict() returns." - ) - if not _is_seed_descriptor(seed): - raise TypeError( - f"Invalid seed type '{type(seed).__name__}'. The seed must be " - "an int, an array_like of ints, a numpy.random.SeedSequence or " - "None, so that to_dict() can write it out." - ) - - # Per-instance RNG, seeded deterministically when a seed is given, so - # the measurement noise is reproducible and independent of the - # process-global NumPy RNG (and therefore safe under parallel or - # forked evaluation). seed=None keeps the noise random but still - # drawn from this instance's generator. + # Each sensor draws its noise from its own generator self._seed = seed self._rng = np.random.default_rng(seed) @@ -462,7 +383,7 @@ def __init__( temperature_scale_factor=0, cross_axis_sensitivity=0, name="Sensor", - seed: SeedLike | None = None, + seed=None, ): """ Initialize the accelerometer sensor @@ -549,14 +470,12 @@ def __init__( no cross-axis sensitivity is applied. name : str, optional The name of the sensor. Default is "Sensor". - seed : int, array_like of ints, numpy.random.SeedSequence, optional + seed : int, list of ints or numpy.random.SeedSequence, optional Seed for the random number generator that draws the measurement - noise. If given, the noise becomes reproducible and independent of - the process-global NumPy RNG. Only seeds that describe a stream are - taken: live ``Generator``, ``BitGenerator`` and ``RandomState`` - objects are rejected, because their state advances as noise is - drawn and so cannot be represented in ``to_dict()``. Default is - None, meaning the noise is seeded from fresh entropy per instance. + noise. If given, the noise is reproducible. Random generator + objects (``numpy.random.Generator``, ``BitGenerator`` or + ``RandomState``) are not accepted, because they cannot be saved. + Default is None, meaning the noise is drawn from a new random seed. Returns ------- @@ -774,7 +693,7 @@ def __init__( temperature_bias=0, temperature_scale_factor=0, name="Sensor", - seed: SeedLike | None = None, + seed=None, ): """ Initialize the accelerometer sensor @@ -824,14 +743,12 @@ def __init__( meaning no temperature scale factor is applied. name : str, optional The name of the sensor. Default is "Sensor". - seed : int, array_like of ints, numpy.random.SeedSequence, optional + seed : int, list of ints or numpy.random.SeedSequence, optional Seed for the random number generator that draws the measurement - noise. If given, the noise becomes reproducible and independent of - the process-global NumPy RNG. Only seeds that describe a stream are - taken: live ``Generator``, ``BitGenerator`` and ``RandomState`` - objects are rejected, because their state advances as noise is - drawn and so cannot be represented in ``to_dict()``. Default is - None, meaning the noise is seeded from fresh entropy per instance. + noise. If given, the noise is reproducible. Random generator + objects (``numpy.random.Generator``, ``BitGenerator`` or + ``RandomState``) are not accepted, because they cannot be saved. + Default is None, meaning the noise is drawn from a new random seed. Returns ------- diff --git a/tests/unit/sensors/test_sensor_validation.py b/tests/unit/sensors/test_sensor_validation.py index 18a0de44e..2e3a61247 100644 --- a/tests/unit/sensors/test_sensor_validation.py +++ b/tests/unit/sensors/test_sensor_validation.py @@ -67,14 +67,9 @@ def test_live_rng_objects_are_rejected(seed): ["5", 5.0, np.float64(5), np.bool_(True), object()], ids=["str", "float", "numpy_float", "numpy_bool", "object"], ) -def test_non_descriptor_seeds_are_rejected(seed): - """Anything that is neither a live RNG nor a stream descriptor is refused. - - ``default_rng`` rejects these too, but only after the sensor has been - built, and its message never names ``seed``. Checking here keeps the error - at the call that caused it. - """ - with pytest.raises(TypeError, match="seed"): +def test_non_integer_seeds_are_rejected(seed): + """NumPy refuses a seed that is not made of integers.""" + with pytest.raises(TypeError): Barometer(sampling_rate=1, seed=seed) @@ -109,23 +104,6 @@ def test_int_array_like_seeds_are_accepted(seed): assert Barometer(sampling_rate=1, seed=seed) is not None -@pytest.mark.parametrize( - "seed", - [[[1, 2], [3, 4]], np.array([[1, 2], [3, 4]], dtype=np.uint32)], - ids=["nested_sequence", "two_dimensional_ndarray"], -) -def test_multi_dimensional_int_seeds_are_rejected(seed): - """``SeedSequence`` takes entropy one dimension deep and no further. - - Nested sequences raise ``TypeError`` there and 2-D arrays ``ValueError``, - neither message naming the seed, so both are caught here instead. Older - NumPy accepted the nested form and the dependency carries no upper bound, - so refusing it is also what keeps one answer across versions. - """ - with pytest.raises(TypeError, match="seed"): - Barometer(sampling_rate=1, seed=seed) - - def test_integer_ndarray_seed_is_accepted(): """An ndarray of ints is array_like of ints, and ``RocketPyEncoder`` writes it out as a list, so it round trips like a plain list does.""" @@ -136,7 +114,7 @@ def test_integer_ndarray_seed_is_accepted(): def test_float_ndarray_seed_is_rejected(): """The dtype is what decides it: a float array cannot seed ``default_rng``, so it must be refused with the others.""" - with pytest.raises(TypeError, match="seed"): + with pytest.raises(TypeError): Barometer(sampling_rate=1, seed=np.array([1.0, 2.0])) From f42149afe9c5b5d9ec23eb44a77f4bc2b9526df2 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 28 Nov 2026 20:14:46 -0300 Subject: [PATCH 3/6] MNT: clean up the tip-off and energy code in Flight - The out_of_rail_* docstrings say the upper rail button leaves the rail. - Remove Flight.attitude_unit; udot_rail2 computes the rail direction. - Remove _gravitational_potential_per_mass; potential_energy integrates Environment.gravity with Function.integral. Co-Authored-By: Claude Opus 5.5 --- docs/technical/tip_off.rst | 3 +- rocketpy/simulation/flight.py | 84 +++++-------------- tests/unit/simulation/test_flight.py | 16 ---- .../simulation/test_udot_rail2_feature.py | 28 +++++-- 4 files changed, 43 insertions(+), 88 deletions(-) diff --git a/docs/technical/tip_off.rst b/docs/technical/tip_off.rst index ecb46676f..0a237722e 100644 --- a/docs/technical/tip_off.rst +++ b/docs/technical/tip_off.rst @@ -76,8 +76,7 @@ instantaneous center of mass gives - \mathbf{r}_{CM}\mathbf{r}_{CM}^{\mathsf T}\right). The rail is a line fixed in the inertial frame, set by the launch inclination -and heading. Its unit vector is the ``attitude_unit`` attribute of -:class:`rocketpy.Flight`. The constrained body point is the lower rail button, +and heading. The constrained body point is the lower rail button, at the fixed body position :math:`\mathbf{r}_{B}` relative to the CDM. The constraint diff --git a/rocketpy/simulation/flight.py b/rocketpy/simulation/flight.py index 131165743..fecd58632 100644 --- a/rocketpy/simulation/flight.py +++ b/rocketpy/simulation/flight.py @@ -162,13 +162,12 @@ class Flight: Flight.y : list Current integration state vector u. Flight.out_of_rail_time : int, float - Time, in seconds, in which the rocket completely leaves the - rail. + Time, in seconds, at which the upper rail button leaves the rail. The + rocket is fully off the rail at ``tip_off_end_time``. Flight.out_of_rail_state : list - State vector u corresponding to state when the rocket - completely leaves the rail. + State vector u when the upper rail button leaves the rail. Flight.out_of_rail_velocity : int, float - Velocity, in m/s, with which the rocket completely leaves the + Velocity, in m/s, of the rocket when the upper rail button leaves the rail. Flight.apogee_state : array State vector u corresponding to state when the rocket's @@ -425,7 +424,8 @@ class Flight: Flight.initial_stability_margin : float Rocket's initial stability margin in calibers. Flight.out_of_rail_stability_margin : float - Rocket's stability margin in calibers when it leaves the rail. + Rocket's stability margin in calibers when the upper rail button + leaves the rail. Flight.stream_velocity_x : Function Freestream velocity x (East) component, in m/s, as a function of time. @@ -1622,16 +1622,6 @@ def __init_solution_monitors(self): def __init_flight_state(self): """Initialize flight state variables.""" - # The rail is a fixed inertial line set by the launch inclination and - # heading, so its unit vector is known regardless of how the flight - # state is initialized. udot_rail2 constrains the lower button to it. - self.attitude_unit = Vector( - [ - np.cos(np.radians(self.inclination)) * np.sin(np.radians(self.heading)), - np.cos(np.radians(self.inclination)) * np.cos(np.radians(self.heading)), - np.sin(np.radians(self.inclination)), - ] - ) if self.initial_solution is None: # Initialize time and state variables self.t_initial = 0 @@ -2018,9 +2008,19 @@ def udot_rail2(self, t, u, post_processing=False): - Matrix([[shift, 0, 0], [0, shift, 0], [0, 0, 0]]) ).inverse + # Unit vector along the rail, in the inertial frame + inclination = np.radians(self.inclination) + heading = np.radians(self.heading) + rail_direction = Vector( + [ + np.cos(inclination) * np.sin(heading), + np.cos(inclination) * np.cos(heading), + np.sin(inclination), + ] + ) # Two unit vectors perpendicular to the rail, in the body frame, built # from a body axis that is not parallel to the rail - rail = Kt @ self.attitude_unit + rail = Kt @ rail_direction e1 = rail ^ Vector([1, 0, 0] if abs(rail.x) < 0.9 else [0, 1, 0]) e1 = e1 / abs(e1) e2 = rail ^ e1 @@ -3311,7 +3311,9 @@ def speed(self): @property def out_of_rail_velocity(self): - """Velocity at which the rocket leaves the launch rail.""" + """Velocity of the rocket when the upper rail button leaves the rail, + in m/s. The rocket is fully off the rail at :attr:`tip_off_end_time`. + """ return self.speed.get_value_opt(self.out_of_rail_time) @property @@ -3597,7 +3599,7 @@ def initial_stability_margin(self): @property def out_of_rail_stability_margin(self): - """Stability margin at the time the rocket leaves the rail. + """Stability margin when the upper rail button leaves the rail. Returns ------- @@ -3723,7 +3725,8 @@ def potential_energy(self): """ total_mass = deepcopy(self.rocket.total_mass) total_mass.set_discrete_based_on_model(self.z) - potential_per_mass = self._gravitational_potential_per_mass(self.z.y_array) + gravity = self.env.gravity + potential_per_mass = [gravity.integral(0, z) for z in self.z.y_array] gravitational_potential = Function( np.column_stack((self.z.x_array, potential_per_mass)), "Time (s)", @@ -3733,47 +3736,6 @@ def potential_energy(self): ) return total_mass * gravitational_potential - def _gravitational_potential_per_mass(self, altitude): - """Potential per unit mass relative to sea level. - - Parameters - ---------- - altitude : float or array_like - Geometric height above sea level in meters. - - Returns - ------- - float or np.ndarray - ``∫_0^z g(h) dh`` in J/kg, using ``Environment.gravity``. - Non-sampled gravity is discretized once over the altitude - range without mutating ``Environment.gravity``, so its - potential carries that sampling error. The - antiderivative of the interpolant is evaluated so that the - potential stays consistent with the dynamics, including - constant extrapolation of ``g`` outside its sampled domain. - NaN altitudes yield NaN potential. - """ - gravity = self.env.gravity - altitudes = np.asarray(altitude, dtype=float) - if not (gravity.is_array_source() and gravity.__dom_dim__ == 1): - finite_altitudes = np.atleast_1d(altitudes) - finite_altitudes = finite_altitudes[np.isfinite(finite_altitudes)] - if finite_altitudes.size: - lower = min(0.0, float(np.min(finite_altitudes))) - upper = max(0.0, float(np.max(finite_altitudes))) - else: - lower, upper = 0.0, 1.0 - if lower == upper: - upper = lower + 1.0 - gravity = gravity.set_discrete(lower, upper, mutate_self=False) - potential_per_mass = gravity._evaluator.definite_integral(0.0, altitudes) - potential_per_mass = np.where( - np.isfinite(altitudes), potential_per_mass, np.nan - ) - if np.ndim(altitude) == 0: - return float(np.reshape(potential_per_mass, -1)[0]) - return potential_per_mass - # Total Mechanical Energy @funcify_method("Time (s)", "Mechanical Energy (J)", "spline", "constant") def total_energy(self): diff --git a/tests/unit/simulation/test_flight.py b/tests/unit/simulation/test_flight.py index ac736cd57..ab32a0714 100644 --- a/tests/unit/simulation/test_flight.py +++ b/tests/unit/simulation/test_flight.py @@ -744,22 +744,6 @@ def test_potential_energy_extrapolates_gravity_above_sampled_domain(): assert delta_potential == pytest.approx(expected_delta, rel=1e-6) -def test_gravitational_potential_per_mass_nan_altitude(): - """A NaN altitude must yield NaN potential per mass so a diverged - trajectory node appears as a gap rather than a finite (often zero) - value. - """ - flight = _drag_free_ballistic_flight(gravity=9.81) - altitudes = np.array([0.0, np.nan, 100.0]) - - potential_per_mass = flight._gravitational_potential_per_mass(altitudes) - - assert potential_per_mass[0] == pytest.approx(0.0) - assert np.isnan(potential_per_mass[1]) - assert potential_per_mass[2] == pytest.approx(9.81 * 100.0) - assert np.isnan(flight._gravitational_potential_per_mass(np.nan)) - - @pytest.mark.parametrize( "flight_time_attr", ["t_initial", "out_of_rail_time", "apogee_time", "t_final"], diff --git a/tests/unit/simulation/test_udot_rail2_feature.py b/tests/unit/simulation/test_udot_rail2_feature.py index c52252f5a..56def3648 100644 --- a/tests/unit/simulation/test_udot_rail2_feature.py +++ b/tests/unit/simulation/test_udot_rail2_feature.py @@ -26,6 +26,19 @@ from rocketpy.simulation.flight import Flight +def _rail_direction(flight): + """Unit vector along the rail, in the inertial frame.""" + inclination = math.radians(flight.inclination) + heading = math.radians(flight.heading) + return Vector( + [ + math.cos(inclination) * math.sin(heading), + math.cos(inclination) * math.cos(heading), + math.sin(inclination), + ] + ) + + def _make_flight(rocket, environment, **kwargs): return Flight( rocket=rocket, @@ -159,7 +172,7 @@ def test_udot_rail2_button_stays_on_rail(calisto_robust, example_spaceport_env): """The lower rail button stays on the rail line throughout the window.""" flight = _make_flight(calisto_robust, example_spaceport_env) r_b = _lower_button_body_position(flight.rocket) - rail_dir = flight.attitude_unit + rail_dir = _rail_direction(flight) rows = _tip_off_rows(flight) first_state = rows[0][1:] rail_origin = ( @@ -264,7 +277,7 @@ def derivative(_, y): ) return [s_dot, phi_dot, s_ddot, phi_ddot] - speed = start[3:6] @ np.array(list(flight.attitude_unit)) + speed = start[3:6] @ np.array(list(_rail_direction(flight))) end = solve_ivp( derivative, (t1, t2), @@ -280,7 +293,7 @@ def _pitch_from_the_rail(flight, state): """Pitch angle and pitch rate of the rocket in the vertical plane of the rail, measured from the rail and positive when the nose rises.""" state = np.array(state) - rail = np.array(list(flight.attitude_unit)) + rail = np.array(list(_rail_direction(flight))) up = np.array([0.0, 0.0, 1.0]) across = up - (up @ rail) * rail across /= np.linalg.norm(across) @@ -363,7 +376,7 @@ def test_udot_rail2_reports_the_force_on_the_lower_button(): ] ) force = np.array(Matrix.transformation(state[6:10])) @ force_body - rail = np.array(list(flight.attitude_unit)) + rail = np.array(list(_rail_direction(flight))) up_across_the_rail = np.array([0.0, 0.0, 1.0]) - rail[2] * rail up_across_the_rail /= np.linalg.norm(up_across_the_rail) @@ -416,8 +429,8 @@ def test_udot_rail2_is_skipped_where_it_cannot_run( def test_udot_rail2_is_skipped_for_a_given_initial_solution( calisto_robust, example_spaceport_env ): - """A flight that starts from a given state has no rail phases. The rail - direction is still defined, and no window is reported.""" + """A flight that starts from a given state has no rail phases, and no + window is reported.""" launch = _make_flight(calisto_robust, example_spaceport_env) mid_flight_state = list(launch.solution[len(launch.solution) // 2]) @@ -427,9 +440,6 @@ def test_udot_rail2_is_skipped_for_a_given_initial_solution( assert "udot_rail2" not in _phase_names(continuation) assert continuation.tip_off_duration == 0 - assert abs(continuation.attitude_unit) == pytest.approx(1) - for axis in range(3): - assert continuation.attitude_unit[axis] == launch.attitude_unit[axis] def test_udot_rail2_reports_the_window_in_prints( From d3e7bc783f12505391080d5de3167f6cb58143dd Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 28 Nov 2026 20:14:46 -0300 Subject: [PATCH 4/6] MNT: let Parachute alone decide what a valid trigger is Inline the height trigger check in Parachute, and have StochasticParachute build a Parachute for each trigger member instead of restating the rules. Co-Authored-By: Claude Opus 5.5 --- rocketpy/rocket/parachute.py | 33 ++----------- rocketpy/stochastic/stochastic_parachute.py | 42 ++++------------- .../stochastic/test_stochastic_parachute.py | 47 ------------------- 3 files changed, 12 insertions(+), 110 deletions(-) diff --git a/rocketpy/rocket/parachute.py b/rocketpy/rocket/parachute.py index 6fe3c498f..66a99701b 100644 --- a/rocketpy/rocket/parachute.py +++ b/rocketpy/rocket/parachute.py @@ -9,28 +9,6 @@ from ..prints.parachute_prints import _ParachutePrints -def _is_a_height_trigger(trigger): - """Whether ``trigger`` is a number this class will read as a height. - - ``numbers.Real`` rather than ``(int, float)`` so that NumPy scalars are - accepted: ``numpy.float64`` happens to subclass ``float``, but - ``numpy.int64`` and ``numpy.float32`` subclass neither and were refused - even though every arithmetic use of them here works. - - What that spelling leaves out is what should be left out. ``numpy.bool_`` - and the complex types are not ``Real``, so they still fall through to the - error. ``bool`` is excluded by hand because it *is* an ``int``, and ``True`` - would otherwise be taken as a height of one metre. - - This is the single definition of the numeric boundary. The height form and - the delay of a ``("time", t_deploy)`` trigger both use it, and - ``StochasticParachute`` validates the same triggers before a ``Parachute`` - is ever built and calls this rather than restating it, because the two - spellings drifted apart once already. - """ - return isinstance(trigger, Real) and not isinstance(trigger, bool) - - class Parachute: """Keeps information of the parachute, which is modeled as a hemispheroid. @@ -409,8 +387,8 @@ def wrapper(p, h, y, sensors, u_dot): self.triggerfunc = _make_wrapper(trigger) return - # Numeric altitude trigger - if _is_a_height_trigger(trigger): + # Numeric altitude trigger. Real accepts NumPy numbers, bool is an int + if isinstance(trigger, Real) and not isinstance(trigger, bool): self._trigger_falling_only = True def triggerfunc(p, h, y, sensors, u_dot): # pylint: disable=unused-argument @@ -442,11 +420,8 @@ def triggerfunc(p, h, y, sensors, u_dot): # pylint: disable=unused-argument and isinstance(trigger[0], str) and trigger[0].lower() == "time" ): - # Same numeric boundary as a height, so the two forms cannot - # disagree about what counts as a number. Notably this refuses a - # string delay rather than quietly coercing it: float("3.0") would - # otherwise make ("time", "3.0") work by accident. - if not _is_a_height_trigger(trigger[1]): + # A number, as for a height. A string delay is refused, not converted. + if not isinstance(trigger[1], Real) or isinstance(trigger[1], bool): raise ValueError( f"Unable to set the trigger function for parachute '{self.name}'. " + "Time trigger delay must be a positive number of seconds, " diff --git a/rocketpy/stochastic/stochastic_parachute.py b/rocketpy/stochastic/stochastic_parachute.py index 427883cd2..066784d9b 100644 --- a/rocketpy/stochastic/stochastic_parachute.py +++ b/rocketpy/stochastic/stochastic_parachute.py @@ -2,38 +2,10 @@ from rocketpy.exceptions import StochasticTypeError, StochasticValueError from rocketpy.rocket import Parachute -from rocketpy.rocket.parachute import _is_a_height_trigger from .stochastic_model import StochasticModel, _sampler_seed -def _is_a_trigger(member): - """One of the forms ``Parachute`` accepts, and no more. - - The numeric forms defer to ``Parachute``'s own predicate instead of - restating it. Both were written out separately before and drifted: this one - kept ``(int, float)`` while ``Parachute`` widened to ``numbers.Real``, so a - ``numpy.int64`` height was refused here even though the ``Parachute`` it - would have built accepts it. Calling the same function is what keeps the - promise that what this accepts is what a parachute accepts. - - That applies to the delay of a ``("time", t_deploy)`` trigger too, so a - string is refused rather than quietly coerced by ``float()``. - """ - if callable(member): - return True - if isinstance(member, str): - return member.lower() == "apogee" - if ( - isinstance(member, (tuple, list)) - and len(member) == 2 - and isinstance(member[0], str) - and member[0].lower() == "time" - ): - return bool(_is_a_height_trigger(member[1]) and member[1] > 0) - return _is_a_height_trigger(member) - - class StochasticParachute(StochasticModel): """A Stochastic Parachute class that inherits from StochasticModel. @@ -170,15 +142,17 @@ def _validate_trigger(self, trigger): "`trigger` must be a non-empty list whose members are " "callables, the string 'apogee', heights, or ('time', t_deploy)" ) - # Raised rather than asserted: `python -O` strips an assert, and this - # is the only thing standing between a bad trigger and a Parachute - # that either refuses it much later or reads True as a height of 1. - if not isinstance(trigger, list) or not all( - _is_a_trigger(member) for member in trigger - ): + if not isinstance(trigger, list): raise StochasticTypeError(error_msg) if not trigger: raise StochasticValueError(error_msg) + # Parachute decides what a valid trigger is. Each simulation draws one + # member, so a bad one would otherwise fail only when it is drawn. + for member in trigger: + try: + Parachute(self.parachute.name, 1.0, member, 100) + except ValueError as error: + raise StochasticTypeError(f"{error_msg}. {error}") from error def _validate_noise(self, noise): """Validates the noise input. If the noise input argument is not diff --git a/tests/unit/stochastic/test_stochastic_parachute.py b/tests/unit/stochastic/test_stochastic_parachute.py index d18024c28..09ddae337 100644 --- a/tests/unit/stochastic/test_stochastic_parachute.py +++ b/tests/unit/stochastic/test_stochastic_parachute.py @@ -5,7 +5,6 @@ from rocketpy.stochastic import StochasticParachute from rocketpy.rocket.parachute import Parachute -from rocketpy.stochastic.stochastic_parachute import _is_a_trigger def test_stochastic_parachute_create_object(stochastic_main_parachute): @@ -141,52 +140,6 @@ def test_what_this_refuses_is_what_a_parachute_refuses(calisto_main_chute, membe StochasticParachute(calisto_main_chute, trigger=[member]) -def test_neither_check_can_drift_from_the_other_again(): - """The two checks were written out separately and disagreed: a - `numpy.int64` height was refused in `stochastic/` and accepted by the - `Parachute` that would have been built from it. Nothing failed, because - each side had a test asserting its own half. - - They now share one predicate, so this asserts the agreement itself over the - whole boundary rather than a list of types on either side.""" - boundary = [ - 800, - 800.0, - np.float64(800), - np.float32(800), - np.int64(800), - np.int32(800), - True, - np.bool_(True), - complex(800), - np.complex64(800), - "apogee", - "banana", - None, - ("time", 5.0), - ("TIME", np.float64(2.5)), - ["time", 1], - ("time", -1.0), - ("time", True), - ("time", "3.0"), - ("time",), - ("burnout", 3.0), - ] - - for member in boundary: - try: - Parachute("probe", 10.0, member, 105, 1.5) - except ValueError: - parachute_accepts = False - else: - parachute_accepts = True - - assert _is_a_trigger(member) is parachute_accepts, ( - f"{member!r}: stochastic/ says {_is_a_trigger(member)}, " - f"Parachute says {parachute_accepts}" - ) - - def test_the_check_is_not_stripped_by_python_dash_o(): """`python -O` removes an `assert` outright, and this check is the only thing between a bad trigger and a `Parachute` that either refuses it much From 60258f76b9448e9c1fb0ef1bfbe7199156db9f80 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 28 Nov 2026 20:14:46 -0300 Subject: [PATCH 5/6] DOC: list the current required packages on the installation page Co-Authored-By: Claude Opus 5.5 --- docs/user/installation.rst | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/user/installation.rst b/docs/user/installation.rst index 6ad84c056..fe5c9f73e 100644 --- a/docs/user/installation.rst +++ b/docs/user/installation.rst @@ -94,16 +94,15 @@ Required Packages The following packages are needed in order to run RocketPy: -- requests -- Numpy >= 1.13 -- Scipy >= 1.0 -- Matplotlib >= 3.0 +- Numpy >= 1.23 +- Scipy >= 1.8 +- Matplotlib >= 3.9 - netCDF4 >= 1.6.4 -- windrose >= 1.6.8 - requests - pytz -- simplekml - platformdirs +- simplekml +- dill All of these packages, are automatically installed when RocketPy is installed using either ``pip`` or ``conda``. However, in case the user wants to install these packages manually, they can do so by following the instructions bellow. @@ -115,14 +114,15 @@ The packages needed can be installed via ``pip`` by running the following lines .. code-block:: shell - pip install "numpy>=1.13" - pip install "scipy>=1.0" - pip install "matplotlib>=3.0" + pip install "numpy>=1.23" + pip install "scipy>=1.8" + pip install "matplotlib>=3.9" pip install "netCDF4>=1.6.4" pip install requests pip install pytz - pip install simplekml pip install platformdirs + pip install simplekml + pip install dill Installing Required Packages Using ``conda`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -133,7 +133,7 @@ To update Scipy and install netCDF4 using Conda, the following code is used: .. code-block:: shell - conda install "scipy>=1.0" + conda install "scipy>=1.8" conda install -c anaconda "netcdf4>=1.6.4" From 45f350869ffc070826e64f55858cf7d0a4473800 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 28 Nov 2026 20:14:46 -0300 Subject: [PATCH 6/6] MNT: install contextily on Python 3.14 too rasterio, which contextily needs, now ships Python 3.14 wheels for Linux, macOS and Windows, so the background map of the Monte Carlo plots no longer needs to be skipped there. Co-Authored-By: Claude Opus 5.5 --- .../monte_carlo_analysis/monte_carlo_class_usage.ipynb | 8 +------- pyproject.toml | 2 +- requirements-optional.txt | 2 +- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/notebooks/monte_carlo_analysis/monte_carlo_class_usage.ipynb b/docs/notebooks/monte_carlo_analysis/monte_carlo_class_usage.ipynb index 53650b8f4..9ddba2431 100644 --- a/docs/notebooks/monte_carlo_analysis/monte_carlo_class_usage.ipynb +++ b/docs/notebooks/monte_carlo_analysis/monte_carlo_class_usage.ipynb @@ -973,13 +973,7 @@ "- `\"terrain\"` - uses Esri.WorldTopoMap for terrain maps\n", "- Any contextily provider name (e.g., `\"CartoDB.Positron\"`)\n", "\n", - "Note that if both `image` and `background` parameters are provided, the `image` parameter takes precedence. The background map is automatically downloaded based on the environment's latitude and longitude coordinates.\n", - "\n", - "> **Note on Python 3.14 Support:**\n", - "> Currently, the `background` feature is automatically enabled only for **Python 3.13 and lower**.\n", - "> This is due to the lack of pre-built binary wheels for `rasterio` (a core dependency) on Python 3.14 (see [rasterio issue #3419](https://github.com/rasterio/rasterio/issues/3419)).\n", - ">\n", - "> **Advanced Users:** If you are using Python 3.14 and are comfortable compiling C-extensions from source (e.g., setting up a GDAL environment), you can manually install `contextily`. Once installed, this feature will become available." + "Note that if both `image` and `background` parameters are provided, the `image` parameter takes precedence. The background map is automatically downloaded based on the environment's latitude and longitude coordinates." ] }, { diff --git a/pyproject.toml b/pyproject.toml index 9133029e8..6ec30dcd2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,7 +68,7 @@ monte-carlo = [ "multiprocess>=0.70", "statsmodels", "prettytable", - "contextily>=1.0.0; python_version < '3.14'", + "contextily>=1.0.0", ] animation = [ diff --git a/requirements-optional.txt b/requirements-optional.txt index e47096ff2..4d7a23181 100644 --- a/requirements-optional.txt +++ b/requirements-optional.txt @@ -7,7 +7,7 @@ imageio multiprocess>=0.70 statsmodels prettytable -contextily>=1.0.0; python_version < '3.14' +contextily>=1.0.0 pyvista>=0.45 imageio-ffmpeg>=0.5 folium>=0.14