From 903a021ea5f2bf9144b441e308fd6b5fd5fb8ecd Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Thu, 19 Nov 2026 09:07:17 -0800 Subject: [PATCH 1/8] Suspend PSG re-solves during the vertical ascent and pitch program After liftoff the vertical ascent and the pitch program fly a fixed program, and the pitch program hands over to guidance where it meets the solution's pitch, so a re-solve from the climb would move that pitch. The optimizer now holds off until guidance takes over, and says so with two new OptimizerState values, VERTICAL_ASCENT and PITCH_PROGRAM. Without a solution yet the solves go on, or guidance would never take over. A solve still running at liftoff was started on the pad and is kept. --- MechJeb2/MechJebModulePSGSimulation.cs | 42 ++++++++++++++++++-------- MechJeb2/PSGFeedback.cs | 4 +++ 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/MechJeb2/MechJebModulePSGSimulation.cs b/MechJeb2/MechJebModulePSGSimulation.cs index bbfe156e4..af547bcf5 100644 --- a/MechJeb2/MechJebModulePSGSimulation.cs +++ b/MechJeb2/MechJebModulePSGSimulation.cs @@ -24,18 +24,20 @@ namespace MuMech /// What the PSG optimizer is doing, or why it is not solving (MechJebModulePSGSimulation.State). public enum OptimizerState { - READY, // between two solves - SOLVING, // a solve is running - NO_PLAN, // no flight plan, or nothing left in it to plan - STAGE_ENDING, // the current stage is about to end: the solution is frozen through staging - AFTER_STAGING, // a short wait after staging - AFTER_PHASE, // the same wait after a phase ended without staging (the start or end of a coast during a stage) - ON_PAD, // either wait before liftoff: the stage not lit yet has no phase in the solution, so its time to go reads 0 - COAST_PAUSE, // a long coast above the atmosphere, once a solve started there has converged: resumes 20 s before the burn - TERMINAL, // terminal guidance flies the end of the burn on the frozen solution - UNGUIDED_ONLY, // only unguided stages are left, which the optimizer can't steer - FINISHED, // guidance is done - RETRYING // the problem could not be built (a setting PSG refuses): tried again every second + READY, // between two solves + SOLVING, // a solve is running + NO_PLAN, // no flight plan, or nothing left in it to plan + STAGE_ENDING, // the current stage is about to end: the solution is frozen through staging + AFTER_STAGING, // a short wait after staging + AFTER_PHASE, // the same wait after a phase ended without staging (the start or end of a coast during a stage) + ON_PAD, // either wait before liftoff: the stage not lit yet has no phase in the solution, so its time to go reads 0 + VERTICAL_ASCENT, // after liftoff, the vertical ascent to the pitch start height: no re-solve until guidance takes over + PITCH_PROGRAM, // the pitch program, pitching over to the guidance pitch of the solution it has: no re-solve until guidance takes over + COAST_PAUSE, // a long coast above the atmosphere, once a solve started there has converged: resumes 20 s before the burn + TERMINAL, // terminal guidance flies the end of the burn on the frozen solution + UNGUIDED_ONLY, // only unguided stages are left, which the optimizer can't steer + FINISHED, // guidance is done + RETRYING // the problem could not be built (a setting PSG refuses): tried again every second } /// @@ -672,6 +674,22 @@ public override void OnFixedUpdate() } } + // After liftoff the vertical ascent and the pitch program fly a fixed program, and the pitch program hands over to + // guidance where it meets the solution's pitch: a re-solve from the climb would move that pitch. Without a solution + // yet the solves go on, or guidance would never take over. + if (Vessel.VesselOffGround() && Core.PSGAutopilot.Solution != null) + { + switch (Core.PSGAutopilot.State) + { + case PSGState.VERTICAL_ASCENT: + SetState(OptimizerState.VERTICAL_ASCENT); + return; + case PSGState.PITCH_PROGRAM: + SetState(OptimizerState.PITCH_PROGRAM); + return; + } + } + if (_blockOptimizerUntilTime > VesselState.Time) { // the routine second between two solves is not a pause. A staging event names its own wait (HandleStageEvent): a diff --git a/MechJeb2/PSGFeedback.cs b/MechJeb2/PSGFeedback.cs index f5b240003..0fab78558 100644 --- a/MechJeb2/PSGFeedback.cs +++ b/MechJeb2/PSGFeedback.cs @@ -44,6 +44,10 @@ internal static class PSGFeedback return $"Optimizer: paused after staging, {Ceiling(seconds):F0} s"; case OptimizerState.ON_PAD: return "Optimizer: paused until liftoff"; + case OptimizerState.VERTICAL_ASCENT: + return "Optimizer: paused for the vertical ascent, resumes when guidance takes over"; + case OptimizerState.PITCH_PROGRAM: + return "Optimizer: paused for the pitch program, resumes when guidance takes over"; case OptimizerState.AFTER_PHASE: return $"Optimizer: paused while the next phase starts, {Ceiling(seconds):F0} s"; case OptimizerState.COAST_PAUSE: From 0f5b10f185e57853bb7e875471733016cfa4ebbc Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Thu, 19 Nov 2026 12:23:19 -0800 Subject: [PATCH 2/8] Hold the PSG launch in PRELAUNCH instead of in the countdown The PSG autopilot used to leave PRELAUNCH as soon as the countdown's prelaunch was done and then ask LaunchCountdown.HoldForLiftoff every tick, which reached back into PSG (WaitingForGuidance) to find out whether there was a Solution. The AscentStateMachine now stays in PRELAUNCH on the ground while the countdown is running or there is no Solution, with the throttle off and the attitude axes let go (AscentAttitude.OFF). The countdown's prelaunch is only driven until it is done. Off the ground nothing is cut, since a one-tick throttle cut could cost a RealFuels engine its ignition. A Solution dropped on the pad by a new countdown sends VERTICAL_ASCENT back to PRELAUNCH, and the prelaunch runs again. The countdown no longer knows about PSG: the autopilot holds T-0 with SetLaunchHold until its prelaunch is done and it has a Solution. HoldForLiftoff and WaitingForGuidance are gone, and the classic autopilot inlines its own wait for T-0. CheckLiftoffHold and AllowThrottle are replaced by a CountdownActive input. GUIDANCESTATUS reads INITIALIZED in PRELAUNCH with a Solution. --- .../MechJebModuleAscentClassicAutopilot.cs | 8 +- MechJeb2/MechJebModuleLaunchCountdown.cs | 37 +++--- MechJeb2/MechJebModulePSGAutopilot.cs | 88 +++++++------- MechJebKos/AscentPSGBinding.cs | 2 +- MechJebLib/PSG/AscentStateMachine.cs | 55 ++++++--- MechJebLibTest/PSGTests/AscentFlight.cs | 4 +- .../PSGTests/AscentStateMachineTests.cs | 108 +++++++++++++++++- 7 files changed, 211 insertions(+), 91 deletions(-) diff --git a/MechJeb2/MechJebModuleAscentClassicAutopilot.cs b/MechJeb2/MechJebModuleAscentClassicAutopilot.cs index 66d5e1de3..03bc2dbfe 100644 --- a/MechJeb2/MechJebModuleAscentClassicAutopilot.cs +++ b/MechJeb2/MechJebModuleAscentClassicAutopilot.cs @@ -190,7 +190,13 @@ public override void Drive(FlightCtrlState s) return; } - if (Countdown.HoldForLiftoff(Status)) return; + // the countdown stages at T-0: until then the vessel waits on the pad + if (Countdown.Active) + { + Status.Set(Localizer.Format("#MechJeb_Ascent_status6")); //"Awaiting liftoff" + Core.Attitude.SetAxisControl(false, false, false); + return; + } Core.Solarpanel.DriveForAscent(); Core.AntennaControl.DriveForAscent(); diff --git a/MechJeb2/MechJebModuleLaunchCountdown.cs b/MechJeb2/MechJebModuleLaunchCountdown.cs index ea9958879..4f0ff1666 100644 --- a/MechJeb2/MechJebModuleLaunchCountdown.cs +++ b/MechJeb2/MechJebModuleLaunchCountdown.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using KSP.Localization; using KSP.UI.Screens; using MechJebLib.Functions; @@ -5,7 +6,8 @@ namespace MuMech { /// - /// The launch sequence the ascent autopilots share: the countdown, warping to it, staging at T-0 and the prelaunch hold. + /// The launch sequence the ascent autopilots share: the countdown, warping to it, the prelaunch, and staging at T-0, which + /// waits while an autopilot isn't ready to fly (SetLaunchHold). The autopilots hold the vessel on the pad until T-0. /// An engaged autopilot adds itself to Users, so a countdown started while no autopilot is engaged doesn't run until one is. /// The countdown owns the launch mode (the three Launching* flags of the ascent settings): only Abort ends it, not a window. /// @@ -30,9 +32,21 @@ private enum LaunchKind { PLANE_OF_TARGET, TARGET_LAN, LAN } /// The target's LAN when a launch into its plane or to its LAN started: the LAN that launch flies to. public double TargetLan { get; private set; } - // Starting a countdown flushes the PSG solution and the optimizer restarts cold late in the countdown, which can take longer - // than the countdown does. Staging with no solution would release the rocket at zero throttle, so T-0 waits for one. - private bool WaitingForGuidance => AscentSettings.AscentType == AscentType.PSG && Core.PSGAutopilot.Solution == null; + // the users holding T-0, the staging, until they are ready to fly + private readonly HashSet _launchHolds = new HashSet(); + + /// + /// Holds T-0, the staging, while user isn't ready to fly: the PSG autopilot until it has a Solution. Starting a + /// countdown flushes the PSG solution and the optimizer restarts cold late in the countdown, which can take longer than + /// the countdown does, and staging with no solution would release the rocket at zero throttle. + /// + public void SetLaunchHold(object user, bool hold) + { + if (hold) + _launchHolds.Add(user); + else + _launchHolds.Remove(user); + } // the target inclination, one for both ascent types public EditableDouble InclinationSetting => AscentSettings.DesiredInclination; @@ -123,19 +137,6 @@ public bool DrivePrelaunch(AscentStatus status) return false; } - /// Returns true while the countdown is still running after prelaunch, when the autopilot must not fly yet. - public bool HoldForLiftoff(AscentStatus status) - { - if (!Active) - return false; - - status.Set(TMinus <= 0 && WaitingForGuidance - ? "Holding launch for guidance" - : Localizer.Format("#MechJeb_Ascent_status6")); //"Awaiting liftoff" - Core.Attitude.SetAxisControl(false, false, false); - return true; - } - // The countdown only runs while an autopilot is engaged. One started with none engaged and engaged after T-0 counts down // to the next launch of the same kind, rather than launch at once, off the window it was timed for. protected override void OnModuleEnabled() @@ -167,7 +168,7 @@ public override void OnFixedUpdate() if (TMinus < 3 * VesselState.DeltaT || (TMinus > 10.0 && _lastTMinus < 1.0)) { // StageManager stages the active vessel, so T-0 holds while the player is on another one - if (!WaitingForGuidance && Vessel.isActiveVessel) + if (_launchHolds.Count == 0 && Vessel.isActiveVessel) { if (VesselState.ThrustAvailable < 10E-4) // only stage if we have no engines active StageManager.ActivateNextStage(); diff --git a/MechJeb2/MechJebModulePSGAutopilot.cs b/MechJeb2/MechJebModulePSGAutopilot.cs index 18f00f26e..c749413a7 100644 --- a/MechJeb2/MechJebModulePSGAutopilot.cs +++ b/MechJeb2/MechJebModulePSGAutopilot.cs @@ -84,9 +84,6 @@ public MechJebModulePSGAutopilot(MechJebCore core) : base(core) { } // what guidance does with RCS (PSGFeedback), said once at each change private ScreenMessage _rcsCoastMessage = null!, _rcsTrimMessage = null!, _rcsOffMessage = null!; - // the countdown holds the throttle - private bool _allowThrottle; - // Countdown.DrivePrelaunch is done private bool _prelaunchDone; @@ -95,7 +92,9 @@ public MechJebModulePSGAutopilot(MechJebCore core) : base(core) { } private Vessel? _partIdsVessel; private int _partIdsCount = -1; - private string? _awaitingComputing, _awaitingProgress, _awaitingProgressFrom; + // the status while the first solve runs on the pad (AwaitingComputing), and what it was built from + private string? _awaitingStatus, _awaitingFrom; + private bool _awaitingHolding; private string? _lockStatus, _lockStatusId; public override void OnStart(PartModule.StartState state) @@ -144,6 +143,7 @@ protected override void OnModuleDisabled() Core.Staging.AutoStageLimitRemove(this); Core.Spinup.Users.Remove(this); _countdown.Users.Remove(this); + _countdown.SetLaunchHold(this, false); _ascentSettings.ReleaseOwnValues(this); _countdown.Abort(); @@ -160,7 +160,6 @@ private void ResetGuidance() { _machine.ResetGuidance(); PadSolution = null; - _allowThrottle = false; _prelaunchDone = false; } @@ -200,22 +199,16 @@ private void UpdateFlightPlan() Core.PSGSimulation.UpdateLogicalPlan(); } - // the optimizer starts late in a countdown (or at once without one), and the throttle waits for the countdown to end + // The optimizer starts late in a countdown (or at once without one), and T-0 waits until the autopilot is ready to fly. + // The vessel itself waits on the pad in PRELAUNCH (AscentInputs.CountdownActive). private void UpdateCountdownGate() { - if (_countdown.Active) - { - if (_countdown.TMinus <= Math.Max(_ascentSettings.WarpCountDown, 0)) - Core.PSGSimulation.Users.Add(this); - else - Core.PSGSimulation.Users.Remove(this); - _allowThrottle = false; - } - else - { + if (!_countdown.Active || _countdown.TMinus <= Math.Max(_ascentSettings.WarpCountDown, 0)) Core.PSGSimulation.Users.Add(this); - _allowThrottle = true; - } + else + Core.PSGSimulation.Users.Remove(this); + + _countdown.SetLaunchHold(this, !_prelaunchDone || Solution == null); } /* @@ -250,7 +243,7 @@ private AscentInputs GatherInputs() VacT = Core.StageStats.VacT, PartIds = _partIds, PrelaunchDone = _prelaunchDone, - AllowThrottle = _allowThrottle, + CountdownActive = _countdown.Active, PitchStartHeight = _ascentSettings.PitchStartHeight, PitchRate = _ascentSettings.PitchRate, UllageLeadTime = UllageLeadTime, @@ -272,16 +265,13 @@ private void UpdatePartIds() _partIds.Add(part.persistentId); } - // the transitions' part of the command, then (unless the countdown holds for liftoff) the tick's + // the transitions' part of the command, then the tick's private void Apply(in AscentCommand cmd) { ApplyTransition(cmd); _ascentSettings.LimitingAoA = false; - if (cmd.CheckLiftoffHold && _countdown.HoldForLiftoff(Status)) - return; - if (cmd.DriveAscentParts) { Core.Solarpanel.DriveForAscent(); @@ -363,6 +353,9 @@ private void ApplyAttitude(in AscentCommand cmd) { switch (cmd.Attitude) { + case AscentAttitude.OFF: + Core.Attitude.SetAxisControl(false, false, false); + break; case AscentAttitude.VERTICAL: //during the vertical ascent we just thrust straight up at max throttle Core.Attitude.AttitudeToVerticalLaunch(cmd.Heading, @@ -408,14 +401,23 @@ private void UpdateStatus() { switch (State) { + case PSGState.PRELAUNCH: + // the countdown's prelaunch says what it is doing until it is done, and is skipped off the pad + if (!_prelaunchDone || !IsGrounded()) + break; + + // the first solve can take minutes on a slow machine: say so, or the pad looks stuck (the optimizer only + // starts late in a countdown) + if (Solution == null && Core.PSGSimulation.Enabled) + Status.Set(AwaitingComputing(_countdown.Active && _countdown.TMinus <= 0)); //"Awaiting liftoff: computing the ascent…" + else + Status.Set(Localizer.Format("#MechJeb_Ascent_status12")); //"Awaiting liftoff" + break; case PSGState.VERTICAL_ASCENT: + // on the pad from T-0 until the clamps let go if (!LiftedOff()) { - // the first solve can take minutes on a slow machine: say so, or the pad looks stuck - if (Solution == null) - Status.Set(AwaitingComputing()); //"Awaiting liftoff: computing the ascent…" - else - Status.Set(Localizer.Format("#MechJeb_Ascent_status12")); //"Awaiting liftoff" + Status.Set(Localizer.Format("#MechJeb_Ascent_status12")); //"Awaiting liftoff" break; } @@ -489,42 +491,36 @@ public void SetSolution(Solution solution) } /// - /// Drops a Solution that no longer applies and goes back to waiting for one. Only for use on the ground, the timed launch - /// buttons and kOS suffixes require a landed vessel. Does nothing while disabled, so a countdown started before engaging - /// leaves the throttle alone. + /// Drops a Solution that no longer applies and goes back to waiting for one, in PRELAUNCH with the throttle off, which + /// runs the countdown's prelaunch again. Only for use on the ground, the timed launch buttons and kOS suffixes require a + /// landed vessel. Does nothing while disabled. /// public void FlushSolution() { if (!Enabled) return; - bool prelaunchDone = _prelaunchDone; ResetGuidance(); - _prelaunchDone = prelaunchDone; - - // engaging without a countdown leaves the throttle up on the pad, and once the autopilot has left prelaunch nothing - // else lowers it before T-0 - ThrustOff(); } /* * Status and drawing */ - // "Awaiting liftoff: computing the ascent, step 2 of 5 (1m 12s)", rebuilt only when the progress text changes - private string AwaitingComputing() + // "Awaiting liftoff: computing the ascent, step 2 of 5 (1m 12s)", or "Holding launch for guidance: …" once T-0 waits for + // it, rebuilt only when the progress text or the hold changes + private string AwaitingComputing(bool holding) { string? progress = Core.PSGSimulation.ProgressShort; - if (progress == null) - return _awaitingComputing ??= Localizer.Format("#MechJeb_Ascent_status12") + ": computing the ascent…"; //"Awaiting liftoff" - - if (!ReferenceEquals(progress, _awaitingProgressFrom) || _awaitingProgress == null) + if (_awaitingStatus == null || !ReferenceEquals(progress, _awaitingFrom) || holding != _awaitingHolding) { - _awaitingProgressFrom = progress; - _awaitingProgress = Localizer.Format("#MechJeb_Ascent_status12") + ": " + progress; + _awaitingFrom = progress; + _awaitingHolding = holding; + _awaitingStatus = (holding ? "Holding launch for guidance" : Localizer.Format("#MechJeb_Ascent_status12")) + //"Awaiting liftoff" + ": " + (progress ?? "computing the ascent…"); } - return _awaitingProgress; + return _awaitingStatus; } // says why MechJeb can't fly the vessel while another mod has taken its controls; the string is rebuilt only when the lock diff --git a/MechJebKos/AscentPSGBinding.cs b/MechJebKos/AscentPSGBinding.cs index 93d1890e3..7eeb4b133 100644 --- a/MechJebKos/AscentPSGBinding.cs +++ b/MechJebKos/AscentPSGBinding.cs @@ -93,7 +93,7 @@ protected override void InitializeTypeSuffixes() AddSuffix("HASSOLUTION", new Suffix(() => Core.PSGAutopilot.Solution != null, "True once the optimizer has produced a guidance solution; starting a timed launch clears it until the optimizer solves again. Wait on this before staging to launch manually (a timed launch holds its own staging until there is one).")); AddSuffix("GUIDANCESTATUS", new Suffix(() => Core.PSGAutopilot.GuidanceStatus, - "PSG guidance status: ENABLED (no solution yet), INITIALIZED (the countdown holds the throttle), BURNING (from ignition on the pad), COASTING, TERMINAL_STAGING (staging off a cut stage), TERMINAL, TERMINAL_RCS or FINISHED. STATE gives the autopilot's own states.")); + "PSG guidance status: ENABLED (no solution yet), INITIALIZED (a solution, holding on the pad for the countdown), BURNING (from ignition on the pad), COASTING, TERMINAL_STAGING (staging off a cut stage), TERMINAL, TERMINAL_RCS or FINISHED. STATE gives the autopilot's own states.")); AddSuffix("STATE", new Suffix(() => Core.PSGAutopilot.State.ToString(), "PSG ascent autopilot state: PRELAUNCH, VERTICAL_ASCENT, PITCH_PROGRAM, BURNING, JETTISON, COASTING, TERMINAL, TERMINAL_RCS or FINISHED (use HASSOLUTION to wait for a solution).")); AddSuffix("VGO", new Suffix(() => Core.PSGAutopilot.Vgo, diff --git a/MechJebLib/PSG/AscentStateMachine.cs b/MechJebLib/PSG/AscentStateMachine.cs index 43333d894..220c8272f 100644 --- a/MechJebLib/PSG/AscentStateMachine.cs +++ b/MechJebLib/PSG/AscentStateMachine.cs @@ -56,6 +56,9 @@ public enum AscentAttitude // leave the attitude alone NONE, + // the attitude controller lets go of the axes (on the pad) + OFF, + // straight up, rolled to Heading VERTICAL, @@ -153,8 +156,8 @@ public struct AscentInputs // the countdown's prelaunch is done (its result from the last tick that drove it) public bool PrelaunchDone; - // the countdown lets the autopilot throttle up - public bool AllowThrottle; + // a launch countdown is running (it stages at T-0): on the pad the vessel waits in PRELAUNCH until it ends + public bool CountdownActive; public double PitchStartHeight; @@ -169,8 +172,8 @@ public struct AscentInputs } /// - /// What the ascent asks the vessel and the rest of MechJeb to do this tick. The transitions' part is applied first; the - /// tick's part only when CheckLiftoffHold is clear or the countdown isn't holding for liftoff. + /// What the ascent asks the vessel and the rest of MechJeb to do this tick. The transitions' part is applied first, then + /// the tick's. /// public struct AscentCommand { @@ -181,10 +184,7 @@ public struct AscentCommand // turn the RCS action group on public bool RCSGroupOn; - // set by the state's tick: the countdown's liftoff hold stops everything below - public bool CheckLiftoffHold; - - // drive the countdown's prelaunch, which sets the next tick's PrelaunchDone + // set by the state's tick: drive the countdown's prelaunch, which sets the next tick's PrelaunchDone public bool DrivePrelaunch; // the solar panels and the antennas for the ascent @@ -310,8 +310,9 @@ public class AscentStateMachine /// /// kOS GUIDANCESTATUS: State in the status names of the guidance controller this autopilot replaced, which launch scripts - /// wait on. ENABLED until there is a Solution and INITIALIZED while the countdown holds the throttle, then BURNING from - /// the ignition on the pad on, through the vertical ascent and the pitch program. JETTISON was TERMINAL_STAGING. + /// wait on. ENABLED until there is a Solution and INITIALIZED while it holds on the pad with one (PRELAUNCH, through + /// the countdown), then BURNING from the ignition on the pad on, through the vertical ascent and the pitch program. + /// JETTISON was TERMINAL_STAGING. /// public string GuidanceStatus { @@ -319,13 +320,14 @@ public string GuidanceStatus { switch (_state) { + case PSGState.PRELAUNCH: return Solution == null ? "ENABLED" : "INITIALIZED"; case PSGState.BURNING: return "BURNING"; case PSGState.JETTISON: return "TERMINAL_STAGING"; case PSGState.COASTING: return "COASTING"; case PSGState.TERMINAL: return "TERMINAL"; case PSGState.TERMINAL_RCS: return "TERMINAL_RCS"; case PSGState.FINISHED: return "FINISHED"; - default: return Solution == null ? "ENABLED" : _in.AllowThrottle ? "BURNING" : "INITIALIZED"; + default: return Solution == null ? "ENABLED" : "BURNING"; } } } @@ -475,8 +477,12 @@ private PSGState DetermineState(PSGState desired) if (desired == PSGState.FINISHED) return desired; - if (desired == PSGState.PRELAUNCH && _in.PrelaunchDone) + // the vessel waits on the pad until the countdown is over and there is a Solution to fly, and waits again when a + // countdown started on the pad drops the Solution (PSGSimulation.FlushSolution) + if (desired == PSGState.PRELAUNCH && _in.PrelaunchDone && !LaunchHeld()) desired = PSGState.VERTICAL_ASCENT; + else if (desired == PSGState.VERTICAL_ASCENT && LaunchHeld()) + desired = PSGState.PRELAUNCH; if (desired == PSGState.VERTICAL_ASCENT && _in.LiftedOff && _in.AltitudeBottom > _in.PitchStartHeight) desired = PSGState.PITCH_PROGRAM; // not in the tick the pitch program is entered: its pitch starts at 90° from the time OnEnterPitchProgram records, @@ -582,8 +588,6 @@ private void TickState() { if (_state != PSGState.PRELAUNCH && _state != PSGState.FINISHED) { - // nothing below while the countdown holds for liftoff - _cmd.CheckLiftoffHold = true; _cmd.DriveAscentParts = true; UpdateAutostageLimit(); } @@ -602,10 +606,25 @@ private void TickState() } } - // the autopilot keeps PrelaunchDone, which it clears as it engages + // the autopilot keeps PrelaunchDone, which it clears as it engages and when the Solution is dropped on the pad private void OnEnterPrelaunch() { } - private void TickPrelaunch() => _cmd.DrivePrelaunch = true; + // The countdown's prelaunch runs until it is done, then the vessel waits (LaunchHeld) with the throttle off and the axes + // let go, as the prelaunch has them. Engaged in flight, the prelaunch is skipped and nothing is cut: a throttle cut for + // a tick could cost a RealFuels engine its ignition. + private void TickPrelaunch() + { + _cmd.DrivePrelaunch = !_in.PrelaunchDone; + + if (!_in.Grounded) + return; + + _cmd.Throttle = AscentThrottle.OFF; + _cmd.Attitude = AscentAttitude.OFF; + } + + // on the pad, the launch waits for the countdown, which stages at T-0, and for a Solution to fly + private bool LaunchHeld() => _in.Grounded && (_in.CountdownActive || Solution == null); private void OnEnterVerticalAscent() { } @@ -1254,7 +1273,7 @@ private void UpdateDisplayVariables() // stage off a spent engine with no relights, and with it the RCS the insertion stage still needs. private void UpdateAutostageLimit() { - if (Solution == null || !_in.AllowThrottle) + if (Solution == null) return; _cmd.AutostageLimit = AutostageFloor(); @@ -1326,7 +1345,7 @@ private void ThrottleGuided() // the guided throttle of phase p private void ThrottleGuided(int p) { - if (Solution == null || !_in.AllowThrottle) + if (Solution == null) return; _cmd.Throttle = AscentThrottle.GUIDED; diff --git a/MechJebLibTest/PSGTests/AscentFlight.cs b/MechJebLibTest/PSGTests/AscentFlight.cs index 6f6b0e85c..3c2ed1931 100644 --- a/MechJebLibTest/PSGTests/AscentFlight.cs +++ b/MechJebLibTest/PSGTests/AscentFlight.cs @@ -172,7 +172,7 @@ public Staging(double met, int from, StagedBy by) public bool HasAtmosphere; public double AltitudeBottom = 100000; public bool PrelaunchDone = true; - public bool AllowThrottle = true; + public bool CountdownActive; public double PitchStartHeight = 100; public double PitchRate = 1; public double UllageLeadTime = 2; @@ -475,7 +475,7 @@ private AscentInputs Inputs() => VacT = _statsTime, PartIds = PartIds(), PrelaunchDone = PrelaunchDone, - AllowThrottle = AllowThrottle, + CountdownActive = CountdownActive, PitchStartHeight = PitchStartHeight, PitchRate = PitchRate, UllageLeadTime = UllageLeadTime, diff --git a/MechJebLibTest/PSGTests/AscentStateMachineTests.cs b/MechJebLibTest/PSGTests/AscentStateMachineTests.cs index ce6519990..e939d1461 100644 --- a/MechJebLibTest/PSGTests/AscentStateMachineTests.cs +++ b/MechJebLibTest/PSGTests/AscentStateMachineTests.cs @@ -92,22 +92,22 @@ public void PadThroughThePitchProgram() flight.PitchRate = 10; flight.Engage(Solve(flight.Plan(), MET0, Fixed(60), Fixed(40), Fixed(30))); - // the countdown's prelaunch, which nothing holds for + // the countdown's prelaunch, with the throttle off and the axes let go flight.Step(); Assert.Equal(PSGState.PRELAUNCH, flight.Machine.State); AscentCommand cmd = flight.Log.Last().Command; Assert.True(cmd.DrivePrelaunch); - Assert.False(cmd.CheckLiftoffHold); - Assert.Equal(AscentThrottle.NONE, cmd.Throttle); + Assert.Equal(AscentThrottle.OFF, cmd.Throttle); + Assert.Equal(AscentAttitude.OFF, cmd.Attitude); + Assert.False(cmd.DriveAscentParts); - // straight up under the guidance throttle, behind the liftoff hold + // straight up under the guidance throttle flight.PrelaunchDone = true; flight.Step(); Assert.Equal(PSGState.VERTICAL_ASCENT, flight.Machine.State); cmd = flight.Log.Last().Command; Assert.Equal(AscentAttitude.VERTICAL, cmd.Attitude); Assert.Equal(AscentThrottle.GUIDED, cmd.Throttle); - Assert.True(cmd.CheckLiftoffHold); Assert.True(cmd.DriveAscentParts); // off the pad, below the pitch start height @@ -129,6 +129,104 @@ public void PadThroughThePitchProgram() Assert.Equal("PRELAUNCH VERTICAL_ASCENT PITCH_PROGRAM BURNING", flight.Sequence()); } + // the three stages on the pad, the countdown's prelaunch done + private static AscentFlight OnThePad() + { + AscentFlight flight = ThreeStages(); + flight.HasAtmosphere = true; + flight.Grounded = true; + flight.LiftedOff = false; + flight.AltitudeBottom = 0; + return flight; + } + + [Fact] + public void PadHoldsInPrelaunchUntilThereIsASolution() + { + AscentFlight flight = OnThePad(); + flight.Machine.Start(); + + // the prelaunch done isn't driven again: the vessel waits with the throttle off and the axes let go + flight.Run(1); + Assert.Equal(PSGState.PRELAUNCH, flight.Machine.State); + Assert.All(flight.Log, t => Assert.False(t.Command.DrivePrelaunch)); + AscentCommand cmd = flight.Log.Last().Command; + Assert.Equal(AscentThrottle.OFF, cmd.Throttle); + Assert.Equal(AscentAttitude.OFF, cmd.Attitude); + Assert.Equal("ENABLED", flight.Machine.GuidanceStatus); + + // the first solve arrives: straight up under the guidance throttle + Assert.True(flight.Machine.SetSolution(Solve(flight.Plan(), MET0, Fixed(60), Fixed(40), Fixed(30)))); + flight.Step(); + Assert.Equal(PSGState.VERTICAL_ASCENT, flight.Machine.State); + Assert.Equal(AscentThrottle.GUIDED, flight.Log.Last().Command.Throttle); + Assert.Equal("BURNING", flight.Machine.GuidanceStatus); + } + + [Fact] + public void PadHoldsInPrelaunchThroughTheCountdown() + { + AscentFlight flight = OnThePad(); + flight.CountdownActive = true; + flight.Engage(Solve(flight.Plan(), MET0, Fixed(60), Fixed(40), Fixed(30))); + + // a Solution, but no throttle and no autostaging until T-0 + flight.Run(1); + Assert.Equal(PSGState.PRELAUNCH, flight.Machine.State); + AscentCommand cmd = flight.Log.Last().Command; + Assert.Equal(AscentThrottle.OFF, cmd.Throttle); + Assert.Equal(-1, cmd.AutostageLimit); + Assert.Equal("INITIALIZED", flight.Machine.GuidanceStatus); + + // T-0 stages and ends the countdown + flight.CountdownActive = false; + flight.Step(); + Assert.Equal(PSGState.VERTICAL_ASCENT, flight.Machine.State); + Assert.Equal(AscentThrottle.GUIDED, flight.Log.Last().Command.Throttle); + Assert.Equal("BURNING", flight.Machine.GuidanceStatus); + } + + [Fact] + public void ASolutionDroppedOnThePadGoesBackToPrelaunch() + { + AscentFlight flight = OnThePad(); + flight.Engage(Solve(flight.Plan(), MET0, Fixed(60), Fixed(40), Fixed(30))); + flight.Step(); + Assert.Equal(PSGState.VERTICAL_ASCENT, flight.Machine.State); + + // a countdown started on the pad (PSGSimulation.FlushSolution): the autopilot runs the prelaunch again + flight.Machine.ResetGuidance(); + flight.PrelaunchDone = false; + flight.CountdownActive = true; + flight.Step(); + Assert.Equal(PSGState.PRELAUNCH, flight.Machine.State); + AscentCommand cmd = flight.Log.Last().Command; + Assert.True(cmd.DrivePrelaunch); + Assert.Equal(AscentThrottle.OFF, cmd.Throttle); + Assert.Equal("PRELAUNCH VERTICAL_ASCENT PRELAUNCH", flight.Sequence()); + } + + [Fact] + public void PrelaunchEngagedInFlightCutsNothing() + { + AscentFlight flight = OneStage(); + flight.PrelaunchDone = false; + flight.Machine.Start(); + + // the countdown's prelaunch skips itself off the pad, and the throttle and attitude are left alone meanwhile + flight.Step(); + Assert.Equal(PSGState.PRELAUNCH, flight.Machine.State); + AscentCommand cmd = flight.Log.Last().Command; + Assert.True(cmd.DrivePrelaunch); + Assert.Equal(AscentThrottle.NONE, cmd.Throttle); + Assert.Equal(AscentAttitude.NONE, cmd.Attitude); + + // off the pad nothing holds for a Solution: the pitch program flies without one + flight.PrelaunchDone = true; + flight.Step(); + Assert.Equal(PSGState.PITCH_PROGRAM, flight.Machine.State); + } + [Fact] public void PitchProgramMeetsTheGuidanceOfANewSolutionAtOnce() { From a9fb77b956e556c9f4ef4a7bd517db2f48d47e7f Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Thu, 19 Nov 2026 14:37:43 -0800 Subject: [PATCH 3/8] Presolve the PSG vertical rise before solving on the ground Guidance flies straight up at full throttle to the pitch start height before the pitch program, but on the ground PSG solved from the pad itself. On the ground the PSG simulation now asks the AscentBuilder for a VerticalRise of the height left to climb. The rise is integrated ahead of the solve with the optimizer's own full throttle dynamics (AscentProblem.FullThrottleAcceleration, shared with the guesser), and the Problem starts at its top. The first phase starts there with the propellant the rise left it, and every burn's VexCurrent moves to the density at the top so the thrust stays the same at every height. With a first phase that coasts, a thrust-to-weight under 1, or a stage that burns out before the top, the solve runs from the pad as before. The rise is not a Phase, since the optimizer, its warm start and guidance's phase indices all start at the first phase. The Problem carries it (Problem.Rise) and each Solution keeps its own copy in front of its phases, from TStart on the ground to T0. Only the queries by time see it: R, V, U, M, StateVectors, DV, Vgo, and the time and delta-v left in the first phase, which burns it. It goes with DeepCopy, DeNormalized and RotateToLaunchSite, which still turns about the pad. The warm start reads the old Solution from its T0 on, so it never reads the rise. The rise is presolved whenever the vessel is on the ground, not only at MET zero, so a launch from the surface of a moon gets it too. What used to be T0 <= 0 is now Solution.FromPad (TStart <= 0), which still decides the rotation to the launch site and the PadSolution, and Problem.PadStart starts the guesser's guess vertically. VERTICAL_ASCENT flies full throttle with a rise, as it was planned. SolutionTrace samples the rise first as phase -1 and has a PhaseCount for the graph's status line, and the map trajectory starts at TStart. --- MechJeb2.UI/src/PSGSolutionGraphView.cs | 2 +- MechJeb2/MechJebModulePSGAutopilot.cs | 7 +- MechJeb2/MechJebModulePSGSimulation.cs | 6 + MechJebLib/PSG/AscentBuilder.cs | 19 + MechJebLib/PSG/AscentGuesser.cs | 27 +- MechJebLib/PSG/AscentProblem.cs | 31 +- MechJebLib/PSG/AscentStateMachine.cs | 12 +- MechJebLib/PSG/Problem.cs | 18 +- MechJebLib/PSG/Solution.cs | 130 ++++- MechJebLib/PSG/SolutionTrace.cs | 56 ++- MechJebLib/PSG/VerticalRise.cs | 113 +++++ MechJebLibTest/PSGTests/AscentFlight.cs | 20 +- .../PSGTests/AscentStateMachineTests.cs | 42 ++ MechJebLibTest/PSGTests/SolutionTests.cs | 79 ++- MechJebLibTest/PSGTests/VerticalRiseTests.cs | 465 ++++++++++++++++++ 15 files changed, 930 insertions(+), 97 deletions(-) create mode 100644 MechJebLib/PSG/VerticalRise.cs create mode 100644 MechJebLibTest/PSGTests/VerticalRiseTests.cs diff --git a/MechJeb2.UI/src/PSGSolutionGraphView.cs b/MechJeb2.UI/src/PSGSolutionGraphView.cs index 3d16526b3..56c7fc5c0 100644 --- a/MechJeb2.UI/src/PSGSolutionGraphView.cs +++ b/MechJeb2.UI/src/PSGSolutionGraphView.cs @@ -348,7 +348,7 @@ string StatusText() if (Plan.Count == 0) statusText = "No PSG solution yet: engage the PSG ascent"; else - statusText = $"Solution {g.Sampled}: MET {Plan.T0:F0} to {Plan.Tf:F0} s, {Plan.PhaseBoundaries.Count - 1} phases" + + statusText = $"Solution {g.Sampled}: MET {Plan.T0:F0} to {Plan.Tf:F0} s, {Plan.PhaseCount} phases" + (current ? "" : g.Hold ? " (held, guidance has a newer one)" : " (guidance has none now)"); return statusText; } diff --git a/MechJeb2/MechJebModulePSGAutopilot.cs b/MechJeb2/MechJebModulePSGAutopilot.cs index c749413a7..d79879154 100644 --- a/MechJeb2/MechJebModulePSGAutopilot.cs +++ b/MechJeb2/MechJebModulePSGAutopilot.cs @@ -486,7 +486,7 @@ private Vector3d ApplyAoALimiter(Vector3d desiredThrustVector) // guidance flies in SI units and MET seconds, so this takes a DeNormalized() Solution public void SetSolution(Solution solution) { - if (_machine.SetSolution(solution) && solution.T0 <= 0) + if (_machine.SetSolution(solution) && solution.FromPad) PadSolution = solution; } @@ -557,11 +557,12 @@ private void DrawTrajectory() const int SEGMENTS = 50; _trajectory.Clear(); - double dt = (Solution.Tf - Solution.T0) / SEGMENTS; + // from the ground, with the vertical rise + double dt = (Solution.Tf - Solution.TStart) / SEGMENTS; for (int i = 0; i <= SEGMENTS; i++) { - double t = Solution.T0 + dt * i; + double t = Solution.TStart + dt * i; _trajectory.Add(Solution.R(t).V3ToWorldRotated() + MainBody.position); } diff --git a/MechJeb2/MechJebModulePSGSimulation.cs b/MechJeb2/MechJebModulePSGSimulation.cs index af547bcf5..6c73e35ab 100644 --- a/MechJeb2/MechJebModulePSGSimulation.cs +++ b/MechJeb2/MechJebModulePSGSimulation.cs @@ -715,6 +715,12 @@ public override void OnFixedUpdate() .SetTarget(peR, apR, attR, Deg2Rad(Inc), Deg2Rad(lan), ArgP, fpa, attachAltFlag, lanflag, ArgPFlag) .FlightPlan(FlightPlan); + // On the ground guidance flies straight up at full throttle to the pitch start height before the pitch program, + // so the solve starts at the top of that rise, which the solution keeps in front of its first phase. After + // liftoff the solves are paused until guidance takes over, past the rise. + if (!Vessel.VesselOffGround()) + ascentBuilder.VerticalRise(Max(_ascentSettings.PitchStartHeight - VesselState.AltitudeBottom, 0)); + // note that we have to solve the atmospheric solution even when flying in vacuum, or the optimizer may decide to dip back // into the atmosphere again and burn up the rocket. if (MainBody.atmosphere) diff --git a/MechJebLib/PSG/AscentBuilder.cs b/MechJebLib/PSG/AscentBuilder.cs index 3d1339240..baadc628d 100644 --- a/MechJebLib/PSG/AscentBuilder.cs +++ b/MechJebLib/PSG/AscentBuilder.cs @@ -43,6 +43,7 @@ public class AscentBuilder private bool _argpflag { get; set; } private bool _fixedBurnTime { get; set; } private int _optimizerTimeout { get; set; } = Optimizer.DEFAULT_TIMEOUT; + private double _riseHeight { get; set; } private Solution? _solution { get; set; } private FlightPlan? _flightPlan; @@ -204,6 +205,9 @@ public Ascent Build() normalizedPhases.AddRange(_phases.Select(phase => phase.Rescale(problem.Scale))); + // on the ground the problem starts at the top of the vertical rise, from the first phase's rest + problem = PSG.VerticalRise.Presolve(problem, normalizedPhases, _riseHeight / problem.Scale.LengthScale); + normalizedPhases.FixLastShutdownStage(); var ascent = new Ascent(problem, normalizedPhases, _flightPlan, _solution, _fixedBurnTime, _optimizerTimeout); @@ -271,6 +275,21 @@ public AscentBuilder OptimizerTimeout(int milliseconds) return this; } + /// + /// On the ground, guidance flies straight up at full throttle for height meters before it pitches over, so the + /// problem is solved from the top of that rise (PSG.VerticalRise), with the rise kept in front of the Solution. + /// Zero, the default, solves from the initial state. + /// + public AscentBuilder VerticalRise(double height) + { + PrintDebug($"[MechJebLib.AscentBuilder] VerticalRise({height})"); + + Check.NonNegativeFinite(height, nameof(height)); + + _riseHeight = height; + return this; + } + public AscentBuilder OldSolution(Solution solution) { PrintDebug("[MechJebLib.AscentBuilder] OldSolution()"); diff --git a/MechJebLib/PSG/AscentGuesser.cs b/MechJebLib/PSG/AscentGuesser.cs index 18c2a5fd4..b6b34eff3 100644 --- a/MechJebLib/PSG/AscentGuesser.cs +++ b/MechJebLib/PSG/AscentGuesser.cs @@ -120,8 +120,8 @@ public AscentGuesser(Problem problem, FlightPlan? flightPlan) _flightPlan = flightPlan; // the same atmosphere as AscentProblem - _atmosphere = problem.H0 > 0 && problem.Rho0CdAref > 0; - _invDensityR0 = problem.H0 > 0 ? 1.0 / AscentProblem.NormalizedDensity(problem.R0.magnitude, problem.RBody, problem.H0).M : 0; + _atmosphere = AscentProblem.HasAtmosphere(problem); + _invDensityR0 = AscentProblem.InvDensityR0(problem); Scale scale = problem.Scale; _rFloor = Min(problem.R0.magnitude, problem.RBody) - IMPACT_MARGIN / scale.LengthScale; @@ -195,22 +195,8 @@ private V3 SteeringRate(V3 r, V3 v, V3 a, double t) } } - // the optimizer's dynamics (AscentProblem.VDotAtmo and VDotVacuum) at full throttle, with the drag written so that - // it is still finite at zero airspeed on the pad - private V3 Acceleration(V3 r, V3 v, double m, V3 u) - { - double rm = r.magnitude; - V3 gravity = -r / (rm * rm * rm); - - if (!_atmosphere) - return gravity + _phase.VacThrust / m * u; - - double density = AscentProblem.NormalizedDensity(rm, _problem.RBody, _problem.H0).M; - V3 vr = SurfaceVelocity(r, v); - V3 drag = 0.5 * _problem.Rho0CdAref * density * vr.magnitude * vr; - double thrust = _phase.Mdot * (_phase.VexCurrent + (_phase.VexVacuum - _phase.VexCurrent) * (1.0 - density * _invDensityR0)); - return gravity + thrust / m * u - drag / m; - } + // the optimizer's dynamics (AscentProblem.VDotAtmo and VDotVacuum) at full throttle + private V3 Acceleration(V3 r, V3 v, double m, V3 u) => AscentProblem.FullThrottleAcceleration(_problem, _phase, _invDensityR0, r, v, m, u); private void Rhs(Vec yin, double t, Vec dyout) { @@ -577,7 +563,7 @@ private void InitialVariables() double twr = LiftoffTWR(); // the guess also runs in flight when there is no solution to start from: then the first phase is the current stage, // at its current mass, and the problem's MET is past zero - if (_problem.T0 > 0) + if (!_problem.PadStart) throw new Exception( $"No ascent found from here: the rocket falls back even flying almost straight up (thrust-to-weight now {twr:F2})"); throw new Exception(twr < 1 @@ -630,7 +616,8 @@ public Solution InitialGuess(PhaseCollection phases, CancellationToken cancellat _rT = _problem.Terminal.GuessRadius(); _incT = _problem.Terminal.IncT(); - _padStart = _problem.T0 <= 0; + // from the pad, or from the top of the vertical rise presolved from it, which is still going straight up + _padStart = _problem.PadStart; _kickVariables = _padStart && _atmosphere; _tStackEnd = StackEndTime(); diff --git a/MechJebLib/PSG/AscentProblem.cs b/MechJebLib/PSG/AscentProblem.cs index 15d1ee5a1..ad716b624 100644 --- a/MechJebLib/PSG/AscentProblem.cs +++ b/MechJebLib/PSG/AscentProblem.cs @@ -41,8 +41,35 @@ public AscentProblem(Optimizer optimizer) _vars = new VariableProxy(_optimizer.Problem, _optimizer.Phases, _optimizer.Terminal, _optimizer.N); Problem problem = _optimizer.Problem; - _atmosphere = problem.H0 > 0 && problem.Rho0CdAref > 0; - _invDensityR0 = problem.H0 > 0 ? 1.0 / NormalizedDensity(problem.R0.magnitude, problem.RBody, problem.H0).M : 0; + _atmosphere = HasAtmosphere(problem); + _invDensityR0 = InvDensityR0(problem); + } + + // whether the dynamics have drag and back pressure (VDotAtmo) or are in vacuum (VDotVacuum) + internal static bool HasAtmosphere(Problem problem) => problem.H0 > 0 && problem.Rho0CdAref > 0; + + // one over the density at the problem's initial position, which the engines' back pressure is relative to (0 without + // an atmosphere): their VexCurrent is the exhaust velocity there + internal static double InvDensityR0(Problem problem) => + problem.H0 > 0 ? 1.0 / NormalizedDensity(problem.R0.magnitude, problem.RBody, problem.H0).M : 0; + + /// + /// VDot at full throttle in doubles, for the AscentGuesser and the VerticalRise, with the drag written so that it is + /// still finite at zero airspeed on the pad. Normalized units. + /// + internal static V3 FullThrottleAcceleration(Problem problem, Phase phase, double invDensityR0, V3 r, V3 v, double m, V3 u) + { + double rm = r.magnitude; + V3 gravity = -r / (rm * rm * rm); + + if (!HasAtmosphere(problem)) + return gravity + phase.VacThrust / m * u; + + double density = NormalizedDensity(rm, problem.RBody, problem.H0).M; + V3 vr = v - V3.Cross(problem.W, r); + V3 drag = 0.5 * problem.Rho0CdAref * density * vr.magnitude * vr; + double thrust = phase.Mdot * (phase.VexCurrent + (phase.VexVacuum - phase.VexCurrent) * (1.0 - density * invDensityR0)); + return gravity + thrust / m * u - drag / m; } public readonly struct ConstraintArgs diff --git a/MechJebLib/PSG/AscentStateMachine.cs b/MechJebLib/PSG/AscentStateMachine.cs index 220c8272f..19d286d31 100644 --- a/MechJebLib/PSG/AscentStateMachine.cs +++ b/MechJebLib/PSG/AscentStateMachine.cs @@ -630,10 +630,17 @@ private void OnEnterVerticalAscent() { } private void TickVerticalAscent() { - //during the vertical ascent we just thrust straight up at max throttle _cmd.Attitude = AscentAttitude.VERTICAL; _cmd.Heading = Heading; + // a solution with the vertical rise in front of it planned the rise at full throttle (VerticalRise) + if (Solution is { HasRise: true }) + { + _cmd.Throttle = AscentThrottle.GUIDED; + _cmd.ThrottleValue = 1.0; + return; + } + ThrottleGuided(); } @@ -1239,7 +1246,8 @@ private void UpdateDisplayVariables() if (Solution == null || IsFinished) return; - // the Solution's clock is MET, which stays at zero until liftoff, so on the ground this flies its first point + // the Solution's clock is MET, which stays at zero until liftoff, so on the ground this shows the whole solution + // (with its vertical rise, if it has one) and steers by the first point of its first phase int p = CurrentPhase(IsCoasting); // frozen from the engine cut on: the RCS trim runs past the end of the Solution diff --git a/MechJebLib/PSG/Problem.cs b/MechJebLib/PSG/Problem.cs index b09bbb1f1..a8c6fb19e 100644 --- a/MechJebLib/PSG/Problem.cs +++ b/MechJebLib/PSG/Problem.cs @@ -3,6 +3,7 @@ * 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.Interpolants; using MechJebLib.Primitives; using MechJebLib.PSG.Terminal; @@ -25,8 +26,19 @@ public readonly struct Problem public readonly double H0; public readonly V3 W; + /// + /// The vertical rise off the ground presolved ahead of this problem (VerticalRise), normalized, from the MET on the + /// ground to T0, or null. It is not a phase: each Solution for the problem keeps its own copy of it, and it is never + /// evaluated here. + /// + public readonly VecInterpolant? Rise; + + /// The problem starts on the pad at liftoff, or at the top of the vertical rise off the ground. + public bool PadStart => Rise != null || T0 <= 0; + public Problem(V3 r0, V3 v0, V3 u0, double m0, double t0, double mu, double rbody, double h0, double rho0CdAref, double rho0InvQAlphaMax, double rho0InvQMax, V3 w, ITerminal terminal) { + Rise = null; Scale = Scale.Create(mu, r0.magnitude, m0); Mu = mu; R0 = r0 / Scale.LengthScale; @@ -43,8 +55,10 @@ public Problem(V3 r0, V3 v0, V3 u0, double m0, double t0, double mu, double rbod W = w * Scale.TimeScale; } - public Problem(Scale scale, V3 r0, V3 v0, V3 u0, double m0, double t0, double mu, double rbody, double h0, double rho0CdAref, double rho0InvQAlphaMax, double rho0InvQMax, V3 w, ITerminal terminal) + public Problem(Scale scale, V3 r0, V3 v0, V3 u0, double m0, double t0, double mu, double rbody, double h0, double rho0CdAref, double rho0InvQAlphaMax, double rho0InvQMax, V3 w, ITerminal terminal, + VecInterpolant? rise = null) { + Rise = rise; Scale = scale; Mu = mu; R0 = r0; @@ -64,7 +78,7 @@ public Problem(Scale scale, V3 r0, V3 v0, V3 u0, double m0, double t0, double mu public Problem WithoutDynamicPressure() { return new Problem( - Scale, R0, V0, U0, M0, T0, Mu, RBody, H0, Rho0CdAref, 0, 0, W, Terminal + Scale, R0, V0, U0, M0, T0, Mu, RBody, H0, Rho0CdAref, 0, 0, W, Terminal, Rise ); } } diff --git a/MechJebLib/PSG/Solution.cs b/MechJebLib/PSG/Solution.cs index 5682e0c1e..b1f77ee82 100644 --- a/MechJebLib/PSG/Solution.cs +++ b/MechJebLib/PSG/Solution.cs @@ -32,6 +32,12 @@ namespace MechJebLib.PSG // gets its first point, and one computed in flight starts at the MET of its initial state. While it waits on the ground // the launch site turns with the planet, which RotateToLaunchSite turns the solution to follow. // + // A solution computed on the ground may start with the vertical rise guidance flies before it pitches over, which was + // presolved ahead of the optimizer (VerticalRise): the trajectory then starts at TStart on the ground, and its phases at T0 + // at the top of the rise. The rise is not a phase, so the phases, their times and indices, and the state on a phase's own + // interpolant are the optimizer's. Only the queries by time see it: the state before T0 (R, V, U, M, StateVectors), the + // delta-v used and left (DV, Vgo), and the time and delta-v left in the first phase, which burns the rise. + // // A phase SolutionBuilder.AnalyzeStages marks Skip (one the optimizer left too short to fly, or a pruned stage) is never // flown, but it stays in the Solution: its phases line up with the optimizer's for the warm start of the next solve, which // reads the old Solution phase by phase. The queries about what guidance flies (CoastIndex, CoastKSPStage, NextPhase, @@ -56,11 +62,14 @@ public class Solution : IDisposable private readonly List _dvend = new List(); private readonly List _interpolants = new List(); + // the vertical rise from TStart to T0, or null (see Problem.Rise) + private VecInterpolant? _rise; + // in SI units, for TerminalLines private readonly double _mu; private readonly double _rbody; - // the initial position the solution was solved from, in its units + // the launch site the solution was solved at (the start of the rise, or the initial position), in its units private readonly V3 _r0; // the turn RotateToLaunchSite applies to every vector the solution returns @@ -68,24 +77,37 @@ public class Solution : IDisposable public int Segments => Phases.Count; - // the MET of the start and the end of the trajectory + // the MET of the start of the phases and the end of the trajectory public double T0 => _tmin[0]; public double Tf => _tmax[Segments - 1]; + // the trajectory starts with the vertical rise to T0 + public bool HasRise => _rise != null; + + // the MET of the start of the trajectory: of the rise, or of the phases + public double TStart => _rise?.MinT ?? T0; + + // computed on the ground at liftoff, so RotateToLaunchSite turns it to follow the launch site + public bool FromPad => TStart <= 0; + // a normalized solution for the problem public Solution(Problem problem, FlightPlan? flightPlan) - : this(problem.Scale, true, problem.Mu, problem.RBody * problem.Scale.LengthScale, problem.R0, AeroModel.From(problem), flightPlan) + : this(problem.Scale, true, problem.Mu, problem.RBody * problem.Scale.LengthScale, problem.R0, AeroModel.From(problem), flightPlan, + problem.Rise?.DeepCopy()) { } - private Solution(Scale scale, bool normalized, double mu, double rbody, V3 r0, AeroModel aero, FlightPlan? flightPlan) + // takes ownership of rise + private Solution(Scale scale, bool normalized, double mu, double rbody, V3 r0, AeroModel aero, FlightPlan? flightPlan, + VecInterpolant? rise) { Aero = aero; Scale = scale; Normalized = normalized; _mu = mu; _rbody = rbody; - _r0 = r0; + _rise = rise; + _r0 = rise != null ? RiseRaw(rise.MinT).R : r0; FlightPlan = flightPlan; } @@ -98,7 +120,8 @@ public void AddSegment(VecInterpolant interpolant, Phase phase) Phases.Add(phase.DeepCopy()); _interpolants.Add(interpolant); int idx = _interpolants.Count - 1; - double dvstart = _dvend.Count > 0 ? _dvend[_dvend.Count - 1] : 0; + // the first phase burns the rise + double dvstart = _dvend.Count > 0 ? _dvend[_dvend.Count - 1] : RiseDV(phase, T0); double dvend = dvstart + phase.DeltaVFromMass(M(idx, interpolant.MinT), M(idx, interpolant.MaxT)); _dvstart.Add(dvstart); _dvend.Add(dvend); @@ -106,7 +129,7 @@ public void AddSegment(VecInterpolant interpolant, Phase phase) public Solution DeepCopy() { - var dup = new Solution(Scale, Normalized, _mu, _rbody, _r0, Aero, FlightPlan?.DeepCopy()) { _rotation = _rotation }; + var dup = new Solution(Scale, Normalized, _mu, _rbody, _r0, Aero, FlightPlan?.DeepCopy(), _rise?.DeepCopy()) { _rotation = _rotation }; for (int i = 0; i < _interpolants.Count; i++) dup.AddSegment(_interpolants[i].DeepCopy(), Phases[i]); return dup; @@ -120,9 +143,6 @@ public Solution DeNormalized() { Check.True(Normalized, "the Solution is already in SI units"); - var dup = new Solution(Scale, false, _mu, _rbody, _r0 * Scale.LengthScale, Aero.DeNormalize(Scale), - FlightPlan?.DeepCopy()) { _rotation = _rotation }; - using var yScale = Vec.Rent(InterpolantLayout.INTERPOLANT_LAYOUT_LEN); new InterpolantLayout { @@ -133,6 +153,12 @@ public Solution DeNormalized() T = 1 }.CopyTo(yScale); + VecInterpolant? rise = _rise?.DeepCopy(); + rise?.Rescale(Scale.TimeScale, yScale); + + var dup = new Solution(Scale, false, _mu, _rbody, _r0 * Scale.LengthScale, Aero.DeNormalize(Scale), + FlightPlan?.DeepCopy(), rise) { _rotation = _rotation }; + for (int i = 0; i < _interpolants.Count; i++) { VecInterpolant interpolant = _interpolants[i].DeepCopy(); @@ -147,15 +173,15 @@ public Solution DeNormalized() /// The launch site turns with the planet while the vessel waits on the ground, so this turns a solution computed on /// the ground about the planet's pole (V3.northpole), from the launch site it was solved at to r0, the launch site /// now. Every vector the solution returns is turned, which carries its initial position and velocity exactly onto the - /// moved launch site and keeps its inclination. A solution computed in flight (T0 > 0) is never turned. Once the - /// vessel has lifted off a solution computed on the ground keeps following the vessel, which is close enough while it - /// climbs over the launch site, until the first solution computed in flight replaces it. - /// Only the direction of r0 matters, so it can be in meters or normalized units. Each call replaces the last - /// rotation, so it can be called every tick. + /// moved launch site and keeps its inclination, and the vertical rise along with the rest. A solution which doesn't + /// start at liftoff (FromPad) is never turned. Once the vessel has lifted off a solution computed on the ground + /// keeps following the vessel, which is close enough while it climbs over the launch site, until the first solution + /// computed in flight replaces it. Only the direction of r0 matters, so it can be in meters or normalized units. + /// Each call replaces the last rotation, so it can be called every tick. /// public void RotateToLaunchSite(V3 r0) { - if (T0 > 0) + if (!FromPad) return; // the angle about the pole between the two launch sites' projections onto the equator @@ -179,10 +205,31 @@ public InterpolantLayout State(int p, double t) return x; } + /// The state on the vertical rise at t, turned like every other accessor. It extrapolates outside the rise. + public InterpolantLayout RiseState(double t) + { + Check.True(HasRise, "the Solution has no vertical rise"); + + InterpolantLayout x = RiseRaw(t); + x.R = _rotation * x.R; + x.V = _rotation * x.V; + x.U = _rotation * x.U; + return x; + } + + // adds the bounds between the rise's interpolant nodes, its start and end included + public void RiseNodeBoundaries(List into) + { + Check.True(HasRise, "the Solution has no vertical rise"); + + AddNodeBoundaries(_rise!, into); + } + // adds the bounds between phase p's interpolant nodes, its start and end included - public void NodeBoundaries(int p, List into) + public void NodeBoundaries(int p, List into) => AddNodeBoundaries(_interpolants[p], into); + + private static void AddNodeBoundaries(VecInterpolant interpolant, List into) { - VecInterpolant interpolant = _interpolants[p]; for (int i = 0; i < interpolant.NodeCount; i++) into.Add(interpolant.NodeLeftT(i)); if (interpolant.NodeCount > 0) @@ -227,19 +274,47 @@ private double M(int segment, double t) return InterpolantLayout.CreateFrom(xRaw).M; } - // the delta-v used since the start of the trajectory + // the delta-v used since the start of the trajectory, the rise included public double DV(double t) { + if (InRise(t)) + return RiseDV(Phases[0], t); + int idx = IndexFor(t); double dv = Phases[idx].DeltaVFromMass(M(idx, _tmin[idx]), M(idx, t)); return _dvstart[idx] + dv; } - // the delta-v left in phase n + // the delta-v left in phase n, the rest of the rise included in the first phase public double DV(double t, int n) { + double mf = M(n, _tmax[n]); + + if (n == 0 && InRise(t)) + return Phases[0].DeltaVFromMass(RiseRaw(Max(t, TStart)).M, mf); + t = Clamp(t, _tmin[n], _tmax[n]); - return Phases[n].DeltaVFromMass(M(n, t), M(n, _tmax[n])); + return Phases[n].DeltaVFromMass(M(n, t), mf); + } + + // the time is before T0 on a solution with a rise + private bool InRise(double t) => _rise != null && t < T0; + + // the state on the rise, unturned + private InterpolantLayout RiseRaw(double t) + { + using Vec xRaw = _rise!.Evaluate(t); + return InterpolantLayout.CreateFrom(xRaw); + } + + // the delta-v the first phase burns on the rise from its start to t (none without a rise) + private double RiseDV(Phase first, double t) + { + if (_rise == null) + return 0; + + t = Clamp(t, TStart, _rise.MaxT); + return first.DeltaVFromMass(RiseRaw(TStart).M, RiseRaw(t).M); } /// @@ -305,12 +380,14 @@ public double DeltaVShortfall() // runs negative past Tf public double Tgo(double t) => Tf - t; - // the time left in phase n: all of it before the phase starts, and none of it once it is over + // the time left in phase n: all of it before the phase starts, and none of it once it is over. The first phase + // starts with the rise. public double Tgo(double t, int n) { - if (t > _tmin[n]) + double start = n == 0 ? TStart : _tmin[n]; + if (t > start) return Max(_tmax[n] - t, 0); - return _tmax[n] - _tmin[n]; + return _tmax[n] - start; } public double Vgo(double t) => DV(Tf) - DV(t); @@ -471,7 +548,8 @@ public int IndexForKSPStage(int kspStage, bool coasting) return idx; } - private Vec Interpolate(double t) => _interpolants[IndexFor(t)].Evaluate(t); + // the rise before T0 + private Vec Interpolate(double t) => InRise(t) ? _rise!.Evaluate(t) : _interpolants[IndexFor(t)].Evaluate(t); private Vec Interpolate(int segment, double t) => _interpolants[segment].Evaluate(t); @@ -480,6 +558,8 @@ public void Dispose() foreach (VecInterpolant i in _interpolants) i.Dispose(); _interpolants.Clear(); + _rise?.Dispose(); + _rise = null; } } } diff --git a/MechJebLib/PSG/SolutionTrace.cs b/MechJebLib/PSG/SolutionTrace.cs index 5946aaafd..73852b4ee 100644 --- a/MechJebLib/PSG/SolutionTrace.cs +++ b/MechJebLib/PSG/SolutionTrace.cs @@ -18,8 +18,10 @@ namespace MechJebLib.PSG /// A SI Solution sampled for plotting and export: a row per sample, phase by phase, with SamplesPerNode samples across /// each interpolant node so that what the cubic pieces do between their collocation points shows. Each phase is sampled /// on its own interpolant from its start to its end, so a jump at a phase boundary shows as two rows at the same MET. - /// It also keeps the phase boundaries, the node boundaries and the collocation points. Sampling evaluates the solution, - /// which updates its lookup caches: sample on the thread that owns it. + /// The vertical rise of a solution computed on the ground comes first, as phase -1 in the first phase's stage. It + /// also keeps the phase boundaries, the node boundaries and the collocation points of the phases, which the rise, not + /// being optimizer output, doesn't add to. Sampling evaluates the solution, which updates its lookup caches: sample + /// on the thread that owns it. /// public sealed class SolutionTrace { @@ -51,9 +53,12 @@ public enum Column private readonly List[] _columns = new List[ColumnCount]; - // the MET where each phase starts, and the end of the last one + // the MET where the rise and each phase starts, and the end of the last one public readonly List PhaseBoundaries = new List(); + // the number of phases, without the rise + public int PhaseCount { get; private set; } + // the bounds between interpolant nodes, of every phase public readonly List NodeBoundaries = new List(); @@ -83,6 +88,7 @@ public void Clear() NodeBoundaries.Clear(); Knots.Clear(); T0 = Tf = 0; + PhaseCount = 0; } /// @@ -98,11 +104,27 @@ public void Sample(Solution solution, int samplesPerNode = DEFAULT_SAMPLES_PER_N Clear(); Aero = solution.Aero; - T0 = solution.T0; + T0 = solution.TStart; Tf = solution.Tf; + PhaseCount = solution.Segments; var bounds = new List(); + if (solution.HasRise) + { + PhaseBoundaries.Add(solution.TStart); + solution.RiseNodeBoundaries(bounds); + + for (int n = 0; n + 1 < bounds.Count; n++) + { + double left = bounds[n], right = bounds[n + 1]; + for (int k = 0; k < samplesPerNode; k++) + AddRiseRow(solution, left + (right - left) * k / samplesPerNode); + } + + AddRiseRow(solution, solution.T0); + } + for (int p = 0; p < solution.Segments; p++) { double start = solution.StartTime(p); @@ -137,25 +159,37 @@ public void Sample(Solution solution, int samplesPerNode = DEFAULT_SAMPLES_PER_N private void AddRow(Solution solution, int p, double t) { - InterpolantLayout x = solution.State(p, t); Phase phase = solution.Phases[p]; + double dv = solution.DV(Math.Min(Math.Max(t, solution.StartTime(p)), solution.EndTime(p))); + AddRow(solution, solution.State(p, t), t, p, phase.KSPStage, phase.MJPhase, phase.Coast, phase.Unguided, dv); + } + + // a row on the vertical rise, which the first phase's stage burns, guided straight up + private void AddRiseRow(Solution solution, double t) + { + Phase phase = solution.Phases[0]; + AddRow(solution, solution.RiseState(t), t, -1, phase.KSPStage, phase.MJPhase, false, false, solution.DV(t)); + } + + private void AddRow(Solution solution, InterpolantLayout x, double t, int p, int kspStage, int mjPhase, bool coast, bool unguided, + double dv) + { AeroModel aero = solution.Aero; (double pitch, double heading) = Astro.ECIToPitchHeading(x.R, x.U); Add(Column.MET, t); Add(Column.PHASE, p); - Add(Column.KSP_STAGE, phase.KSPStage); - Add(Column.MJ_PHASE, phase.MJPhase); - Add(Column.COAST, phase.Coast ? 1 : 0); - Add(Column.UNGUIDED, phase.Unguided ? 1 : 0); + Add(Column.KSP_STAGE, kspStage); + Add(Column.MJ_PHASE, mjPhase); + Add(Column.COAST, coast ? 1 : 0); + Add(Column.UNGUIDED, unguided ? 1 : 0); Add(Column.ALTITUDE, x.R.magnitude - aero.RBody); Add(Column.SPEED, x.V.magnitude); Add(Column.SURFACE_SPEED, aero.SurfaceVelocity(x.R, x.V).magnitude); Add(Column.PITCH, Rad2Deg(pitch)); Add(Column.HEADING, Rad2Deg(heading)); - Add(Column.THROTTLE, phase.Coast ? 0 : x.T); + Add(Column.THROTTLE, coast ? 0 : x.T); Add(Column.MASS, x.M); - double dv = solution.DV(Math.Min(Math.Max(t, solution.StartTime(p)), solution.EndTime(p))); Add(Column.DELTA_V, dv); Add(Column.DELTA_V_LEFT, solution.DV(solution.Tf) - dv); Add(Column.AOA, Rad2Deg(aero.AngleOfAttack(x.R, x.V, x.U))); diff --git a/MechJebLib/PSG/VerticalRise.cs b/MechJebLib/PSG/VerticalRise.cs new file mode 100644 index 000000000..f7916a035 --- /dev/null +++ b/MechJebLib/PSG/VerticalRise.cs @@ -0,0 +1,113 @@ +/* + * 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.Interpolants; +using MechJebLib.ODE; +using MechJebLib.Primitives; +using MechJebLib.Utils; + +namespace MechJebLib.PSG +{ + /// + /// Guidance flies a fixed vertical ascent off the ground, at full throttle straight up, before the pitch program hands + /// over to the solution: so a problem on the ground is solved from the top of that rise instead of from the ground. + /// The rise is integrated ahead of the solve with the optimizer's own dynamics (AscentProblem.FullThrottleAcceleration) + /// in the first burn, and the problem starts where it ends. The rise itself is not a phase: the optimizer, its warm + /// start and guidance's phase indices all start at the first phase. The problem carries it (Problem.Rise) for each + /// Solution to keep as the trajectory from the ground to its T0. + /// + internal static class VerticalRise + { + /// + /// The problem from the top of the vertical rise from pad, with the first phase starting there. Without a rise to + /// fly (no height, a first phase that coasts, or a rocket that can't lift off or burns out before the top) it is + /// pad and the phases are untouched. + /// + /// the normalized problem on the ground + /// the normalized phases, the first of which flies the rise, changed in place + /// the normalized height of the rise + public static Problem Presolve(Problem pad, PhaseCollection phases, double height) + { + if (!(height > 0) || phases.Count == 0 || phases[0].Coast) + return pad; + + Phase phase = phases[0]; + CheckDebug.True(phase.Normalized); + + double invDensityR0 = AscentProblem.InvDensityR0(pad); + double rTop = pad.R0.magnitude + height; + + void Rhs(Vec yin, double t, Vec dyout) + { + var y = InterpolantLayout.CreateFrom(yin); + double rm = y.R.magnitude; + V3 rhat = y.R / rm; + + var dy = new InterpolantLayout + { + R = y.V, + V = AscentProblem.FullThrottleAcceleration(pad, phase, invDensityR0, y.R, y.V, y.M, rhat), + M = -phase.Mdot, + // the thrust direction is the radial unit vector, which turns with the position + U = (y.V - V3.Dot(rhat, y.V) * rhat) / rm, + T = 0 + }; + + dy.CopyTo(dyout); + } + + // can't lift off: straight up, the acceleration from rest (on the rotating planet) is not upwards + V3 r0hat = pad.R0.normalized; + V3 vh = pad.V0 - V3.Dot(pad.V0, r0hat) * r0hat; + double climb = V3.Dot(AscentProblem.FullThrottleAcceleration(pad, phase, invDensityR0, pad.R0, pad.V0, pad.M0, r0hat), r0hat) + + vh.sqrMagnitude / pad.R0.magnitude; + if (!(climb > 0)) + return pad; + + var y0 = new InterpolantLayout { R = pad.R0, V = pad.V0, M = pad.M0, U = r0hat, T = 1 }; + double tf = pad.T0 + phase.BurnTimeFromMass(pad.M0); + + using var y0Vec = Vec.Rent(InterpolantLayout.INTERPOLANT_LAYOUT_LEN); + using var yfVec = Vec.Rent(InterpolantLayout.INTERPOLANT_LAYOUT_LEN); + y0.CopyTo(y0Vec); + + var solver = new Tsit5 { Rtol = 1e-10, Atol = 1e-10, MaxEvals = 100000 }; + var top = new Event((y, t, i) => InterpolantLayout.CreateFrom(y).R.magnitude - rTop); + var rise = VecInterpolant.Rent(); + + solver.Solve(Rhs, y0Vec, yfVec, pad.T0, tf, rise, new[] { top }); + + // burned out before the top + if (solver.Status != AbstractIVP.IVPStatus.EventTerminated) + { + rise.Dispose(); + return pad; + } + + var y1 = InterpolantLayout.CreateFrom(yfVec); + double t1 = solver.T; + + // the first burn starts at the top, with the propellant the rise left it + phase.M0 = y1.M; + phase.Bt = phase.BurnTimeFromMass(y1.M); + phase.MinT = phase.AllowShutdown ? 0 : phase.Bt; + phase.MaxT = phase.Bt / phase.MinThrottle; + + // The back pressure of every burn is relative to the density at the problem's initial position (InvDensityR0), + // which is now the top of the rise, so each VexCurrent moves to the exhaust velocity there to keep the thrust the + // same at every height. + if (AscentProblem.HasAtmosphere(pad)) + { + double ratio = AscentProblem.NormalizedDensity(y1.R.magnitude, pad.RBody, pad.H0).M * invDensityR0; + foreach (Phase p in phases) + if (!p.Coast) + p.VexCurrent = p.VexVacuum - (p.VexVacuum - p.VexCurrent) * ratio; + } + + return new Problem(pad.Scale, y1.R, y1.V, y1.R.normalized, y1.M, t1, pad.Mu, pad.RBody, pad.H0, pad.Rho0CdAref, + pad.Rho0InvQAlphaMax, pad.Rho0InvQMax, pad.W, pad.Terminal, rise); + } + } +} diff --git a/MechJebLibTest/PSGTests/AscentFlight.cs b/MechJebLibTest/PSGTests/AscentFlight.cs index 3c2ed1931..efd10fa6d 100644 --- a/MechJebLibTest/PSGTests/AscentFlight.cs +++ b/MechJebLibTest/PSGTests/AscentFlight.cs @@ -349,7 +349,17 @@ public Leg(double seconds, bool coast, bool allowShutdown, bool propellantLeft) /// optimized burn has the precise shutdown, and the legs before it too short to fly (a zero-length coast or burn) are /// skipped. Guidance flies its own copy of the flight plan. /// - public static Solution Solve(FlightPlan plan, double start, int startIndex, params Leg[] legs) + public static Solution Solve(FlightPlan plan, double start, int startIndex, params Leg[] legs) => + Solve(plan, start, startIndex, double.NaN, 1, legs); + + /// + /// Like Solve, with the vertical rise of a solution computed on the ground in front of it, from MET riseStart to + /// start, and every burn planned at the given throttle (which is also its MinThrottle). + /// + public static Solution SolveWithRise(FlightPlan plan, double riseStart, double start, double throttle, params Leg[] legs) => + Solve(plan, start, plan.Stages.Count - 1, riseStart, throttle, legs); + + private static Solution Solve(FlightPlan plan, double start, int startIndex, double riseStart, double throttle, Leg[] legs) { var indices = new List(); for (int i = startIndex; i >= 0; i--) @@ -362,6 +372,7 @@ public static Solution Solve(FlightPlan plan, double start, int startIndex, para var segs = new Seg[legs.Length]; double tbar = (start - T0) / TIME_SCALE; double m = 64 * Math.Pow(4, legs.Length); + double riseM0 = 2 * m; for (int k = 0; k < legs.Length; k++) { @@ -378,9 +389,10 @@ public static Solution Solve(FlightPlan plan, double start, int startIndex, para else { // a zero-length burn burns nothing, though its stage's thrust needs a burn time - phase = NewBurn(stage.KSPStage, stage.MJStage, m, m / 2, 300, leg.Seconds > 0 ? leg.Seconds : 1, leg.AllowShutdown); + phase = NewBurn(stage.KSPStage, stage.MJStage, m, m / 2, 300, leg.Seconds > 0 ? leg.Seconds : 1, leg.AllowShutdown, + minThrottle: throttle); phase.PropellantLeft = leg.PropellantLeft; - segs[k] = new Seg(phase, tbar, tbar1, m, leg.Seconds > 0 ? m / 2 : m, _yHat, _yHat, 1, 1); + segs[k] = new Seg(phase, tbar, tbar1, m, leg.Seconds > 0 ? m / 2 : m, _yHat, _yHat, throttle, throttle); m /= 4; } @@ -391,7 +403,7 @@ public static Solution Solve(FlightPlan plan, double start, int startIndex, para tbar = tbar1; } - return Build(plan, segs); + return double.IsNaN(riseStart) ? Build(plan, segs) : BuildWithRise(plan, (riseStart - T0) / TIME_SCALE, riseM0, segs); } public static Solution Solve(FlightPlan plan, double start, params Leg[] legs) => Solve(plan, start, plan.Stages.Count - 1, legs); diff --git a/MechJebLibTest/PSGTests/AscentStateMachineTests.cs b/MechJebLibTest/PSGTests/AscentStateMachineTests.cs index e939d1461..f2bea39bb 100644 --- a/MechJebLibTest/PSGTests/AscentStateMachineTests.cs +++ b/MechJebLibTest/PSGTests/AscentStateMachineTests.cs @@ -129,6 +129,48 @@ public void PadThroughThePitchProgram() Assert.Equal("PRELAUNCH VERTICAL_ASCENT PITCH_PROGRAM BURNING", flight.Sequence()); } + // A solution computed on the ground starts its phases at the top of the vertical rise, which it planned at full + // throttle (VerticalRise), so the vertical ascent flies full throttle whatever the first phase's throttle is, from the + // pad until the pitch program, which flies the planned throttle. Without the rise the vertical ascent flies the + // first phase's throttle. + [Fact] + public void TheVerticalRiseIsFlownAtFullThrottle() + { + AscentFlight flight = OnThePad(); + flight.Engage(SolveWithRise(flight.Plan(), MET0, MET0 + 2, 0.5, Fixed(60), Fixed(40), Fixed(30))); + Assert.True(flight.Machine.Solution!.HasRise); + + flight.Step(); + Assert.Equal(PSGState.VERTICAL_ASCENT, flight.Machine.State); + AscentCommand cmd = flight.Log.Last().Command; + Assert.Equal(AscentAttitude.VERTICAL, cmd.Attitude); + Assert.Equal(AscentThrottle.GUIDED, cmd.Throttle); + Assert.Equal(1, cmd.ThrottleValue); + + // off the pad, below the pitch start height, still in the rise + flight.Grounded = false; + flight.LiftedOff = true; + flight.AltitudeBottom = 50; + flight.Run(1); + Assert.Equal(PSGState.VERTICAL_ASCENT, flight.Machine.State); + Assert.All(flight.Log, t => Assert.Equal(1, t.Command.ThrottleValue)); + + flight.AltitudeBottom = 150; + flight.Step(); + Assert.Equal(PSGState.PITCH_PROGRAM, flight.Machine.State); + cmd = flight.Log.Last().Command; + Assert.Equal(AscentThrottle.GUIDED, cmd.Throttle); + cmd.ThrottleValue.ShouldEqual(0.5, 1e-12); + + AscentFlight noRise = OnThePad(); + noRise.Engage(SolveWithRise(noRise.Plan(), double.NaN, MET0, 0.5, Fixed(60), Fixed(40), Fixed(30))); + Assert.False(noRise.Machine.Solution!.HasRise); + + noRise.Step(); + Assert.Equal(PSGState.VERTICAL_ASCENT, noRise.Machine.State); + noRise.Log.Last().Command.ThrottleValue.ShouldEqual(0.5, 1e-12); + } + // the three stages on the pad, the countdown's prelaunch done private static AscentFlight OnThePad() { diff --git a/MechJebLibTest/PSGTests/SolutionTests.cs b/MechJebLibTest/PSGTests/SolutionTests.cs index 1a1cc4635..a7e240fac 100644 --- a/MechJebLibTest/PSGTests/SolutionTests.cs +++ b/MechJebLibTest/PSGTests/SolutionTests.cs @@ -612,43 +612,65 @@ internal static Solution Build(FlightPlan? plan, params Seg[] segs) private static Solution BuildNormalized(params Seg[] segs) => BuildNormalized(null, segs); - // each segment is a single cubic Hermite node whose end slopes are both the chord's, so it interpolates linearly - private static Solution BuildNormalized(FlightPlan? plan, params Seg[] segs) + private static Solution BuildNormalized(FlightPlan? plan, params Seg[] segs) => BuildNormalized(plan, null, segs); + + /// + /// The SI copy of the normalized solution with a vertical rise in front of its phases (Solution.HasRise), as a + /// solution computed on the ground has: on the shared R and V from riseTbar0 to the first segment's start, burning + /// the first segment's stage from riseM0 (kg) down to its mass there, at full throttle straight out along R. + /// + internal static Solution BuildWithRise(FlightPlan? plan, double riseTbar0, double riseM0, params Seg[] segs) + { + Seg first = segs[0]; + var rise = new Seg(first.Phase, riseTbar0, first.Tbar0, riseM0, first.Y0.M * MASS_SCALE, RBarAt(riseTbar0).normalized, + RBarAt(first.Tbar0).normalized, 1, 1); + using Solution normalized = BuildNormalized(plan, rise, segs); + return normalized.DeNormalized(); + } + + // each segment is a single cubic Hermite node whose end slopes are both the chord's, so it interpolates linearly; the + // rise's Phase is not used + private static Solution BuildNormalized(FlightPlan? plan, Seg? rise, Seg[] segs) { InterpolantLayout x0 = segs[0].Y0; var problem = new Problem(_scale, x0.R, x0.V, x0.U, x0.M, TBAR0, MU, RBODY / LENGTH_SCALE, 0, 0, 0, 0, V3.zero, - new Kepler3(1, 0, 0)); + new Kepler3(1, 0, 0), rise.HasValue ? LinearInterpolant(rise.Value) : null); var solution = new Solution(problem, plan); + // the solution keeps its own copy + problem.Rise?.Dispose(); + + foreach (Seg seg in segs) + solution.AddSegment(LinearInterpolant(seg), seg.Phase); + + return solution; + } + private static VecInterpolant LinearInterpolant(Seg seg) + { using var y = Vec.Rent(InterpolantLayout.INTERPOLANT_LAYOUT_LEN); using var ynew = Vec.Rent(InterpolantLayout.INTERPOLANT_LAYOUT_LEN); using var dy = Vec.Rent(InterpolantLayout.INTERPOLANT_LAYOUT_LEN); - foreach (Seg seg in segs) + double h = seg.Tbar1 - seg.Tbar0; + // a zero-length segment (a pruned stage) has no slope, and CubicHermiteVecNode makes it a constant + double invH = h > 0 ? 1 / h : 0; + var slope = new InterpolantLayout { - double h = seg.Tbar1 - seg.Tbar0; - // a zero-length segment (a pruned stage) has no slope, and CubicHermiteVecNode makes it a constant - double invH = h > 0 ? 1 / h : 0; - var slope = new InterpolantLayout - { - R = (seg.Y1.R - seg.Y0.R) * invH, - V = (seg.Y1.V - seg.Y0.V) * invH, - M = (seg.Y1.M - seg.Y0.M) * invH, - U = (seg.Y1.U - seg.Y0.U) * invH, - T = (seg.Y1.T - seg.Y0.T) * invH - }; - - seg.Y0.CopyTo(y); - seg.Y1.CopyTo(ynew); - slope.CopyTo(dy); - - // the solution's clock is normalized MET - var interpolant = VecInterpolant.Rent(); - interpolant.Append(CubicHermiteVecNode.Rent(TBAR0 + seg.Tbar0, h, y, dy, ynew, dy), TBAR0 + seg.Tbar0, TBAR0 + seg.Tbar1); - solution.AddSegment(interpolant, seg.Phase); - } + R = (seg.Y1.R - seg.Y0.R) * invH, + V = (seg.Y1.V - seg.Y0.V) * invH, + M = (seg.Y1.M - seg.Y0.M) * invH, + U = (seg.Y1.U - seg.Y0.U) * invH, + T = (seg.Y1.T - seg.Y0.T) * invH + }; - return solution; + seg.Y0.CopyTo(y); + seg.Y1.CopyTo(ynew); + slope.CopyTo(dy); + + // the solution's clock is normalized MET + var interpolant = VecInterpolant.Rent(); + interpolant.Append(CubicHermiteVecNode.Rent(TBAR0 + seg.Tbar0, h, y, dy, ynew, dy), TBAR0 + seg.Tbar0, TBAR0 + seg.Tbar1); + return interpolant; } /* @@ -665,7 +687,8 @@ private static Solution BuildNormalized(FlightPlan? plan, params Seg[] segs) * * The thrust direction is x in the booster, turns from x to y in p1, and turns from y to z in the coast. */ - private static Solution TheStandardLike(bool normalized = false) + // with rise, the vertical rise of a solution computed on the ground is in front of it, 32 s (4064-4096 s) from 16384 kg + private static Solution TheStandardLike(bool normalized = false, bool rise = false) { Phase booster = NewBurn(4, 7, 8192, 4096, 256, 64, false, true); Phase burn1 = NewBurn(2, 5, 2048, 1024, 320, 32, minThrottle: 0.5); @@ -684,6 +707,8 @@ private static Solution TheStandardLike(bool normalized = false) new Seg(upper, 2, 2.25, 256, 128, _zHat, _zHat, 1, 1) }; + if (rise) + return BuildWithRise(null, -0.25, 16384, segs); return normalized ? BuildNormalized(segs) : Build(segs); } diff --git a/MechJebLibTest/PSGTests/VerticalRiseTests.cs b/MechJebLibTest/PSGTests/VerticalRiseTests.cs new file mode 100644 index 000000000..f5cda4999 --- /dev/null +++ b/MechJebLibTest/PSGTests/VerticalRiseTests.cs @@ -0,0 +1,465 @@ +/* + * 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 System; +using MechJebLib.Functions; +using MechJebLib.Primitives; +using MechJebLib.PSG; +using MechJebLib.PSG.Terminal; +using MechJebLib.Utils; +using Xunit; +using static MechJebLib.Utils.Statics; +using Column = MechJebLib.PSG.SolutionTrace.Column; + +namespace MechJebLibTest.PSGTests +{ + // The vertical rise presolved ahead of a solve on the ground (VerticalRise), and the Solution keeping it in front of its + // phases + public partial class SolutionTests + { + private const double RISE = 100; + + // TinCanBuilder's first stage + private const double TIN_CAN_M0 = 79699.9986022711; + private const double TIN_CAN_MF = 15700.0014199451; + private const double TIN_CAN_THRUST = 1500000.09246676; + private const double TIN_CAN_ISP = 310.000018173591; + private const double TIN_CAN_ISP_CURRENT = 285.387620615011; + private const double KERBIN_MU = 3531600000000; + + // the TinCan problem on the pad, with its first stage, normalized as AscentBuilder.Build makes them; with atmosphere + // it has KerbinTests' atmosphere + private static (Problem, PhaseCollection) TinCanPad(double thrust = TIN_CAN_THRUST, double mf = TIN_CAN_MF, bool atmosphere = false) + { + double h0 = atmosphere ? 6797.80562531277 : 0; + double rho0CdAref = atmosphere ? 0.5 * 19.6 * 1.22497705725583 : 0; + V3 w = atmosphere ? new V3(0, 0, 0.000291570900559802) : V3.zero; + + var problem = new Problem(_tinCanR0, _tinCanV0, _tinCanU0, TIN_CAN_M0, 0, KERBIN_MU, 600000, h0, rho0CdAref, 0, 0, w, + new Kepler3(700000, 0, 0)); + + using Phase stage = Phase.NewStage(TIN_CAN_M0, mf, thrust, TIN_CAN_ISP, 0, 0, ispCurrent: TIN_CAN_ISP_CURRENT, minThrottle: 0); + return (problem, new PhaseCollection { stage.Rescale(problem.Scale) }); + } + + // The rise ends RISE up, where the problem and its first phase start, with the propellant it left, and the thrust of + // every height stays what it was, though the back pressure is now relative to the top of the rise. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void PresolveStartsTheProblemAtTheTop(bool atmosphere) + { + (Problem pad, PhaseCollection phases) = TinCanPad(atmosphere: atmosphere); + Phase before = phases[0].DeepCopy(); + double height = RISE / pad.Scale.LengthScale; + + Problem top = VerticalRise.Presolve(pad, phases, height); + Phase phase = phases[0]; + + Assert.NotNull(top.Rise); + top.PadStart.ShouldBeTrue(); + top.Rise!.MinT.ShouldEqual(pad.T0, 0); + top.Rise.MaxT.ShouldEqual(top.T0, 0); + Assert.InRange(top.T0 * pad.Scale.TimeScale, 4.5, atmosphere ? 5.5 : 4.9); + + (top.R0.magnitude - pad.R0.magnitude).ShouldEqual(height, 1e-12); + top.U0.ShouldEqual(top.R0.normalized, 1e-15); + top.M0.ShouldEqual(pad.M0 - before.Mdot * top.T0, 1e-12); + top.Scale.LengthScale.ShouldEqual(pad.Scale.LengthScale, 0); + top.Scale.TimeScale.ShouldEqual(pad.Scale.TimeScale, 0); + + // straight up, which keeps the angular momentum (but for a whisper of drag across the radial) + V3 rhat = top.R0.normalized; + V3.Cross(top.R0, top.V0).ShouldEqual(V3.Cross(pad.R0, pad.V0), atmosphere ? 1e-5 : 1e-9); + Assert.True(V3.Dot(top.V0, rhat) > 0); + + phase.M0.ShouldEqual(top.M0, 0); + phase.Bt.ShouldEqual(before.Bt - top.T0, 1e-12); + phase.MinT.ShouldEqual(0, 0); + phase.MaxT.ShouldEqual(phase.Bt / phase.MinThrottle, 0); + + double invPad = AscentProblem.InvDensityR0(pad); + double invTop = AscentProblem.InvDensityR0(top); + + foreach (double altitude in new double[] { 0, 50, RISE, 1000, 10000, 70000 }) + { + V3 r = rhat * (pad.RBody + altitude / pad.Scale.LengthScale); + V3 a0 = AscentProblem.FullThrottleAcceleration(pad, before, invPad, r, top.V0, top.M0, rhat); + V3 a1 = AscentProblem.FullThrottleAcceleration(top, phase, invTop, r, top.V0, top.M0, rhat); + a1.ShouldEqual(a0, 1e-12); + } + + if (atmosphere) + Assert.True(phase.VexCurrent > before.VexCurrent && phase.VexCurrent < phase.VexVacuum); + else + phase.VexCurrent.ShouldEqual(before.VexCurrent, 0); + } + + // without a rise to fly the problem is the one on the pad, and the phases are left alone + [Fact] + public void NoRiseToFly() + { + void NoRise(Problem pad, PhaseCollection phases, double height) + { + double m0 = phases[0].M0, bt = phases[0].Bt, vex = phases[0].VexCurrent; + + Problem problem = VerticalRise.Presolve(pad, phases, height / pad.Scale.LengthScale); + + Assert.Null(problem.Rise); + problem.T0.ShouldEqual(pad.T0, 0); + problem.R0.ShouldEqual(pad.R0, 0); + problem.M0.ShouldEqual(pad.M0, 0); + phases[0].M0.ShouldEqual(m0, 0); + phases[0].Bt.ShouldEqual(bt, 0); + phases[0].VexCurrent.ShouldEqual(vex, 0); + } + + // no height + (Problem pad, PhaseCollection phases) = TinCanPad(atmosphere: true); + NoRise(pad, phases, 0); + + // can't lift off, at a thrust-to-weight of 0.64 + (pad, phases) = TinCanPad(500000, atmosphere: true); + NoRise(pad, phases, RISE); + + // burns out 0.02 s off the pad + (pad, phases) = TinCanPad(mf: TIN_CAN_M0 - 10); + NoRise(pad, phases, RISE); + + // the first phase coasts + (pad, phases) = TinCanPad(); + using (Phase coast = Phase.NewCoast(TIN_CAN_M0, TIN_CAN_M0, 0, 450, 0, 0)) + phases.Insert(0, coast.Rescale(pad.Scale)); + NoRise(pad, phases, RISE); + } + + // On the pad the solve starts at the top of a rise straight up at full throttle from the pad, which the solution keeps + // in front of its phases, and the rise is the first phase's: it counts in that phase's time and delta-v left. + [Fact] + public void TinCanRisesStraightUpFromThePad() + { + Ascent ascent = TinCanBuilder().VerticalRise(RISE).Build(); + ascent.Run(); + + Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); + psg.Success().ShouldBeTrue(); + using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); + + double t0 = solution.T0; + Logger.Print($"rise {t0} s, Vgo {solution.Vgo(0)} m/s, Tgo {solution.Tgo(0)} s"); + + solution.HasRise.ShouldBeTrue(); + solution.FromPad.ShouldBeTrue(); + solution.TStart.ShouldEqual(0, 0); + // 0.92 g up for 100 m + Assert.InRange(t0, 4.5, 4.9); + + solution.R(0).ShouldEqual(_tinCanR0, 1e-12); + solution.V(0).ShouldEqual(_tinCanV0, 1e-12); + solution.M(0).ShouldEqual(TIN_CAN_M0, 1e-12); + (solution.R(t0).magnitude - _tinCanR0.magnitude).ShouldEqual(RISE, 1e-7); + + // the first phase starts where the rise ends + InterpolantLayout top = solution.RiseState(t0); + InterpolantLayout first = solution.State(0, t0); + first.R.ShouldEqual(top.R, 1e-12); + first.V.ShouldEqual(top.V, 1e-12); + first.M.ShouldEqual(top.M, 1e-12); + + // straight up at full throttle (at T0 U is the first phase's steering) + double mdot = TIN_CAN_THRUST / (TIN_CAN_ISP * G0); + top.M.ShouldEqual(TIN_CAN_M0 - mdot * t0, 1e-10); + top.U.ShouldEqual(top.R.normalized, 1e-9); + for (int i = 0; i < SAMPLES; i++) + { + double t = t0 * i / SAMPLES; + solution.U(t).ShouldEqual(solution.R(t).normalized, 1e-9); + solution.RiseState(t).T.ShouldEqual(1, 1e-14); + Assert.True(solution.R(t).magnitude > _tinCanR0.magnitude - 1e-6); + } + + double vex = TIN_CAN_ISP * G0; + solution.DV(0).ShouldEqual(0, 0); + solution.DV(t0).ShouldEqual(vex * Math.Log(TIN_CAN_M0 / top.M), 1e-10); + solution.Vgo(0).ShouldEqual(solution.DV(solution.Tf), 0); + solution.Tgo(0).ShouldEqual(solution.Tf, 0); + solution.Tgo(0, 0).ShouldEqual(solution.EndTime(0), 0); + solution.Tgo(t0 / 2, 0).ShouldEqual(solution.EndTime(0) - t0 / 2, 1e-12); + solution.DV(0, 0).ShouldEqual(solution.DV(t0) + solution.DV(t0, 0), 1e-10); + + (V3 rf, V3 vf) = solution.TerminalStateVectors(); + (double smaf, double eccf, double incf, _, _, _, _) = Astro.KeplerianFromStateVectors(KERBIN_MU, rf, vf); + smaf.ShouldEqual(700000, 1e-7); + eccf.ShouldBeZero(1e-6); + incf.ShouldBeZero(1e-7); + } + + // The rise goes with every copy of the solution and with the turn to the launch site, and a re-solve on the pad warm + // started from the solution rises the same way, which puts the warm start right on the pinned initial state at the + // top. As in WarmStartFromATurnedLaunchSite the solution warm started is itself a warm start, since a warm start + // from the cold start changes the objective (Tf goes from 609 s to 544 s here, and from 610 s to 543 s without the + // rise) and takes many iterations wherever it is. + [Fact] + public void TinCanRiseRoundTrips() + { + Ascent cold = TinCanBuilder().VerticalRise(RISE).Build(); + cold.Run(); + + Ascent ascent = TinCanBuilder().VerticalRise(RISE).OldSolution(cold.GetOptimizer()?.Solution ?? throw new Exception("null solution")) + .Build(); + ascent.Run(); + + Solution normalized = ascent.GetOptimizer()?.Solution ?? throw new Exception("null solution"); + Scale scale = normalized.Scale; + + using Solution solution = normalized.DeNormalized(); + using Solution copy = solution.DeepCopy(); + using Solution normalizedCopy = normalized.DeepCopy(); + + double t0 = solution.T0; + normalizedCopy.HasRise.ShouldBeTrue(); + copy.HasRise.ShouldBeTrue(); + + for (int i = 0; i <= SAMPLES; i++) + { + double t = t0 * i / SAMPLES; + InterpolantLayout x = solution.RiseState(t); + + InterpolantLayout c = copy.RiseState(t); + c.R.ShouldEqual(x.R, 0); + c.V.ShouldEqual(x.V, 0); + c.M.ShouldEqual(x.M, 0); + + InterpolantLayout xbar = normalizedCopy.RiseState(t / scale.TimeScale); + (xbar.R * scale.LengthScale).ShouldEqual(x.R, 1e-14); + (xbar.V * scale.VelocityScale).ShouldEqual(x.V, 1e-14); + (xbar.M * scale.MassScale).ShouldEqual(x.M, 1e-14); + } + + copy.DV(t0).ShouldEqual(solution.DV(t0), 0); + (normalizedCopy.DV(t0 / scale.TimeScale) * scale.VelocityScale).ShouldEqual(solution.DV(t0), 1e-14); + + // turned to the launch site the planet has turned to, the rise and all + Q3 turn = Q3.AngleAxis(TURN, V3.northpole); + using Solution turned = normalized.DeNormalized(); + turned.RotateToLaunchSite(turn * _tinCanR0); + + turned.R(0).ShouldEqual(turn * _tinCanR0, 1e-12); + turned.RiseState(t0 / 2).R.ShouldEqual(turn * solution.RiseState(t0 / 2).R, 1e-12); + for (int i = 0; i <= SAMPLES; i++) + { + double t = solution.Tf * i / SAMPLES; + turned.R(t).ShouldEqual(turn * solution.R(t), 1e-12); + turned.U(t).ShouldEqual(turn * solution.U(t), 1e-12); + turned.DV(t).ShouldEqual(solution.DV(t), 0); + } + + // as the solver does between solves on the pad + Ascent again = TinCanBuilder().VerticalRise(RISE).OldSolution(normalized).Build(); + again.Run(); + + Optimizer psg = again.GetOptimizer() ?? throw new Exception("null optimizer"); + psg.Success().ShouldBeTrue(); + psg.InitialPrimalFeasibility.ShouldBeZero(1e-6); + Assert.InRange(psg.Iterations, 0, 5); + using Solution s1 = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); + + s1.HasRise.ShouldBeTrue(); + s1.T0.ShouldEqual(t0, 0); + s1.Tf.ShouldEqual(solution.Tf, 1e-6); + s1.Vgo(0).ShouldEqual(solution.Vgo(0), 1e-6); + } + + // Off the surface of a moon the vessel is on the ground long after MET zero: the rise starts at the MET there, and as + // the solution doesn't start at liftoff it isn't turned to follow the launch site. + [Fact] + public void RiseOffTheGroundLaterInTheMission() + { + const double MET0 = 100; + + Ascent ascent = TinCanBuilder(met0: MET0).VerticalRise(RISE).Build(); + ascent.Run(); + + Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); + psg.Success().ShouldBeTrue(); + using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); + + solution.HasRise.ShouldBeTrue(); + solution.FromPad.ShouldBeFalse(); + solution.TStart.ShouldEqual(MET0, 0); + Assert.InRange(solution.T0 - MET0, 4.5, 4.9); + solution.R(MET0).ShouldEqual(_tinCanR0, 1e-12); + solution.DV(MET0).ShouldEqual(0, 0); + solution.Tgo(MET0, 0).ShouldEqual(solution.EndTime(0) - MET0, 0); + + using Solution turned = solution.DeepCopy(); + turned.RotateToLaunchSite(Q3.AngleAxis(TURN, V3.northpole) * _tinCanR0); + turned.R(MET0).ShouldEqual(solution.R(MET0), 0); + turned.R(solution.Tf).ShouldEqual(solution.R(solution.Tf), 0); + } + + // TheStandardPeriapsis with a sea level Isp for its first stage, rising 100 m through the atmosphere off the pad + [Fact] + public void TheStandardRisesThroughTheAtmosphere() + { + var r0 = new V3(-521765.111703417, -5568874.59934707, 3050608.87783524); + var v0 = new V3(406.088016257895, -38.0495807832894, 0.000701038889818476); + var u0 = new V3(-0.0820737379089317, -0.874094973679233, 0.478771328926086); + const double MU = 3.986004418e+14; + const double RBODY = 6.371e+6; + + const double PE_R = 6.371e+6 + 185e+3; + const double AP_R = 6.371e+6 + 10e+6; + double incT = Deg2Rad(28.608); + + double thrust1 = Astro.ThrustFromMassesIspBurntime(49119.7842689869, 7114.2513992454, 288.000034332275, 170.308460385726); + double thrust2 = Astro.ThrustFromMassesIspBurntime(2848.62586760223, 1363.71123994759, 270.15767003304, 116.391834883409); + double thrust3 = Astro.ThrustFromMassesIspBurntime(678.290157913434, 177.582604389742, 230.039271734103, 53.0805126571005); + + Ascent ascent = Ascent.Builder() + .Initial(r0, v0, u0, 0, MU, RBODY) + .AerodynamicConstants(0.5, 10, 1.225, 2000, 35000, 7200, 7.29211585e-5 * V3.northpole) + .SetTarget(PE_R, AP_R, PE_R, incT, 0, 0, 0, true, false, false) + .AddStage(49119.7842689869, 7114.2513992454, thrust1, 288.000034332275, 3, 3, ispCurrent: 260) + .AddStage(2848.62586760223, 1363.71123994759, thrust2, 270.15767003304, 1, 1) + .AddCoast(678.290157913434, 678.290157913434, 0, 450, 1, 1) + .AddStage(678.290157913434, 177.582604389742, thrust3, 230.039271734103, 0, 0, true, false) + .VerticalRise(RISE) + .Build(); + + ascent.Run(); + + Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); + psg.PrimalFeasibility.ShouldBeZero(1e-5); + using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); + + Logger.Print($"rise {solution.T0} s, Vgo {solution.Vgo(0)} m/s, Tgo {solution.Tgo(0)} s"); + + solution.HasRise.ShouldBeTrue(); + solution.FromPad.ShouldBeTrue(); + // 0.30 g up for 100 m, rising as the propellant burns + Assert.InRange(solution.T0, 7, 9); + solution.R(0).ShouldEqual(r0, 1e-12); + (solution.R(solution.T0).magnitude - r0.magnitude).ShouldEqual(RISE, 1e-7); + solution.M(0).ShouldEqual(49119.7842689869, 1e-12); + + (V3 rf, V3 vf) = solution.TerminalStateVectors(); + (double smaf, double eccf, double incf, _, _, _, _) = Astro.KeplerianFromStateVectors(MU, rf, vf); + smaf.ShouldEqual((PE_R + AP_R) / 2, 1e-4); + eccf.ShouldEqual((AP_R - PE_R) / (AP_R + PE_R), 1e-4); + incf.ShouldEqual(incT, 1e-4); + rf.magnitude.ShouldEqual(PE_R, 1e-6); + } + + // the rise is traced first, as phase -1 in the first phase's stage, without node or collocation markers + [Fact] + public void TraceSamplesTheRiseFirst() + { + using Solution solution = TheStandardLike(rise: true); + var trace = new SolutionTrace(); + trace.Sample(solution, 8); + + trace.Count.ShouldEqual(6 * 9); + trace.PhaseCount.ShouldEqual(5); + trace.T0.ShouldEqual(4064, 0); + trace.Tf.ShouldEqual(4384, 0); + Assert.Equal(new double[] { 4064, 4096, 4160, 4192, 4224, 4352, 4384 }, trace.PhaseBoundaries); + Assert.Equal(new double[] { 4096, 4160, 4160, 4192, 4192, 4224, 4224, 4352, 4352, 4384 }, trace.NodeBoundaries); + Assert.Equal(trace.NodeBoundaries, trace.Knots); + + double vex = 256 * G0; + for (int row = 0; row < 9; row++) + { + trace[Column.PHASE, row].ShouldEqual(-1); + trace[Column.MET, row].ShouldEqual(4064 + 32.0 * row / 8, 1e-12); + trace[Column.KSP_STAGE, row].ShouldEqual(4); + trace[Column.MJ_PHASE, row].ShouldEqual(7); + trace[Column.COAST, row].ShouldEqual(0); + trace[Column.UNGUIDED, row].ShouldEqual(0); + trace[Column.THROTTLE, row].ShouldEqual(1, 1e-12); + trace[Column.MASS, row].ShouldEqual(16384 - 8192.0 * row / 8, 1e-9); + trace[Column.DELTA_V, row].ShouldEqual(vex * Math.Log(16384 / trace[Column.MASS, row]), 1e-9); + } + + // straight up, to the precision of the arcsine there + trace[Column.PITCH, 0].ShouldEqual(90, 1e-5); + trace[Column.PITCH, 8].ShouldEqual(90, 1e-5); + + // then the phases, from the top of the rise, where the booster has burned its share + for (int row = 9; row < trace.Count; row++) + trace[Column.PHASE, row].ShouldEqual((row - 9) / 9); + trace[Column.MET, 8].ShouldEqual(trace[Column.MET, 9], 0); + trace[Column.MASS, 8].ShouldEqual(trace[Column.MASS, 9], 1e-9); + trace[Column.DELTA_V, 9].ShouldEqual(vex * Math.Log(2), 1e-9); + + for (int row = 0; row < trace.Count; row++) + (trace[Column.DELTA_V, row] + trace[Column.DELTA_V_LEFT, row]).ShouldEqual(solution.DV(solution.Tf), 1e-9); + } + + // the queries by time see the rise in front of the phases, and the phases are the same as without it + [Fact] + public void TheRiseIsInFrontOfThePhases() + { + using Solution solution = TheStandardLike(rise: true); + using Solution plain = TheStandardLike(); + + solution.HasRise.ShouldBeTrue(); + plain.HasRise.ShouldBeFalse(); + // not at liftoff, so it is never turned + solution.FromPad.ShouldBeFalse(); + solution.TStart.ShouldEqual(4064, 0); + solution.T0.ShouldEqual(4096, 0); + solution.Segments.ShouldEqual(plain.Segments); + for (int p = 0; p < solution.Segments; p++) + { + solution.StartTime(p).ShouldEqual(plain.StartTime(p), 0); + solution.EndTime(p).ShouldEqual(plain.EndTime(p), 0); + } + + solution.R(4080).ShouldEqual(ExpectedR(4080), 1e-12); + solution.V(4080).ShouldEqual(ExpectedV(4080), 1e-12); + solution.M(4080).ShouldEqual(12288, 1e-12); + solution.M(4096).ShouldEqual(8192, 1e-12); + solution.State(0, 4080).M.ShouldEqual(plain.State(0, 4080).M, 0); + + // the booster burns the rise: 16384 kg down to 8192 kg before its phase, then down to 4096 kg + double vex = 256 * G0; + double riseDV = vex * Math.Log(2); + solution.DV(4064).ShouldEqual(0, 0); + solution.DV(4080).ShouldEqual(vex * Math.Log(16384.0 / 12288), 1e-12); + solution.DV(4096).ShouldEqual(riseDV, 1e-12); + for (double t = 4096; t <= 4384; t += 16) + { + solution.DV(t).ShouldEqual(plain.DV(t) + riseDV, 1e-12); + solution.Vgo(t).ShouldEqual(plain.Vgo(t), 1e-12); + solution.Tgo(t).ShouldEqual(plain.Tgo(t), 0); + } + + solution.Vgo(4064).ShouldEqual(plain.Vgo(4096) + riseDV, 1e-12); + solution.Tgo(4064).ShouldEqual(320, 0); + + // the time and delta-v left in the booster count the rest of the rise, and the other phases' are the same + solution.Tgo(4000, 0).ShouldEqual(96, 0); + solution.Tgo(4080, 0).ShouldEqual(80, 0); + solution.Tgo(4128, 0).ShouldEqual(plain.Tgo(4128, 0), 0); + solution.DV(4000, 0).ShouldEqual(vex * Math.Log(4), 1e-12); + solution.DV(4080, 0).ShouldEqual(vex * Math.Log(12288.0 / 4096), 1e-12); + solution.DV(4128, 0).ShouldEqual(plain.DV(4128, 0), 0); + for (int p = 1; p < solution.Segments; p++) + { + solution.Tgo(4080, p).ShouldEqual(plain.Tgo(4080, p), 0); + solution.DV(4080, p).ShouldEqual(plain.DV(4080, p), 0); + } + + // RiseState is on the rise whatever the time, and the copies carry it + solution.RiseState(4080).M.ShouldEqual(12288, 1e-12); + using Solution copy = solution.DeepCopy(); + copy.M(4080).ShouldEqual(solution.M(4080), 0); + copy.TStart.ShouldEqual(4064, 0); + + Assert.ThrowsAny(() => plain.RiseState(4080)); + } + } +} From de269318bd54d451f3c5b85ed73c8761ae10b20c Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Fri, 20 Nov 2026 09:49:18 -0800 Subject: [PATCH 4/8] Drop the vertical climb from the AscentGuesser A problem on the ground now starts at the top of the vertical rise, which VerticalRise presolves, and the optimizer is held off through the real vertical ascent and pitch program. The guesser's own climb to 50 m/s vertical speed was a second climb on top of the rise that guidance never flies. Mode.VERTICAL, V_KICK and the kick event are gone. A ground start (Problem.PadStart) kicks over at once: the pitchover into a gravity turn in an atmosphere, linear tangent steering from the 45 degrees up seed in vacuum. An in-flight start is unchanged. AscentGuesserTests guess the Titan II, The Standard and the Mainsail TinCan from the top of a 100 m rise and check that the guess is off the vertical just after the top. Known issues, 8 PSG tests fail: Atmospheric pad fixtures that solve from the pad without a VerticalRise now kick over from a standstill, and the guess's gravity turn tips over before it has any speed: AscentGuesserTests.TheStandardAtmosphere falls back (TWR 1.44) TheStandardTests.TheStandardPeriapsis falls back (TWR 1.44) TheStandardTests.TheStandardPeriapsisUpperStageShutdown falls back (TWR 1.44) RealRocketTests.Falcon9ExpendableGeoStationary falls back (TWR 1.40) RealRocketTests.Delta3GeoSynchronous guesser SQP -8 BuggyTests.FourStagesNeedsTwo guesser SQP -8 Either these fixtures need a VerticalRise like the PSG simulation uses, or the guess needs a pitchover that holds up from low speed. The same failure can show up in flight with a short pitch start height or a low thrust-to-weight. Two VerticalRiseTests also fail: TinCanRisesStraightUpFromThePad the 1e-12 R/V/M continuity check is off by about 1e-10, too tight TinCanRiseRoundTrips the warm start takes 6 iterations against a bound of 5, since the cold guess changed --- MechJebLib/PSG/AscentGuesser.cs | 52 ++++------- MechJebLibTest/PSGTests/AscentGuesserTests.cs | 90 ++++++++++++++++--- 2 files changed, 96 insertions(+), 46 deletions(-) diff --git a/MechJebLib/PSG/AscentGuesser.cs b/MechJebLib/PSG/AscentGuesser.cs index b6b34eff3..1f3dceeb1 100644 --- a/MechJebLib/PSG/AscentGuesser.cs +++ b/MechJebLib/PSG/AscentGuesser.cs @@ -19,18 +19,19 @@ namespace MechJebLib.PSG { /// /// The initial guess for the optimizer, by single shooting. The stages are flown in order at full throttle with a - /// single cutoff, which may land in any stage. On the pad the rocket rises vertically, and in an atmosphere it then - /// kicks over into a gravity turn, until it switches to linear tangent steering u = normalize(A - B (t - ts)) once it - /// is out of the atmosphere. A small SQP (with finite difference gradients) over the kick, its azimuth, A, B and the - /// cutoff time burns the least propellant into a circular orbit at the target's GuessRadius() and inclination. + /// single cutoff, which may land in any stage. From the ground, which is the top of the vertical rise (VerticalRise) + /// where guidance pitches over, it kicks over at once into a gravity turn in an atmosphere, until it switches to + /// linear tangent steering u = normalize(A - B (t - ts)) once it is out of the atmosphere, and in vacuum it starts on + /// linear tangent steering. In flight it starts on linear tangent steering from the current attitude. A small SQP + /// (with finite difference gradients) over the kick, its azimuth, A, B and the cutoff time burns the least propellant + /// into a circular orbit at the target's GuessRadius() and inclination. /// Coasts are zero length, and unguided stages, shutdown flags and throttling are ignored: all of that is left to /// the optimizer, this only has to produce a roughly feasible path. /// public class AscentGuesser { - private enum Mode { NONE, VERTICAL, PITCHOVER, GRAVITY_TURN, LINEAR_TANGENT } + private enum Mode { NONE, PITCHOVER, GRAVITY_TURN, LINEAR_TANGENT } - private const double V_KICK = 50; // vertical speed (m/s) which ends the vertical rise private const double T_PITCHOVER = 5; // time (s) to ramp the kick in private const double T_DECAY = 5; // time constant (s) of the decay of the kick into the gravity turn private const double KICK0 = 3; // starting kick (degrees) @@ -62,12 +63,10 @@ private enum Mode { NONE, VERTICAL, PITCHOVER, GRAVITY_TURN, LINEAR_TANGENT } private readonly double _invDensityR0; private readonly double _rFloor; private readonly double _rSwitch; - private readonly double _vKick; private readonly double _tPitchover; private readonly double _tDecay; private readonly Event _impactEvent; - private readonly Event _kickEvent; private readonly Event _switchEvent; private readonly Event _energyEvent; private readonly List _events = new List(); @@ -126,25 +125,16 @@ public AscentGuesser(Problem problem, FlightPlan? flightPlan) Scale scale = problem.Scale; _rFloor = Min(problem.R0.magnitude, problem.RBody) - IMPACT_MARGIN / scale.LengthScale; _rSwitch = problem.RBody + problem.H0 * Log(1.0 / RHO_SWITCH); - _vKick = V_KICK / scale.VelocityScale; _tPitchover = T_PITCHOVER / scale.TimeScale; _tDecay = T_DECAY / scale.TimeScale; _impactEvent = new Event(Impact); - _kickEvent = new Event(Kick); _switchEvent = new Event(Switch); _energyEvent = new Event(OrbitalEnergy); } private double Impact(Vec yin, double t, AbstractIVP i) => InterpolantLayout.CreateFrom(yin).R.magnitude - _rFloor; - private double Kick(Vec yin, double t, AbstractIVP i) - { - var y = InterpolantLayout.CreateFrom(yin); - - return V3.Dot(y.V, y.R.normalized) - _vKick; - } - private double Switch(Vec yin, double t, AbstractIVP i) => InterpolantLayout.CreateFrom(yin).R.magnitude - _rSwitch; // the orbital energy relative to the circular orbit at rT @@ -162,8 +152,6 @@ private V3 Steering(V3 r, V3 v, double t) { switch (_mode) { - case Mode.VERTICAL: - return r; case Mode.PITCHOVER: double theta = _kick * (t - _tk) / _tPitchover; return Cos(theta) * _rk + Sin(theta) * _ek; @@ -179,8 +167,6 @@ private V3 SteeringRate(V3 r, V3 v, V3 a, double t) { switch (_mode) { - case Mode.VERTICAL: - return v; case Mode.PITCHOVER: double theta = _kick * (t - _tk) / _tPitchover; return _kick / _tPitchover * (-Sin(theta) * _rk + Cos(theta) * _ek); @@ -224,7 +210,8 @@ private V3 FortyFiveDegreesUp(V3 r) return Astro.ENUToECI(r, enu).normalized; } - private Mode AfterVertical => _atmosphere ? Mode.PITCHOVER : Mode.LINEAR_TANGENT; + // the first mode from the ground, the top of the vertical rise + private Mode PadMode => _atmosphere ? Mode.PITCHOVER : Mode.LINEAR_TANGENT; // the initial pass picks A itself (with B = 0) private void EnterMode(Mode mode, ref InterpolantLayout y, double t, bool initialPass) @@ -236,14 +223,6 @@ private void EnterMode(Mode mode, ref InterpolantLayout y, double t, bool initia switch (mode) { - case Mode.VERTICAL: - if (V3.Dot(y.V, y.R.normalized) >= _vKick) - { - EnterMode(AfterVertical, ref y, t, initialPass); - return; - } - - break; case Mode.PITCHOVER: _tk = t; _rk = y.R.normalized; @@ -265,7 +244,8 @@ private void EnterMode(Mode mode, ref InterpolantLayout y, double t, bool initia _rs = y.R; if (initialPass) { - _a = (previous == Mode.VERTICAL ? FortyFiveDegreesUp(y.R) : u) + _pitchUp * y.R.normalized; + // from the ground U0 is straight up, so the seed is 45 degrees up + _a = (previous == Mode.NONE && _padStart ? FortyFiveDegreesUp(y.R) : u) + _pitchUp * y.R.normalized; _a = _a.normalized; _b = V3.zero; } @@ -349,7 +329,7 @@ private bool Shoot(Solution? solution, bool initialPass) p0 = 0; _phase = _phases[0]; _mode = Mode.NONE; - EnterMode(_padStart ? Mode.VERTICAL : Mode.LINEAR_TANGENT, ref y, t, initialPass); + EnterMode(_padStart ? PadMode : Mode.LINEAR_TANGENT, ref y, t, initialPass); } for (int p = p0; p < _phases.Count; p++) @@ -382,8 +362,6 @@ private bool Shoot(Solution? solution, bool initialPass) _events.Clear(); _events.Add(_impactEvent); - if (_mode == Mode.VERTICAL) - _events.Add(_kickEvent); if (_mode == Mode.GRAVITY_TURN) _events.Add(_switchEvent); if (initialPass) @@ -429,7 +407,8 @@ private bool Shoot(Solution? solution, bool initialPass) _cachedY = y; } - EnterMode(fired == _kickEvent ? AfterVertical : Mode.LINEAR_TANGENT, ref y, t, initialPass); + // the switch out of the gravity turn + EnterMode(Mode.LINEAR_TANGENT, ref y, t, initialPass); } if (interpolant != null) @@ -616,7 +595,8 @@ public Solution InitialGuess(PhaseCollection phases, CancellationToken cancellat _rT = _problem.Terminal.GuessRadius(); _incT = _problem.Terminal.IncT(); - // from the pad, or from the top of the vertical rise presolved from it, which is still going straight up + // from the ground (the top of the vertical rise presolved from it, or the pad itself without one), which kicks + // over at once _padStart = _problem.PadStart; _kickVariables = _padStart && _atmosphere; _tStackEnd = StackEndTime(); diff --git a/MechJebLibTest/PSGTests/AscentGuesserTests.cs b/MechJebLibTest/PSGTests/AscentGuesserTests.cs index 6ee3432e4..e7101cba1 100644 --- a/MechJebLibTest/PSGTests/AscentGuesserTests.cs +++ b/MechJebLibTest/PSGTests/AscentGuesserTests.cs @@ -23,7 +23,7 @@ public class AscentGuesserTests private const double EARTH_MU = 3.986004418e+14; private const double EARTH_RADIUS = 6.371e+6; - private static void CheckGuess(Problem problem, PhaseCollection phases) + private static void CheckGuess(Problem problem, PhaseCollection phases, Action? check = null) { var stopwatch = Stopwatch.StartNew(); var guesser = new AscentGuesser(problem, null); @@ -51,6 +51,37 @@ private static void CheckGuess(Problem problem, PhaseCollection phases) Astro.FlightPathAngle(rf, vf).ShouldBeZero(1e-6); (rT * vf.sqrMagnitude - 1).ShouldBeZero(1e-6); incf.ShouldEqual(Abs(incT), 1e-5); + + check?.Invoke(solution); + } + + // The problem from the top of a 100 m vertical rise, as AscentBuilder.Build() makes it on the ground. The rise ends + // under the 50 m/s vertical speed where the guess used to stop climbing straight up: the guess now kicks over at + // once at the top, as guidance does. In an atmosphere its pitchover is under way half a second later, and in vacuum + // it starts on linear tangent steering. + private static void CheckRiseGuess(Problem pad, PhaseCollection phases) + { + Problem top = VerticalRise.Presolve(pad, phases, 100 / pad.Scale.LengthScale); + phases.FixLastShutdownStage(); + + Assert.NotNull(top.Rise); + Assert.InRange(V3.Dot(top.V0, top.R0.normalized) * top.Scale.VelocityScale, 0, 50); + + CheckGuess(top, phases, solution => + { + solution.HasRise.ShouldBeTrue(); + + if (AscentProblem.HasAtmosphere(top)) + { + double t = solution.T0 + 0.5 / top.Scale.TimeScale; + Rad2Deg(V3.Angle(solution.U(t), solution.R(t))).ShouldBeGreaterThan(0.01); + } + else + { + (double pitch, _) = Astro.ECIToPitchHeading(solution.R(solution.T0), solution.U(solution.T0)); + Rad2Deg(pitch).ShouldBeLessThan(85); + } + }); } private static PhaseCollection Phases(Problem problem, params Phase[] phases) @@ -63,8 +94,7 @@ private static PhaseCollection Phases(Problem problem, params Phase[] phases) } // the Titan2Tests rocket in vacuum, which has no planetary rotation, so it starts with 408 m/s of horizontal airspeed - [Fact] - public void Titan2Circular() + private static (Problem, PhaseCollection) Titan2CircularProblem() { var r0 = new V3(5593203.65707947, 0, 3050526.81522927); var v0 = new V3(0, 407.862893197274, 0); @@ -74,11 +104,25 @@ public void Titan2Circular() var problem = new Problem(r0, v0, r0.normalized, 157355.487476332, 0, EARTH_MU, EARTH_RADIUS, 0, 0, 0, 0, V3.zero, new Kepler3(rT, 0, incT)); - CheckGuess(problem, Phases(problem, + return (problem, Phases(problem, Phase.NewStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4), Phase.NewStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3))); } + [Fact] + public void Titan2Circular() + { + (Problem problem, PhaseCollection phases) = Titan2CircularProblem(); + CheckGuess(problem, phases); + } + + [Fact] + public void Titan2CircularFromTheTopOfTheRise() + { + (Problem problem, PhaseCollection phases) = Titan2CircularProblem(); + CheckRiseGuess(problem, phases); + } + // the Titan II with its first stage cut to 1000 kN can't lift its own weight: the guess fails, and says so with the figure [Fact] public void TooHeavyToLiftOffGivesTheThrustToWeight() @@ -116,8 +160,7 @@ public void Titan2CircularEquatorial() } // Carnasa's TheStandard in an atmosphere, with a coast and an elliptical target: the guess is circular at periapsis - [Fact] - public void TheStandardAtmosphere() + private static (Problem, PhaseCollection) TheStandardAtmosphereProblem() { var r0 = new V3(-521765.111703417, -5568874.59934707, 3050608.87783524); var v0 = new V3(406.088016257895, -38.0495807832894, 0.000701038889818476); @@ -133,17 +176,30 @@ public void TheStandardAtmosphere() var problem = new Problem(r0, v0, u0, 49119.7842689869, 0, EARTH_MU, EARTH_RADIUS, 7200, 0.5 * 10 * 1.225, 0, 0, 7.29211585e-5 * V3.northpole, new Kepler3(smaT, eccT, incT)); - CheckGuess(problem, Phases(problem, + return (problem, Phases(problem, Phase.NewStage(49119.7842689869, 7114.2513992454, thrust1, 288.000034332275, 3, 3), Phase.NewStage(2848.62586760223, 1363.71123994759, thrust2, 270.15767003304, 1, 1), Phase.NewCoast(678.290157913434, 678.290157913434, 0, 450, 1, 1), Phase.NewStage(678.290157913434, 177.582604389742, thrust3, 230.039271734103, 0, 0, allowShutdown: false))); } + [Fact] + public void TheStandardAtmosphere() + { + (Problem problem, PhaseCollection phases) = TheStandardAtmosphereProblem(); + CheckGuess(problem, phases); + } + + [Fact] + public void TheStandardAtmosphereFromTheTopOfTheRise() + { + (Problem problem, PhaseCollection phases) = TheStandardAtmosphereProblem(); + CheckRiseGuess(problem, phases); + } + // the Mainsail Tin Can from the KerbinTests, without its coast, in Kerbin's atmosphere. It can't make the 100 km orbit of // the KerbinTests without the coast, but it has a few seconds of burn to spare going to 75 km - [Fact] - public void MainSailTinCanAtmosphere() + private static (Problem, PhaseCollection) MainSailTinCanAtmosphereProblem() { const double MU = 3531600000000; var r0 = new V3(365592.912061998, -475862.737003702, -1017.92554628857); @@ -154,8 +210,22 @@ public void MainSailTinCanAtmosphere() var problem = new Problem(r0, v0, u0, 79699.9986022711, 0, MU, 600000, 6797.80562531277, 0.5 * 19.6 * 1.22497705725583, 0, 0, new V3(0, 0, 0.000291570900559802), new Kepler3(675000, 0, 0)); - CheckGuess(problem, Phases(problem, + return (problem, Phases(problem, Phase.NewStage(79699.9986022711, 15700.0014199451, 1500000.09246676, 310.000018173591, 0, 0, ispCurrent: 285.387620615011))); } + + [Fact] + public void MainSailTinCanAtmosphere() + { + (Problem problem, PhaseCollection phases) = MainSailTinCanAtmosphereProblem(); + CheckGuess(problem, phases); + } + + [Fact] + public void MainSailTinCanAtmosphereFromTheTopOfTheRise() + { + (Problem problem, PhaseCollection phases) = MainSailTinCanAtmosphereProblem(); + CheckRiseGuess(problem, phases); + } } } From 65d209ed41d83ff6a40412c237b13c78967b9377 Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Fri, 20 Nov 2026 10:22:31 -0800 Subject: [PATCH 5/8] Give every PSG pad test fixture the vertical rise AscentBuilder.VerticalRise is opt-in, and only the PSG simulation called it, so the pad fixtures solved from the pad itself, a start the game never makes. They passed only while the guesser climbed straight up on its own. Every fixture that starts on the pad now rises 100 m, the default pitch start height, before it solves. The in-flight re-solve in Titan2Tests and InputValidationTests, which never solve, are left without one, and SolutionTests.TinCanBuilder takes a rise that is 0 for its solve in flight. The assertions that meant liftoff now say so: the pinned steering is checked at the top of the rise (T0), where guidance takes over, since the solution points straight up at the pad. Phase time-to-go is measured from TStart, which counts the rise in the first phase, so the Titan II booster still burns 156 s, and the delta-v shortfall compares with Vgo from TStart. The rise costs the vacuum fixtures 30 to 64 m/s of Vgo, within its own gravity loss of about 45 to 67 m/s: they have no planetary rotation in their dynamics, and their optimum pitches over about 40 degrees right off the pad. The fixed burn time fixtures reach orbits 105 to 126 km lower in semi-major axis. The atmospheric fixtures barely move, since their optimum left the pad nearly vertical anyway. AscentGuesserTests guess every pad problem from the top of the rise, and TooHeavyToLiftOffGivesTheThrustToWeight checks it gets no rise. This fixes the 8 failures left by de269318. The TinCan warm start from a cold start stops at a primal feasibility of 5e-8 with the rise, so the warm start from it takes 6 iterations to tighten it and lands on the same trajectory: TinCanRiseRoundTrips and WarmStartFromATurnedLaunchSite allow up to 10. The continuity check between the rise and the first phase is 1e-9. --- MechJebLibTest/PSGTests/AscentGuesserTests.cs | 84 +++------- .../PSGTests/AscentTests/BuggyTests.cs | 29 ++-- .../AscentTests/DeltaVShortfallTests.cs | 6 +- .../PSGTests/AscentTests/KerbinTests.cs | 9 +- .../PSGTests/AscentTests/RealRocketTests.cs | 26 +-- .../AscentTests/SolveProgressTests.cs | 4 + .../PSGTests/AscentTests/TheStandardTests.cs | 56 ++++--- .../PSGTests/AscentTests/Titan2Tests.cs | 148 +++++++++++------- MechJebLibTest/PSGTests/SolutionTests.cs | 43 +++-- MechJebLibTest/PSGTests/VerticalRiseTests.cs | 23 +-- 10 files changed, 236 insertions(+), 192 deletions(-) diff --git a/MechJebLibTest/PSGTests/AscentGuesserTests.cs b/MechJebLibTest/PSGTests/AscentGuesserTests.cs index e7101cba1..7afcf8f5b 100644 --- a/MechJebLibTest/PSGTests/AscentGuesserTests.cs +++ b/MechJebLibTest/PSGTests/AscentGuesserTests.cs @@ -55,10 +55,9 @@ private static void CheckGuess(Problem problem, PhaseCollection phases, Action(() => guesser.InitialGuess(Phases(problem, - Phase.NewStage(157355.487476332, 40267.56108456338, 1000000, 301.817977905273, 4, 4), - Phase.NewStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3)))); + Exception e = Assert.ThrowsAny(() => guesser.InitialGuess(phases)); double twr = 1000000 / (157355.487476332 * EARTH_MU / r0.sqrMagnitude); Assert.Contains($"thrust-to-weight at liftoff is {twr:F2}, under 1", e.Message); @@ -154,13 +146,14 @@ public void Titan2CircularEquatorial() var problem = new Problem(r0, v0, r0.normalized, 157355.487476332, 0, EARTH_MU, EARTH_RADIUS, 0, 0, 0, 0, V3.zero, new Kepler3(rT, 0, 0)); - CheckGuess(problem, Phases(problem, + CheckRiseGuess(problem, Phases(problem, Phase.NewStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4), Phase.NewStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3))); } // Carnasa's TheStandard in an atmosphere, with a coast and an elliptical target: the guess is circular at periapsis - private static (Problem, PhaseCollection) TheStandardAtmosphereProblem() + [Fact] + public void TheStandardAtmosphere() { var r0 = new V3(-521765.111703417, -5568874.59934707, 3050608.87783524); var v0 = new V3(406.088016257895, -38.0495807832894, 0.000701038889818476); @@ -176,30 +169,17 @@ private static (Problem, PhaseCollection) TheStandardAtmosphereProblem() var problem = new Problem(r0, v0, u0, 49119.7842689869, 0, EARTH_MU, EARTH_RADIUS, 7200, 0.5 * 10 * 1.225, 0, 0, 7.29211585e-5 * V3.northpole, new Kepler3(smaT, eccT, incT)); - return (problem, Phases(problem, + CheckRiseGuess(problem, Phases(problem, Phase.NewStage(49119.7842689869, 7114.2513992454, thrust1, 288.000034332275, 3, 3), Phase.NewStage(2848.62586760223, 1363.71123994759, thrust2, 270.15767003304, 1, 1), Phase.NewCoast(678.290157913434, 678.290157913434, 0, 450, 1, 1), Phase.NewStage(678.290157913434, 177.582604389742, thrust3, 230.039271734103, 0, 0, allowShutdown: false))); } - [Fact] - public void TheStandardAtmosphere() - { - (Problem problem, PhaseCollection phases) = TheStandardAtmosphereProblem(); - CheckGuess(problem, phases); - } - - [Fact] - public void TheStandardAtmosphereFromTheTopOfTheRise() - { - (Problem problem, PhaseCollection phases) = TheStandardAtmosphereProblem(); - CheckRiseGuess(problem, phases); - } - // the Mainsail Tin Can from the KerbinTests, without its coast, in Kerbin's atmosphere. It can't make the 100 km orbit of // the KerbinTests without the coast, but it has a few seconds of burn to spare going to 75 km - private static (Problem, PhaseCollection) MainSailTinCanAtmosphereProblem() + [Fact] + public void MainSailTinCanAtmosphere() { const double MU = 3531600000000; var r0 = new V3(365592.912061998, -475862.737003702, -1017.92554628857); @@ -210,22 +190,8 @@ private static (Problem, PhaseCollection) MainSailTinCanAtmosphereProblem() var problem = new Problem(r0, v0, u0, 79699.9986022711, 0, MU, 600000, 6797.80562531277, 0.5 * 19.6 * 1.22497705725583, 0, 0, new V3(0, 0, 0.000291570900559802), new Kepler3(675000, 0, 0)); - return (problem, Phases(problem, + CheckRiseGuess(problem, Phases(problem, Phase.NewStage(79699.9986022711, 15700.0014199451, 1500000.09246676, 310.000018173591, 0, 0, ispCurrent: 285.387620615011))); } - - [Fact] - public void MainSailTinCanAtmosphere() - { - (Problem problem, PhaseCollection phases) = MainSailTinCanAtmosphereProblem(); - CheckGuess(problem, phases); - } - - [Fact] - public void MainSailTinCanAtmosphereFromTheTopOfTheRise() - { - (Problem problem, PhaseCollection phases) = MainSailTinCanAtmosphereProblem(); - CheckRiseGuess(problem, phases); - } } } diff --git a/MechJebLibTest/PSGTests/AscentTests/BuggyTests.cs b/MechJebLibTest/PSGTests/AscentTests/BuggyTests.cs index 9766990f1..489b3917e 100644 --- a/MechJebLibTest/PSGTests/AscentTests/BuggyTests.cs +++ b/MechJebLibTest/PSGTests/AscentTests/BuggyTests.cs @@ -16,6 +16,9 @@ namespace MechJebLibTest.PSGTests.AscentTests [ParallelTestMethods] public class BuggyTests { + // guidance's default pitch start height, which the PSG simulation rises to straight up from the pad before it solves + private const double RISE = 100; + // Very short burn time suborbital rocket that had trouble with a high altitude convergence // Tested against N=20, eps=0 [Fact] @@ -36,6 +39,7 @@ public void ExtremeSuborbitalCoast() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(attR, attR, attR, 0.498274048151861, 0, 0, 0, true, false, false) .AddStage(23796.5132378765, 3243.62653856172, thrust1, 241.889217870454, 4, 4) .AddCoast(438.273627540912, 438.273627540912, 0, 450, 3, 3) @@ -52,11 +56,11 @@ public void ExtremeSuborbitalCoast() psg.PrimalFeasibility.ShouldBeZero(1e-4); - solution.Tgo(solution.T0, 0).ShouldEqual(118.31907500900883, 1e-2); - solution.Tgo(solution.T0, 1).ShouldEqual(208.65944623583906, 1e-1); - solution.Tgo(solution.T0, 2).ShouldEqual(5.8270302676667614, 1e-6); - solution.Tgo(solution.T0, 3).ShouldEqual(5.8270300015709351, 1e-6); - solution.Tgo(solution.T0, 4).ShouldEqual(5.8270300015709351, 1e-6); + solution.Tgo(solution.TStart, 0).ShouldEqual(118.31907500900883, 1e-2); + solution.Tgo(solution.TStart, 1).ShouldEqual(208.65944623583906, 1e-1); + solution.Tgo(solution.TStart, 2).ShouldEqual(5.8270302676667614, 1e-6); + solution.Tgo(solution.TStart, 3).ShouldEqual(5.8270300015709351, 1e-6); + solution.Tgo(solution.TStart, 4).ShouldEqual(5.8270300015709351, 1e-6); // the booster before the coast gets the precise shutdown, not the coast solution.OptimizeKSPStage().ShouldEqual(4); @@ -91,6 +95,7 @@ public void SubOrbitalThor() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(6556000, 6557000, 6556000, 0.499303792410538, 0, 0, 0, true, false, false) .AddStage(52831.1138786043, 6373.37509359599, thrust1, 287.450291861922, 3, 3, allowShutdown: false) .AddStage(2517.01227921406, 738.314292468521, thrust2, 270.157637827755, 1, 1, allowShutdown: false) @@ -124,9 +129,9 @@ public void SubOrbitalThor() solution.V(t0).ShouldEqual(v0, 1e-6); solution.M(t0).ShouldEqual(52831.1138786043, 1e-6); solution.Vgo(t0).ShouldEqual(9419.6763414588168, 1e-9); - solution.U(t0).ShouldEqual(new V3(0.75137961801287534, -0.53341140218376049, 0.38845970917867412).normalized, 1e-2); + solution.U(solution.T0).ShouldEqual(new V3(0.76647312839776127, -0.51690692721441966, 0.38218532769890096).normalized, 1e-2); - smaf.ShouldEqual(8404523.5714891925, 1e-2); + smaf.ShouldEqual(8299417.2515510637, 1e-2); eccf.ShouldEqual(0.21994388566652009, 1e-1); incf.ShouldEqual(incT, 1e-6); lanf.ShouldEqual(3.4079327119886518, 1e-2); @@ -155,6 +160,7 @@ private void BuggyDelta4ExtremelyHeavy() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(6571000, 6571000, 6571000, 0.558505360638185, 0, 0, 0.349065850398866, true, false, false) .AddStage(731995.326793174 - decmass, 328918.196876464 - decmass, thrust1, 408.091742854086, 4, 4) .AddStage(268744.821741949 - decmass, 168530.570801559 - decmass, thrust2, 408.091702159863, 2, 2) @@ -197,6 +203,7 @@ private void BiggerEarlyRocketMaybe() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(6621000, 6623000, 6621000, 0.558505360638185, 0, 0, 0.349065850398866, false, false, false) .AddStage(51814.6957082437, 12381.5182945184, thrust1, 277.252333393375, 2, 2) .AddStage(9232.92402212159, 887.216491554419, thrust2, 252.019434034823, 1, 1) @@ -232,6 +239,7 @@ private void FourStagesNeedsTwo() Ascent ascent = Ascent.Builder() .Initial(new V3(-2750001.81262551, -4870536.29021665, 3050610.57762817), new V3(355.169076284135, -200.527924207868, -0.00280072807318912), new V3(-0.431553114381181, -0.764704888551875, 0.478527367115021), 0, 398600435436096, 6371000) + .VerticalRise(RISE) .SetTarget(6551000, 6551000, 6551000, 0.499303792410538, 0, 0, 0, false, false, false) //.SetTarget(8051000, 8051000, 8051000, 0.499303792410538, 0, 0, false, false) .AddStage(176568.069166482, 33739.9978121645, thrust1, 294.100105371403, 7, 7) @@ -247,7 +255,7 @@ private void FourStagesNeedsTwo() using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); solution.Tgo(0, 0).ShouldEqual(150.314019929573, 1e-4); - solution.Tgo(0, 1).ShouldEqual(399.27103168733788, 1e-3); + solution.Tgo(0, 1).ShouldEqual(403.42808806551551, 1e-3); solution.Tgo(0, 2).ShouldBeZero(1e-2); solution.Tgo(0, 3).ShouldBeZero(1e-2); @@ -280,6 +288,7 @@ private void MakingUpperStageUnguided() Ascent ascent = Ascent.Builder() .Initial(new V3(-3255967.18116409, -4547891.60302231, 3050610.57695918), new V3(331.637492561945, -237.428880310986, 7.25192369772431E-06), new V3(-0.511086312614353, -0.713789180806743, 0.478848457336426), 0, 398600435436096, 6371000) + .VerticalRise(RISE) .SetTarget(PER, 6371000, PER, 0.499303792410538, 0, 0, 0, false, false, false) .AddStage(176568.069166482, 33739.9978121645, thrust1, 294.100108674295, 7, 7) .AddStage(22640.1444759873, 7657.9646078915, thrust2, 427.000108671115, 4, 4) @@ -307,6 +316,7 @@ private void MakingUpperStageUnguided() Ascent ascent2 = Ascent.Builder() .Initial(new V3(-3255967.18116409, -4547891.60302231, 3050610.57695918), new V3(331.637492561945, -237.428880310986, 7.25192369772431E-06), new V3(-0.511086312614353, -0.713789180806743, 0.478848457336426), 0, 398600435436096, 6371000) + .VerticalRise(RISE) .SetTarget(PER, 6371000, PER, 0.499303792410538, 0, 0, 0, false, false, false) .AddStage(176568.069166482, 33739.9978121645, thrust1, 294.100108674295, 7, 7) .AddStage(22640.1444759873, 7657.9646078915, thrust2, 427.000108671115, 4, 4) @@ -338,6 +348,7 @@ public void Falcon9WithSRBSTest() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, 6371000) + .VerticalRise(RISE) .SetTarget(6551000, 6551000, 6551000, incT, 0, 0, 0, false, false, false) .AerodynamicConstants(0.5, 30, 1.2494765593625, 2000, 0, 7566.61914736748, new V3(0, 0, 7.2921151467069236E-05)) @@ -375,7 +386,7 @@ public void Falcon9WithSRBSTest() solution.V(t0).ShouldEqual(v0, 1e-6); solution.M(t0).ShouldEqual(m0, 1e-6); solution.Vgo(t0).ShouldEqual(8620.1405495395156, 1e-3); - solution.U(t0).ShouldEqual(new V3(-0.57978971705636706, -0.66407516766532904, 0.47206785349321667).normalized, 1e-2); + solution.U(solution.T0).ShouldEqual(new V3(-0.51529358006704529, -0.72130368102293241, 0.46350703132698), 1e-2); smaf.ShouldEqual(6551000.0104806134, 1e-2); eccf.ShouldEqual(0, 1e-1); diff --git a/MechJebLibTest/PSGTests/AscentTests/DeltaVShortfallTests.cs b/MechJebLibTest/PSGTests/AscentTests/DeltaVShortfallTests.cs index bf541a158..8d1b84868 100644 --- a/MechJebLibTest/PSGTests/AscentTests/DeltaVShortfallTests.cs +++ b/MechJebLibTest/PSGTests/AscentTests/DeltaVShortfallTests.cs @@ -15,6 +15,9 @@ namespace MechJebLibTest.PSGTests.AscentTests [ParallelTestMethods] public class DeltaVShortfallTests { + // guidance's default pitch start height, which the PSG simulation rises to straight up from the pad before it solves + private const double RISE = 100; + private const double MU = 3531600000000; private const double M0 = 79699.9986022711; private const double ISP = 310.000018173591; @@ -28,6 +31,7 @@ private static Solution Solve(double mf) .AddStage(M0, mf, 1500000.09246676, ISP, 0, 0, allowShutdown: true, ispCurrent: 285.387620615011, minThrottle: 0.0, massContinuity: true) .Initial(new V3(365592.912061998, -475862.737003702, -1017.92554628857), new V3(138.749920001822, 106.593409136045, 5.05460467277035E-06), new V3(0.608250428397881, -0.793743408918215, -0.00172494351863861), 0, MU, 600000) + .VerticalRise(RISE) .SetTarget(700000, 700000, 700000, 0, 0, 0, 0, false, false, false) .Build(); @@ -58,7 +62,7 @@ private void TooLittlePropellantGivesTheShortfall() double shortfall = solution.DeltaVShortfall(); shortfall.ShouldBePositive(); - shortfall.ShouldEqual(solution.Vgo(solution.T0) - stageDeltaV, 1e-6); + shortfall.ShouldEqual(solution.Vgo(solution.TStart) - stageDeltaV, 1e-6); (shortfall > 300 && shortfall < 1000).ShouldBeTrue(); } } diff --git a/MechJebLibTest/PSGTests/AscentTests/KerbinTests.cs b/MechJebLibTest/PSGTests/AscentTests/KerbinTests.cs index dd0d20c04..0230235d5 100644 --- a/MechJebLibTest/PSGTests/AscentTests/KerbinTests.cs +++ b/MechJebLibTest/PSGTests/AscentTests/KerbinTests.cs @@ -15,6 +15,9 @@ namespace MechJebLibTest.PSGTests.AscentTests [ParallelTestMethods] public class KerbinTests { + // guidance's default pitch start height, which the PSG simulation rises to straight up from the pad before it solves + private const double RISE = 100; + private const double MU = 3531600000000; // the MainSailTinCan stages are the stage stats of the stock MechJebLibTest/Craft/Stock/Mainsail Tin Can.craft @@ -29,6 +32,7 @@ private void MainSailTinCanVacuum() .AddCoast(79699.9986022711, 79699.9986022711, 0, 450, 0, 0, massContinuity: true) .AddStage(79699.9986022711, 15700.0014199451, 1500000.09246676, 310.000018173591, 0, 0, allowShutdown: true, ispCurrent: 285.387620615011, minThrottle: 0.0, massContinuity: true) .Initial(new V3(365592.912061998, -475862.737003702, -1017.92554628857), new V3(138.749920001822, 106.593409136045, 5.05460467277035E-06), new V3(0.608250428397881, -0.793743408918215, -0.00172494351863861), t0, MU, 600000) + .VerticalRise(RISE) .SetTarget(700000, 700000, 700000, 0, 0, 0, 0, false, false, false) .Build(); @@ -39,8 +43,8 @@ private void MainSailTinCanVacuum() (psg.Objective == Optimizer.ObjectiveType.MIN_THRUST_ACCEL).ShouldBeTrue(); psg.PrimalFeasibility.ShouldBeZero(1e-5); - solution.Vgo(t0).ShouldEqual(2595.8963285782665, 1e-3); - solution.Tgo(t0).ShouldEqual(610.08086261522431, 1e-3); + solution.Vgo(t0).ShouldEqual(2652.834525208435, 1e-3); + solution.Tgo(t0).ShouldEqual(609.0392887818382, 1e-3); solution.OptimizeKSPStage().ShouldEqual(0); solution.TerminalKSPStage().ShouldEqual(0); @@ -72,6 +76,7 @@ private void MainSailTinCanAtmo() .AddCoast(79699.9986022711, 79699.9986022711, 0, 450, 0, 0, massContinuity: true) .AddStage(79699.9986022711, 15700.0014199451, 1500000.09246676, 310.000018173591, 0, 0, allowShutdown: true, ispCurrent: 285.387620615011, minThrottle: 0.0, massContinuity: true) .Initial(new V3(365592.912061998, -475862.737003702, -1017.92554628857), new V3(138.749920001822, 106.593409136045, 5.05460467277035E-06), new V3(0.608250428397881, -0.793743408918215, -0.00172494351863861), t0, MU, 600000) + .VerticalRise(RISE) .SetTarget(700000, 700000, 700000, 0, 0, 0, 0, false, false, false) // the final MIN_THRUST_ACCEL stage runs close to the default timeout, which would fall back to the MIN_TIME solution .OptimizerTimeout(Timeout.Infinite) diff --git a/MechJebLibTest/PSGTests/AscentTests/RealRocketTests.cs b/MechJebLibTest/PSGTests/AscentTests/RealRocketTests.cs index ea012618d..f6a87ce7d 100644 --- a/MechJebLibTest/PSGTests/AscentTests/RealRocketTests.cs +++ b/MechJebLibTest/PSGTests/AscentTests/RealRocketTests.cs @@ -17,6 +17,9 @@ namespace MechJebLibTest.PSGTests.AscentTests [ParallelTestMethods] public class RealRocketTests { + // guidance's default pitch start height, which the PSG simulation rises to straight up from the pad before it solves + private const double RISE = 100; + // This is the classic test from Betts. [Fact] public void Delta3GeoSynchronous() @@ -54,6 +57,7 @@ public void Delta3GeoSynchronous() .AddStage(72783.770115, 32294.000000, 1083100.000000, isp3, 2, 2) .AddStage(23464.000000, 6644.000000, 110094.000000, isp4, 1, 1) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, lanT, argpT, 0, false, true, true) .Build(); @@ -71,10 +75,10 @@ public void Delta3GeoSynchronous() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(301454.000000, 1e-6); - solution.Tgo(solution.T0, 0).ShouldEqual(75.200000, 1e-3); - solution.Tgo(solution.T0, 1).ShouldEqual(75.200000, 1e-3); - solution.Tgo(solution.T0, 2).ShouldEqual(110.600000, 1e-3); - solution.Tgo(solution.T0, 3).ShouldEqual(663.139, 1e-3); + solution.Tgo(solution.TStart, 0).ShouldEqual(75.200000, 1e-3); + solution.Tgo(solution.TStart, 1).ShouldEqual(75.200000, 1e-3); + solution.Tgo(solution.TStart, 2).ShouldEqual(110.600000, 1e-3); + solution.Tgo(solution.TStart, 3).ShouldEqual(664.01199254810535, 1e-3); solution.Tgo(0).ShouldEqual(924.139, 1e-3); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -89,7 +93,7 @@ public void Delta3GeoSynchronous() solution.IndexForKSPStage(1, false).ShouldEqual(3); solution.IndexForKSPStage(1, true).ShouldEqual(-1); - //solution.U(0).normalized.ShouldEqual(new V3(0.69734975209707417, 0.6074944955387559, 0.38033374967291772), 1e-2); + //solution.U(solution.T0).normalized.ShouldEqual(new V3(0.69734975209707417, 0.6074944955387559, 0.38033374967291772), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -151,6 +155,7 @@ public void Falcon9ExpendableGeoStationary() .AddCoast(SECOND_STAGE_M0, SECOND_STAGE_MF, 0, 1300, 1, 1, massContinuity: true) .AddStage(SECOND_STAGE_M0, SECOND_STAGE_MF, SECOND_THRUST, SECOND_ISP, 1, 1, minThrottle: 0.385389461457581, massContinuity: true) .Initial(r0, v0, r0.normalized, T0, MU, R_BODY) + .VerticalRise(RISE) .SetTarget(PER_T, APR_T, PER_T, INC_T, LAN_T, ARGP_T, 0, false, true, true) .Build(); @@ -165,14 +170,14 @@ public void Falcon9ExpendableGeoStationary() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(FIRST_STAGE_M0, 1e-6); - solution.Tgo(solution.T0, 0).ShouldEqual(FIRST_BT, 1e-3); - solution.Tgo(solution.T0, 1).ShouldBeLessThanOrEqual(SECOND_BT); + solution.Tgo(solution.TStart, 0).ShouldEqual(FIRST_BT, 1e-3); + solution.Tgo(solution.TStart, 1).ShouldBeLessThanOrEqual(SECOND_BT); // NOTE: this GTO case sits at the edge of what the SQP solver can handle (ultimately wants a // convex SCvx formulation), so the optimizer converges to slightly different feasible solutions // across runtimes/platforms. The soft outputs below carry loose tolerances; the terminal orbit // (per/apr/inc/lan/argp) is still pinned tightly. See TODO: convert to SCvx. - solution.Tgo(solution.T0, 2).ShouldEqual(1055.0665736765161, 5e-2); - (solution.Tgo(solution.T0, 1) + solution.Tgo(solution.T0, 3)).ShouldEqual(381.26954084989723, 5e-2); + solution.Tgo(solution.TStart, 2).ShouldEqual(1055.0665736765161, 5e-2); + (solution.Tgo(solution.TStart, 1) + solution.Tgo(solution.TStart, 3)).ShouldEqual(381.26954084989723, 5e-2); psg.PrimalFeasibility.ShouldBeZero(1e-5); solution.Tgo(0).ShouldEqual(1600.5671186447382, 5e-2); @@ -186,7 +191,7 @@ public void Falcon9ExpendableGeoStationary() solution.IndexForKSPStage(1, false).ShouldEqual(1); solution.IndexForKSPStage(1, true).ShouldEqual(2); - (double pitch, double heading) = Astro.ECIToPitchHeading(r0, solution.U(0)); + (double pitch, double heading) = Astro.ECIToPitchHeading(solution.R(solution.T0), solution.U(solution.T0)); Rad2Deg(pitch).ShouldEqual(83.373269308213963, 5e-2); Rad2Deg(heading).ShouldEqual(89.53966801098629, 1e-1); @@ -238,6 +243,7 @@ public void Falcon9ToGeoSynchronous() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, T0, MU, R_BODY) + .VerticalRise(RISE) .SetTarget(PER_T, APR_T, PER_T, INC_T, 3.7873644768277, 3.14159265358979, 0, false, false, false) .AerodynamicConstants(0.5, 10.7, 1.2494765593625, 2000, 0, 7566.61914736748, new V3(0, 0, 7.2921151467069236E-05)) .AddStage(FIRST_STAGE_M0, FIRST_STAGE_MF, FIRST_THRUST, FIRST_ISP, 3, 3, allowShutdown: false, diff --git a/MechJebLibTest/PSGTests/AscentTests/SolveProgressTests.cs b/MechJebLibTest/PSGTests/AscentTests/SolveProgressTests.cs index 7f2a7362d..cea173709 100644 --- a/MechJebLibTest/PSGTests/AscentTests/SolveProgressTests.cs +++ b/MechJebLibTest/PSGTests/AscentTests/SolveProgressTests.cs @@ -14,6 +14,9 @@ namespace MechJebLibTest.PSGTests.AscentTests [ParallelTestMethods] public class SolveProgressTests { + // guidance's default pitch start height, which the PSG simulation rises to straight up from the pad before it solves + private const double RISE = 100; + private const double MU = 3531600000000; private const double M0 = 79699.9986022711; @@ -26,6 +29,7 @@ private static Ascent TinCan() => massContinuity: true) .Initial(new V3(365592.912061998, -475862.737003702, -1017.92554628857), new V3(138.749920001822, 106.593409136045, 5.05460467277035E-06), new V3(0.608250428397881, -0.793743408918215, -0.00172494351863861), 0, MU, 600000) + .VerticalRise(RISE) .SetTarget(700000, 700000, 700000, 0, 0, 0, 0, false, false, false) .Build(); diff --git a/MechJebLibTest/PSGTests/AscentTests/TheStandardTests.cs b/MechJebLibTest/PSGTests/AscentTests/TheStandardTests.cs index d1fba95fd..559accc45 100644 --- a/MechJebLibTest/PSGTests/AscentTests/TheStandardTests.cs +++ b/MechJebLibTest/PSGTests/AscentTests/TheStandardTests.cs @@ -15,6 +15,9 @@ namespace MechJebLibTest.PSGTests.AscentTests [ParallelTestMethods] public class TheStandardTests { + // guidance's default pitch start height, which the PSG simulation rises to straight up from the pad before it solves + private const double RISE = 100; + // Carnasa's TheStandard rocket (ish). // This tests optimality of a burn-optimizedBurn-coast-burn with all stages guided with periapsis attachment [Fact] @@ -37,6 +40,7 @@ public void TheStandardGuidedUpperPeriapsis() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, 0, 0, 0, true, false, false) .AddStage(49119.7842689869, 7114.2513992454, thrust1, 288.000034332275, 3, 3) .AddStage(2848.62586760223, 1363.71123994759, thrust2, 270.15767003304, 1, 1) @@ -50,12 +54,12 @@ public void TheStandardGuidedUpperPeriapsis() using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); psg.PrimalFeasibility.ShouldBeZero(1e-5); - solution.Vgo(t0).ShouldEqual(9669.6899155829542, 1e-3); + solution.Vgo(t0).ShouldEqual(9727.1878195249446, 1e-3); - solution.Tgo(solution.T0, 0).ShouldBePositive(); - solution.Tgo(solution.T0, 1).ShouldBePositive(); - solution.Tgo(solution.T0, 2).ShouldEqual(234.78752267826667, 1e-3); - solution.Tgo(solution.T0, 3).ShouldBePositive(); + solution.Tgo(solution.TStart, 0).ShouldBePositive(); + solution.Tgo(solution.TStart, 1).ShouldBePositive(); + solution.Tgo(solution.TStart, 2).ShouldEqual(228.22479646960139, 1e-3); + solution.Tgo(solution.TStart, 3).ShouldBePositive(); solution.OptimizeKSPStage().ShouldEqual(1); solution.TerminalKSPStage().ShouldEqual(0); @@ -82,8 +86,9 @@ public void TheStandardGuidedUpperPeriapsis() dv += solution.DV(t0, p); dv.ShouldEqual(solution.Vgo(t0), 1e-9); - (V3 u, _) = solution.InertialGuidance(0, t0, 0); - u.ShouldEqual(solution.U(t0).normalized, 1e-12); + // guidance takes over at the top of the rise, on the first phase's steering + (V3 u, _) = solution.InertialGuidance(0, solution.T0, 0); + u.ShouldEqual(solution.U(solution.T0).normalized, 1e-12); (V3 rf, V3 vf) = solution.TerminalStateVectors(); @@ -93,7 +98,7 @@ public void TheStandardGuidedUpperPeriapsis() solution.R(t0).ShouldEqual(r0, 1e-6); solution.V(t0).ShouldEqual(v0, 1e-6); solution.M(t0).ShouldEqual(49119.7842689869, 1e-6); - solution.U(t0).normalized.ShouldEqual(new V3(0.77936242810570966, -0.56640344307712909, 0.26792040856856347), 1e-1); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.77936242810570966, -0.56640344307712909, 0.26792040856856347), 1e-1); smaf.ShouldEqual(11463499.98898875, 1e-4); eccf.ShouldEqual(0.4280978753095433, 1e-4); @@ -119,7 +124,7 @@ public void TheStandardGuidedUpperFree() double ApR = 6.371e+6 + 10e+6; double incT = Deg2Rad(28.608); - const double OPTIMUMVGO = 9670.9023790445626; + const double OPTIMUMVGO = 9726.0697386041211; double thrust1 = Astro.ThrustFromMassesIspBurntime(49119.7842689869, 7114.2513992454, 288.000034332275, 170.308460385726); double thrust2 = Astro.ThrustFromMassesIspBurntime(2848.62586760223, 1363.71123994759, 270.15767003304, 116.391834883409); @@ -127,6 +132,7 @@ public void TheStandardGuidedUpperFree() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, 0, 0, 0, false, false, false) .AddStage(49119.7842689869, 7114.2513992454, thrust1, 288.000034332275, 3, 3) .AddStage(2848.62586760223, 1363.71123994759, thrust2, 270.15767003304, 1, 1) @@ -139,10 +145,10 @@ public void TheStandardGuidedUpperFree() Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); - solution.Tgo(solution.T0, 0).ShouldBePositive(); - solution.Tgo(solution.T0, 1).ShouldBePositive(); - solution.Tgo(solution.T0, 2).ShouldEqual(221.93374918746366, 1e-2); - solution.Tgo(solution.T0, 3).ShouldBePositive(); + solution.Tgo(solution.TStart, 0).ShouldBePositive(); + solution.Tgo(solution.TStart, 1).ShouldBePositive(); + solution.Tgo(solution.TStart, 2).ShouldEqual(215.2590138476908, 1e-2); + solution.Tgo(solution.TStart, 3).ShouldBePositive(); solution.OptimizeKSPStage().ShouldEqual(1); solution.TerminalKSPStage().ShouldEqual(0); @@ -165,7 +171,7 @@ public void TheStandardGuidedUpperFree() solution.V(t0).ShouldEqual(v0, 1e-6); solution.M(t0).ShouldEqual(49119.7842689869, 1e-6); solution.Vgo(t0).ShouldEqual(OPTIMUMVGO, 1e-2); - solution.U(t0).normalized.ShouldEqual(new V3(0.77953530499830737, -0.56621745928946121, 0.26781056188467101), 1e-1); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.77953530499830737, -0.56621745928946121, 0.26781056188467101), 1e-1); smaf.ShouldEqual(11463499.98898875, 1e-4); eccf.ShouldEqual(0.4280978753095433, 1e-4); @@ -206,6 +212,7 @@ public void TheStandardPeriapsis() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .AerodynamicConstants(aref, CD, RHO0, Q_ALPHA_MAX, Q_MAX, H0, w) .SetTarget(PeR, ApR, PeR, incT, 0, 0, 0, true, false, false) .AddStage(49119.7842689869, 7114.2513992454, thrust1, 288.000034332275, 3, 3) @@ -219,10 +226,10 @@ public void TheStandardPeriapsis() Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); - solution.Tgo(solution.T0, 0).ShouldBePositive(); - solution.Tgo(solution.T0, 1).ShouldBePositive(); - solution.Tgo(solution.T0, 2).ShouldEqual(135.22924418942029, 1e-2); - solution.Tgo(solution.T0, 3).ShouldBePositive(); + solution.Tgo(solution.TStart, 0).ShouldBePositive(); + solution.Tgo(solution.TStart, 1).ShouldBePositive(); + solution.Tgo(solution.TStart, 2).ShouldEqual(135.22924418942029, 1e-2); + solution.Tgo(solution.TStart, 3).ShouldBePositive(); solution.OptimizeKSPStage().ShouldEqual(1); solution.TerminalKSPStage().ShouldEqual(0); @@ -245,7 +252,7 @@ public void TheStandardPeriapsis() solution.V(t0).ShouldEqual(v0, 1e-6); solution.M(t0).ShouldEqual(49119.7842689869, 1e-6); solution.Vgo(t0).ShouldEqual(10510.620490322281, 1e-3); - solution.U(t0).normalized.ShouldEqual(new V3(-0.012214116666567524, -0.87839128647452269, 0.47778610611830125), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.0030145601949507781, -0.87873665051131311, 0.47729740359129269), 1e-2); smaf.ShouldEqual(11463499.98898875, 1e-4); eccf.ShouldEqual(0.4280978753095433, 1e-4); @@ -284,6 +291,7 @@ public void TheStandardPeriapsisUpperStageShutdown() Ascent ascent = Ascent.Builder() .Initial(r0, v0, u0, t0, mu, rbody) + .VerticalRise(RISE) .AerodynamicConstants(aref, CD, RHO0, Q_ALPHA_MAX, Q_MAX, H0, w) .SetTarget(PeR, ApR, PeR, incT, 0, 0, 0, true, false, false) .AddStage(49119.7842689869, 7114.2513992454, thrust1, 288.000034332275, 3, 3) @@ -298,10 +306,10 @@ public void TheStandardPeriapsisUpperStageShutdown() using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); - solution.Tgo(solution.T0, 0).ShouldBePositive(); - solution.Tgo(solution.T0, 1).ShouldBePositive(); - solution.Tgo(solution.T0, 2).ShouldEqual(130.80357401545331, 1e-2); - solution.Tgo(solution.T0, 3).ShouldBePositive(); + solution.Tgo(solution.TStart, 0).ShouldBePositive(); + solution.Tgo(solution.TStart, 1).ShouldBePositive(); + solution.Tgo(solution.TStart, 2).ShouldEqual(130.80357401545331, 1e-2); + solution.Tgo(solution.TStart, 3).ShouldBePositive(); solution.OptimizeKSPStage().ShouldEqual(0); solution.TerminalKSPStage().ShouldEqual(0); @@ -324,7 +332,7 @@ public void TheStandardPeriapsisUpperStageShutdown() solution.V(t0).ShouldEqual(v0, 1e-6); solution.M(t0).ShouldEqual(49119.7842689869, 1e-6); solution.Vgo(t0).ShouldEqual(10510.620490322281, 1e-3); - solution.U(t0).normalized.ShouldEqual(new V3(-0.012214116666567524, -0.87839128647452269, 0.47778610611830125), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.0030549988939650935, -0.8787435243059073, 0.477284491128919), 1e-2); smaf.ShouldEqual(11463499.98898875, 1e-4); eccf.ShouldEqual(0.4280978753095433, 1e-4); diff --git a/MechJebLibTest/PSGTests/AscentTests/Titan2Tests.cs b/MechJebLibTest/PSGTests/AscentTests/Titan2Tests.cs index 972e18bbb..8bb3c4ad4 100644 --- a/MechJebLibTest/PSGTests/AscentTests/Titan2Tests.cs +++ b/MechJebLibTest/PSGTests/AscentTests/Titan2Tests.cs @@ -15,6 +15,9 @@ namespace MechJebLibTest.PSGTests.AscentTests [ParallelTestMethods] public class Titan2Tests { + // guidance's default pitch start height, which the PSG simulation rises to straight up from the pad before it solves + private const double RISE = 100; + // this is a forced periapsis attachment problem, which chooses an ApR such that it winds up burning the whole rocket. [Fact] public void FlightPathAngle4Elliptical() @@ -32,6 +35,7 @@ public void FlightPathAngle4Elliptical() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, true, false, false) .Build(); @@ -49,8 +53,8 @@ public void FlightPathAngle4Elliptical() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(153180, 1e-6); - solution.U(0).normalized.ShouldEqual(new V3(0.68052484128120905, 0.6317658413531414, 0.37115746267392064), 1e-2); - solution.Vgo(0).ShouldEqual(9369.7098971395462, 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66800916662161625, 0.64863008334323413, 0.36475028209947058), 1e-2); + solution.Vgo(0).ShouldEqual(9404.3677823357357, 1e-3); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -88,6 +92,7 @@ public void FlightPathAngle3EnergyElliptical() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4, allowShutdown: false) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3, allowShutdown: false) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, true, false, false) .Build(); @@ -104,8 +109,8 @@ public void FlightPathAngle3EnergyElliptical() solution.R(0).ShouldEqual(r0, 1e-6); solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(153180, 1e-6); - solution.Tgo(solution.T0, 0).ShouldEqual(156, 1e-6); - solution.Tgo(solution.T0, 1).ShouldEqual(180, 1e-6); + solution.Tgo(solution.TStart, 0).ShouldEqual(156, 1e-6); + solution.Tgo(solution.TStart, 1).ShouldEqual(180, 1e-6); // all fixed burn time stages with no coast, so no stage needs a precise shutdown solution.OptimizeKSPStage().ShouldEqual(-1); @@ -116,12 +121,12 @@ public void FlightPathAngle3EnergyElliptical() solution.IndexForKSPStage(3, false).ShouldEqual(1); solution.IndexForKSPStage(3, true).ShouldEqual(-1); - solution.U(0).normalized.ShouldEqual(new V3(0.68052484128120905, 0.6317658413531414, 0.37115746267392064), 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66883450021136781, 0.64767206625159712, 0.36494014019342491), 1e-3); solution.Vgo(0).ShouldEqual(9369.7098971395462, 1e-3); psg.PrimalFeasibility.ShouldBeZero(1e-5); - smaf.ShouldEqual(8614160.805091612, 1e-5); - eccf.ShouldEqual(0.23892760440170616, 1e-5); + smaf.ShouldEqual(8501798.7938651778, 1e-5); + eccf.ShouldEqual(0.22886907123134159, 1e-5); incf.ShouldEqual(incT, 1e-5); lanf.ShouldEqual(Deg2Rad(270), 1e-2); argpf.ShouldEqual(1.7643342507444935, 1e-2); @@ -147,6 +152,7 @@ public void FlightPathAngle3EnergyEllipticalCoast() .AddCoast(31980, 31980, 0, 450, 3, 3) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3, allowShutdown: false) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, true, false, false) .Build(); @@ -165,9 +171,9 @@ public void FlightPathAngle3EnergyEllipticalCoast() solution.IndexForKSPStage(3, false).ShouldEqual(2); solution.IndexForKSPStage(3, true).ShouldEqual(1); - solution.Tgo(solution.T0, 0).ShouldEqual(156, 1e-6); - solution.Tgo(solution.T0, 1).ShouldEqual(43.991685211719087, 1e-2); - solution.Tgo(solution.T0, 2).ShouldEqual(180, 1e-6); + solution.Tgo(solution.TStart, 0).ShouldEqual(156, 1e-6); + solution.Tgo(solution.TStart, 1).ShouldEqual(41.763222532138712, 1e-2); + solution.Tgo(solution.TStart, 2).ShouldEqual(180, 1e-6); solution.Vgo(0).ShouldEqual(9369.7101019898018, 1e-3); (V3 rf, V3 vf) = solution.TerminalStateVectors(); @@ -175,8 +181,8 @@ public void FlightPathAngle3EnergyEllipticalCoast() (double smaf, double eccf, double incf, double lanf, double argpf, double tanof, _) = Astro.KeplerianFromStateVectors(mu, rf, vf); - smaf.ShouldEqual(8716713.6265901383, 1e-5); - eccf.ShouldEqual(0.24788168100301983, 1e-5); + smaf.ShouldEqual(8590793.288745543, 1e-5); + eccf.ShouldEqual(0.23685743799833212, 1e-5); incf.ShouldEqual(incT, 1e-5); lanf.ShouldEqual(Deg2Rad(270), 1e-2); argpf.ShouldEqual(1.7884827346201035, 1e-2); @@ -199,6 +205,7 @@ public void FlightPathAngle5Elliptical() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, true, true, false) .Build(); @@ -216,8 +223,8 @@ public void FlightPathAngle5Elliptical() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(153180, 1e-6); - solution.U(0).normalized.ShouldEqual(new V3(0.68052484128120905, 0.6317658413531414, 0.37115746267392064), 1e-2); - solution.Vgo(0).ShouldEqual(9369.7098971395462, 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66818571265471838, 0.64862916685663541, 0.36442839805231036), 1e-2); + solution.Vgo(0).ShouldEqual(9404.3677303224067, 1e-3); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -253,6 +260,7 @@ public void FlightPathAngle4EnergyElliptical() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4, allowShutdown: false) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3, allowShutdown: false) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, true, true, false) .Build(); @@ -269,10 +277,10 @@ public void FlightPathAngle4EnergyElliptical() solution.R(0).ShouldEqual(r0, 1e-6); solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(153180, 1e-6); - solution.Tgo(solution.T0, 0).ShouldEqual(156, 1e-6); - solution.Tgo(solution.T0, 1).ShouldEqual(180, 1e-6); + solution.Tgo(solution.TStart, 0).ShouldEqual(156, 1e-6); + solution.Tgo(solution.TStart, 1).ShouldEqual(180, 1e-6); - solution.U(0).normalized.ShouldEqual(new V3(0.68052484128120905, 0.6317658413531414, 0.37115746267392064), 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66889606779756527, 0.6476787226136359, 0.3648154639794256), 1e-3); solution.Vgo(0).ShouldEqual(9369.7098971395462, 1e-3); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -286,8 +294,8 @@ public void FlightPathAngle4EnergyElliptical() solution.IndexForKSPStage(3, false).ShouldEqual(1); solution.IndexForKSPStage(3, true).ShouldEqual(-1); - smaf.ShouldEqual(8614160.805091612, 1e-6); - eccf.ShouldEqual(0.23892760440170616, 1e-6); + smaf.ShouldEqual(8501798.8036084659, 1e-6); + eccf.ShouldEqual(0.22886907212890106, 1e-6); incf.ShouldEqual(incT, 1e-6); lanf.ShouldEqual(Deg2Rad(270), 1e-2); argpf.ShouldEqual(1.7643342507444935, 1e-2); @@ -312,6 +320,7 @@ public void FlightPathAngle4EllipticalAbovePeriapsis() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, AttR, incT, Deg2Rad(270), 0, 0, true, false, false) .Build(); @@ -361,6 +370,7 @@ public void FlightPathAngle5EllipticalAbovePeriapsis() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, AttR, incT, Deg2Rad(270), 0, 0, true, true, false) .Build(); @@ -412,6 +422,7 @@ public void FlightPathAngle3EnergyNonZeroFPA() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4, allowShutdown: false) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3, allowShutdown: false) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, PeR, AttR, incT, Deg2Rad(270), 0, fpaT, true, false, false) .Build(); @@ -457,6 +468,7 @@ public void FlightPathAngle4EnergyNonZeroFPA() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4, allowShutdown: false) .AddStage(31980, 6125.823788668185, 443700, 315, 3, 3, allowShutdown: false) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, PeR, AttR, incT, Deg2Rad(270), 0, fpaT, true, true, false) .Build(); @@ -502,6 +514,7 @@ public void Kepler3Elliptical() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -519,8 +532,8 @@ public void Kepler3Elliptical() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(157355.487476332, 1e-6); - solution.Vgo(0).ShouldEqual(9334.0379052112639, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.67311315112262493, 0.64198533000545521, 0.36711513431559445), 1e-2); + solution.Vgo(0).ShouldEqual(9369.4641184722932, 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66075285413606588, 0.65818147618986356, 0.36083626501721638), 1e-2); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -558,6 +571,7 @@ public void Kepler3EllipticalEquatorial() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -575,8 +589,8 @@ public void Kepler3EllipticalEquatorial() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(157355.487476332, 1e-6); - solution.Vgo(0).ShouldEqual(9297.8638266388862, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.76488059901505068, 0.63826715097728237, -0.087021337807001872), 1e-2); + solution.Vgo(0).ShouldEqual(9332.93928775276, 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.75071643895089812, 0.654551834663789, -0.089368473340157739), 1e-2); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -612,6 +626,7 @@ public void Kepler4Elliptical() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, true, false) .Build(); @@ -629,8 +644,8 @@ public void Kepler4Elliptical() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(157355.487476332, 1e-6); - solution.Vgo(0).ShouldEqual(9334.0379052112639, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.67311315112262493, 0.64198533000545521, 0.36711513431559445), 1e-2); + solution.Vgo(0).ShouldEqual(9369.4640563002649, 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66094928215047744, 0.65817849624817071, 0.360481779707748), 1e-2); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -666,6 +681,7 @@ public void Kepler5Elliptical() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 1.6625138637074874, 0, false, true, true) .Build(); @@ -683,8 +699,8 @@ public void Kepler5Elliptical() solution.V(0).ShouldEqual(v0, 1e-6); solution.M(0).ShouldEqual(157355.487476332, 1e-6); - solution.Vgo(0).ShouldEqual(9334.0379052112639, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.67311315112262493, 0.64198533000545521, 0.36711513431559445), 1e-2); + solution.Vgo(0).ShouldEqual(9369.4665174003785, 1e-3); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66093259680604444, 0.658201314687611, 0.36047070868895725), 1e-2); psg.PrimalFeasibility.ShouldBeZero(1e-5); @@ -722,6 +738,7 @@ public void Kepler3ExtremeElliptical() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, false, false) .Build(); @@ -744,7 +761,7 @@ public void Kepler3ExtremeElliptical() tanof.ShouldEqual(0.0063452857807080321, 0.1); - solution.U(0).normalized.ShouldEqual(new V3(0.87754205429590737, 0.029189246151212624, 0.47861041657202014), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.87754205429590737, 0.029189246151212624, 0.47861041657202014), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -777,6 +794,7 @@ public void Circular() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -805,11 +823,11 @@ public void Circular() solution.IndexForKSPStage(3, false).ShouldEqual(1); solution.IndexForKSPStage(3, true).ShouldEqual(-1); - solution.Vgo(0).ShouldEqual(8518.1366714811684, 1e-3); + solution.Vgo(0).ShouldEqual(8549.452067127284, 1e-3); solution.DV(0, 0).ShouldEqual(4034.1207426276151, 1e-3); - solution.DV(0, 1).ShouldEqual(4483.5493109058016, 1e-3); + solution.DV(0, 1).ShouldEqual(4515.3313124354372, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.69734975209707417, 0.6074944955387559, 0.38033374967291772), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.68564570530840407, 0.624540692757553, 0.37395038425178395), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -825,6 +843,7 @@ public void Circular() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .OldSolution(psg.Solution ?? throw new Exception("null solution")) .Build(); @@ -855,6 +874,7 @@ public void CircularEquatorial() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -884,11 +904,11 @@ public void CircularEquatorial() solution.IndexForKSPStage(3, false).ShouldEqual(1); solution.IndexForKSPStage(3, true).ShouldEqual(-1); - solution.Vgo(0).ShouldEqual(8488.0759353442518, 1e-3); + solution.Vgo(0).ShouldEqual(8519.5422820333151, 1e-3); solution.DV(0, 0).ShouldEqual(4034.1207312126335, 1e-3); - solution.DV(0, 1).ShouldEqual(4453.9552041316174, 1e-3); + solution.DV(0, 1).ShouldEqual(4485.4215386894521, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.792248028862705, 0.60239243312017887, -0.097295515224028031), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.77857265138749432, 0.61953845104396443, -0.099983669614055012), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -903,6 +923,7 @@ public void CircularEquatorial() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .OldSolution(psg.Solution ?? throw new Exception("null solution")) .Build(); @@ -939,6 +960,7 @@ Ascent.AscentBuilder Builder(V3 r, V3 v) => .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r, v, r.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false); Ascent ascent = Builder(r0, v0).Build(); @@ -993,6 +1015,7 @@ public void CircularOptimizedBooster() .AddStage(157355.487476332, 40267.56108456338, 2340000, 301.817977905273, 4, 4) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3, allowShutdown: false) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -1026,9 +1049,9 @@ public void CircularOptimizedBooster() solution.TerminalIndex().ShouldEqual(1); solution.CoastIndex().ShouldEqual(-1); - solution.Vgo(0).ShouldEqual(8562.0125605993326, 1e-3); + solution.Vgo(0).ShouldEqual(8592.1679195577981, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.71091349069509358, 0.58674209774568975, 0.38773150436958898), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.69939288441266212, 0.60443937333132947, 0.38144807929751939), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -1058,6 +1081,7 @@ public void CircularCoast() .AddCoast(32758.6353093992, 32758.6353093992, 0, 450, 3, 3) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -1086,13 +1110,13 @@ public void CircularCoast() solution.IndexForKSPStage(3, false).ShouldEqual(2); solution.IndexForKSPStage(3, true).ShouldEqual(1); - solution.Vgo(0).ShouldEqual(8474.9669267192712, 1e-3); + solution.Vgo(0).ShouldEqual(8512.6306429145188, 1e-3); - solution.Tgo(solution.T0, 0).ShouldBePositive(); - solution.Tgo(solution.T0, 1).ShouldEqual(46.192475615255354, 1e-2); - solution.Tgo(solution.T0, 2).ShouldBePositive(); + solution.Tgo(solution.TStart, 0).ShouldBePositive(); + solution.Tgo(solution.TStart, 1).ShouldEqual(43.697861068036985, 1e-2); + solution.Tgo(solution.TStart, 2).ShouldBePositive(); - solution.U(0).normalized.ShouldEqual(new V3(0.67428533585626949, 0.64038742246275127, 0.36775431336792186), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.66402706101968934, 0.6541159160878357, 0.362215999859373), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -1109,6 +1133,7 @@ public void CircularCoast() .AddCoast(32758.6353093992, 32758.6353093992, 0, 450, 3, 3) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .OldSolution(psg.Solution ?? throw new Exception("null solution")) .Build(); @@ -1139,6 +1164,7 @@ public void CircularCoastOptimizedBooster() .AddCoast(32758.6353093992, 32758.6353093992, 0, 450, 3, 3) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3, allowShutdown: false) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -1147,10 +1173,10 @@ public void CircularCoastOptimizedBooster() Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); using Solution solution = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); - solution.Tgo(solution.T0, 0).ShouldBePositive(); - solution.Tgo(solution.T0, 1).ShouldEqual(15.113269375351896, 1e-2); - solution.Tgo(solution.T0, 2).ShouldBePositive(); - solution.Vgo(0).ShouldEqual(8557.8736963926785, 1e-3); + solution.Tgo(solution.TStart, 0).ShouldBePositive(); + solution.Tgo(solution.TStart, 1).ShouldEqual(15.113269375351896, 1e-2); + solution.Tgo(solution.TStart, 2).ShouldBePositive(); + solution.Vgo(0).ShouldEqual(8588.02885538735, 1e-3); (V3 rf, V3 vf) = solution.TerminalStateVectors(); @@ -1178,7 +1204,7 @@ public void CircularCoastOptimizedBooster() solution.TerminalIndex().ShouldEqual(2); solution.CoastIndex().ShouldEqual(1); - solution.U(0).normalized.ShouldEqual(new V3(0.70743037652982543, 0.59217914188368692, 0.38583173311790908), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.69601469152854378, 0.6096732662115627, 0.37929152065838617), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -1209,6 +1235,7 @@ public void CircularCoastWithinStage() .AddCoast(32758.6353093992, 6384.144733613521, 0, 450, 3, 3, massContinuity: true) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3, massContinuity: true) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -1237,14 +1264,14 @@ public void CircularCoastWithinStage() solution.IndexForKSPStage(3, false).ShouldEqual(1); solution.IndexForKSPStage(3, true).ShouldEqual(2); - solution.Tgo(solution.T0, 0).ShouldEqual(148.10238013870301, 1e-2); - solution.Tgo(solution.T0, 1).ShouldEqual(153.53757758636579, 1e-2); - solution.Tgo(solution.T0, 2).ShouldEqual(449.99973855863101, 1e-2); - solution.Tgo(solution.T0, 3).ShouldEqual(9.1537185650994335, 1e-2); + solution.Tgo(solution.TStart, 0).ShouldEqual(148.10238013870301, 1e-2); + solution.Tgo(solution.TStart, 1).ShouldEqual(153.53757758636579, 1e-2); + solution.Tgo(solution.TStart, 2).ShouldEqual(449.99973855863101, 1e-2); + solution.Tgo(solution.TStart, 3).ShouldEqual(8.7489488121921113, 1e-2); - solution.Vgo(0).ShouldEqual(8101.193073142621, 1e-3); + solution.Vgo(0).ShouldEqual(8158.509566601695, 1e-3); - solution.U(0).normalized.ShouldEqual(new V3(0.46268355846501641, 0.84975061932167251, 0.25268124126769614), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.4506283008932096, 0.85807077092551975, 0.24626954037676546), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); @@ -1262,6 +1289,7 @@ public void CircularCoastWithinStage() .AddCoast(32758.6353093992, 6384.144733613521, 0, 450, 3, 3, massContinuity: true) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3, massContinuity: true) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .OldSolution(psg.Solution ?? throw new Exception("null solution")) .Build(); @@ -1274,7 +1302,7 @@ public void CircularCoastWithinStage() psg2.PrimalFeasibility.ShouldBeZero(1e-5); psg2.InitialPrimalFeasibility.ShouldBeZero(1e-3); - solution2.Vgo(0).ShouldEqual(8101.193073142621, 1e-3); + solution2.Vgo(0).ShouldEqual(8158.5092907149847, 1e-3); } // Re-solves from mid-flight after staging, so the new Problem has a different length/time/mass scale than the old @@ -1297,6 +1325,7 @@ public void CircularCoastWithinStageResolveAfterStaging() .AddCoast(32758.6353093992, 6384.144733613521, 0, 450, 3, 3, massContinuity: true) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3, massContinuity: true) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -1376,6 +1405,7 @@ public void HighlyEllipticalCoastWithinStage() .AddCoast(32758.6353093992, 32758.6353093992, 0, 450, 3, 3, massContinuity: true) .AddStage(32758.6353093992, 6384.144733613521, 456100.006103516, 315.000112652779, 3, 3, massContinuity: true) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(PeR, ApR, PeR, incT, Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -1404,14 +1434,14 @@ public void HighlyEllipticalCoastWithinStage() solution.IndexForKSPStage(3, false).ShouldEqual(1); solution.IndexForKSPStage(3, true).ShouldEqual(2); - solution.Vgo(0).ShouldEqual(9949.1675404048201, 1e-3); + solution.Vgo(0).ShouldEqual(10013.332037161936, 1e-3); - solution.Tgo(solution.T0, 0).ShouldBePositive(); - solution.Tgo(solution.T0, 1).ShouldEqual(176.13643532153222, 1e-2); - solution.Tgo(solution.T0, 2).ShouldEqual(449.99999999922886, 1e-2); - solution.Tgo(solution.T0, 3).ShouldEqual(13.03613615732877, 1e-2); + solution.Tgo(solution.TStart, 0).ShouldBePositive(); + solution.Tgo(solution.TStart, 1).ShouldEqual(176.13643532153222, 1e-2); + solution.Tgo(solution.TStart, 2).ShouldEqual(449.99999999922886, 1e-2); + solution.Tgo(solution.TStart, 3).ShouldEqual(12.597983444291344, 1e-2); - solution.U(0).normalized.ShouldEqual(new V3(0.38075918032302986, 0.9006976112150552, 0.20920387126252593), 1e-2); + solution.U(solution.T0).normalized.ShouldEqual(new V3(0.36938563329430579, 0.9072664476031892, 0.20105185144448243), 1e-2); double aprf = Astro.ApoapsisFromKeplerian(smaf, eccf); double perf = Astro.PeriapsisFromKeplerian(smaf, eccf); diff --git a/MechJebLibTest/PSGTests/SolutionTests.cs b/MechJebLibTest/PSGTests/SolutionTests.cs index a7e240fac..bd183ddb6 100644 --- a/MechJebLibTest/PSGTests/SolutionTests.cs +++ b/MechJebLibTest/PSGTests/SolutionTests.cs @@ -26,8 +26,10 @@ public partial class SolutionTests // KerbinTests.MainSailTinCanVacuum: a burn, a coast-during coast and the rest of the burn. With a plan the three phases // are built from its stages 2, 1 and 0 (see TinCanFlightPlan). met0 is the MET of the initial state, and turn turns - // the initial state (the launch site turning with the planet when it turns about the pole). - private static Ascent.AscentBuilder TinCanBuilder(FlightPlan? plan = null, double met0 = 0, Q3? turn = null) + // the initial state (the launch site turning with the planet when it turns about the pole). The initial state is on + // the pad, so the solve starts at the top of a vertical rise of rise meters, as the PSG simulation's does on the + // ground, and with no rise it is a solve in flight. + private static Ascent.AscentBuilder TinCanBuilder(FlightPlan? plan = null, double met0 = 0, Q3? turn = null, double rise = RISE) { bool hasPlan = plan != null; Q3 q = turn ?? Q3.identity; @@ -39,6 +41,7 @@ private static Ascent.AscentBuilder TinCanBuilder(FlightPlan? plan = null, doubl .AddStage(79699.9986022711, 15700.0014199451, 1500000.09246676, 310.000018173591, 0, 0, allowShutdown: true, ispCurrent: 285.387620615011, minThrottle: 0.0, massContinuity: true, flightPlanIndex: hasPlan ? 0 : -1) .Initial(q * _tinCanR0, q * _tinCanV0, q * _tinCanU0, met0, 3531600000000, 600000) + .VerticalRise(rise) .SetTarget(700000, 700000, 700000, 0, 0, 0, 0, false, false, false); if (plan != null) @@ -253,6 +256,7 @@ public void StagingAheadOfTheClock() .AddStage(153180, 35248.993172173155, 2194400, 296, 4, 4, allowShutdown: false) .AddStage(31980, 6125.823788668185, 443700, 315, 2, 2) .Initial(r0, v0, r0.normalized, t0, mu, rbody) + .VerticalRise(RISE) .SetTarget(peR, peR, peR, Deg2Rad(28.608), Deg2Rad(270), 0, 0, false, false, false) .Build(); @@ -285,10 +289,11 @@ public void StagingAheadOfTheClock() u.ShouldEqual(uStart, 1e-12); } - // The clock is MET, and a solve started in flight starts at the MET of its initial state. The optimizer doesn't depend - // on absolute time, so the same problem started at MET 100 is the MET 0 trajectory moved 100 s later. The two only - // agree to the optimizer's convergence: this solve is flat enough that moving the start by 1e-9 s already moves the - // states by ~5e-6 (relative), while a clock that is off by even a fraction of a second fails by orders of magnitude. + // The clock is MET, and a solve started after liftoff starts at the MET of its initial state, here on the ground with + // its rise, as off a moon. The optimizer and the rise don't depend on absolute time, so the same problem started at + // MET 100 is the MET 0 trajectory moved 100 s later. The two only agree to the optimizer's convergence: this solve is + // flat enough that moving the start by 1e-9 s already moves the states by ~5e-6 (relative), while a clock that is off + // by even a fraction of a second fails by orders of magnitude. [Fact] public void StartMetShiftsTheTrajectory() { @@ -303,9 +308,10 @@ public void StartMetShiftsTheTrajectory() using Solution s0 = (ascent.GetOptimizer()?.Solution ?? throw new Exception("null solution")).DeNormalized(); using Solution s1 = (shifted.GetOptimizer()?.Solution ?? throw new Exception("null solution")).DeNormalized(); - // the shifted trajectory starts at its initial state at MET0 - s0.T0.ShouldBeZero(); - s1.T0.ShouldEqual(MET0, 1e-12); + // the shifted trajectory starts at its initial state at MET0, and rises from there + s0.TStart.ShouldBeZero(); + s1.TStart.ShouldEqual(MET0, 1e-12); + s1.T0.ShouldEqual(s0.T0 + MET0, 1e-12); s1.R(MET0).ShouldEqual(_tinCanR0, 1e-6); s1.V(MET0).ShouldEqual(_tinCanV0, 1e-6); @@ -363,7 +369,7 @@ public void RotateToLaunchSiteTurnsAboutThePole() normalized.RotateToLaunchSite(r0); using Solution turnedSI = normalized.DeNormalized(); - turned.T0.ShouldBeZero(); + turned.TStart.ShouldBeZero(); turned.R(0).ShouldEqual(r0, 1e-6); turned.V(0).ShouldEqual(turn * _tinCanV0, 1e-6); @@ -440,7 +446,7 @@ public void RotateToLaunchSiteIgnoresAFlightSolution() { const double MET0 = 100; - Ascent ascent = TinCanBuilder(met0: MET0).Build(); + Ascent ascent = TinCanBuilder(met0: MET0, rise: 0).Build(); ascent.Run(); using Solution solution = (ascent.GetOptimizer()?.Solution ?? throw new Exception("null solution")).DeNormalized(); @@ -461,10 +467,11 @@ public void RotateToLaunchSiteIgnoresAFlightSolution() // the pad. TinCan is in vacuum with an equatorial target, so it is symmetric about the pole: the old solution turned // to the launch site warm starts the problem there as well as it does on the pad it was solved at, and the solve lands // on the old trajectory turned. The old solution is itself a warm start, as on the pad, since a warm start from the - // cold start changes the objective and takes many iterations wherever it is. Without the turn the guess misses the - // box constraints pinning the initial state, so InitialPrimalFeasibility is 1e-2 instead of 4e-11, and the solve still - // lands on the turned trajectory, but takes 17 iterations instead of 1 to move the whole trajectory onto the launch - // site. + // cold start changes the objective and takes many iterations wherever it is. That warm start stops at a primal + // feasibility of 5e-8, so this solve takes 6 iterations to tighten it (a third warm start takes 1). Without the turn + // the guess misses the box constraints pinning the initial state, so InitialPrimalFeasibility is 1e-2 instead of 3e-9, + // and the solve still lands on the turned trajectory, but takes 30 iterations instead of 6 to move the whole trajectory + // onto the launch site. [Fact] public void WarmStartFromATurnedLaunchSite() { @@ -490,10 +497,12 @@ public void WarmStartFromATurnedLaunchSite() Optimizer psg = warm.GetOptimizer() ?? throw new Exception("null optimizer"); psg.Success().ShouldBeTrue(); psg.InitialPrimalFeasibility.ShouldBeZero(1e-3); - Assert.InRange(psg.Iterations, 0, 5); + Assert.InRange(psg.Iterations, 0, 10); using Solution s1 = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); - s1.T0.ShouldBeZero(); + // the rise from the turned launch site is the same, to the integrator's round-off + s1.TStart.ShouldBeZero(); + s1.T0.ShouldEqual(s0.T0, 1e-9); s1.Segments.ShouldEqual(s0.Segments); s1.Tf.ShouldEqual(s0.Tf, SOLVE_TOL); diff --git a/MechJebLibTest/PSGTests/VerticalRiseTests.cs b/MechJebLibTest/PSGTests/VerticalRiseTests.cs index f5cda4999..a571c8789 100644 --- a/MechJebLibTest/PSGTests/VerticalRiseTests.cs +++ b/MechJebLibTest/PSGTests/VerticalRiseTests.cs @@ -140,7 +140,7 @@ void NoRise(Problem pad, PhaseCollection phases, double height) [Fact] public void TinCanRisesStraightUpFromThePad() { - Ascent ascent = TinCanBuilder().VerticalRise(RISE).Build(); + Ascent ascent = TinCanBuilder().Build(); ascent.Run(); Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); @@ -161,12 +161,12 @@ public void TinCanRisesStraightUpFromThePad() solution.M(0).ShouldEqual(TIN_CAN_M0, 1e-12); (solution.R(t0).magnitude - _tinCanR0.magnitude).ShouldEqual(RISE, 1e-7); - // the first phase starts where the rise ends + // the first phase starts where the rise ends, to the optimizer's accuracy on the initial state it pins InterpolantLayout top = solution.RiseState(t0); InterpolantLayout first = solution.State(0, t0); - first.R.ShouldEqual(top.R, 1e-12); - first.V.ShouldEqual(top.V, 1e-12); - first.M.ShouldEqual(top.M, 1e-12); + first.R.ShouldEqual(top.R, 1e-9); + first.V.ShouldEqual(top.V, 1e-9); + first.M.ShouldEqual(top.M, 1e-9); // straight up at full throttle (at T0 U is the first phase's steering) double mdot = TIN_CAN_THRUST / (TIN_CAN_ISP * G0); @@ -200,14 +200,15 @@ public void TinCanRisesStraightUpFromThePad() // started from the solution rises the same way, which puts the warm start right on the pinned initial state at the // top. As in WarmStartFromATurnedLaunchSite the solution warm started is itself a warm start, since a warm start // from the cold start changes the objective (Tf goes from 609 s to 544 s here, and from 610 s to 543 s without the - // rise) and takes many iterations wherever it is. + // rise) and takes many iterations wherever it is. That warm start stops at a primal feasibility of 5e-8, so the + // re-solve takes 6 iterations to tighten it, and lands on the same trajectory. [Fact] public void TinCanRiseRoundTrips() { - Ascent cold = TinCanBuilder().VerticalRise(RISE).Build(); + Ascent cold = TinCanBuilder().Build(); cold.Run(); - Ascent ascent = TinCanBuilder().VerticalRise(RISE).OldSolution(cold.GetOptimizer()?.Solution ?? throw new Exception("null solution")) + Ascent ascent = TinCanBuilder().OldSolution(cold.GetOptimizer()?.Solution ?? throw new Exception("null solution")) .Build(); ascent.Run(); @@ -257,13 +258,13 @@ public void TinCanRiseRoundTrips() } // as the solver does between solves on the pad - Ascent again = TinCanBuilder().VerticalRise(RISE).OldSolution(normalized).Build(); + Ascent again = TinCanBuilder().OldSolution(normalized).Build(); again.Run(); Optimizer psg = again.GetOptimizer() ?? throw new Exception("null optimizer"); psg.Success().ShouldBeTrue(); psg.InitialPrimalFeasibility.ShouldBeZero(1e-6); - Assert.InRange(psg.Iterations, 0, 5); + Assert.InRange(psg.Iterations, 0, 10); using Solution s1 = (psg.Solution ?? throw new Exception("null solution")).DeNormalized(); s1.HasRise.ShouldBeTrue(); @@ -279,7 +280,7 @@ public void RiseOffTheGroundLaterInTheMission() { const double MET0 = 100; - Ascent ascent = TinCanBuilder(met0: MET0).VerticalRise(RISE).Build(); + Ascent ascent = TinCanBuilder(met0: MET0).Build(); ascent.Run(); Optimizer psg = ascent.GetOptimizer() ?? throw new Exception("null optimizer"); From 2be3843a8f91a25dc77be2749725df714e455c0c Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Fri, 20 Nov 2026 21:16:38 -0800 Subject: [PATCH 6/8] Throw away PSG solutions that arrive after guidance has moved on The PSG simulation handed every converged solve to the autopilot, whatever state the autopilot had reached while the solve ran. Only AscentStateMachine.SetSolution refused one, and only in terminal guidance and once finished. A solve started on the pad that converged after liftoff, or one that converged during a jettison, still reached guidance. A solution is now handed off only while the autopilot is in PRELAUNCH, BURNING or COASTING (TakesSolution). In any other state it is thrown away and logged, and none of the success bookkeeping runs: the warm start, the reach check, VacuumCoastSolved, the converge count and the staleness all stay as they were. This replaces the rule from 903a021e that a solve still running at liftoff is kept. Ascents engaged in flight aren't supported, so the vertical ascent and the pitch program always have the pad solution and need no exception for a first one. --- MechJeb2/MechJebModulePSGSimulation.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/MechJeb2/MechJebModulePSGSimulation.cs b/MechJeb2/MechJebModulePSGSimulation.cs index 6c73e35ab..e9710490d 100644 --- a/MechJeb2/MechJebModulePSGSimulation.cs +++ b/MechJeb2/MechJebModulePSGSimulation.cs @@ -497,6 +497,21 @@ public bool ResetPlan() return true; } + // Guidance is handed a solution only on the pad, in a burn or in the coast. One that converges once the autopilot has + // moved on (the vertical ascent and the pitch program, a jettison, terminal guidance, the end) is late, and is thrown away. + private bool TakesSolution() + { + switch (Core.PSGAutopilot.State) + { + case PSGState.PRELAUNCH: + case PSGState.BURNING: + case PSGState.COASTING: + return true; + default: + return false; + } + } + private void HandleDoneTask() { if (!(_ascent is { IsCompleted: true })) @@ -517,6 +532,12 @@ private void HandleDoneTask() if (psg.Success() && psg.Solution != null) { + if (!TakesSolution()) + { + Debug.Log($"[MechJebModulePSGSimulation] threw away a late solution: the autopilot is in {Core.PSGAutopilot.State}"); + return; + } + _solution = psg.Solution; Solution flown = psg.Solution.DeNormalized(); CheckReach(flown); From 6ea89378a78cfe7fd3a8d64c3ddf946d835ff7b1 Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Fri, 20 Nov 2026 21:31:48 -0800 Subject: [PATCH 7/8] Start PSG solves only in PRELAUNCH, BURNING and COASTING 2be3843a throws away a solve that converges in any other state, so the PSG simulation no longer starts one there either. The same TakesSolution gate now comes right after the stages are reconciled, and PausedState says why the optimizer waits: VERTICAL_ASCENT ON_PAD from T-0 until the clamps let go, then VERTICAL_ASCENT PITCH_PROGRAM PITCH_PROGRAM JETTISON JETTISON (new): "paused for the jettison, resumes in the burn" TERMINAL(_RCS) TERMINAL FINISHED FINISHED It replaces the separate checks for terminal guidance and the end, the TERMINAL and FINISHED cases of the "only unguided stages left" state, and the pause for the vertical ascent and the pitch program. That pause kept solving without a Solution, for an ascent engaged in flight, which isn't supported: every launch starts in PRELAUNCH on the ground and has its Solution before the vertical ascent. TerminalStarted and GuidanceFinished still cancel a running solve, to free the worker sooner. CoastStarted and CoastEnded are still needed, since COASTING takes solutions. --- MechJeb2/MechJebModulePSGAutopilot.cs | 2 - MechJeb2/MechJebModulePSGSimulation.cs | 57 ++++++++++++-------------- MechJeb2/PSGFeedback.cs | 2 + 3 files changed, 29 insertions(+), 32 deletions(-) diff --git a/MechJeb2/MechJebModulePSGAutopilot.cs b/MechJeb2/MechJebModulePSGAutopilot.cs index d79879154..a2abcb73e 100644 --- a/MechJeb2/MechJebModulePSGAutopilot.cs +++ b/MechJeb2/MechJebModulePSGAutopilot.cs @@ -71,8 +71,6 @@ public MechJebModulePSGAutopilot(MechJebCore core) : base(core) { } public bool IsCoasting => _machine.IsCoasting; - public bool IsTerminal => _machine.IsTerminal; - public bool IsFinished => _machine.IsFinished; /// Set when the coast starts, and kept after it: the Solution's burns before the coast are behind the vessel. diff --git a/MechJeb2/MechJebModulePSGSimulation.cs b/MechJeb2/MechJebModulePSGSimulation.cs index e9710490d..9cee5171d 100644 --- a/MechJeb2/MechJebModulePSGSimulation.cs +++ b/MechJeb2/MechJebModulePSGSimulation.cs @@ -30,9 +30,10 @@ public enum OptimizerState STAGE_ENDING, // the current stage is about to end: the solution is frozen through staging AFTER_STAGING, // a short wait after staging AFTER_PHASE, // the same wait after a phase ended without staging (the start or end of a coast during a stage) - ON_PAD, // either wait before liftoff: the stage not lit yet has no phase in the solution, so its time to go reads 0 + ON_PAD, // a wait before liftoff: the stage not lit yet has no phase in the solution, so its time to go reads 0, and the vertical ascent from T-0 until the clamps let go VERTICAL_ASCENT, // after liftoff, the vertical ascent to the pitch start height: no re-solve until guidance takes over PITCH_PROGRAM, // the pitch program, pitching over to the guidance pitch of the solution it has: no re-solve until guidance takes over + JETTISON, // a jettison of a cut burn's engines: no re-solve until it is back in the burn COAST_PAUSE, // a long coast above the atmosphere, once a solve started there has converged: resumes 20 s before the burn TERMINAL, // terminal guidance flies the end of the burn on the frozen solution UNGUIDED_ONLY, // only unguided stages are left, which the optimizer can't steer @@ -512,6 +513,21 @@ private bool TakesSolution() } } + // what the optimizer reports while guidance takes no solution (TakesSolution) + private OptimizerState PausedState() + { + switch (Core.PSGAutopilot.State) + { + case PSGState.VERTICAL_ASCENT: return Vessel.VesselOffGround() ? OptimizerState.VERTICAL_ASCENT : OptimizerState.ON_PAD; + case PSGState.PITCH_PROGRAM: return OptimizerState.PITCH_PROGRAM; + case PSGState.JETTISON: return OptimizerState.JETTISON; + case PSGState.TERMINAL: + case PSGState.TERMINAL_RCS: return OptimizerState.TERMINAL; + case PSGState.FINISHED: return OptimizerState.FINISHED; + default: throw new ArgumentOutOfRangeException(); + } + } + private void HandleDoneTask() { if (!(_ascent is { IsCompleted: true })) @@ -653,23 +669,20 @@ public override void OnFixedUpdate() attR = apR; } - if (Vessel.VesselOffGround()) + // Solves start only while guidance takes their solutions: one started in any other state would be thrown away + // (HandleDoneTask). The vertical ascent and the pitch program fly a fixed program, and the pitch program hands over + // to guidance where it meets the solution's pitch, which a re-solve from the climb would move. Terminal guidance + // flies the end of a frozen solution. + if (!TakesSolution()) { - // if we have only inertially guided stages we can't run the optimizer - if (FlightPlan.AllUnguidedStages()) - { - // also true once no stage is left at all, as in terminal guidance on the last stage: name that instead - SetState(Core.PSGAutopilot.IsTerminal ? OptimizerState.TERMINAL - : Core.PSGAutopilot.IsFinished ? OptimizerState.FINISHED - : UnguidedBurnLeft() ? OptimizerState.UNGUIDED_ONLY : OptimizerState.NO_PLAN); - return; - } + SetState(PausedState()); + return; } - // not in terminal guidance, which flies the end of a frozen solution, and not finished - if (Core.PSGAutopilot.IsTerminal || Core.PSGAutopilot.IsFinished) + // if we have only inertially guided stages we can't run the optimizer + if (Vessel.VesselOffGround() && FlightPlan.AllUnguidedStages()) { - SetState(Core.PSGAutopilot.IsTerminal ? OptimizerState.TERMINAL : OptimizerState.FINISHED); + SetState(UnguidedBurnLeft() ? OptimizerState.UNGUIDED_ONLY : OptimizerState.NO_PLAN); return; } @@ -695,22 +708,6 @@ public override void OnFixedUpdate() } } - // After liftoff the vertical ascent and the pitch program fly a fixed program, and the pitch program hands over to - // guidance where it meets the solution's pitch: a re-solve from the climb would move that pitch. Without a solution - // yet the solves go on, or guidance would never take over. - if (Vessel.VesselOffGround() && Core.PSGAutopilot.Solution != null) - { - switch (Core.PSGAutopilot.State) - { - case PSGState.VERTICAL_ASCENT: - SetState(OptimizerState.VERTICAL_ASCENT); - return; - case PSGState.PITCH_PROGRAM: - SetState(OptimizerState.PITCH_PROGRAM); - return; - } - } - if (_blockOptimizerUntilTime > VesselState.Time) { // the routine second between two solves is not a pause. A staging event names its own wait (HandleStageEvent): a diff --git a/MechJeb2/PSGFeedback.cs b/MechJeb2/PSGFeedback.cs index 0fab78558..965d54de9 100644 --- a/MechJeb2/PSGFeedback.cs +++ b/MechJeb2/PSGFeedback.cs @@ -48,6 +48,8 @@ internal static class PSGFeedback return "Optimizer: paused for the vertical ascent, resumes when guidance takes over"; case OptimizerState.PITCH_PROGRAM: return "Optimizer: paused for the pitch program, resumes when guidance takes over"; + case OptimizerState.JETTISON: + return "Optimizer: paused for the jettison, resumes in the burn"; case OptimizerState.AFTER_PHASE: return $"Optimizer: paused while the next phase starts, {Ceiling(seconds):F0} s"; case OptimizerState.COAST_PAUSE: From a3484804aad185677c7e0d41539a9c4db5a87698 Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Sat, 21 Nov 2026 05:32:12 -0800 Subject: [PATCH 8/8] Refuse late PSG Solutions in the AscentStateMachine A Solution solved before a jettison cut could land while JETTISON waited for KSP's staging cooldown. If it ended the burn later than the one being cut, guidance went back to BURNING and throttled the cut engines up again (#2782). 8b173b5a kept the PSG simulation from handing such a Solution over, but the state machine still took one. AscentStateMachine.TakesSolution is now the rule: PRELAUNCH, BURNING and COASTING. SetSolution refuses a Solution in any other state, which extends its old refusal in terminal guidance and once finished. The vertical ascent and the pitch program fly the pad Solution to guidance, a jettison drops the burn its Solution cut, and terminal guidance flies to the end of the Solution it started with. The PSG autopilot passes TakesSolution through, and its SetSolution returns whether the Solution was taken. The simulation drops its own copy of the rule: HandleDoneTask throws away a Solution SetSolution refused, before any of its bookkeeping, and solves start only while the autopilot TakesSolution. The autopilot's IsTerminal, which nothing used any more, is gone. JettisonRefusesALateSolution is the scenario from #2782 (it lit the cut booster twice before this). ClimbRefusesALateSolution replaces PitchProgramMeetsTheGuidanceOfANewSolutionAtOnce, which gave an ascent engaged in flight its first Solution in the pitch program. Ascents engaged in flight aren't supported, and the pitch program now refuses that Solution: the new test checks the refusal in the vertical ascent and the pitch program of a pad launch, which keeps its pad Solution. --- MechJeb2/MechJebModulePSGAutopilot.cs | 14 ++++- MechJeb2/MechJebModulePSGSimulation.cs | 32 +++------- MechJebLib/PSG/AscentStateMachine.cs | 21 ++++--- .../PSGTests/AscentStateMachineTests.cs | 58 ++++++++++++++----- 4 files changed, 78 insertions(+), 47 deletions(-) diff --git a/MechJeb2/MechJebModulePSGAutopilot.cs b/MechJeb2/MechJebModulePSGAutopilot.cs index a2abcb73e..9a437cd5b 100644 --- a/MechJeb2/MechJebModulePSGAutopilot.cs +++ b/MechJeb2/MechJebModulePSGAutopilot.cs @@ -481,11 +481,19 @@ private Vector3d ApplyAoALimiter(Vector3d desiredThrustVector) * Solutions */ - // guidance flies in SI units and MET seconds, so this takes a DeNormalized() Solution - public void SetSolution(Solution solution) + /// Whether SetSolution takes a Solution now: in PRELAUNCH, BURNING and COASTING (AscentStateMachine.TakesSolution). + public bool TakesSolution => _machine.TakesSolution; + + // guidance flies in SI units and MET seconds, so this takes a DeNormalized() Solution. False if it was ignored + // (TakesSolution). + public bool SetSolution(Solution solution) { - if (_machine.SetSolution(solution) && solution.FromPad) + if (!_machine.SetSolution(solution)) + return false; + + if (solution.FromPad) PadSolution = solution; + return true; } /// diff --git a/MechJeb2/MechJebModulePSGSimulation.cs b/MechJeb2/MechJebModulePSGSimulation.cs index 9cee5171d..2ee16d0c1 100644 --- a/MechJeb2/MechJebModulePSGSimulation.cs +++ b/MechJeb2/MechJebModulePSGSimulation.cs @@ -498,22 +498,7 @@ public bool ResetPlan() return true; } - // Guidance is handed a solution only on the pad, in a burn or in the coast. One that converges once the autopilot has - // moved on (the vertical ascent and the pitch program, a jettison, terminal guidance, the end) is late, and is thrown away. - private bool TakesSolution() - { - switch (Core.PSGAutopilot.State) - { - case PSGState.PRELAUNCH: - case PSGState.BURNING: - case PSGState.COASTING: - return true; - default: - return false; - } - } - - // what the optimizer reports while guidance takes no solution (TakesSolution) + // what the optimizer reports while guidance takes no solution (AscentStateMachine.TakesSolution) private OptimizerState PausedState() { switch (Core.PSGAutopilot.State) @@ -548,16 +533,17 @@ private void HandleDoneTask() if (psg.Success() && psg.Solution != null) { - if (!TakesSolution()) + // one that converges once guidance has moved on is late (AscentStateMachine.TakesSolution): it is thrown away, + // and the next solve warm starts from the last one guidance took + Solution flown = psg.Solution.DeNormalized(); + if (!Core.PSGAutopilot.SetSolution(flown)) { Debug.Log($"[MechJebModulePSGSimulation] threw away a late solution: the autopilot is in {Core.PSGAutopilot.State}"); return; } _solution = psg.Solution; - Solution flown = psg.Solution.DeNormalized(); CheckReach(flown); - Core.PSGAutopilot.SetSolution(flown); // the coast's start and end cancel the job, so a job started in the coast lands in it CheckDebug.True(!_vacuumCoastJob || Core.PSGAutopilot.IsCoasting); @@ -669,11 +655,9 @@ public override void OnFixedUpdate() attR = apR; } - // Solves start only while guidance takes their solutions: one started in any other state would be thrown away - // (HandleDoneTask). The vertical ascent and the pitch program fly a fixed program, and the pitch program hands over - // to guidance where it meets the solution's pitch, which a re-solve from the climb would move. Terminal guidance - // flies the end of a frozen solution. - if (!TakesSolution()) + // solves start only while guidance takes their solutions (AscentStateMachine.TakesSolution): one started in any other + // state would be thrown away (HandleDoneTask) + if (!Core.PSGAutopilot.TakesSolution) { SetState(PausedState()); return; diff --git a/MechJebLib/PSG/AscentStateMachine.cs b/MechJebLib/PSG/AscentStateMachine.cs index 19d286d31..49ea468a4 100644 --- a/MechJebLib/PSG/AscentStateMachine.cs +++ b/MechJebLib/PSG/AscentStateMachine.cs @@ -341,6 +341,15 @@ public string GuidanceStatus // flying the Solution, after the pitch program public bool IsGuided => _state == PSGState.BURNING || _state == PSGState.JETTISON || IsCoasting || IsTerminal; + /// + /// Whether SetSolution takes a Solution now: on the pad, in a burn or in the coast. A Solution that arrives in any other + /// state is late: the vertical ascent and the pitch program fly the pad Solution to guidance (a new one would move the + /// pitch the pitch program hands over at), a jettison drops the burn its Solution cut (one that ends that burn later + /// would take it back to BURNING and throttle the cut engines up again), and terminal guidance flies to the end of the + /// Solution it started with. PSGSimulation starts no solve in them. + /// + public bool TakesSolution => _state == PSGState.PRELAUNCH || _state == PSGState.BURNING || IsCoasting; + /// Set when the coast starts, and kept after it: the Solution's burns before the coast are behind the vessel. public bool HasCoasted { get; private set; } @@ -418,23 +427,21 @@ public AscentCommand Finish() } /// - /// Takes a DeNormalized() Solution to fly (guidance flies in SI units and MET seconds). False if it was ignored: terminal - /// guidance flies to the end of the Solution it started with. + /// Takes a DeNormalized() Solution to fly (guidance flies in SI units and MET seconds). False if it was ignored, outside + /// PRELAUNCH, BURNING and COASTING (TakesSolution). /// public bool SetSolution(Solution solution) { Check.False(solution.Normalized, "guidance needs a DeNormalized() Solution"); + if (!TakesSolution) + return false; + // PSGSimulation cancels the solve in progress when the coast starts and when it ends (CoastStarted, CoastEnded), so a // solution that arrives during the coast starts with it, and one that arrives after it has no coast CheckDebug.True(!IsCoasting || solution.CoastPhase(0)); CheckDebug.True(!HasCoasted || IsCoasting || solution.CoastIndex() < 0); - // terminal guidance flies to the end of the Solution it started with (PSGSimulation drops the solve in progress when - // it starts, so this is only a solve that was done before) - if (IsTerminal || IsFinished) - return false; - Solution = solution; // its flight plan is as old as its solve: reconcile it with the stage stats now diff --git a/MechJebLibTest/PSGTests/AscentStateMachineTests.cs b/MechJebLibTest/PSGTests/AscentStateMachineTests.cs index f2bea39bb..80d96cc0e 100644 --- a/MechJebLibTest/PSGTests/AscentStateMachineTests.cs +++ b/MechJebLibTest/PSGTests/AscentStateMachineTests.cs @@ -269,24 +269,31 @@ public void PrelaunchEngagedInFlightCutsNothing() Assert.Equal(PSGState.PITCH_PROGRAM, flight.Machine.State); } + // The vertical ascent and the pitch program fly the pad Solution to guidance, so a Solution that arrives in them (a solve + // still running at liftoff) is refused: it would move the pitch the pitch program hands over at. [Fact] - public void PitchProgramMeetsTheGuidanceOfANewSolutionAtOnce() + public void ClimbRefusesALateSolution() { - // in an atmosphere at 1°/s with no Solution, the pitch program pitches down to 3° in 87 s - AscentFlight flight = OneStage(); - flight.HasAtmosphere = true; - flight.Machine.Start(); - flight.Run(87); - Assert.Equal(PSGState.PITCH_PROGRAM, flight.Machine.State); + AscentFlight flight = OnThePad(); + Solution pad = Solve(flight.Plan(), MET0, Fixed(60), Fixed(40), Fixed(30)); + flight.Engage(pad); + Assert.True(flight.Machine.TakesSolution); - // where the synthetic trajectory's guidance pitch is about 5° - flight.TrajectoryT = MET0 + 87; - Assert.True(flight.Machine.SetSolution(Solve(flight.Plan(), MET0, Fixed(100)))); + flight.Step(); + Assert.Equal(PSGState.VERTICAL_ASCENT, flight.Machine.State); + Assert.False(flight.Machine.TakesSolution); + Assert.False(flight.Machine.SetSolution(Solve(flight.Plan(), MET0, Fixed(60), Fixed(40), Fixed(30)))); - // below it on the Solution's first tick: guidance takes over then, not a tick later + // off the pad, above the pitch start height + flight.Grounded = false; + flight.LiftedOff = true; + flight.AltitudeBottom = 150; flight.Step(); - Assert.Equal(PSGState.BURNING, flight.Machine.State); - Assert.InRange(flight.Machine.Pitch, 4, 6); + Assert.Equal(PSGState.PITCH_PROGRAM, flight.Machine.State); + Assert.False(flight.Machine.TakesSolution); + Assert.False(flight.Machine.SetSolution(Solve(flight.Plan(), MET0, Fixed(60), Fixed(40), Fixed(30)))); + + Assert.Same(pad, flight.Machine.Solution); } /* @@ -681,6 +688,31 @@ public void JettisonWaitsForKSPToStage() Assert.All(flight.Engines, e => Assert.Equal(1, e.Burns)); } + // A solve started before the cut lands while JETTISON waits for KSP to stage, its booster ending 3 s later (the vessel + // was behind when it started). Flown, it would take guidance back to BURNING and throttle the cut booster up again (a + // RealFuels engine with no relights lost), so it is refused and the jettison goes on (#2782). + [Fact] + public void JettisonRefusesALateSolution() + { + AscentFlight flight = ThreeStages(); + flight.RefuseStagingUntil = MET0 + 51; + Solution pad = Solve(flight.Plan(), MET0, Cut(50), Fixed(40), Fixed(30)); + flight.Engage(pad); + + Assert.True(flight.RunUntil(PSGState.JETTISON, 100)); + flight.Run(0.4); + Assert.Equal(PSGState.JETTISON, flight.Machine.State); + Assert.False(flight.Machine.TakesSolution); + + Assert.False(flight.Machine.SetSolution(Solve(flight.FlownPlan, MET0 + 39, Cut(14), Fixed(40), Fixed(30)))); + Assert.Same(pad, flight.Machine.Solution); + + flight.Fly(); + + Assert.Equal("PRELAUNCH PITCH_PROGRAM BURNING JETTISON BURNING FINISHED", flight.Sequence()); + Assert.All(flight.Engines, e => Assert.Equal(1, e.Burns)); + } + [Fact] public void JettisonDropsTheBoostersOfASustainer() {