diff --git a/CHANGELOG.md b/CHANGELOG.md index a54c868e0..1b6c6551e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,7 @@ Attention: The newest changes should be on top --> ### Fixed +- BUG: Compute `Flight.potential_energy` from `Environment.gravity` instead of a hard-coded inverse-square `mu`, so `total_energy` matches the integrated dynamics. Stored `potential_energy` and `total_energy` values change; trajectories do not. [#1216](https://github.com/RocketPy-Team/RocketPy/issues/1216) - BUG: Keep checkpoint metadata out of Monte Carlo plots and statistics, recover missing simulation indices without repeating completed flights, and warn when appending v1.13 logs. Preserve explicit initial flight states, `terminate_on_apogee` (warning when an inherited `True` stops every sampled flight at apogee) and solid-motor grain bonding in stochastic models. [#1209](https://github.com/RocketPy-Team/RocketPy/issues/1209) - BUG: A `Flight` continued from another `Flight` object now records `t_initial`, so a rocket carrying sensors or controllers no longer raises `AttributeError` on that path. [#920](https://github.com/RocketPy-Team/RocketPy/pull/920) - BUG: Correct the gravity sign an `Accelerometer` applies when `consider_gravity=True`. The gravitational field was added to the inertial acceleration instead of subtracted from it, so the sensor reported the negative of the proper acceleration along the vertical: one at rest read -g rather than +g. Recorded accelerometer data taken with `consider_gravity=True` changes sign in that term. [#1175](https://github.com/RocketPy-Team/RocketPy/pull/1175) diff --git a/rocketpy/simulation/flight.py b/rocketpy/simulation/flight.py index d48bb1947..131165743 100644 --- a/rocketpy/simulation/flight.py +++ b/rocketpy/simulation/flight.py @@ -3714,20 +3714,65 @@ def kinetic_energy(self): # Potential Energy @funcify_method("Time (s)", "Potential Energy (J)", "spline", "constant") def potential_energy(self): - """Gravitational potential energy as a Function of time, given by - ``mu * m * (1 / R - 1 / (R + z))``. It is zero at sea level and - positive above it, increasing with altitude.""" - # Constants - # TODO: this constant should come from Environment. - standard_gravitational_parameter = 3.986004418e14 - # Redefine total_mass time grid to allow for efficient Function algebra + """Gravitational potential energy as a Function of time. + + Computed as ``m * ∫_0^z g(h) dh``, where ``g`` is + ``Environment.gravity``, the same model used to integrate the + trajectory. The potential is zero at sea level and positive above + it, increasing with altitude. + """ total_mass = deepcopy(self.rocket.total_mass) total_mass.set_discrete_based_on_model(self.z) - return ( - standard_gravitational_parameter - * total_mass - * (1 / self.env.earth_radius - 1 / (self.z + self.env.earth_radius)) + potential_per_mass = self._gravitational_potential_per_mass(self.z.y_array) + gravitational_potential = Function( + np.column_stack((self.z.x_array, potential_per_mass)), + "Time (s)", + "Gravitational Potential (J/kg)", + interpolation=self.z.__interpolation__, + extrapolation="constant", + ) + return total_mass * gravitational_potential + + def _gravitational_potential_per_mass(self, altitude): + """Potential per unit mass relative to sea level. + + Parameters + ---------- + altitude : float or array_like + Geometric height above sea level in meters. + + Returns + ------- + float or np.ndarray + ``∫_0^z g(h) dh`` in J/kg, using ``Environment.gravity``. + Non-sampled gravity is discretized once over the altitude + range without mutating ``Environment.gravity``, so its + potential carries that sampling error. The + antiderivative of the interpolant is evaluated so that the + potential stays consistent with the dynamics, including + constant extrapolation of ``g`` outside its sampled domain. + NaN altitudes yield NaN potential. + """ + gravity = self.env.gravity + altitudes = np.asarray(altitude, dtype=float) + if not (gravity.is_array_source() and gravity.__dom_dim__ == 1): + finite_altitudes = np.atleast_1d(altitudes) + finite_altitudes = finite_altitudes[np.isfinite(finite_altitudes)] + if finite_altitudes.size: + lower = min(0.0, float(np.min(finite_altitudes))) + upper = max(0.0, float(np.max(finite_altitudes))) + else: + lower, upper = 0.0, 1.0 + if lower == upper: + upper = lower + 1.0 + gravity = gravity.set_discrete(lower, upper, mutate_self=False) + potential_per_mass = gravity._evaluator.definite_integral(0.0, altitudes) + potential_per_mass = np.where( + np.isfinite(altitudes), potential_per_mass, np.nan ) + if np.ndim(altitude) == 0: + return float(np.reshape(potential_per_mass, -1)[0]) + return potential_per_mass # Total Mechanical Energy @funcify_method("Time (s)", "Mechanical Energy (J)", "spline", "constant") diff --git a/tests/unit/simulation/test_flight.py b/tests/unit/simulation/test_flight.py index 5868d1b51..ac736cd57 100644 --- a/tests/unit/simulation/test_flight.py +++ b/tests/unit/simulation/test_flight.py @@ -8,7 +8,7 @@ import pytest from scipy import optimize -from rocketpy import Components, Flight, Function, Rocket +from rocketpy import Components, Environment, Flight, Function, Rocket from rocketpy.simulation import FlightDataExporter plt.rcParams.update({"figure.max_open_warning": 0}) @@ -559,6 +559,207 @@ def test_potential_energy_reference_and_total_energy(flight_calisto): ) +def _drag_free_ballistic_flight( + gravity=None, initial_altitude=100.0, initial_speed=200.0 +): + """Build a zero-drag, constant-mass Flight that coasts from an initial + vertical speed until apogee. + + Aerodynamics, thrust and rail constraints are removed so the only force + doing work is gravity. That isolates ``Flight.potential_energy`` against + the ``Environment.gravity`` model used by the integrator. + + Parameters + ---------- + gravity : int, float, callable, optional + Passed to ``Environment(gravity=...)``. ``None`` keeps the default + Somigliana model. + initial_altitude : float, optional + Geometric height above sea level at t = 0, in meters. + initial_speed : float, optional + Upward inertial speed at t = 0, in meters per second. + + Returns + ------- + rocketpy.Flight + Completed trajectory terminated at apogee. + """ + environment = Environment(gravity=gravity) + rocket = Rocket( + radius=0.0635, + mass=10.0, + inertia=(1, 1, 0.1), + power_off_drag=0, + power_on_drag=0, + center_of_mass_without_motor=0, + ) + initial_solution = [ + 0, + 0, + 0, + initial_altitude, + 0, + 0, + initial_speed, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + ] + return Flight( + rocket=rocket, + environment=environment, + rail_length=1, + inclination=90, + heading=0, + initial_solution=initial_solution, + terminate_on_apogee=True, + max_time=60, + ) + + +def test_potential_energy_matches_constant_gravity_mg_dz(): + """With user-defined constant gravity, the potential difference over an + altitude change equals ``m * g * dz``. The sign stays the develop + convention: potential increases as the rocket climbs. + + The hard-coded inverse-square ``mu`` on develop is not 9.81, so this + assertion fails there (issue #1216). + """ + gravity = 9.81 + flight = _drag_free_ballistic_flight(gravity=gravity) + mass = flight.rocket.total_mass(flight.apogee_time) + delta_z = flight.z(flight.apogee_time) - flight.z(flight.t_initial) + delta_potential = flight.potential_energy( + flight.apogee_time + ) - flight.potential_energy(flight.t_initial) + expected_delta = mass * gravity * delta_z + + assert delta_z > 0 + assert delta_potential > 0 + assert delta_potential == pytest.approx(expected_delta, rel=1e-6) + + +def test_total_energy_conserved_drag_free_default_gravity(): + """On a drag-free coast with default Somigliana gravity, total energy + must not drift with the ~0.18% / ~367 J mismatch of the old inverse- + square ``mu`` formula (issue #1216). + + The remaining residual is integrator truncation. The relative + tolerance of ``1e-4`` is about 20 times tighter than the ~1.8e-3 + drift measured on develop for this trajectory, and still well above + the ~1e-6 Runge-Kutta residual of a consistent potential. + """ + flight = _drag_free_ballistic_flight() + t_initial = flight.t_initial + t_apogee = flight.apogee_time + delta_potential = flight.potential_energy(t_apogee) - flight.potential_energy( + t_initial + ) + energy_drift = flight.total_energy(t_apogee) - flight.total_energy(t_initial) + + assert delta_potential > 0 + # Documented against the issue: ~0.18% of m*g*dz, ~367 J on this coast. + assert abs(energy_drift) == pytest.approx(0, abs=1e-4 * delta_potential) + + +def test_potential_energy_matches_altitude_dependent_gravity_integral(): + """Altitude-dependent user gravity must be integrated, not replaced by + a hard-coded inverse-square law. The potential difference is + ``m * ∫_{z0}^{z1} g(h) dh``, still positive as altitude increases. + """ + + def gravity(height): + return 9.81 - height / 1e5 + + flight = _drag_free_ballistic_flight(gravity=gravity) + mass = flight.rocket.total_mass(flight.apogee_time) + z_initial = flight.z(flight.t_initial) + z_apogee = flight.z(flight.apogee_time) + expected_delta = mass * ( + 9.81 * (z_apogee - z_initial) - (z_apogee**2 - z_initial**2) / 2e5 + ) + delta_potential = flight.potential_energy( + flight.apogee_time + ) - flight.potential_energy(flight.t_initial) + + assert z_apogee > z_initial + assert delta_potential > 0 + assert delta_potential == pytest.approx(expected_delta, rel=1e-5) + + +def test_potential_energy_with_callable_gravity_assigned_on_environment(): + """Users can replace ``env.gravity`` with a non-discretized Function + after construction. Potential energy must still integrate that model + without falling back to a per-node numerical quadrature. + """ + flight = _drag_free_ballistic_flight(gravity=9.81) + flight.env.gravity = Function(lambda height: 9.81 - height / 1e5) + + assert not flight.env.gravity.is_array_source() + + mass = flight.rocket.total_mass(flight.apogee_time) + z_initial = flight.z(flight.t_initial) + z_apogee = flight.z(flight.apogee_time) + expected_delta = mass * ( + 9.81 * (z_apogee - z_initial) - (z_apogee**2 - z_initial**2) / 2e5 + ) + delta_potential = flight.potential_energy( + flight.apogee_time + ) - flight.potential_energy(flight.t_initial) + + assert z_apogee > z_initial + assert delta_potential > 0 + assert delta_potential == pytest.approx(expected_delta, rel=1e-4) + assert not flight.env.gravity.is_array_source() + + +def test_potential_energy_extrapolates_gravity_above_sampled_domain(): + """A short gravity table must keep using constant extrapolation of + ``g`` above its last sample, matching the potential implied by + ``F_z = -m g(z)``. + """ + flight = _drag_free_ballistic_flight(gravity=9.81) + flight.env.gravity = Function( + [(0, 9.81), (1000, 9.80)], + interpolation="linear", + extrapolation="constant", + ) + mass = flight.rocket.total_mass(flight.apogee_time) + z_initial = flight.z(flight.t_initial) + z_apogee = flight.z(flight.apogee_time) + expected_delta = mass * ( + 9.81 * (1000 - z_initial) + - (1000**2 - z_initial**2) / 2e5 + + 9.80 * (z_apogee - 1000) + ) + delta_potential = flight.potential_energy( + flight.apogee_time + ) - flight.potential_energy(flight.t_initial) + + assert z_apogee > 1000 + assert delta_potential == pytest.approx(expected_delta, rel=1e-6) + + +def test_gravitational_potential_per_mass_nan_altitude(): + """A NaN altitude must yield NaN potential per mass so a diverged + trajectory node appears as a gap rather than a finite (often zero) + value. + """ + flight = _drag_free_ballistic_flight(gravity=9.81) + altitudes = np.array([0.0, np.nan, 100.0]) + + potential_per_mass = flight._gravitational_potential_per_mass(altitudes) + + assert potential_per_mass[0] == pytest.approx(0.0) + assert np.isnan(potential_per_mass[1]) + assert potential_per_mass[2] == pytest.approx(9.81 * 100.0) + assert np.isnan(flight._gravitational_potential_per_mass(np.nan)) + + @pytest.mark.parametrize( "flight_time_attr", ["t_initial", "out_of_rail_time", "apogee_time", "t_final"],