From d6b6ddd36fdc00e5a6b747a4cf3395cbe018ec7e Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Sat, 21 Nov 2026 14:12:27 -0800 Subject: [PATCH] Hoverslam simulation: normalized units, as PSG The simulation integrated in SI, where the Tsit5 Atol of 1e-6 is 1e-6 m, m/s and kg on every component: very tight on the components near zero (z in an equatorial orbit, the Dv at the start) while the Rtol governs the rest. It now runs in normalized units, like PSG's Problem: the manager takes and logs SI inputs, and Reconfigure builds a HoverslamProblem scaled by the target radius, the circular speed there and the starting mass (so mu is 1), and normalizes the phases. The results are reported back in SI. Rhs checks the phase is normalized. Phase gets RescaleInPlace, for the hoverslam's pooled phases, which Rescale's copy would allocate on every cycle (MunLander's ShouldNotAllocate). Rescale is now a copy and RescaleInPlace. Brent stops within 2 rtol max(|t|, 1), whose floor is now one unit of time (several hundred seconds), so its rtol is divided by the time scale to keep the 2e-6 s floor for an ignition near now. Away from now it is tighter than before: the landing radius ends within 1e-6 m of the target instead of a few cm, for about one more root solve iteration. Over the 16 test scenarios a solve is 27% faster (38.3 to 28.0 ms), all of them faster. Against a 1e-10 tolerance reference, the ignition time stays within 2.5e-4 s, better in some scenarios and worse in others. Dv on Earth is looser, up to 0.014 m/s of 3,922 m/s, the velocity Atol being 1e-6 of 7.9 km/s. VerticalDropApolloMoon15Km, EarthJustAfterLiftoff and FalconNineAtBecoIgnitesBeforeApoapsis are re-pinned; the largest move is 2.1e-4 s on the Falcon 9 ignition. MunLanderTwoStage loses a stale comment about ~0.2 m/s of Dv chatter, and its Dv is re-pinned at 1e-5 instead of 1e-3. --- .../HoverslamSimulation/HoverslamProblem.cs | 38 +++++++++ .../HoverslamSimulation.cs | 77 +++++++++++-------- .../HoverslamSimulationManager.cs | 20 +++-- MechJebLib/PSG/Phase.cs | 30 +++++--- MechJebLibTest/HoverslamTests.cs | 20 +++-- 5 files changed, 121 insertions(+), 64 deletions(-) create mode 100644 MechJebLib/HoverslamSimulation/HoverslamProblem.cs diff --git a/MechJebLib/HoverslamSimulation/HoverslamProblem.cs b/MechJebLib/HoverslamSimulation/HoverslamProblem.cs new file mode 100644 index 000000000..7a1407232 --- /dev/null +++ b/MechJebLib/HoverslamSimulation/HoverslamProblem.cs @@ -0,0 +1,38 @@ +/* + * Copyright Lamont Granquist, Sebastien Gaggini and the MechJeb contributors + * SPDX-License-Identifier: LicenseRef-PD-hp OR Unlicense OR CC0-1.0 OR 0BSD OR MIT-0 OR MIT OR LGPL-2.1+ + */ + +using MechJebLib.Primitives; + +namespace MechJebLib.HoverslamSimulation +{ + /// + /// The hoverslam's initial state and target in normalized units, as PSG's Problem: the target radius is the unit of + /// length, the circular speed there the unit of velocity and the starting mass the unit of mass, so mu is 1. + /// + public readonly struct HoverslamProblem + { + public readonly Scale Scale; + public readonly V3 R0; + public readonly V3 V0; + public readonly V3 W; + public readonly double Height; // the target radius + public readonly double Vfm; // the final vertical speed, negative for a descent + + // The UT of r0/v0 in seconds. The simulation's clock counts from it, so it never enters the dynamics, and left in SI + // an ignition now reports exactly this. + public readonly double T0; + + public HoverslamProblem(V3 r0, V3 v0, double t0, double mu, V3 w, double height, double vfm, double m0) + { + Scale = Scale.Create(mu, height, m0); + R0 = r0 / Scale.LengthScale; + V0 = v0 / Scale.VelocityScale; + W = w * Scale.TimeScale; + Height = height / Scale.LengthScale; + Vfm = vfm / Scale.VelocityScale; + T0 = t0; + } + } +} diff --git a/MechJebLib/HoverslamSimulation/HoverslamSimulation.cs b/MechJebLib/HoverslamSimulation/HoverslamSimulation.cs index d2cef35be..bf1510989 100644 --- a/MechJebLib/HoverslamSimulation/HoverslamSimulation.cs +++ b/MechJebLib/HoverslamSimulation/HoverslamSimulation.cs @@ -18,13 +18,12 @@ namespace MechJebLib.HoverslamSimulation { public partial class HoverslamSimulation : AsyncJob { - private double _height; - private V3 _r0; - private V3 _v0; - private double _t0; - private double _mu; - private V3 _w; - private double _vfm; + // the problem and the phases are normalized (HoverslamProblem), the outputs below are SI + private HoverslamProblem _problem; + + // BURN_END_TIME and BURN_END_DV in normalized units + private double _burnEndTime; + private double _burnEndDv; private readonly List _phases = new List(); @@ -62,6 +61,8 @@ private struct TrajectoryResult public double Af; } + // the tolerances are in normalized units: the Atol floors are 1e-6 of the target radius, of the circular speed there + // and of the starting mass private readonly Tsit5 _solver = new Tsit5 { Rtol = 1e-6, @@ -111,11 +112,11 @@ private bool PropagatePhase(ref HoverslamLayout x, double t0, ref double tf, Pha // the integrator can only creep up on that point. The burn's event ends the integration a little earlier, once the error // is down to what the thrust removes in BURN_END_TIME: the steps that near the flip are short enough to end inside that // window, which they rarely do inside a fixed millimetre per second. FinishBurn does the rest analytically. BURN_END_DV - // is the window's floor. + // is the window's floor. Both are SI, Reconfigure normalizes them into _burnEndTime and _burnEndDv. private const double BURN_END_TIME = 0.02; private const double BURN_END_DV = 1e-3; - private static double BurnEndDv(Phase phase, double m) => Math.Max(BURN_END_DV, BURN_END_TIME * phase.VacThrust / m); + private double BurnEndDv(Phase phase, double m) => Math.Max(_burnEndDv, _burnEndTime * phase.VacThrust / m); private readonly List _events; @@ -138,7 +139,7 @@ private void FinishBurn(ref HoverslamLayout x, ref double t, Phase phase) // how the error changes without thrust: gravity, less how the target velocity changes as the vessel moves (the // ground's rotation, and the final descent's direction turning with the position) - V3 drift = -_mu / (r * r) * rhat - V3.Cross(_w, x.V) - _vfm / r * (x.V - V3.Dot(x.V, rhat) * rhat); + V3 drift = -rhat / (r * r) - V3.Cross(_problem.W, x.V) - _problem.Vfm / r * (x.V - V3.Dot(x.V, rhat) * rhat); double driftAlong = V3.Dot(dv.normalized, drift); double rate = phase.VacThrust / x.M - driftAlong; // -d|dv|/dt @@ -161,23 +162,25 @@ private void FinishBurn(ref HoverslamLayout x, ref double t, Phase phase) double mf = x.M - phase.Mdot * dt; x.R += (x.V - 0.5 * dv) * dt; - x.V = V3.Cross(_w, x.R) + x.R.normalized * _vfm; + x.V = V3.Cross(_problem.W, x.R) + x.R.normalized * _problem.Vfm; x.DV += phase.VexVacuum * Math.Log(x.M / mf); x.M = mf; t += dt; } // surface-relative velocity minus the target final velocity, the burn steers retrograde to this - private V3 VelocityError(V3 r, V3 v) => v - V3.Cross(_w, r) - r.normalized * _vfm; + private V3 VelocityError(V3 r, V3 v) => v - V3.Cross(_problem.W, r) - r.normalized * _problem.Vfm; private TrajectoryResult PropagateTrajectory(double t) { - var x = new HoverslamLayout { R = _r0, V = _v0, M = _phases[0].M0, DV = 0 }; + var x = new HoverslamLayout { R = _problem.R0, V = _problem.V0, M = _phases[0].M0, DV = 0 }; double t0 = 0; double tf = t; + // the coast's times are normalized already, and it has no thrust or mass to rescale using var coastPhase = Phase.NewCoast(1.0, 1.0, t0, tf, 0, 0); + coastPhase.Normalized = true; PropagatePhase(ref x, t0, ref tf, coastPhase); V3 uBurn = -VelocityError(x.R, x.V).normalized; @@ -202,36 +205,40 @@ private TrajectoryResult PropagateTrajectory(double t) } // how far above the target radius the burn after ignition at t ends: positive when the ignition is early enough - private double Residual(in TrajectoryResult result) => result.X.R.magnitude - _height; + private double Residual(in TrajectoryResult result) => result.X.R.magnitude - _problem.Height; private double AltitudeResidual(double t, object? o) => Residual(PropagateTrajectory(t)); private readonly Func _eventFunc; - // The ignition times to search between, and whether the vessel is still rising to its apoapsis. + // The ignition times to search between, and whether the vessel is still rising to its apoapsis. Normalized, so mu is 1. private (double minT, double maxT, bool rising) GenerateBracketGuess() { - if (Astro.EccFromStateVectors(_mu, _r0, _v0) < 1.0) + V3 r0 = _problem.R0; + V3 v0 = _problem.V0; + double height = _problem.Height; + + if (Astro.EccFromStateVectors(1.0, r0, v0) < 1.0) { - double tanom = Astro.TrueAnomalyFromStateVectors(_mu, _r0, _v0); + double tanom = Astro.TrueAnomalyFromStateVectors(1.0, r0, v0); if (ClampPi(tanom) > 0) { // still rising, advance to the apoapsis - double tApoapsis = Astro.TimeToNextApoapsis(_mu, _r0, _v0); - (V3 rApr, V3 vApr) = Shepperd.Solve(_mu, tApoapsis, _r0, _v0); - return (tApoapsis, tApoapsis + Astro.TimeToNextRadius(_mu, rApr, vApr, _height), true); + double tApoapsis = Astro.TimeToNextApoapsis(1.0, r0, v0); + (V3 rApr, V3 vApr) = Shepperd.Solve(1.0, tApoapsis, r0, v0); + return (tApoapsis, tApoapsis + Astro.TimeToNextRadius(1.0, rApr, vApr, height), true); } // falling, back to the apoapsis just passed. Below the target height, every ignition from now on starts // below it, and the next time of the target radius is the ascending crossing on the far side of the planet. - double tLastApoapsis = Astro.TimeToNextApoapsis(_mu, _r0, _v0) - Astro.PeriodFromStateVectors(_mu, _r0, _v0); - double tImpact = _r0.magnitude <= _height ? 0 : Astro.TimeToNextRadius(_mu, _r0, _v0, _height); + double tLastApoapsis = Astro.TimeToNextApoapsis(1.0, r0, v0) - Astro.PeriodFromStateVectors(1.0, r0, v0); + double tImpact = r0.magnitude <= height ? 0 : Astro.TimeToNextRadius(1.0, r0, v0, height); return (tLastApoapsis, tImpact, false); } // heuristically, try to capture a range that includes the ignition point. I'd rather not // use the mainBody SOI radius here, but that would certainly do it. - return (Astro.TimeToLastRadius(_mu, _r0, _v0, _r0.magnitude * 2.0), Astro.TimeToNextRadius(_mu, _r0, _v0, _height), false); + return (Astro.TimeToLastRadius(1.0, r0, v0, r0.magnitude * 2.0), Astro.TimeToNextRadius(1.0, r0, v0, height), false); } public override void Run(object? o = null) @@ -295,28 +302,32 @@ private void Solve() } } - double t1 = BrentRoot.Solve(_eventFunc, minT, maxT, fMin, fMax, null, rtol: 1e-6); + // Brent stops within 2 rtol max(|t|, 1), whose floor is one unit of time, several hundred seconds: dividing by the + // time scale keeps the floor at the 2e-6 s it was in seconds, for an ignition near now. + double t1 = BrentRoot.Solve(_eventFunc, minT, maxT, fMin, fMax, null, rtol: 1e-6 / _problem.Scale.TimeScale); Report(t1, PropagateTrajectory(t1)); } + // the results, back in SI units private void Report(double t, in TrajectoryResult result) { - IgnitionUT = _t0 + t; + Scale scale = _problem.Scale; + + IgnitionUT = _problem.T0 + t * scale.TimeScale; IgnitionAttitude = result.UBurn; - Rf = result.X.R; - Vf = result.X.V; - Dv = result.X.DV; - LandingUT = _t0 + result.Tf; - FinalThrustAccel = result.Af; + Rf = result.X.R * scale.LengthScale; + Vf = result.X.V * scale.VelocityScale; + Dv = result.X.DV * scale.VelocityScale; + LandingUT = _problem.T0 + result.Tf * scale.TimeScale; + FinalThrustAccel = result.Af * scale.AccelScale; } public static int N => HoverslamLayout.HOVERSLAM_LAYOUT_LEN; public void Rhs(Vec yin, double x, Vec dyout) { - // TODO: normalization - //CheckDebug.True(_phase.Normalized); + CheckDebug.True(_phase.Normalized); var y = HoverslamLayout.CreateFrom(yin); var dy = new HoverslamLayout(); @@ -330,7 +341,7 @@ public void Rhs(Vec yin, double x, Vec dyout) V3 u = -VelocityError(y.R, y.V).normalized; dy.R = y.V; - dy.V = -_mu * y.R / r3 + at * u; + dy.V = -y.R / r3 + at * u; dy.M = -_phase.Mdot; dy.DV = at; diff --git a/MechJebLib/HoverslamSimulation/HoverslamSimulationManager.cs b/MechJebLib/HoverslamSimulation/HoverslamSimulationManager.cs index 3c6c43b16..b4eee1cf6 100644 --- a/MechJebLib/HoverslamSimulation/HoverslamSimulationManager.cs +++ b/MechJebLib/HoverslamSimulation/HoverslamSimulationManager.cs @@ -59,22 +59,26 @@ public void Reconfigure(HoverslamSimulation simulation) if (_height <= 0) throw new InvalidOperationException("HoverslamSimulationBuilder: TargetConditions() must be called before Build()"); - simulation._height = _height; - simulation._r0 = _r0; - simulation._v0 = _v0; - simulation._t0 = _t0; - simulation._mu = _mu; - simulation._w = _w; - simulation._vfm = _vfm; + // the inputs arrive (and are logged) in SI units, the simulation runs in normalized ones, as PSG does + var problem = new HoverslamProblem(_r0, _v0, _t0, _mu, _w, _height, _vfm, _phases[0].M0); + Scale scale = problem.Scale; + + simulation._problem = problem; + simulation._burnEndTime = BURN_END_TIME / scale.TimeScale; + simulation._burnEndDv = BURN_END_DV / scale.VelocityScale; // empty out the destination list first foreach (Phase phase in simulation._phases) phase.Dispose(); simulation._phases.Clear(); - // then move all the phases into the destination list + // then move all the phases into the destination list, normalizing them on the way foreach (Phase phase in _phases) + { + phase.RescaleInPlace(scale); simulation._phases.Add(phase); + } + _phases.Clear(); } diff --git a/MechJebLib/PSG/Phase.cs b/MechJebLib/PSG/Phase.cs index 584a4206b..180be92f1 100644 --- a/MechJebLib/PSG/Phase.cs +++ b/MechJebLib/PSG/Phase.cs @@ -152,24 +152,30 @@ private void Set(double m0, double vacThrust, double ispVacuum, double mf, doubl public Phase Rescale(Scale scale) { - CheckDebug.False(Normalized); - var phase = (Phase)MemberwiseClone(); - phase.VexVacuum = VexVacuum / scale.VelocityScale; - phase.VexCurrent = VexCurrent / scale.VelocityScale; - phase.Mdot = Mdot / scale.MdotScale; - phase.Bt = Bt / scale.TimeScale; - phase.MinT = MinT / scale.TimeScale; - phase.MaxT = MaxT / scale.TimeScale; - phase.M0 = M0 / scale.MassScale; - phase.Mf = Mf / scale.MassScale; - phase.MinM = MinM / scale.MassScale; - phase.Normalized = true; + phase.RescaleInPlace(scale); return phase; } + // Rescale without the copy, for a caller that owns a pooled phase and can't allocate one + public void RescaleInPlace(Scale scale) + { + CheckDebug.False(Normalized); + + VexVacuum /= scale.VelocityScale; + VexCurrent /= scale.VelocityScale; + Mdot /= scale.MdotScale; + Bt /= scale.TimeScale; + MinT /= scale.TimeScale; + MaxT /= scale.TimeScale; + M0 /= scale.MassScale; + Mf /= scale.MassScale; + MinM /= scale.MassScale; + Normalized = true; + } + // the inverse of Rescale, back to SI units public Phase DeNormalize(Scale scale) { diff --git a/MechJebLibTest/HoverslamTests.cs b/MechJebLibTest/HoverslamTests.cs index e39c68bf6..c200d9a8b 100644 --- a/MechJebLibTest/HoverslamTests.cs +++ b/MechJebLibTest/HoverslamTests.cs @@ -36,8 +36,8 @@ private void VerticalDropApolloMoon15Km() hoverslam.Rf.magnitude.ShouldEqual(rbody, 1e-8); hoverslam.Vf.ShouldEqual(V3.Cross(w, hoverslam.Rf), 1e-8); - (hoverslam.IgnitionUT - t0).ShouldEqual(94.755558282881168, 1e-8); - hoverslam.Dv.ShouldEqual(313.25594640963067, 1e-8); + (hoverslam.IgnitionUT - t0).ShouldEqual(94.755557526153552, 1e-8); + hoverslam.Dv.ShouldEqual(313.25595938006933, 1e-8); } [Fact] @@ -133,9 +133,7 @@ private void MunLanderTwoStage() hoverslam.Rf.magnitude.ShouldEqual(height, 1e-6); (hoverslam.IgnitionUT - t0).ShouldEqual(352.36724527248589, 1e-4); hoverslam.Vf.ShouldEqual(V3.Cross(w, hoverslam.Rf) - descentSpeed * hoverslam.Rf.normalized, 1e-6); - // at Rtol = 1e-6 the steps at the end of the burn cross the steering singularity without tripping the - // BURN_END_DV event, and the thrust chatters for a few ms, so Dv is ~0.2 m/s high (it converges at 1e-7) - hoverslam.Dv.ShouldEqual(384.35206383554907, 1e-3); + hoverslam.Dv.ShouldEqual(384.35183735858374, 1e-5); } [Fact] @@ -193,10 +191,10 @@ private void EarthJustAfterLiftoff() hoverslam.Run(); hoverslam.Rf.magnitude.ShouldEqual(height, 1e-6); - (hoverslam.IgnitionUT - t0).ShouldEqual(1.34234016085975, 1e-5); - (hoverslam.LandingUT - t0).ShouldEqual(3.43880722904578, 1e-5); + (hoverslam.IgnitionUT - t0).ShouldEqual(1.3423393998527899, 1e-5); + (hoverslam.LandingUT - t0).ShouldEqual(3.4388401878532022, 1e-5); hoverslam.Vf.ShouldEqual(V3.Cross(w, hoverslam.Rf), 1e-8); - hoverslam.Dv.ShouldEqual(31.246491642967, 1e-5); + hoverslam.Dv.ShouldEqual(31.246996798903844, 1e-5); } // a direct impact from outside the sphere of influence follows a hyperbola, which the simulation plans as it plans an ellipse @@ -291,9 +289,9 @@ private void FalconNineAtBecoIgnitesBeforeApoapsis() hoverslam.Rf.magnitude.ShouldEqual(height, 1e-6); hoverslam.Vf.ShouldEqual(V3.Cross(w, hoverslam.Rf) - descentSpeed * hoverslam.Rf.normalized, 1e-6); (hoverslam.IgnitionUT - t0).ShouldBeLessThan(Astro.TimeToNextApoapsis(mu, r0, v0)); - (hoverslam.IgnitionUT - t0).ShouldEqual(1.5488141343230382, 1e-5); - (hoverslam.LandingUT - t0).ShouldEqual(305.60697760852054, 1e-5); - hoverslam.Dv.ShouldEqual(4012.0544684282654, 1e-5); + (hoverslam.IgnitionUT - t0).ShouldEqual(1.5490269472356886, 1e-5); + (hoverslam.LandingUT - t0).ShouldEqual(305.60734391061123, 1e-5); + hoverslam.Dv.ShouldEqual(4012.0582078650391, 1e-5); } // The same Falcon 9 earlier, with 28 t of propellant left in the booster: even igniting now, the burn ends 22 km below