diff --git a/docs/technical/references.rst b/docs/technical/references.rst index 02b90b8ff..e62d0c61d 100644 --- a/docs/technical/references.rst +++ b/docs/technical/references.rst @@ -10,3 +10,5 @@ References .. [Chou] Chou, P.-C., et al. *Tip-off effect analysis of a vehicle moving along an inclined guideway by considering dynamic interactions*. .. [Hosken] Hosken, R. W., et al. *Analysis of missile launchers, part Q: tip-off effects in helical rail launchers*. + +.. [Peng] Peng, W., Zhang, Q., Yang, T., and Feng, Z. (2017). *A high-precision dynamic model of a sounding rocket and rapid wind compensation method research*. Advances in Mechanical Engineering, 9(7). diff --git a/docs/technical/tip_off.rst b/docs/technical/tip_off.rst index 50c983afd..ecb46676f 100644 --- a/docs/technical/tip_off.rst +++ b/docs/technical/tip_off.rst @@ -7,27 +7,24 @@ Tip-off: the 3-DOF Single Rail Button Phase Introduction ------------ -Between the moment the *upper* rail button leaves the launch rail and the moment -the *lower* button follows it, the rocket is still guided --- but only at one -point. It slides along the rail while free to pitch and yaw about that remaining -button. This short interval is what the literature calls **tip-off**, and it sets -the attitude and angular rate with which the rocket begins free flight. +Between the moment the upper rail button leaves the launch rail and the moment +the lower button follows it, the rocket is guided at one point only. It slides +along the rail while free to pitch and yaw about the remaining button. This +short interval is called **tip-off**, and it sets the attitude and angular rate +with which the rocket begins free flight. This document derives the equations of motion used by :meth:`rocketpy.Flight.udot_rail2`, the flight phase that models this interval. -It is enabled with ``Flight(..., use_udot_rail2=True)``; when disabled (the -default) the simulation transitions straight from the 1-DOF rail phase to the -generalized 6-DOF equations, exactly as it did before this phase existed. - -Because the phase works by patching the *generalized* 6-DOF solution with a -constraint wrench built from the full inertia tensor, it requires -``simulation_mode="6 DOF"`` and ``equations_of_motion="standard"``. The reduced -formulations do not carry the state the patch describes --- the 3 DOF equations -model no attitude at all, and ``solid_propulsion`` uses a different, -axisymmetric set --- so asking for the tip-off phase together with either of -them raises a ``ValueError`` instead of silently producing non-physical -kinematics. Note that a point-mass motor forces ``simulation_mode`` to -``"3 DOF"``, and therefore cannot be combined with this phase either. +The phase runs whenever the rocket has two rail buttons. + +The phase adds a constraint wrench (a force and a moment), built from the full +inertia tensor, to the generalized 6-DOF solution. It therefore needs +``simulation_mode="6 DOF"`` and ``equations_of_motion="standard"``. The other +formulations do not have the state this correction needs: the 3 DOF equations +model no attitude, and ``solid_propulsion`` uses a different, axisymmetric set. +Flights that use either of them skip the phase and go straight from the 1-DOF +rail phase to free flight, and so does a flight with a point-mass motor, which +forces ``simulation_mode`` to ``"3 DOF"``. The three flight phases around rail departure are, in order of the distance ``d`` travelled from the launch point: @@ -44,7 +41,7 @@ The three flight phases around rail departure are, in order of the distance \end{aligned} where :math:`\ell_1` and :math:`\ell_2` are the ``effective_1rl`` and -``effective_2rl`` attributes of :class:`rocketpy.Flight` --- the distances at +``effective_2rl`` attributes of :class:`rocketpy.Flight`, the distances at which the upper and the lower button reach the end of the rail. Their difference is the button-to-button distance, so the phase has zero length for a rocket with a single rail button and is skipped in that case. @@ -60,10 +57,10 @@ right-hand sides, \mathbf{u} = [\,x,\ y,\ z,\ v_x,\ v_y,\ v_z,\ e_0,\ e_1,\ e_2,\ e_3,\ \omega_1,\ \omega_2,\ \omega_3\,] -with :math:`\mathbf{r} = [x, y, z]` the inertial position of the **center of dry -mass** (CDM, the tracked point), :math:`\mathbf{v}` its inertial velocity, +with :math:`\mathbf{r} = [x, y, z]` the inertial position of the center of dry +mass (CDM, the tracked point), :math:`\mathbf{v}` its inertial velocity, :math:`\mathbf{e}` the attitude quaternion and :math:`\boldsymbol{\omega}` the -angular velocity in the **body** frame. The matrix +angular velocity in the body frame. The matrix :math:`\mathbf{K} = \texttt{Matrix.transformation}(\mathbf{e})` rotates body components into inertial ones, and :math:`\hat{\mathbf{z}}_b = [0, 0, 1]` is the body roll (symmetry) axis. @@ -78,11 +75,10 @@ instantaneous center of mass gives \mathbf{I}_{CM} = \mathbf{I} - m\left(|\mathbf{r}_{CM}|^2 \mathbb{1} - \mathbf{r}_{CM}\mathbf{r}_{CM}^{\mathsf T}\right). -**Rail geometry.** 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, at the fixed body position :math:`\mathbf{r}_{B}` relative to the -CDM. +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, +at the fixed body position :math:`\mathbf{r}_{B}` relative to the CDM. The constraint -------------- @@ -90,34 +86,34 @@ The constraint A free rigid body has six degrees of freedom. The single engaged button removes three of them: -#. **The button stays on the rail line.** Its position may only vary along the - rail, so the component of its acceleration perpendicular to the rail - vanishes. That is **two** scalar constraints. -#. **Roll is suppressed** by the button in its rail slot: - :math:`\dot{\boldsymbol{\omega}} \cdot \hat{\mathbf{z}}_b = 0`. That is - **one** more. +#. The button stays on the rail line. Its position may only vary along the + rail, so the component of its acceleration perpendicular to the rail is + zero. That is two scalar constraints. +#. The button in its rail slot prevents roll: + :math:`\dot{\boldsymbol{\omega}} \cdot \hat{\mathbf{z}}_b = 0`. That is one + more. Three constraints leave :math:`6 - 3 = 3` degrees of freedom: translation along -the rail, pitch and yaw --- the 3 DOF this phase is named for. +the rail, pitch and yaw. The forces that enforce them are the unknowns of the problem: -* a **normal reaction** at the button, perpendicular to the rail because a +* a normal reaction at the button, perpendicular to the rail because a frictionless slot can neither pull nor push along it. Writing an orthonormal body triad :math:`\{\hat{\mathbf{e}}_1, \hat{\mathbf{e}}_2, \hat{\mathbf{n}}_b\}` around the body-frame rail direction :math:`\hat{\mathbf{n}}_b = \mathbf{K}^{\mathsf T}\hat{\mathbf{n}}`, it has two components: :math:`\mathbf{N}_b = \lambda_1 \hat{\mathbf{e}}_1 + \lambda_2 \hat{\mathbf{e}}_2`; -* a **roll reaction moment** :math:`\mu \hat{\mathbf{z}}_b` about the body axis. +* a roll reaction moment :math:`\mu \hat{\mathbf{z}}_b` about the body axis. -Three unknowns, three constraints: a :math:`3\times3` linear system, solved once -per evaluation of the right-hand side. +That is three unknowns for three constraints, a :math:`3\times3` linear system +solved once per evaluation of the right-hand side. The initial conditions are consistent with the constraint. The phase is entered from ``udot_rail1``, where the rocket has no angular velocity and its velocity is -along the rail, so the button's perpendicular *velocity* is already zero. -Enforcing zero perpendicular *acceleration* therefore keeps it on the rail. +along the rail, so the button's velocity perpendicular to the rail is already +zero. Enforcing zero perpendicular acceleration therefore keeps it on the rail. Augmented dynamics ------------------ @@ -132,10 +128,10 @@ both in the body frame, and solve \left(\mathbf{T}_{21} + \mathbf{T}_{20} \times \mathbf{r}_{CM}\right), \qquad \mathbf{a}_{\text{free}} = \frac{\mathbf{T}_{20}}{m} - - \mathbf{r}_{CM} \times \dot{\boldsymbol{\omega}}_{\text{free}}. + + \mathbf{r}_{CM} \times \dot{\boldsymbol{\omega}}_{\text{free}}. -Both totals are *sums of external contributions*, which is what makes the -constraint clean to add: the reaction wrench simply enters the sums, +Both totals are sums of external contributions, so the reaction wrench is added +to them directly, .. math:: @@ -157,7 +153,7 @@ vector, \left(\mathbf{d} \times \mathbf{N}_b + \mu \hat{\mathbf{z}}_b\right), \qquad \Delta\mathbf{a} = \frac{\mathbf{N}_b}{m} - - \mathbf{r}_{CM} \times \Delta\dot{\boldsymbol{\omega}}. + + \mathbf{r}_{CM} \times \Delta\dot{\boldsymbol{\omega}}. The button is body-fixed, so its acceleration in body components is @@ -214,26 +210,30 @@ returned derivative: + \mathbf{K}\,\Delta\mathbf{a}. The position and quaternion derivatives are the ordinary kinematic ones. In -particular :math:`\dot{\mathbf{r}} = \mathbf{v}`: the velocity is **not** -projected onto the rail. The constraint acts at the acceleration level on the -*button*, and the CDM legitimately acquires a small perpendicular velocity as the -rocket pitches about that button. +particular :math:`\dot{\mathbf{r}} = \mathbf{v}`: the velocity is not projected +onto the rail. The constraint acts on the acceleration of the button, and the +CDM acquires a small perpendicular velocity as the rocket pitches about that +button. Modelling assumptions and edge cases ------------------------------------ -* **Roll axis.** The constraint suppresses roll about the *body* axis. The rocket - travels only the button-to-button distance during this phase, so the tip-off - angle is small and the body axis stays close to the rail direction; the - difference between body roll and rail-axis roll is of that order. This is - consistent with ``udot_rail1``, which freezes rotation entirely. -* **Radial button offset.** The button is modelled on the rocket axis. The roll - constraint is enforced explicitly by :math:`\mu`, so what is lost is only the - (small) roll coupling through the button's radial standoff. -* **Zero-length phase.** A rocket with a single rail button has +* Roll axis: the constraint prevents roll about the body axis, not about the + rail. The rocket travels only the button-to-button distance during this phase, + so the tip-off angle is small and the body axis stays close to the rail + direction. The difference between body roll and rail-axis roll is of that + order. ``udot_rail1`` allows no rotation at all, so the two phases agree here. +* Radial button offset: the button is modelled on the rocket axis. The roll + constraint is enforced by :math:`\mu`, so the only thing lost is the small + roll coupling through the button's radial standoff. +* Rail friction: the rail is frictionless, as it is in ``udot_rail1``. +* Contact with the rail: only the button touches the rail. Nothing stops the + rocket body or the fins from turning into it, so the model is meant for the + small rotations of a normal launch. A rocket that leaves the rail very slowly + (a thrust barely above its weight on a strongly inclined rail) can turn by + tens of degrees inside the window, which no real rail would allow. +* Zero-length phase: a rocket with a single rail button has :math:`\ell_1 = \ell_2`, and the phase is skipped. -* **Singular system.** Should the geometry make :math:`\mathbf{J}` singular, the - step falls back to the unconstrained dynamics and warns. Expected behaviour ------------------ @@ -241,15 +241,15 @@ Expected behaviour The phase reproduces the two effects tip-off is modelled for. With no wind, the center of mass sits ahead of the button that the rocket now pivots about, so gravity pitches the nose down by a fraction of a degree. With a crosswind, the -aerodynamic moment turns the rocket into the wind before it is fully free --- -the weathercock effect --- and the rocket therefore leaves the rail with a small -angular rate rather than none. +aerodynamic moment turns the rocket into the wind before it is fully free (the +weathercock effect), so the rocket leaves the rail with a small angular rate +instead of none. Reading the results ------------------- -The window itself is recorded on the :class:`rocketpy.Flight` object, so a -dispersion study does not have to recover it from the raw solution: +The window is recorded on the :class:`rocketpy.Flight` object, so a dispersion +study does not have to recover it from the raw solution: .. list-table:: :header-rows: 1 @@ -258,24 +258,70 @@ dispersion study does not have to recover it from the raw solution: * - Attribute - Meaning * - ``out_of_rail_time`` - - Time the *upper* button leaves the rail, starting the window. - * - ``between_rails_time`` - - Time the *lower* button leaves the rail, ending the window. - * - ``between_rails_velocity`` - - Speed at that moment, the true rail-departure velocity. - * - ``between_rails_state`` + - Time the upper button leaves the rail, starting the window. + * - ``tip_off_end_time`` + - Time the lower button leaves the rail, ending the window. Equal to + ``out_of_rail_time`` when the phase does not run. + * - ``tip_off_end_velocity`` + - Speed at that moment, when the rocket is fully off the rail. + * - ``tip_off_end_state`` - Full state vector handed to the free-flight phase. * - ``tip_off_duration`` - - Length of the window, zero when the phase is disabled. + - Length of the window, zero when the phase does not run. + * - ``rail_button2_normal_force``, ``rail_button2_shear_force`` + - Force between the lower button and the rail. Inside the window this is + the force :math:`\mathbf{N}_b` solved above, with the opposite sign + (the force of the rocket on the rail), and the upper button force is + zero. + +While both buttons are on the rail, the rail button forces count the +aerodynamic loads only. Inside the window the lower button force also carries +the weight of the rocket, so it rises when the window starts. The maximum lower +button forces (``max_rail_button2_normal_force`` and +``max_rail_button2_shear_force``) include the window. ``Flight.info()`` prints these under a *Tip-Off State* heading whenever the phase ran, and the attitude plots shade the window so the change in attitude -during tip-off can be read off directly. +during tip-off can be read from them. + +Verification +------------ + +The phase is tested against an independent model of the same problem: a rigid +body of constant mass, under thrust and gravity only, whose lower button slides +along the rail. That model is written in two coordinates, the position +:math:`s` of the button along the rail and the angle :math:`\varphi` of the +rocket axis from the rail. With :math:`l` the distance from the button to the +center of mass, :math:`I` the inertia about the center of mass, :math:`T` the +thrust and :math:`\theta` the rail inclination, + +.. math:: + + \begin{aligned} + \left(I + m l^2 \cos^2\varphi\right) \ddot{\varphi} &= l \cos\varphi + \left(m l \dot{\varphi}^2 \sin\varphi + T \sin\varphi + - m g \cos\theta\right), \\ + \ddot{s} &= \frac{T \cos\varphi}{m} - g \sin\theta + + l \ddot{\varphi} \sin\varphi + l \dot{\varphi}^2 \cos\varphi. + \end{aligned} + +For a rocket with no aerodynamic surfaces, no drag and almost no propellant, +the pitch angle and the pitch rate at the end of the window agree with this +model to about :math:`10^{-7}`, at rail inclinations of 85° and 60°. The +leading term, :math:`\ddot{\varphi} \approx -m g l \cos\theta / (I + m l^2)`, +is also the one in equation (2) of [Peng]_, which treats the same phase in one +plane and adds rail friction. The force on the lower button is checked against +the same model, in which the rail pushes the rocket with +:math:`m g \cos\theta - T \sin\varphi + m l \left(\ddot{\varphi} \cos\varphi +- \dot{\varphi}^2 \sin\varphi\right)`. + +The response to wind is not covered by such a closed model. It rests on the +aerodynamic forces and moments of the generalized equations of motion, which +this phase uses unchanged. References ---------- -The tip-off phase and its effect on the initial conditions of free flight are -treated in the launcher dynamics literature: [Chou]_ studies a vehicle moving -along an inclined guideway with dynamic interactions, and [Hosken]_ analyses -tip-off effects in rail launchers. +[Chou]_ studies a vehicle moving along an inclined guideway with dynamic +interactions, [Hosken]_ analyses tip-off effects in rail launchers, and +[Peng]_ gives a planar model of the single-button phase of a sounding rocket. diff --git a/rocketpy/_encoders.py b/rocketpy/_encoders.py index 01bdc6d9e..291088e74 100644 --- a/rocketpy/_encoders.py +++ b/rocketpy/_encoders.py @@ -204,6 +204,7 @@ def set_minimal_flight_attributes(flight, obj): "name", "solution", "out_of_rail_time", + "tip_off_end_time", "apogee_time", "apogee", "parachute_events", @@ -238,7 +239,12 @@ def set_minimal_flight_attributes(flight, obj): if attribute == "net_thrust": flight.net_thrust = obj["rocket"].motor.thrust flight.net_thrust.set_discrete_based_on_model(flight.speed) + elif attribute == "tip_off_end_time": + # Saved before the tip-off phase existed: there was no window + flight.tip_off_end_time = flight.out_of_rail_time + # Lower button forces of the tip-off phase, absent from older files + flight._tip_off_button_forces = obj.get("tip_off_button_forces", []) flight.t_initial = flight.initial_solution[0] diff --git a/rocketpy/plots/flight_plots.py b/rocketpy/plots/flight_plots.py index 2a0c3f164..e0193e49a 100644 --- a/rocketpy/plots/flight_plots.py +++ b/rocketpy/plots/flight_plots.py @@ -2524,8 +2524,7 @@ def _mark_tip_off_window(self, ax): The window runs from the upper rail button leaving the rail to the lower one leaving it, which is when the rocket pivots about the lower - button. It is a no-op unless the flight was run with - ``use_udot_rail2=True``, since otherwise the phase never runs. + button. Nothing is drawn when the tip-off phase did not run. Parameters ---------- @@ -2536,13 +2535,11 @@ def _mark_tip_off_window(self, ax): ------- None """ - if not self.flight.use_udot_rail2: - return - if self.flight.between_rails_time <= self.flight.out_of_rail_time: + if self.flight.tip_off_duration <= 0: return ax.axvspan( self.flight.out_of_rail_time, - self.flight.between_rails_time, + self.flight.tip_off_end_time, color="0.5", alpha=0.25, zorder=0, diff --git a/rocketpy/prints/flight_prints.py b/rocketpy/prints/flight_prints.py index cfa7164c8..6590db168 100644 --- a/rocketpy/prints/flight_prints.py +++ b/rocketpy/prints/flight_prints.py @@ -166,26 +166,24 @@ def out_of_rail_conditions(self): def tip_off_conditions(self): """Prints out the tip-off window, i.e. the interval during which the rocket pivots about the lower rail button after the upper one has left - the rail. Only printed when the flight was run with - ``use_udot_rail2=True``; otherwise the phase never runs and there is - nothing to report. + the rail. Nothing is printed when the tip-off phase did not run. Returns ------- None """ - if not self.flight.use_udot_rail2: + if self.flight.tip_off_duration <= 0: return print("\nTip-Off State\n") print(f"Tip-Off Duration: {self.flight.tip_off_duration:.3f} s") - print(f"Lower Button Departure Time: {self.flight.between_rails_time:.3f} s") + print(f"Lower Button Departure Time: {self.flight.tip_off_end_time:.3f} s") print( "Lower Button Departure Velocity: " - f"{self.flight.between_rails_velocity:.3f} m/s" + f"{self.flight.tip_off_end_velocity:.3f} m/s" ) print( "Tip-Off Angle of Attack: " - f"{self.flight.angle_of_attack(self.flight.between_rails_time):.3f}°" + f"{self.flight.angle_of_attack(self.flight.tip_off_end_time):.3f}°" ) def burn_out_conditions(self): diff --git a/rocketpy/simulation/flight.py b/rocketpy/simulation/flight.py index 8113bb51f..c806494d3 100644 --- a/rocketpy/simulation/flight.py +++ b/rocketpy/simulation/flight.py @@ -7,6 +7,7 @@ import numpy as np from scipy.integrate import BDF, DOP853, LSODA, RK23, RK45, OdeSolver, Radau +from scipy.optimize import brentq from ..mathutils.function import Function, funcify_method from ..mathutils.vector_matrix import Matrix, Vector @@ -354,28 +355,32 @@ class Flight: as array. Flight.rail_button1_normal_force : Function Upper rail button normal force in N as a function - of time. + of time. Zero once the upper button has left the rail. Flight.max_rail_button1_normal_force : float Maximum upper rail button normal force experienced during rail flight phase in N. Flight.rail_button1_shear_force : Function Upper rail button shear force in N as a function - of time. + of time. Zero once the upper button has left the rail. Flight.max_rail_button1_shear_force : float Maximum upper rail button shear force experienced during rail flight phase in N. Flight.rail_button2_normal_force : Function Lower rail button normal force in N as a function - of time. + of time. While both buttons are on the rail it counts the + aerodynamic loads only. During the tip-off phase, when the lower + button holds the rocket alone, it is the full force between the + button and the rail, which also carries the weight of the rocket. Flight.max_rail_button2_normal_force : float Maximum lower rail button normal force experienced - during rail flight phase in N. + on the rail, tip-off phase included, in N. Flight.rail_button2_shear_force : Function Lower rail button shear force in N as a function - of time. + of time. See ``Flight.rail_button2_normal_force`` for what it + counts in each phase. Flight.max_rail_button2_shear_force : float Maximum lower rail button shear force experienced - during rail flight phase in N. + on the rail, tip-off phase included, in N. Flight.rotational_energy : Function Rocket's rotational kinetic energy as a function of time. Units in J. @@ -472,23 +477,21 @@ class Flight: array. Flight.simulation_mode : str Simulation mode for the flight. Can be "6 DOF" or "3 DOF". - Flight.use_udot_rail2 : bool - Whether the intermediate 3-DOF "tip-off" rail phase was enabled. When - True, the flight goes through ``udot_rail1`` -> ``udot_rail2`` -> - generalized 6-DOF instead of straight from ``udot_rail1`` to the - generalized equations. Requires ``simulation_mode="6 DOF"`` and - ``equations_of_motion="standard"``. - Flight.between_rails_time : float + Flight.tip_off_end_time : float Time at which the lower rail button leaves the rail, ending the tip-off - phase, in seconds. Equal to ``out_of_rail_time`` when the phase is off. - Flight.between_rails_velocity : float + phase, in seconds. Equal to ``out_of_rail_time`` when the tip-off phase + does not run: a rocket with fewer than two rail buttons, a flight with + ``simulation_mode="3 DOF"`` or with + ``equations_of_motion="solid_propulsion"``, or a flight started from an + ``initial_solution``. + Flight.tip_off_end_velocity : float Rocket velocity magnitude when the lower rail button leaves the rail, in m/s. - Flight.between_rails_state : list + Flight.tip_off_end_state : list State vector at the moment the lower rail button leaves the rail. Flight.tip_off_duration : float Time the rocket spends pivoting about the lower rail button, in - seconds. Zero when ``use_udot_rail2`` is False. + seconds. Zero when the tip-off phase does not run. Flight.rail_button1_bending_moment : Function Internal bending moment at upper rail button attachment point in N·m as a function of time. Calculated using beam theory during rail phase. @@ -503,11 +506,6 @@ class Flight: attachment point during rail flight phase in N·m. """ - #: Class-level default so that ``Flight`` objects restored from a ``.rpy`` - #: file written before the tip-off phase existed still answer the flag. - #: Instances built through ``__init__`` always shadow it. - use_udot_rail2 = False - def __init__( # pylint: disable=too-many-arguments,too-many-statements self, rocket, @@ -528,7 +526,6 @@ def __init__( # pylint: disable=too-many-arguments,too-many-statements equations_of_motion="standard", ode_solver="LSODA", simulation_mode="6 DOF", - use_udot_rail2=False, ): """Run a trajectory simulation. @@ -615,15 +612,6 @@ def __init__( # pylint: disable=too-many-arguments,too-many-statements simulation_mode : str, optional Simulation mode to use. Can be "6 DOF" for 6 degrees of freedom or "3 DOF" for 3 degrees of freedom. Default is "6 DOF". - use_udot_rail2 : bool, optional - If True, enable the intermediate 3-DOF "tip-off" rail phase - ``udot_rail2``: after the upper rail button leaves the rail (at - ``effective_1rl``) the rocket pivots about the still-engaged lower - button until it too leaves the rail (at ``effective_2rl``), before - the generalized 6-DOF free flight. If False, the flight transitions - directly from the 1-DOF ``udot_rail1`` phase to the generalized - 6-DOF dynamics at the upper button exit, as in previous versions. - Default is False. Returns ------- None @@ -658,8 +646,6 @@ def __init__( # pylint: disable=too-many-arguments,too-many-statements self.equations_of_motion = equations_of_motion self.simulation_mode = simulation_mode self.ode_solver = ode_solver - # Enable or disable the intermediate 3-DOF rail phase - self.use_udot_rail2 = use_udot_rail2 # Controller initialization self.__init_controllers() @@ -1020,8 +1006,7 @@ def __check_simulation_events(self, phase, phase_index, node_index): + (self.y_sol[2] - self.env.elevation) ** 2 ) # Check for first out of rail event (upper rail button leaving the - # rail, at effective_1rl). This starts the 3-DOF tip-off phase when - # enabled, otherwise transitions straight to generalized 6-DOF flight. + # rail, at effective_1rl). if ( len(self.out_of_rail_state) == 1 and squared_distance_travelled >= self.effective_1rl**2 @@ -1029,14 +1014,11 @@ def __check_simulation_events(self, phase, phase_index, node_index): return self.__handle_out_of_rail_event(phase, phase_index, node_index) # Check for the lower rail button leaving the rail (at effective_2rl), # which ends the tip-off phase and begins generalized 6-DOF flight. - # Only relevant while the intermediate udot_rail2 phase is active. elif ( - self.use_udot_rail2 - and len(self.between_rails_state) == 1 - and len(self.out_of_rail_state) != 1 + phase.derivative == self.udot_rail2 # pylint: disable=comparison-with-callable and squared_distance_travelled >= self.effective_2rl**2 ): - return self.__handle_between_rails_event(phase, phase_index, node_index) + return self.__handle_tip_off_end_event(phase, phase_index, node_index) # Check for apogee event # TODO: negative vz doesn't really mean apogee. Improve this. @@ -1050,74 +1032,43 @@ def __check_simulation_events(self, phase, phase_index, node_index): return False def __root_find_rail_exit_time(self, phase, effective_rl): - """Root-find the exact time at which the squared distance travelled - (from the launch point, ignoring ground elevation) equals - ``effective_rl ** 2``, using cubic Hermite interpolation between the two - most recent solution points. + """Find the time, within the last solver step, at which the distance + travelled from the launch point equals ``effective_rl``. + + The search runs on the solver's own interpolation of the step, so the + result is as accurate as the solution itself, however long the step is. Parameters ---------- phase : FlightPhase - The current flight phase (provides the solver step size). + The current flight phase, whose solver has just taken a step. effective_rl : float - Effective rail length whose crossing is being solved for - (``effective_1rl`` for the upper button, ``effective_2rl`` for the - lower button). + Distance at which a rail button reaches the end of the rail, in + meters: ``effective_1rl`` for the upper button and + ``effective_2rl`` for the lower one. Returns ------- float - Absolute simulation time of the crossing. + Simulation time of the crossing, in seconds. """ - # Check exactly when it went out using root finding - # Disconsider elevation - self.solution[-2][3] -= self.env.elevation - self.solution[-1][3] -= self.env.elevation - # Get points - y0 = sum(self.solution[-2][i] ** 2 for i in [1, 2, 3]) - effective_rl**2 - yp0 = 2 * sum( - self.solution[-2][i] * self.solution[-2][i + 3] for i in [1, 2, 3] - ) - t1 = self.solution[-1][0] - self.solution[-2][0] - y1 = sum(self.solution[-1][i] ** 2 for i in [1, 2, 3]) - effective_rl**2 - yp1 = 2 * sum( - self.solution[-1][i] * self.solution[-1][i + 3] for i in [1, 2, 3] - ) - # Put elevation back - self.solution[-2][3] += self.env.elevation - self.solution[-1][3] += self.env.elevation - # Cubic Hermite interpolation (ax**3 + bx**2 + cx + d) - a, b, c, d = calculate_cubic_hermite_coefficients( - 0, - float(phase.solver.step_size), - y0, - yp0, - y1, - yp1, - ) - a += 1e-5 # TODO: why?? - # Find roots - t_roots = find_roots_cubic_function(a, b, c, d) - # Find correct root - valid_t_root = [ - t_root.real - for t_root in t_roots - if 0 < t_root.real < t1 and abs(t_root.imag) < 0.001 - ] - if len(valid_t_root) > 1: # pragma: no cover - raise ValueError("Multiple roots found when solving for rail exit time.") - if len(valid_t_root) == 0: # pragma: no cover - raise ValueError("No valid roots found when solving for rail exit time.") - return valid_t_root[0] + self.solution[-2][0] + interpolator = phase.solver.dense_output() + elevation = self.env.elevation + + def distance_left(t): + x, y, z = interpolator(t)[:3] + return effective_rl**2 - (x**2 + y**2 + (z - elevation) ** 2) + + return brentq(distance_left, phase.solver.t_old, phase.solver.t) def __handle_out_of_rail_event(self, phase, phase_index, node_index): """Handle the out of rail event (upper rail button leaving the rail, at ``effective_1rl``). Records the out-of-rail state and inserts the next flight phase: the - 3-DOF tip-off phase ``udot_rail2`` when it is enabled and there is a - nonzero single-button window (``effective_2rl > effective_1rl``), - otherwise the generalized 6-DOF dynamics. + 3-DOF tip-off phase ``udot_rail2`` when the rocket has two rail buttons + and the equations of motion support it, otherwise the free-flight + dynamics. Parameters ---------- @@ -1141,13 +1092,20 @@ def __handle_out_of_rail_event(self, phase, phase_index, node_index): self.out_of_rail_time = self.t self.out_of_rail_time_index = len(self.solution) - 1 self.out_of_rail_state = self.y_sol - # Create new flight phase: the intermediate 3-DOF tip-off phase if - # enabled and the two buttons are distinct, otherwise straight to the - # generalized 6-DOF dynamics (previous behavior). - if self.use_udot_rail2 and self.effective_2rl > self.effective_1rl: + # Tip-off runs only with two buttons on the rail and the standard + # 6 DOF equations. Otherwise the rocket goes straight to free flight. + if ( + self.effective_2rl > self.effective_1rl > 0 + and self.simulation_mode == "6 DOF" + and self.equations_of_motion == "standard" + ): next_derivative = self.udot_rail2 else: next_derivative = self.u_dot_generalized + # No tip-off phase: the rocket is free when the upper button leaves + self.tip_off_end_time = self.out_of_rail_time + self.tip_off_end_time_index = self.out_of_rail_time_index + self.tip_off_end_state = self.out_of_rail_state self.flight_phases.add_phase( self.t, next_derivative, @@ -1159,7 +1117,7 @@ def __handle_out_of_rail_event(self, phase, phase_index, node_index): phase.solver.status = "finished" return True - def __handle_between_rails_event(self, phase, phase_index, node_index): + def __handle_tip_off_end_event(self, phase, phase_index, node_index): """Handle the end of the 3-DOF tip-off phase (lower rail button leaving the rail, at ``effective_2rl``). @@ -1185,9 +1143,9 @@ def __handle_between_rails_event(self, phase, phase_index, node_index): interpolator = phase.solver.dense_output() self.y_sol = interpolator(self.t) self.solution[-1] = [self.t, *self.y_sol] - self.between_rails_time = self.t - self.between_rails_time_index = len(self.solution) - 1 - self.between_rails_state = self.y_sol + self.tip_off_end_time = self.t + self.tip_off_end_time_index = len(self.solution) - 1 + self.tip_off_end_state = self.y_sol # Create the generalized 6-DOF free-flight phase self.flight_phases.add_phase( self.t, @@ -1614,9 +1572,9 @@ def __init_solution_monitors(self): self.out_of_rail_time = 0 self.out_of_rail_time_index = 0 self.out_of_rail_state = np.array([0]) - self.between_rails_state = np.array([0]) - self.between_rails_time = 0 - self.between_rails_time_index = 0 + self.tip_off_end_state = np.array([0]) + self.tip_off_end_time = 0 + self.tip_off_end_time_index = 0 self.apogee_state = np.array([0]) self.apogee = 0 self.apogee_time = 0 @@ -1626,6 +1584,7 @@ def __init_solution_monitors(self): self.impact_state = np.array([0]) self.parachute_events = [] self.__post_processed_variables = [] + self._tip_off_button_forces = [] def __init_flight_state(self): """Initialize flight state variables.""" @@ -1695,15 +1654,14 @@ def __init_flight_state(self): self.initial_solution = self.initial_solution.solution[-1] # Initial solution given, ignore rail phases # TODO: Check if rocket is actually out of rail. Otherwise, start at rail - # Both rail phases are skipped, so their monitors record the given - # starting state: out of rail (upper button) and, when the - # intermediate tip-off phase is enabled, between rails (lower button). + # Both rail phases are skipped, so the upper button exit and the + # end of tip-off (lower button exit) record the given starting state self.out_of_rail_state = self.initial_solution[1:] self.out_of_rail_time = self.initial_solution[0] self.out_of_rail_time_index = 0 - self.between_rails_state = self.initial_solution[1:] - self.between_rails_time = self.initial_solution[0] - self.between_rails_time_index = 0 + self.tip_off_end_state = self.initial_solution[1:] + self.tip_off_end_time = self.initial_solution[0] + self.tip_off_end_time_index = 0 self.t_initial = self.initial_solution[0] # Set initial derivative for 6-DOF flight phase self.initial_derivative = self.u_dot_generalized @@ -1758,30 +1716,6 @@ def __init_equations_of_motion(self): "Must be '3 DOF' or '6 DOF'." ) - # The tip-off phase patches the *generalized* 6-DOF solution with a - # constraint wrench built from the full 3x3 inertia tensor. The reduced - # formulations bound above (``u_dot_generalized_3dof`` carries no - # attitude at all, ``u_dot`` uses the axisymmetric solid-propulsion - # equations) do not share that state, so the patch would be applied to - # a solution it does not describe. Refuse the combination instead of - # silently producing non-physical tip-off kinematics. - if self.use_udot_rail2: - if self.simulation_mode != "6 DOF": - raise ValueError( - "use_udot_rail2=True requires simulation_mode='6 DOF', got " - f"'{self.simulation_mode}'. The tip-off phase solves for the " - "rotation about the lower rail button, which the 3 DOF " - "equations of motion do not model. Note that a point-mass " - "motor forces simulation_mode to '3 DOF'." - ) - if self.equations_of_motion != "standard": - raise ValueError( - "use_udot_rail2=True requires equations_of_motion='standard', " - f"got '{self.equations_of_motion}'. The tip-off phase is " - "derived from the generalized variable-mass equations and " - "cannot patch the reduced solid_propulsion formulation." - ) - def __init_controllers(self): """Initialize controllers and sensors""" self._controllers = self.rocket._controllers[:] @@ -1998,25 +1932,16 @@ def udot_rail1(self, t, u, post_processing=False): def udot_rail2(self, t, u, post_processing=False): """Calculates the derivative of the u state vector with respect to time - for the intermediate 3-DOF "tip-off" rail phase: the upper rail button - has left the rail but the lower button is still engaged, so the rocket - slides along the (fixed) rail line while free to pitch and yaw about the - lower button, with roll suppressed. - - The dynamics reuse the free variable-mass generalized equations of - motion (:meth:`u_dot_generalized`) and enforce the single-button - constraint by adding an unknown reaction wrench solved from a small - linear system: a normal force ``N`` at the lower button (perpendicular - to the rail, 2 DOF) plus a roll reaction moment ``mu`` (1 DOF). The - three unknowns are found from three constraints -- the button's - acceleration perpendicular to the rail is zero (2) and the roll angular - acceleration is zero (1). The full derivation is in the technical - documentation, :ref:`Tip-off `. All reaction quantities are - expressed in the "true" - body frame (the one used by ``surfaces_cp_to_cdm``, body-z toward the - nose), so ``r_CM`` and the button position are taken with that sign - convention -- independent of the internal (point-to-CDM) convention used - by the generalized equations. + while only the lower rail button is on the rail (tip-off). + + The rocket slides along the rail and is free to pitch and yaw about the + lower button, while roll is prevented. The accelerations of the free + rocket, from :meth:`u_dot_generalized`, are corrected by a force at the + button, perpendicular to the rail, and a moment about the rocket axis. + These are found from three conditions: the acceleration of the button + has no component perpendicular to the rail (two conditions) and the + roll angular acceleration is zero. The derivation is in the technical + documentation, :ref:`Tip-off `. Parameters ---------- @@ -2035,112 +1960,84 @@ def udot_rail2(self, t, u, post_processing=False): State vector defined by u_dot = [vx, vy, vz, ax, ay, az, e0dot, e1dot, e2dot, e3dot, alpha1, alpha2, alpha3]. """ - # Free (unconstrained) generalized solution. This also handles the - # aerodynamic/post-processing bookkeeping. We keep its position and - # quaternion derivatives and only override the 6-DOF accelerations - # (indices 3:6 inertial linear, 10:13 body angular) with the - # constrained values computed below. u_dot = list(self.u_dot_generalized(t, u, post_processing=post_processing)) - a_cdm_free = Vector(u_dot[3:6]) # inertial CDM acceleration (free) - w_dot_free = Vector(u_dot[10:13]) # body angular acceleration (free) - - # State quantities - e0, e1, e2, e3 = u[6:10] + a_free = Vector(u_dot[3:6]) # center of dry mass, inertial frame + alpha_free = Vector(u_dot[10:13]) # body frame w = Vector(u[10:13]) - K = Matrix.transformation([e0, e1, e2, e3]) + K = Matrix.transformation(u[6:10]) Kt = K.transpose - # ``u_dot_generalized`` just interpolated the mass and the inertia about - # the CM for this very t; reuse them instead of paying for both again on - # every solver evaluation inside the tip-off window. - cached = getattr(self, "_mass_inertia_cache", None) - if cached is not None and cached[0] == t: - _, total_mass, inertia_cm = cached - else: # pragma: no cover - defensive, the call above always fills it - total_mass = self.rocket.total_mass.get_value_opt(t) - inertia_cm = None - - # Geometry in the true body frame (body-z toward the nose): - # position of a point p relative to the CDM = (p - cdm) * csys. - # The generalized EOM store r_CM / r_NOZ as (point -> CDM) vectors, i.e. - # the negative of the true-frame position; hence the sign flips below. - csys = self.rocket._csys - cdm = self.rocket.center_of_dry_mass_position - r_CM = Vector([0, 0, -self.rocket.com_to_cdm_function.get_value_opt(t)]) - lower_button_z = self.rocket.rail_buttons[0].position.z - r_button = Vector([0, 0, (lower_button_z - cdm) * csys]) - - # Inertia about the instantaneous center of mass (sign-independent). - if inertia_cm is None: # pragma: no cover - defensive, see cache above - inertia_tensor = self.rocket.get_inertia_tensor_at_time(t) - inertia_cm = inertia_tensor - ( - (r_CM.cross_matrix @ -r_CM.cross_matrix) * total_mass - ) - inv_inertia_cm = inertia_cm.inverse - - # Orthonormal body triad with the rail direction. The rail is the fixed - # inertial unit vector ``attitude_unit``; express it in the body frame. - n = Kt @ self.attitude_unit - n = n / abs(n) - # Pick the coordinate axis least aligned with n to build a stable basis. - if abs(n.z) <= abs(n.x) and abs(n.z) <= abs(n.y): - helper = Vector([0.0, 0.0, 1.0]) - elif abs(n.y) <= abs(n.x): - helper = Vector([0.0, 1.0, 0.0]) - else: - helper = Vector([1.0, 0.0, 0.0]) - e1_b = n ^ helper - e1_b = e1_b / abs(e1_b) - e2_b = n ^ e1_b # already unit (n, e1_b orthonormal) - z_b = Vector([0.0, 0.0, 1.0]) # body roll axis - - # Linear response of (angular accel, CDM accel, button accel) in the - # body frame to a reaction force ``Fr`` (body) at the button and a roll - # reaction moment ``tau`` about the body axis. - def _response(f_r, tau): - d_wdot = inv_inertia_cm @ ( - ((r_button - r_CM) ^ f_r) + Vector([0.0, 0.0, tau]) - ) - d_a_cdm_body = f_r * (1.0 / total_mass) - (d_wdot ^ r_CM) - d_a_button = d_a_cdm_body + (d_wdot ^ r_button) - return d_wdot, d_a_cdm_body, d_a_button - # Free button acceleration in the body frame. - a_button_free = ( - (Kt @ a_cdm_free) + (w_dot_free ^ r_button) + (w ^ (w ^ r_button)) + # Positions along the rocket axis, from the center of dry mass + rocket = self.rocket + mass = rocket.total_mass.get_value_opt(t) + z_cm = -rocket.com_to_cdm_function.get_value_opt(t) + z_button = ( + rocket.rail_buttons[0].position.z - rocket.center_of_dry_mass_position + ) * rocket._csys + r_cm = Vector([0, 0, z_cm]) + r_button = Vector([0, 0, z_button]) + cm_to_button = Vector([0, 0, z_button - z_cm]) + # Inertia about the center of mass (parallel axis theorem) + shift = mass * z_cm**2 + inertia_cm_inverse = ( + rocket.get_inertia_tensor_at_time(t) + - Matrix([[shift, 0, 0], [0, shift, 0], [0, 0, 0]]) + ).inverse + + # 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 + e1 = rail ^ Vector([1, 0, 0] if abs(rail.x) < 0.9 else [0, 1, 0]) + e1 = e1 / abs(e1) + e2 = rail ^ e1 + roll_axis = Vector([0, 0, 1]) + + # Acceleration of the button if the rocket were free, in the body frame + a_button_free = (Kt @ a_free) + (alpha_free ^ r_button) + (w ^ (w ^ r_button)) + + # Angular acceleration and button acceleration caused by a unit force + # along e1, a unit force along e2 and a unit roll moment + alphas = ( + inertia_cm_inverse @ (cm_to_button ^ e1), + inertia_cm_inverse @ (cm_to_button ^ e2), + inertia_cm_inverse @ roll_axis, ) - - # Assemble the 3x3 system J @ [lambda1, lambda2, mu] = -g_free. - jacobian = np.empty((3, 3)) - for col, (f_r, tau) in enumerate( - ((e1_b, 0.0), (e2_b, 0.0), (Vector([0.0, 0.0, 0.0]), 1.0)) - ): - d_wdot, _, d_a_button = _response(f_r, tau) - jacobian[0, col] = d_a_button @ e1_b - jacobian[1, col] = d_a_button @ e2_b - jacobian[2, col] = d_wdot @ z_b - g_free = np.array( - [a_button_free @ e1_b, a_button_free @ e2_b, w_dot_free @ z_b] + a_buttons = ( + e1 / mass + (alphas[0] ^ cm_to_button), + e2 / mass + (alphas[1] ^ cm_to_button), + alphas[2] ^ cm_to_button, ) - try: - lambda1, lambda2, mu = np.linalg.solve(jacobian, -g_free) - except np.linalg.LinAlgError: # pragma: no cover - warnings.warn( - "Singular constraint system in udot_rail2; falling back to " - "unconstrained dynamics for this step.", - RuntimeWarning, - ) - return u_dot + # Force along e1 and e2 and roll moment that meet the three conditions + response = Matrix( + [ + [a_button @ e1 for a_button in a_buttons], + [a_button @ e2 for a_button in a_buttons], + [alpha @ roll_axis for alpha in alphas], + ] + ) + force_1, force_2, roll_moment = response.inverse @ Vector( + [ + -(a_button_free @ e1), + -(a_button_free @ e2), + -(alpha_free @ roll_axis), + ] + ) - f_r = e1_b * lambda1 + e2_b * lambda2 - d_wdot, d_a_cdm_body, _ = _response(f_r, mu) - w_dot = w_dot_free + d_wdot - # Enforce exactly zero roll acceleration (kills residual round-off). - w_dot = Vector([w_dot.x, w_dot.y, 0.0]) - a_cdm = a_cdm_free + (K @ d_a_cdm_body) + button_force = e1 * force_1 + e2 * force_2 # on the rocket, body frame + delta_alpha = ( + alphas[0] * force_1 + alphas[1] * force_2 + alphas[2] * roll_moment + ) + alpha = alpha_free + delta_alpha + a_cdm = a_free + K @ (button_force / mass - (delta_alpha ^ r_cm)) u_dot[3:6] = [a_cdm.x, a_cdm.y, a_cdm.z] - u_dot[10:13] = [w_dot.x, w_dot.y, w_dot.z] + u_dot[10:13] = [alpha.x, alpha.y, 0.0] # roll is exactly zero + if post_processing: + # u_dot_generalized stored the accelerations of the free rocket + self.__post_processed_variables[-1][1:7] = [*u_dot[3:6], *u_dot[10:13]] + # Force of the lower button on the rail, opposite to the one above + self._tip_off_button_forces.append([t, -button_force.x, -button_force.y]) return u_dot def u_dot(self, t, u, post_processing=False): # pylint: disable=too-many-locals,too-many-statements @@ -2765,12 +2662,6 @@ def u_dot_generalized(self, t, u, post_processing=False): # pylint: disable=too H = (r_CM.cross_matrix @ -r_CM.cross_matrix) * total_mass I_CM = inertia_tensor - H - # Expose the mass and the inertia about the CM for the tip-off phase, - # which patches this solution and would otherwise interpolate both again - # for the same t on every solver evaluation. H is quadratic in r_CM, so - # I_CM does not depend on the sign convention used for it. - self._mass_inertia_cache = (t, total_mass, I_CM) - # Prepare transformation matrices K = Matrix.transformation(e) Kt = K.transpose @@ -3390,24 +3281,22 @@ def out_of_rail_velocity(self): return self.speed.get_value_opt(self.out_of_rail_time) @property - def between_rails_velocity(self): + def tip_off_end_velocity(self): """Velocity at which the lower rail button leaves the launch rail, - ending the ``udot_rail2`` tip-off phase. Only meaningful when the - flight was run with ``use_udot_rail2=True``; otherwise the tip-off - phase never runs and this equals :attr:`out_of_rail_velocity`. + ending the tip-off phase, in m/s. Equal to :attr:`out_of_rail_velocity` + when the tip-off phase does not run. """ - return self.speed.get_value_opt(self.between_rails_time) + return self.speed.get_value_opt(self.tip_off_end_time) @property def tip_off_duration(self): """Duration of the tip-off window, i.e. the time the rocket spends pivoting about the lower rail button between the upper button leaving - the rail and the lower button leaving it. Zero when the flight was run - without ``use_udot_rail2``. + the rail and the lower button leaving it, in seconds. Zero when the + tip-off phase does not run, or when the lower button never leaves the + rail because the flight ends or a parachute opens first. """ - if not self.use_udot_rail2: - return 0.0 - return self.between_rails_time - self.out_of_rail_time + return max(self.tip_off_end_time - self.out_of_rail_time, 0.0) @cached_property def max_speed_time(self): @@ -4228,7 +4117,9 @@ def get_controller_observed_variables(self): def __calculate_rail_button_forces(self): # TODO: complex method. """Calculate the forces applied to the rail buttons while rocket is still on the launch rail. It will return 0 if no rail buttons are - defined. + defined. While both buttons are on the rail only the aerodynamic loads + are shared between them. During the tip-off phase the lower button + takes the force found in ``udot_rail2`` and the upper button none. Returns ------- @@ -4282,8 +4173,11 @@ def __calculate_rail_button_forces(self): # TODO: complex method. F22 = (self.R2 * D1 - self.M1) / (D1 + D2) F22.set_outputs("Lower button force direction 2 (m)") + # Points up to the upper button exit. Selected by time, since flights + # with controllers do not store one point per solution step. + on_rail = F11.get_source() model = Function( - F11.get_source()[: self.out_of_rail_time_index + 1, :], + on_rail[on_rail[:, 0] <= self.out_of_rail_time], interpolation=F11.__interpolation__, ) @@ -4293,6 +4187,29 @@ def __calculate_rail_button_forces(self): # TODO: complex method. F21.set_discrete_based_on_model(model) F22.set_discrete_based_on_model(model) + # During tip-off only the lower button is on the rail: it carries the + # force found in udot_rail2 and the upper button carries none + tip_off = np.array(self._tip_off_button_forces) + if len(tip_off) > 0: + no_force = np.zeros(len(tip_off)) + F11, F12, F21, F22 = ( + Function( + np.vstack( + (force.get_source(), np.column_stack((tip_off[:, 0], values))) + ), + force.__inputs__, + force.__outputs__, + interpolation="linear", + extrapolation="zero", + ) + for force, values in ( + (F11, no_force), + (F12, no_force), + (F21, tip_off[:, 1]), + (F22, tip_off[:, 2]), + ) + ) + rail_button1_normal_force = F11 * np.cos(angular_position_rad) + F12 * np.sin( angular_position_rad ) @@ -4359,6 +4276,7 @@ def __evaluate_post_process(self): [t, ax, ay, az, alpha1, alpha2, alpha3, R1, R2, R3, M1, M2, M3, net_thrust] """ self.__post_processed_variables = [] + self._tip_off_button_forces = [] for phase_index, phase in self.time_iterator(self.flight_phases): init_time = phase.t final_time = self.flight_phases[phase_index + 1].t @@ -4450,6 +4368,7 @@ def to_dict(self, **kwargs): "solution": self.solution, "out_of_rail_time": self.out_of_rail_time, "out_of_rail_time_index": self.out_of_rail_time_index, + "tip_off_end_time": self.tip_off_end_time, "apogee_time": self.apogee_time, "apogee": self.apogee, "parachute_events": self.parachute_events, @@ -4472,6 +4391,7 @@ def to_dict(self, **kwargs): "M2": self.M2, "M3": self.M3, "net_thrust": self.net_thrust, + "tip_off_button_forces": self._tip_off_button_forces, } if kwargs.get("include_outputs", False): @@ -4480,7 +4400,7 @@ def to_dict(self, **kwargs): "time": self.time, "out_of_rail_velocity": self.out_of_rail_velocity, "out_of_rail_state": self.out_of_rail_state, - "between_rails_state": self.between_rails_state, + "tip_off_end_state": self.tip_off_end_state, "apogee_x": self.apogee_x, "apogee_y": self.apogee_y, "apogee_state": self.apogee_state, diff --git a/rocketpy/tools.py b/rocketpy/tools.py index 35d5a4aea..9871d48e7 100644 --- a/rocketpy/tools.py +++ b/rocketpy/tools.py @@ -1203,7 +1203,8 @@ def wrapper(*args, **kwargs): for i in range(max_attempts): try: return func(*args, **kwargs) - except Exception as e: # pragma: no cover # pylint: disable=broad-exception-caught + # pylint: disable-next=broad-exception-caught + except Exception as e: # pragma: no cover if i == max_attempts - 1: raise e from None delay = min(delay * 2, max_delay) diff --git a/tests/unit/simulation/test_flight.py b/tests/unit/simulation/test_flight.py index fe18717db..83c88a681 100644 --- a/tests/unit/simulation/test_flight.py +++ b/tests/unit/simulation/test_flight.py @@ -311,7 +311,7 @@ def test_export_sensor_data(flight_calisto_with_sensors): [ ("t_initial", (0.25886, -0.649623, 0)), ("out_of_rail_time", (0.792028, -1.987634, 0)), - ("apogee_time", (-0.652606, -0.734029, -2.115675e-14)), + ("apogee_time", (-0.669152, -0.694259, -2.115675e-14)), ("t_final", (0, 0, 0)), ], ) @@ -350,7 +350,7 @@ def test_aerodynamic_moments(flight_calisto_custom_wind, flight_time, expected_v [ ("t_initial", (1.654150, 0.659142, -0.067103)), ("out_of_rail_time", (5.052628, 2.013361, -1.75370)), - ("apogee_time", (2.266124, -2.014696, -0.818709)), + ("apogee_time", (2.154305, -2.076229, -0.848628)), ("t_final", (-0.019802, 0.012030, 159.051604)), ], ) @@ -391,7 +391,7 @@ def test_aerodynamic_forces(flight_calisto_custom_wind, flight_time, expected_va ("out_of_rail_time", (0, 2.248540, 25.700928)), ( "apogee_time", - (-11.634095, 16.695945, -0.000173), + (-11.328713, 17.626676, -0.000173), ), ("t_final", (5, 2, -5.660155)), ], @@ -481,8 +481,8 @@ def test_rail_buttons_forces(flight_calisto_custom_wind): atol = 5e-3 assert pytest.approx(1.795539, abs=atol) == test.max_rail_button1_normal_force assert pytest.approx(0.715483, abs=atol) == test.max_rail_button1_shear_force - assert pytest.approx(3.257089, abs=atol) == test.max_rail_button2_normal_force - assert pytest.approx(1.297878, abs=atol) == test.max_rail_button2_shear_force + assert pytest.approx(5.135214, abs=atol) == test.max_rail_button2_normal_force + assert pytest.approx(15.020664, abs=atol) == test.max_rail_button2_shear_force def test_max_values(flight_calisto_robust): diff --git a/tests/unit/simulation/test_udot_rail2_feature.py b/tests/unit/simulation/test_udot_rail2_feature.py index e0486ce25..c52252f5a 100644 --- a/tests/unit/simulation/test_udot_rail2_feature.py +++ b/tests/unit/simulation/test_udot_rail2_feature.py @@ -1,31 +1,32 @@ """Unit tests for the ``udot_rail2`` 3-DOF "tip-off" rail phase (issue #28). -These tests follow the project's testing conventions: each test uses the -Arrange / Act / Assert pattern and documents the expected behaviour in its -docstring. They avoid plotting and optional-dependency features so they run -reliably in CI. +The phase runs whenever the rocket has two rail buttons and the flight uses the +standard 6 DOF equations of motion. Coverage: -Coverage: - Phase ordering: ``udot_rail1`` -> ``udot_rail2`` -> ``u_dot_generalized``. -- Opt-in default: ``use_udot_rail2`` defaults to False and, when disabled, no - ``udot_rail2`` phase is inserted (previous behaviour preserved). -- Constraint satisfaction: the lower rail button stays on the rail line and the - roll acceleration/rate remains zero throughout the phase. -- Physical direction: with no wind the nose pitches over (gravity tip-off). -- Mode compatibility: the phase refuses reduced formulations it cannot patch. -- Reporting: the window shows up in ``.info()`` and in the attitude plots. +- The window starts and ends where the two buttons reach the end of the rail. +- Constraint: the lower button stays on the rail line and roll stays zero. +- Physics: the motion matches an independent model of a rigid body pivoting + about a point that slides along the rail. +- Outputs: the accelerations reported inside the window are the integrated + ones, and the window shows up in ``.info()`` and in the attitude plots. +- The phase is skipped where it cannot run. """ import math import matplotlib.pyplot as plt +import numpy as np import pytest +from scipy.integrate import solve_ivp +from rocketpy import Environment, Rocket, SolidMotor +from rocketpy._encoders import rebuild_minimal_flight from rocketpy.mathutils import Matrix, Vector from rocketpy.simulation.flight import Flight -def _make_flight(rocket, environment, use_udot_rail2): +def _make_flight(rocket, environment, **kwargs): return Flight( rocket=rocket, environment=environment, @@ -33,7 +34,60 @@ def _make_flight(rocket, environment, use_udot_rail2): inclination=85, heading=0, terminate_on_apogee=True, - use_udot_rail2=use_udot_rail2, + **kwargs, + ) + + +def _bare_flight(grain_density=1815, **kwargs): + """Flight of a rocket with no aerodynamics (no surfaces, zero drag) under a + constant thrust, in still air and without Earth rotation. Only thrust and + gravity act, so the motion on the rail can be written down exactly. A very + low ``grain_density`` leaves almost no propellant, which makes the rocket a + rigid body of constant mass. + """ + environment = Environment() + environment.earth_rotation_vector = [0.0, 0.0, 0.0] + motor = SolidMotor( + thrust_source=2000.0, + burn_time=3.9, + dry_mass=1.815, + dry_inertia=(0.125, 0.125, 0.002), + nozzle_radius=33 / 1000, + grain_number=5, + grain_density=grain_density, + grain_outer_radius=33 / 1000, + grain_initial_inner_radius=15 / 1000, + grain_initial_height=120 / 1000, + grain_separation=5 / 1000, + grains_center_of_mass_position=0.397, + center_of_dry_mass_position=0.317, + nozzle_position=0, + throat_radius=11 / 1000, + coordinate_system_orientation="nozzle_to_combustion_chamber", + ) + rocket = Rocket( + radius=0.0635, + mass=14.426, + inertia=(6.321, 6.321, 0.034), + power_off_drag=0.0, + power_on_drag=0.0, + center_of_mass_without_motor=0, + coordinate_system_orientation="tail_to_nose", + ) + rocket.add_motor(motor, position=-1.255) + rocket.set_rail_buttons( + upper_button_position=0.0818, + lower_button_position=-0.6182, + angular_position=45, + ) + return Flight( + rocket=rocket, + environment=environment, + rail_length=5.2, + heading=0, + max_time=1.0, + terminate_on_apogee=False, + **kwargs, ) @@ -45,7 +99,7 @@ def _phase_names(flight): def _lower_button_body_position(rocket): - """Lower rail button position relative to the CDM in the true body frame.""" + """Lower rail button position from the center of dry mass, body frame.""" z = (rocket.rail_buttons[0].position.z - rocket.center_of_dry_mass_position) * ( rocket._csys ) @@ -54,390 +108,436 @@ def _lower_button_body_position(rocket): def _tip_off_rows(flight): """Solution rows [t, *state] within the tip-off window (inclusive).""" - t0, t1 = flight.out_of_rail_time, flight.between_rails_time + t0, t1 = flight.out_of_rail_time, flight.tip_off_end_time return [row for row in flight.solution if t0 - 1e-12 <= row[0] <= t1 + 1e-12] +def _distance_travelled(flight, state): + return math.hypot(state[0], state[1], state[2] - flight.env.elevation) + + def _attitude_inclination_deg(state): """Inclination (deg from horizontal) of the body axis in the inertial frame.""" body_axis = Matrix.transformation(state[6:10]) @ Vector([0.0, 0.0, 1.0]) return math.degrees(math.atan2(body_axis.z, math.hypot(body_axis.x, body_axis.y))) -def test_udot_rail2_default_is_opt_in(calisto_robust, example_spaceport_env): - """``use_udot_rail2`` defaults to False and, when not requested, the flight - keeps the previous rail1 -> generalized transition with no ``udot_rail2``. - - Arrange: build a Flight without passing ``use_udot_rail2``. - Act: read the flag and the phase derivative names. - Assert: the flag is False and no ``udot_rail2`` phase was inserted. - """ - # Arrange / Act - flight = Flight( - rocket=calisto_robust, - environment=example_spaceport_env, - rail_length=5.2, - inclination=85, - heading=0, - terminate_on_apogee=True, - ) - - # Assert - assert flight.use_udot_rail2 is False, ( - "tip-off phase must be opt-in (default False)" - ) - assert "udot_rail2" not in _phase_names(flight) - - -def test_udot_rail2_inserts_phase_in_order(calisto_robust, example_spaceport_env): - """With ``use_udot_rail2=True`` the intermediate 3-DOF ``udot_rail2`` phase - is inserted between the 1-DOF ``udot_rail1`` and the 6-DOF - ``u_dot_generalized`` phases. - - Arrange: build a Flight with ``use_udot_rail2=True``. - Act: inspect the ordered phase derivative names. - Assert: rail1 < rail2 < generalized in the phase list. - """ - # Arrange / Act - flight = _make_flight(calisto_robust, example_spaceport_env, True) +def test_udot_rail2_runs_between_the_rail_phase_and_free_flight( + calisto_robust, example_spaceport_env +): + """A rocket with two rail buttons goes through the tip-off phase, between + the 1-DOF rail phase and free flight, without being asked to.""" + flight = _make_flight(calisto_robust, example_spaceport_env) names = _phase_names(flight) - # Assert - assert "udot_rail2" in names, "udot_rail2 phase not present" - assert names.index("udot_rail1") < names.index("udot_rail2"), ( - "udot_rail2 should follow the 1-DOF rail phase" - ) - assert names.index("udot_rail2") < names.index("u_dot_generalized"), ( - "udot_rail2 should precede the generalized 6-DOF phase" - ) + assert "udot_rail2" in names + assert names.index("udot_rail1") < names.index("udot_rail2") + assert names.index("udot_rail2") < names.index("u_dot_generalized") -def test_udot_rail2_window_is_between_effective_rail_lengths( +def test_udot_rail2_window_starts_and_ends_at_the_button_exits( calisto_robust, example_spaceport_env ): - """The tip-off phase spans the interval between the upper button exit - (``effective_1rl``, recorded as ``out_of_rail``) and the lower button exit - (``effective_2rl``, recorded as ``between_rails``). + """The window opens when the upper button reaches the end of the rail and + closes when the lower one does.""" + flight = _make_flight(calisto_robust, example_spaceport_env) - Arrange: build a Flight with the tip-off phase enabled. - Act: read the event times. - Assert: ``0 < out_of_rail_time < between_rails_time`` and the window is short. - """ - # Arrange / Act - flight = _make_flight(calisto_robust, example_spaceport_env, True) - - # Assert assert flight.effective_2rl > flight.effective_1rl - assert 0 < flight.out_of_rail_time < flight.between_rails_time - assert (flight.between_rails_time - flight.out_of_rail_time) < 1.0 + assert 0 < flight.out_of_rail_time < flight.tip_off_end_time + assert flight.tip_off_duration == pytest.approx( + flight.tip_off_end_time - flight.out_of_rail_time + ) + assert _distance_travelled(flight, flight.out_of_rail_state) == pytest.approx( + flight.effective_1rl, rel=1e-9 + ) + assert _distance_travelled(flight, flight.tip_off_end_state) == pytest.approx( + flight.effective_2rl, rel=1e-9 + ) def test_udot_rail2_button_stays_on_rail(calisto_robust, example_spaceport_env): - """The single-button constraint must keep the lower rail button on the rail - line: its distance from the rail axis stays ~0 throughout the tip-off phase. - - Arrange: run a Flight with the tip-off phase enabled. - Act: for every solution point in the tip-off window, compute the lower - button position and its perpendicular distance to the (fixed) rail line. - Assert: the maximum perpendicular offset is negligible. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, True) + """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_origin = Vector(flight.solution[0][1:4]) + rows = _tip_off_rows(flight) + first_state = rows[0][1:] + rail_origin = ( + Vector(first_state[0:3]) + Matrix.transformation(first_state[6:10]) @ r_b + ) - # Act max_perp = 0.0 - for row in _tip_off_rows(flight): + for row in rows: state = row[1:] - cdm = Vector(state[0:3]) - button = cdm + Matrix.transformation(state[6:10]) @ r_b + button = Vector(state[0:3]) + Matrix.transformation(state[6:10]) @ r_b offset = button - rail_origin perpendicular = offset - rail_dir * (offset @ rail_dir) max_perp = max(max_perp, abs(perpendicular)) - # Assert - assert len(_tip_off_rows(flight)) >= 2, "tip-off window not exercised" + assert len(rows) >= 2, "tip-off window not exercised" assert max_perp < 1e-6, f"button drifted off the rail (max offset {max_perp} m)" def test_udot_rail2_no_roll(calisto_robust, example_spaceport_env): - """The tip-off phase must not induce roll: both the roll angular - acceleration returned by ``udot_rail2`` and the integrated roll rate stay - zero. - - Arrange: run a Flight with the tip-off phase enabled. - Act: evaluate ``udot_rail2`` at the phase-end state and scan the roll rate - over the tip-off window. - Assert: the roll angular acceleration and every sampled roll rate are ~0. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, True) + """Neither the roll angular acceleration nor the roll rate leaves zero.""" + flight = _make_flight(calisto_robust, example_spaceport_env) - # Act - u_dot = flight.udot_rail2(flight.between_rails_time, flight.between_rails_state) - roll_acceleration = u_dot[12] + u_dot = flight.udot_rail2(flight.tip_off_end_time, flight.tip_off_end_state) max_roll_rate = max(abs(row[1:][12]) for row in _tip_off_rows(flight)) - # Assert - assert abs(roll_acceleration) < 1e-12, ( - f"expected zero roll acceleration, got {roll_acceleration}" - ) + assert u_dot[12] == 0 assert max_roll_rate < 1e-9, f"expected zero roll rate, got {max_roll_rate}" -def test_udot_rail2_rail_axis_defined_for_given_initial_solution( - calisto_robust, example_spaceport_env -): - """The rail axis ``udot_rail2`` constrains the button to is set by the launch - inclination and heading, so it must exist even when the rail phase is skipped - because an ``initial_solution`` was supplied. - - Arrange: run a launch and take a mid-flight state from its solution. - Act: build a Flight that starts from that state instead of the rail. - Assert: ``attitude_unit`` is the same rail unit vector as the launch's, so - ``udot_rail2`` cannot raise ``AttributeError``. - """ - # Arrange - launch = _make_flight(calisto_robust, example_spaceport_env, True) - mid_flight_state = list(launch.solution[len(launch.solution) // 2]) - - # Act - continuation = Flight( - rocket=calisto_robust, - environment=example_spaceport_env, - rail_length=5.2, - inclination=85, - heading=0, - terminate_on_apogee=True, - initial_solution=mid_flight_state, - use_udot_rail2=True, - ) - - # Assert - assert abs(abs(continuation.attitude_unit) - 1) < 1e-12 - for axis in range(3): - assert continuation.attitude_unit[axis] == launch.attitude_unit[axis] - - def test_udot_rail2_gravity_tip_off_direction(calisto_robust, example_spaceport_env): - """With no wind, gravity acting on the center of mass (ahead of the lower - button pivot) tips the nose over: the attitude inclination decreases across - the tip-off phase by a small amount. - - Arrange: run a wind-free Flight with the tip-off phase enabled. - Act: measure the attitude inclination at the start and end of the window. - Assert: the inclination decreases, by a small (sub-degree) magnitude. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, True) + """With no wind, gravity on the center of mass, which sits ahead of the + lower button, pitches the nose down by a small amount.""" + flight = _make_flight(calisto_robust, example_spaceport_env) rows = _tip_off_rows(flight) - # Act - incl_start = _attitude_inclination_deg(rows[0][1:]) - incl_end = _attitude_inclination_deg(rows[-1][1:]) - delta = incl_end - incl_start + delta = _attitude_inclination_deg(rows[-1][1:]) - _attitude_inclination_deg( + rows[0][1:] + ) - # Assert assert delta < 0, f"nose should pitch down (gravity tip-off), got {delta:+.4f} deg" assert abs(delta) < 1.0, f"tip-off rotation implausibly large: {delta:+.4f} deg" -def test_udot_rail2_rejects_3dof_simulation_mode(calisto_robust, example_spaceport_env): - """The tip-off phase must refuse ``simulation_mode='3 DOF'``. +def _pivot_model_parameters(flight): + """Mass, distance from the lower button to the center of mass, inertia + about the center of mass, thrust and gravity when the window opens.""" + rocket = flight.rocket + t1 = flight.out_of_rail_time + mass = rocket.total_mass(t1) + center_of_mass = rocket.center_of_mass(t1) + cm_from_cdm = (center_of_mass - rocket.center_of_dry_mass_position) * rocket._csys + arm = (center_of_mass - rocket.rail_buttons[0].position.z) * rocket._csys + inertia = rocket.I_11(t1) - mass * cm_from_cdm**2 + thrust = rocket.motor.thrust(t1) + gravity = flight.env.gravity(flight.out_of_rail_state[2]) + return mass, arm, inertia, thrust, gravity + + +def _pivot_model_pitch_acceleration(flight, theta, phi, phi_dot): + """Second derivative of ``phi`` with respect to time in the model described + in ``_pivot_model_end_state``.""" + mass, arm, inertia, thrust, gravity = _pivot_model_parameters(flight) + return ( + arm + * math.cos(phi) + * ( + mass * arm * phi_dot**2 * math.sin(phi) + + thrust * math.sin(phi) + - mass * gravity * math.cos(theta) + ) + / (inertia + mass * arm**2 * math.cos(phi) ** 2) + ) + + +def _pivot_model_end_state(flight, inclination): + """Pitch angle and pitch rate, at the end of the tip-off window, of a rigid + body of constant mass whose lower button slides along the rail under thrust + and gravity only. - ``udot_rail2`` patches the generalized 6-DOF solution with a constraint - wrench built from the full inertia tensor, but in 3 DOF the bound - ``u_dot_generalized`` is ``u_dot_generalized_3dof``, which carries no - attitude at all. Silently patching it would yield non-physical tip-off - kinematics, so construction must fail loudly. + The model has two coordinates: ``s``, the position of the button along the + rail, and ``phi``, the angle of the rocket axis from the rail. With ``l`` + the distance from the button to the center of mass, ``I`` the inertia about + the center of mass and ``theta`` the rail inclination: - Arrange: a rocket and environment that fly normally in 6 DOF. - Act: build a Flight asking for both the tip-off phase and 3 DOF. - Assert: a ValueError naming the offending argument is raised. + (I + m l^2 cos^2 phi) phi'' = l cos phi (m l phi'^2 sin phi + + T sin phi - m g cos theta) + s'' = T cos phi / m - g sin theta + l phi'' sin phi + l phi'^2 cos phi """ - # Arrange / Act / Assert - with pytest.raises(ValueError, match="simulation_mode='6 DOF'"): - Flight( - rocket=calisto_robust, - environment=example_spaceport_env, - rail_length=5.2, - inclination=85, - heading=0, - terminate_on_apogee=True, - simulation_mode="3 DOF", - use_udot_rail2=True, + t1, t2 = flight.out_of_rail_time, flight.tip_off_end_time + start = np.array(flight.out_of_rail_state) + theta = math.radians(inclination) + mass, arm, _, thrust, gravity = _pivot_model_parameters(flight) + + def derivative(_, y): + _, phi, s_dot, phi_dot = y + phi_ddot = _pivot_model_pitch_acceleration(flight, theta, phi, phi_dot) + s_ddot = ( + thrust * math.cos(phi) / mass + - gravity * math.sin(theta) + + arm * phi_ddot * math.sin(phi) + + arm * phi_dot**2 * math.cos(phi) ) + return [s_dot, phi_dot, s_ddot, phi_ddot] + + speed = start[3:6] @ np.array(list(flight.attitude_unit)) + end = solve_ivp( + derivative, + (t1, t2), + [0.0, 0.0, speed, 0.0], + rtol=1e-12, + atol=1e-14, + method="DOP853", + ).y[:, -1] + return end[1], end[3] + + +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)) + up = np.array([0.0, 0.0, 1.0]) + across = up - (up @ rail) * rail + across /= np.linalg.norm(across) + K = np.array(Matrix.transformation(state[6:10])) + body_axis = K @ np.array([0.0, 0.0, 1.0]) + pitch = math.atan2(body_axis @ across, body_axis @ rail) + pitch_rate = (K @ state[10:13]) @ np.cross(rail, across) + return pitch, pitch_rate + + +@pytest.mark.parametrize("inclination", [85, 60]) +def test_udot_rail2_matches_a_rigid_body_pivoting_on_the_rail(inclination): + """With only thrust and gravity acting on a rocket of constant mass, the + phase must reproduce a rigid body whose lower button slides along the rail. + """ + flight = _bare_flight( + grain_density=1e-3, inclination=inclination, rtol=1e-11, atol=1e-13 + ) + expected_pitch, expected_pitch_rate = _pivot_model_end_state(flight, inclination) + pitch, pitch_rate = _pitch_from_the_rail(flight, flight.tip_off_end_state) -def test_udot_rail2_rejects_solid_propulsion_equations( - calisto_robust, example_spaceport_env -): - """The tip-off phase must refuse ``equations_of_motion='solid_propulsion'``. + assert pitch_rate < 0 + assert pitch == pytest.approx(expected_pitch, rel=1e-5) + assert pitch_rate == pytest.approx(expected_pitch_rate, rel=1e-5) - That option binds ``u_dot_generalized`` to the reduced axisymmetric ``u_dot`` - formulation, which does not share the state the constraint patch describes. - Arrange: a rocket and environment that fly normally with the standard EOM. - Act: build a Flight asking for both the tip-off phase and solid_propulsion. - Assert: a ValueError naming the offending argument is raised. - """ - # Arrange / Act / Assert - with pytest.raises(ValueError, match="equations_of_motion='standard'"): - Flight( - rocket=calisto_robust, - environment=example_spaceport_env, - rail_length=5.2, - inclination=85, - heading=0, - terminate_on_apogee=True, - equations_of_motion="solid_propulsion", - use_udot_rail2=True, - ) +def test_udot_rail2_reports_the_accelerations_it_integrates(): + """The accelerations stored for the window are the ones of the rocket on + the rail, not the ones of a free rocket. Without aerodynamics a free rocket + has no angular acceleration, so the two are easy to tell apart.""" + flight = _bare_flight(inclination=85) + rows = _tip_off_rows(flight) + time, *state = rows[len(rows) // 2] + u_dot = flight.udot_rail2(time, state) + + assert abs(u_dot[10]) > 0.1 + assert flight.alpha1(time) == pytest.approx(u_dot[10], rel=1e-9) + assert flight.alpha2(time) == pytest.approx(u_dot[11], rel=1e-9) + assert flight.alpha3(time) == 0 + assert flight.ax(time) == pytest.approx(u_dot[3], abs=1e-9) + assert flight.ay(time) == pytest.approx(u_dot[4], rel=1e-9) + assert flight.az(time) == pytest.approx(u_dot[5], rel=1e-9) -def test_udot_rail2_disabled_allows_reduced_formulations( - calisto_robust, example_spaceport_env -): - """The guard must only fire when the tip-off phase is actually requested. - Arrange: a rocket and environment. - Act: build flights in 3 DOF and with solid_propulsion, tip-off left off. - Assert: both build without raising, and neither inserts the phase. +def test_udot_rail2_reports_the_force_on_the_lower_button(): + """During the window the lower button carries the rocket alone. In the + pivot model the rail pushes the rocket, across the rail, with + + N = m g cos theta - T sin phi + m l (phi'' cos phi - phi'^2 sin phi) + + and the rocket pushes the rail with the opposite force. The upper button, + already off the rail, carries nothing. """ - # Arrange / Act - three_dof = Flight( - rocket=calisto_robust, - environment=example_spaceport_env, - rail_length=5.2, - inclination=85, - heading=0, - terminate_on_apogee=True, - simulation_mode="3 DOF", + inclination = 60 + flight = _bare_flight( + grain_density=1e-3, inclination=inclination, rtol=1e-11, atol=1e-13 ) - solid = Flight( - rocket=calisto_robust, - environment=example_spaceport_env, - rail_length=5.2, - inclination=85, - heading=0, - terminate_on_apogee=True, - equations_of_motion="solid_propulsion", + time, state = flight.tip_off_end_time, np.array(flight.tip_off_end_state) + theta = math.radians(inclination) + mass, arm, _, thrust, gravity = _pivot_model_parameters(flight) + phi, phi_dot = _pitch_from_the_rail(flight, state) + phi_ddot = _pivot_model_pitch_acceleration(flight, theta, phi, phi_dot) + expected = ( + mass * gravity * math.cos(theta) + - thrust * math.sin(phi) + + mass * arm * (phi_ddot * math.cos(phi) - phi_dot**2 * math.sin(phi)) ) - # Assert - assert "udot_rail2" not in _phase_names(three_dof) - assert "udot_rail2" not in _phase_names(solid) + # Rebuild the force of the button on the rail from its two components + angle = flight.rocket.rail_buttons[0].component.angular_position_rad + normal = flight.rail_button2_normal_force(time) + shear = flight.rail_button2_shear_force(time) + force_body = np.array( + [ + normal * math.cos(angle) - shear * math.sin(angle), + normal * math.sin(angle) + shear * math.cos(angle), + 0.0, + ] + ) + force = np.array(Matrix.transformation(state[6:10])) @ force_body + rail = np.array(list(flight.attitude_unit)) + 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) + + assert expected > 1 + assert force @ up_across_the_rail == pytest.approx(-expected, rel=1e-5) + assert np.linalg.norm(force) == pytest.approx(expected, rel=1e-5) + assert flight.rail_button1_normal_force(time) == 0 + assert flight.rail_button1_shear_force(time) == 0 + assert flight.max_rail_button2_normal_force >= abs(normal) * (1 - 1e-12) + + +def test_rail_exits_are_found_inside_a_long_solver_step(): + """A constant thrust on a rocket of constant mass is smooth enough for the + solver to cross the whole rail in one step. The button exits must still be + placed where the buttons reach the end of the rail.""" + flight = _bare_flight(grain_density=1e-3, inclination=85) + + assert _distance_travelled(flight, flight.out_of_rail_state) == pytest.approx( + flight.effective_1rl, rel=1e-6 + ) + assert _distance_travelled(flight, flight.tip_off_end_state) == pytest.approx( + flight.effective_2rl, rel=1e-6 + ) -def test_udot_rail2_reports_the_window_in_prints( - calisto_robust, example_spaceport_env, capsys +@pytest.mark.parametrize( + "options", + [{"simulation_mode": "3 DOF"}, {"equations_of_motion": "solid_propulsion"}], +) +def test_udot_rail2_is_skipped_where_it_cannot_run( + calisto_robust, example_spaceport_env, options, capsys ): - """The tip-off window must be visible in the rail conditions printout. + """The phase corrects the generalized 6 DOF equations, so flights that use + the 3 DOF or the solid propulsion equations go straight to free flight and + report no window.""" + flight = _make_flight(calisto_robust, example_spaceport_env, **options) + figure, axes = plt.subplots() - Studying tip-off is the point of the feature, so a user who opts in should - not have to dig the window out of the solution by hand. + flight.prints.out_of_rail_conditions() + flight.plots._mark_tip_off_window(axes) - Arrange: fly with the tip-off phase enabled. - Act: print the rail departure conditions. - Assert: the tip-off section is there and reports the measured window. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, True) + assert "udot_rail2" not in _phase_names(flight) + assert flight.tip_off_end_time == flight.out_of_rail_time + assert flight.tip_off_duration == 0 + assert "Tip-Off State" not in capsys.readouterr().out + assert not axes.patches + plt.close(figure) - # Act - flight.prints.out_of_rail_conditions() - out = capsys.readouterr().out - # Assert - assert "Tip-Off State" in out - assert f"{flight.tip_off_duration:.3f} s" in out - assert f"{flight.between_rails_time:.3f} s" in out - assert flight.tip_off_duration > 0 +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.""" + launch = _make_flight(calisto_robust, example_spaceport_env) + mid_flight_state = list(launch.solution[len(launch.solution) // 2]) + + continuation = _make_flight( + calisto_robust, example_spaceport_env, initial_solution=mid_flight_state + ) + 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_prints_no_tip_off_section_when_disabled( + +def test_udot_rail2_reports_the_window_in_prints( calisto_robust, example_spaceport_env, capsys ): - """Flights that did not run the phase must not grow a tip-off section. + """The window is printed with the rail departure conditions.""" + flight = _make_flight(calisto_robust, example_spaceport_env) - Arrange: fly with the tip-off phase disabled. - Act: print the rail departure conditions. - Assert: the output is unchanged from previous versions. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, False) - - # Act flight.prints.out_of_rail_conditions() out = capsys.readouterr().out - # Assert - assert "Tip-Off State" not in out - assert flight.tip_off_duration == 0.0 + assert flight.tip_off_duration > 0 + assert "Tip-Off State" in out + assert f"{flight.tip_off_duration:.3f} s" in out + assert f"{flight.tip_off_end_time:.3f} s" in out def test_udot_rail2_shades_the_window_in_attitude_plots( calisto_robust, example_spaceport_env, tmp_path ): - """The attitude plots must shade the tip-off window when it exists. - - Arrange: fly with the tip-off phase enabled. - Act: render the attitude plots to a file. - Assert: every subplot carries the shaded window, and the file is written. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, True) + """The attitude plots shade the window and are written to the file.""" + flight = _make_flight(calisto_robust, example_spaceport_env) target = tmp_path / "attitude.png" + figure, axes = plt.subplots() - # Act + flight.plots._mark_tip_off_window(axes) flight.plots.attitude_data(filename=str(target)) - # Assert + assert len(axes.patches) == 1 assert target.exists() + plt.close(figure) -def test_udot_rail2_flag_survives_objects_without_it( - calisto_robust, example_spaceport_env, capsys +def test_udot_rail2_window_survives_saving_the_flight( + calisto_robust, example_spaceport_env ): - """Flights restored from a ``.rpy`` written before this feature must still - answer the flag, since they are rebuilt without going through ``__init__``. + """A flight rebuilt from its saved data reports the same window and the + same lower button force. Data saved before the phase existed has no window + to report and still gives the rail button forces.""" + flight = _make_flight(calisto_robust, example_spaceport_env) + data = flight.to_dict() + + restored = rebuild_minimal_flight(Flight, data, None) + del data["tip_off_end_time"] + del data["tip_off_button_forces"] + restored_from_old_data = rebuild_minimal_flight(Flight, data, None) + + assert restored.tip_off_duration == flight.tip_off_duration + assert restored.max_rail_button2_normal_force == pytest.approx( + flight.max_rail_button2_normal_force + ) + assert restored_from_old_data.tip_off_duration == 0 + assert ( + restored_from_old_data.max_rail_button2_normal_force + < flight.max_rail_button2_normal_force + ) - Arrange: fly, then drop the instance attribute to mimic an old object. - Act: read the flag and print the rail conditions. - Assert: the class default answers False and nothing raises. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, True) - del flight.__dict__["use_udot_rail2"] - # Act - flight.prints.out_of_rail_conditions() - out = capsys.readouterr().out +def test_udot_rail2_gives_way_to_a_parachute_opened_inside_the_window( + calisto_robust, example_spaceport_env +): + """A parachute that opens while the lower button is still on the rail takes + over the flight. The lower button exit must not hand it back to free + flight afterwards, and no complete window is reported.""" + window = _make_flight(calisto_robust, example_spaceport_env) + inside = 0.5 * (window.out_of_rail_time + window.tip_off_end_time) + calisto_robust.add_parachute( + name="early", cd_s=1.0, trigger=("time", inside), sampling_rate=500 + ) - # Assert - assert flight.use_udot_rail2 is False - assert flight.tip_off_duration == 0.0 - assert "Tip-Off State" not in out + flight = _make_flight(calisto_robust, example_spaceport_env) + names = _phase_names(flight) + + assert "udot_rail2" in names + assert "u_dot_generalized" not in names[names.index("u_dot_parachute") :] + assert flight.tip_off_duration == 0 -def test_udot_rail2_window_marker_is_a_noop_when_disabled( +def test_udot_rail2_reports_no_window_when_the_flight_ends_inside_it( calisto_robust, example_spaceport_env ): - """The shading helper must do nothing for flights without the phase. + """A flight stopped while the lower button is still on the rail has no + complete window to report.""" + window = _make_flight(calisto_robust, example_spaceport_env) + inside = 0.5 * (window.out_of_rail_time + window.tip_off_end_time) - Arrange: fly with the tip-off phase disabled and make a bare axes. - Act: ask the plot helper to mark the window on it. - Assert: nothing was drawn. - """ - # Arrange - flight = _make_flight(calisto_robust, example_spaceport_env, False) - figure, axes = plt.subplots() + flight = _make_flight(calisto_robust, example_spaceport_env, max_time=inside) - # Act - flight.plots._mark_tip_off_window(axes) + names = _phase_names(flight) + assert "udot_rail2" in names + assert "u_dot_generalized" not in names + assert flight.tip_off_duration == 0 - # Assert - assert not axes.patches - plt.close(figure) + +def test_udot_rail2_is_skipped_when_the_upper_button_starts_off_the_rail( + calisto_robust, example_spaceport_env +): + """On a rail shorter than the distance from the nozzle to the upper button, + the upper button is never on the rail and the phase is not used.""" + flight = Flight( + rocket=calisto_robust, + environment=example_spaceport_env, + rail_length=1.0, + inclination=85, + heading=0, + terminate_on_apogee=True, + ) + + assert flight.effective_1rl < 0 < flight.effective_2rl + assert "udot_rail2" not in _phase_names(flight) + assert flight.tip_off_duration == 0