Repository navigation
ENH: Events Class and Flight Rework - #968
MateusStano wants to merge 80 commits into
Conversation
…ved variables retrieval
…logging Expose recorded sensor measurements as the canonical, per-flight record on `Flight.sensor_data`, and route every flight-scoped consumer through it so results stay correct when a rocket/sensor is reused across simulations. - Sensors: add `flight.sensor_data` as the source of truth; `flight.prints. sensors()` and `flight.plots.sensor_data()` now read from it. Give the per-sensor plots/prints an optional `data=` argument so standalone use still works (`_SensorPlots`, `_SensorPrints`). - Flight plots: improve event markers and the trajectory/ground-track plots (square ground track with equal axis ticks, trajectory omitted from the legend) and related layout cleanups in `flight_plots.py`. - Logging: add a centralized `rocketpy._logging` module exposing `logger`, `set_log_level` and `enable_logging`, following the NullHandler library convention; wire it into the event/simulation code. - Simulation: supporting changes in flight, flight derivatives, flight phases, events (commands, exact-time solvers) and the data exporter. - Stochastic: rebuild the air-brakes `_Controller` with its current signature (controlled_objects / context), fixing a stale constructor call. - Docs: update getting-started and sensors notebooks to the `flight.exports.*` API and document sensor usage.
Parachute noise already had no effect on this branch, but the deprecation was left half done: - The warning was a DeprecationWarning, which Python hides when the parachute comes from Rocket.add_parachute. It is now a FutureWarning. - Every parachute still drew from numpy's global generator when created and at every flight reset. Nothing is drawn any more. - noise_function and the noise entries of to_dict(include_outputs=True) are removed, since nothing fills them. - StochasticParachute warns once when noise is given and no longer samples it, so a Monte Carlo run does not warn on every simulation. - The docs said the legacy trigger arguments p and h carry the noise. They are the clean values. Docstrings and the README are updated too. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Gui-FernandesBR
left a comment
There was a problem hiding this comment.
Review of 5d93d97: 8 bugs and 6 nits, one per inline comment. Most of the bugs are around Event.reset() and backward compatibility of legacy air-brakes controllers. Found with an AI-assisted review, so push back on anything that doesn't hold.
aZira371
left a comment
There was a problem hiding this comment.
@MateusStano, thanks for this PR. Here's my review. Each item below links to the line, and there's an inline comment on that line with the details and a suggested fix.
Must fix before merge
-
np.array(context.state)aliases the solver's live state:rocketpy/simulation/events/state.py:74 -
context.controlledis frozen at construction:rocketpy/control/controller.py:139 -
Event.__call__now hard-requires internal context keys:rocketpy/simulation/events/event.py:352
Should fix
-
Built-in
"apogee"trigger reads a private Event attribute:rocketpy/rocket/parachute.py:342 -
previous_stateis rebuilt on every read:rocketpy/simulation/events/event_context.py:64
Nice to have
-
One name plus a list changes indexing semantics:
rocketpy/control/controller.py:295 -
Phase states named
values/namesare unreachable:rocketpy/simulation/events/state.py:49 -
_StateViewhas no__eq__:rocketpy/simulation/events/state.py:6 -
controller_callbackdocstring is out of date:rocketpy/control/controller.py:220
A single Event given as custom_events could not have events added to it during the flight, and a list given by the user grew with every flight that used it. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
The exact row is dropped in that case, which left out_of_rail_time_index one past the end. The comparison against the previous time is also guarded for a solution with a single row. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Reading context.previous_state twice in a check gives the same object. Co-Authored-By: Claude Fable 5.2 <[email protected]>
"apogee" now means coming down and above the ground, which holds from the apogee on, like "burnout" and a time trigger. An event fires once only with trigger_only_once=True, as the parachute's does. A flight that starts descending, or is released at rest above the ground, deploys an apogee parachute at its first check. The trigger no longer depends on the check falling in the step where the apogee was crossed. Co-Authored-By: Claude Fable 5.2 <[email protected]>
np.array(context.state) is a copy instead of the array the solver is integrating. Two states are compared by their values. A flight phase cannot have a state called names or values, which could not be read. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
A step that leaves the rail or reaches the ground is cut at that moment. The sampled events at the sampling times after it had already run: twice after the rail exit, and at times after the landing. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The noise is added to the pressure a trigger(p, h, y) receives and to the height worked out from it, which a trigger given as a height also uses, until its removal in v1.16. It was accepted but had no effect. The noise is saved with the parachute and passed on by StochasticParachute. The recorded signals are not brought back. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Brings the review fixes of #968 and #1064. Resolved here: - "apogee" is one condition for triggers, gates and parachutes, as on enh/events: _past_apogee, _reached_apogee and _GATE_PRESETS are removed. - The parachute noise reads the pressure and the sensors through the context of this branch. - The loaded flight rebuilds its surface switches instead of starting with none. - The sampled events skipped in a cut step call the rail exit trigger with the flight. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
@MateusStano can you fix conflicts so we can approve this PR? |
Bring the events Flight up to date with develop (4009778) and rebuild develop's Flight features on it: - tip-off phase: TIP_OFF_DYNAMICS with udot_rail2, a "Tip Off End" core event, and the lower button force as a tip-off post-process variable - rail exits found with brentq on the dense output instead of a cubic fit - parachute ("time", t) triggers, legacy triggers that read u_dot, heights given as any real number, and the private noise seed - a parachute triggered while a rail button is still on the rail, tip-off included, raises in its own callback - solid propulsion and generalized equations of motion fixes (#1195, #1196) - potential energy from Environment.gravity, warn_if_unstable, continuous controllers, sensor seeds - develop's removal of the deprecated Flight.export_* methods - logging through module loggers and rocketpy.utilities.enable_logging; rocketpy/_logging.py is removed Develop tests that read the old Flight internals are rewritten for the events API. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- register the tip-off dynamics, so a saved flight finds it by name - build the tip-off rail from the rocket axis at the upper button exit, the rail the rail phase moved the rocket along, instead of from inclination and heading, which a flight started on the rail from an initial_solution does not have to repeat - work out Environment.height_above_ground_level when read, so the placeholder elevation of the forecast reuse never reaches it - the center of pressure plot reads first_parachute_event_time Co-Authored-By: Claude Opus 5.5 <[email protected]>
| apply_rollback_command(flight, event_kwargs["time"], event_kwargs["raw_state"]) | ||
| return True, True | ||
|
|
||
| return rolled_back, False |
There was a problem hiding this comment.
Important: A changes_dynamics event that shares a sample node with an earlier event that already rolled the flight back is silently skipped. In process_overshootable_event, return rolled_back, False marks it as handled without running it, so the second same-rate controller never acts. Fix: after a rollback, still evaluate the remaining changes_dynamics events at that node (add them to the recall list) instead of returning False.
Example: Two changes_dynamics events at 100 Hz: the first is called 1200 times and the second 0 times in the same flight. Two air-brake controllers at the same rate, or a controller plus a custom changes_dynamics event, leave the later one inert.
| def controller_wrapper(context): | ||
| # Build positional args in the historical order described in | ||
| # the docs. | ||
| pos_args = [ |
There was a problem hiding this comment.
Important: The legacy air-brakes controller wrapper no longer matches the v1.13 signature (time, sampling_rate, state, state_history, observed_variables, air_brakes[, sensors[, environment]]). pos_args drops state_history, so 6- and 7-arg controllers get shifted arguments and 8-arg ones fail the (5, 6, 7) check at L2017 with ValueError; the docstring at L1913 still documents the old form. Fix: map 6/7/8 positional args to the v1.13 order and keep accumulating observed_variables.
Example: A v1.13 def c(time, sampling_rate, state, state_history, observed_variables, air_brakes) now gets air_brakes in the observed_variables slot and the sensors list as air_brakes, so air_brakes.deployment_level = x raises AttributeError mid-flight. initial_observed_variables is stored unwrapped, so observed_variables[-1] breaks too. The legacy tests in test_flight.py (L850-935) were rewritten to the shifted form, so they do not catch this.
| Event to disable. | ||
| """ | ||
| if event.sampling_rate is None: | ||
| self.continuous_events.remove(event) |
There was a problem hiding this comment.
Important: A continuous or non-overshootable event disabled during the flight never comes back through enable_on. disable_event removes it from continuous_events (L556) or from every future node, so enable_on is never evaluated again; only sampled overshootable events re-enable. Fix: keep events that have enable_on registered and let Event.__call__ gate them on enabled, or re-add them from apply_enable_commands.
Example: Non-overshootable 10 Hz event with disable_on=3.0, enable_on=6.0: 30 calls, last at t=3.0 s, then it never resumes and enabled_times stays empty. The enable_on tests in test_event.py (L436-502) only cover events that start disabled.
| "dict", | ||
| ) | ||
|
|
||
| if return_annotation not in valid_return_annotations: |
There was a problem hiding this comment.
Important: Valid return annotations are rejected with ValueError. A callback annotated -> None fails under from __future__ import annotations (annotations become strings and only "dict" is accepted), and dict | None, Optional[dict] and dict[str, ...] fail too; a trigger annotated -> np.bool_ fails the check at L566. Fix: resolve with typing.get_type_hints and compare by origin and NoneType, or drop the annotation check.
Example: In a module with from __future__ import annotations, def cb(context) -> None: passed to Event(...) raises ValueError: Callback function return annotation must be None, dict, or unspecified at construction.
| self.triggered_times.clear() | ||
| self._trigger_checked = False | ||
| self._forget_previous_check() | ||
| self.memory = deepcopy(self._initial_memory) |
There was a problem hiding this comment.
Important: Event.reset() rebinds self.memory to a deepcopy, so a _Controller stops sharing its memory dict with its event and the controller's memory leaks across flights. _Controller.memory (controller.py L143, passed to Event at L243) keeps the original dict while the event gets a new one; the deepcopy also detaches live objects held in memory, such as the sensor in Sensor.to_event. Fix: restore in place (self.memory.clear(); self.memory.update(...)) and copy only plain data, keeping live objects by reference.
Example: A controller doing context.controller.memory['count'] += 1 over two flights with the same rocket ends at 60 then 120 instead of 60 twice, because Flight resets event.memory, which is no longer controller.memory.
|
|
||
| if self.enabled is False: | ||
| # If event is disabled, only evaluate enable_on function if it exists. | ||
| if self._call_enable_on(context) is False: |
There was a problem hiding this comment.
Important: enable_on handling in Event.__call__ can drop the enable. enable_on is evaluated twice per call (L335 and L344), its enable command is wiped by _reset_commands, and the event only turns on if its trigger fires in the same call. For changes_dynamics events enabled and enabled_times are never updated. Fix: evaluate enable_on once, apply the enable before _reset_commands and independently of the trigger, and record enabled_times for every event type.
Example: Event(cb, sampling_rate=10, enabled=False, enable_on=lambda c: 2.0 < c.time < 3.0, trigger=lambda c: c.time > 3.5) is called 0 times. The same plain event with enable_on=2.0 shows enabled_times == [2.0], but with changes_dynamics=True it runs 101 times and leaves enabled_times == [] and enabled == False at the end.
| controller_function=self.air_brake_controller.base_controller_function, | ||
| sampling_rate=self.air_brake_controller.sampling_rate, | ||
| initial_observed_variables=self.air_brake_controller.initial_observed_variables, | ||
| controller_function=base_controller.controller_function, |
There was a problem hiding this comment.
Important: A stochastic copy of a legacy air-brakes controller still acts on the template air brakes, not the sampled one. The wrapper built in add_air_brakes closes over the template air_brakes, and create_object only reuses base_controller.controller_function; memory.copy() is also shallow and enabled, enable_on and disable_on are not forwarded. Fix: rebuild the legacy wrapper per sampled object (or take the object from context), deepcopy the memory and forward the event options.
Example: With a legacy controller, the function called for a sampled _Controller receives the template AirBrakes (received is template is True, received is sampled is False), so every Monte Carlo run mutates the template and the sampled air brakes never deploy.
| "and `context.state_dot`. See the Event documentation for " | ||
| "the full list of available values.", | ||
| DeprecationWarning, | ||
| stacklevel=2, |
There was a problem hiding this comment.
Nit (optional): The new positional-trigger DeprecationWarning is hidden for most users. It is raised inside the private __evaluate_trigger_function, so stacklevel=2 points at Parachute.__init__ (rocketpy code), where the default filter drops DeprecationWarning; the initial_observed_variables warning in add_air_brakes has no stacklevel and has the same problem. Fix: use stacklevel=3 here (the noise warning at L282 already does) and a caller-pointing stacklevel in add_air_brakes, or switch to FutureWarning.
Example: Parachute(..., trigger=lambda p, h, y: ...) in a user script prints no warning unless -W default is set, so users are not told the API goes away.
| "Passing `initial_observed_variables` to `add_air_brakes` is " | ||
| "deprecated; supply them via `memory={'observed_variables': ...}` " | ||
| "instead. Support for this argument will be removed in v1.14.", | ||
| DeprecationWarning, |
There was a problem hiding this comment.
Nit (optional): The deprecation messages disagree about the removal version, and one is already past. This warning says "removed in v1.14" and the docstring says .. deprecated:: 1.13, but 1.14.0 is released with the code still present, while the controller and parachute positional APIs say v1.16. Fix: use one removal version (v1.16) for all legacy event and controller APIs and tag .. deprecated:: with the release that introduces each one.
Example: A user on v1.14 gets a warning promising removal in the version they already run.
|
|
||
| self.is_discrete = self.sampling_rate is not None | ||
| self.sampling_interval = ( | ||
| None if sampling_rate is None else 1.0 / float(sampling_rate) |
There was a problem hiding this comment.
Nit (optional): Event.__init__ does not validate sampling_rate. 0 raises a bare ZeroDivisionError from 1.0 / float(sampling_rate), and a negative rate builds a negative interval so the event silently never runs. Fix: raise ValueError unless sampling_rate is None or sampling_rate > 0.
Example: Event(cb, sampling_rate=-10) is accepted and never fires; sampling_rate=0 fails with an unrelated traceback.
| self._random_walk_drift = self._random_walk_drift + Vector( | ||
| [self._rng.normal(0, self.random_walk_variance[i] ** 0.5) for i in range(3)] | ||
| ) & (self.random_walk_density / self.sampling_rate**0.5) | ||
| self._random_walk_drift = self._random_walk_drift + ( |
There was a problem hiding this comment.
Nit (optional): The random-walk precedence fix (drift + (Vector(...) & scale)) changes the numbers of seeded sensor runs compared with develop. The change itself is correct, but the same seed now gives a different drift than before. Fix: say so in the PR description and refresh any pinned seeded outputs.
Example: A user or test comparing a seeded InertialSensor flight against stored values from v1.13 or v1.14 sees different readings without any hint in the PR.
Summary
The addition of custom events was long overdue. In this PR the Event class was added. It was basically impossible to do this without changing a lot of the flight class, so I took the opportunity to rework it and solve all TODOs there.
Several upcoming features will build on top of this (parafoil, multistage, more controllers...). The related work is split into a stack of three PRs, merged in this order:
flight.solutionas aSolutionobject that allows a variable state length per phase;GenericSurfacethe Mother Class #1064: the aerodynamics refactor,GenericSurfaceas the mother class of every surface;Here is a summary of all the changes:
flight.pySome flight class methods were reworked, some were moved:
flight_derivatives.py: the motion functions (u_dot,u_dot_generalized,u_dot_generalized_3dof, rail and parachute), moved out offlight.py.flight_phase.py: now has the_FlightPhasesand_TimeNodesclasses.event_execution.py: runs the events in the flight and applies the commands they return.New event code (
rocketpy/simulation/events/)event.py(Event): An event has a trigger and a callback. The trigger is checked each step; when it is true, the callback runs. Callbacks can read the state, save data, log results, and send commands that change the simulation. It comes with ready-made presets likeapogeeandburnout. It also only computes expensive values when an event actually needs them.commands.py(Commands): what a callback can ask for. An event can start anew phase, swap the motion function, turn other events on or off, add or
remove controllers, undo a step (rollback), or stop the flight.
event_builders.py: ready-made events that recreate the normal flight steps(like leaving the rail).
exact_time_solvers.py: finds the exact time an event happens inside a step(using a few math methods).
Parachutes, controllers and sensors are no longer special cases in the flight loop. Each one now has a
to_event()method that wraps it into anEvent. The built-in flight milestones (apogee, out of rail, impact) are now events too.Parachute triggers and controller functions now take one argument, the event context, and read what they need from it by name (
context.pressure,context.height_agl,context.state.vz,context.sensors, etc.); the old positional parachute and controller signatures still work but raise aDeprecationWarning.Flight.__init_events()just collects all events (core events, then sensors, parachutes, controllers, and user custom events) and runs them uniformly, and commands an event returns (like swapping the derivative or starting a phase) are applied back to the flight byevent_commands.py.The
noiseparameter onParachuteis deprecated (removal in v1.16) but still works, with a warning. The recommended way to model a noisy trigger is aBarometerwhose measurement the trigger reads fromcontext.sensors. This fits the new model, where sensors are events and the trigger reads their measurements.Plots and prints
flight_plots.pyandflight_prints.pynow show sensor data too.compare_flights.pyupdated.Docs
docs/user/event_usage.rstanddocs/user/sensors_usage.rst.docs/technical/simulation_loop.rst.Notes for reviewers
This will be a difficult one to review, specially because the diff tracking in flight.py is not that helpful given I changed the order of a few methods. So I suggest that the best way to understand how events work is to read the user guide:
docs/user/event_usage.rst. It walks through the API with runnable examples.Changes after the review (November 2026)
"apogee"(as a trigger,enable_onordisable_on) is the condition "coming down and above the ground", which holds from the apogee on. A flight that starts descending, or a rocket dropped from rest, deploys at its first check; a rocket at rest on the pad does not.Flightkeeps its own copy ofcustom_events, so a singleEventis accepted and the caller's list is never changed.context.state:np.array(context.state)is a copy,==compares values, and a phase cannot have a state callednamesorvalues.context.previous_stategives the same object on every read within a check.__repr__and__str__ofEventclose their parenthesis; the unused"format"key is gone from the saved solution.zofGenericSurfaceis documented as the altitude above sea level.Breaking change