namespace XFEEDToolBox.Core.Navigation;
/// <summary>A live, ship/axis-specific first-order angular response, in degrees and seconds.</summary>
public sealed record AxisResponse(double MaximumRate,double TimeConstant,double InputDelay,double FitError,int Samples,bool Calibrated)
{
// An unmeasured ship starts with low authority; this is a bound, not a ship specification.
public static AxisResponse Unknown { get; }=new(400,.08,.12,0,0,false);
public double Acceleration=>MaximumRate/TimeConstant;
public double StoppingAngle(double rate)=>InputDelay*Math.Abs(rate)+TimeConstant*(Math.Abs(rate)-MaximumRate*Math.Log(1+Math.Abs(rate)/MaximumRate));
}
/// <summary>
/// Fits rate(t+dt)=rate(t)*exp(-dt/tau)+K*u(t-delay)*(1-exp(-dt/tau)).
/// Uses only ordinary, acknowledged steering: it never injects calibration manoeuvres.
/// Each axis and ship/flight-mode has its own fit. No shared yaw/pitch/roll gains.
/// </summary>
public sealed class AxisResponseEstimator
{
private readonly record struct Sample(double Time,double Rate);
private readonly record struct Command(double Time,double Value);
private readonly List<Sample> samples=[];
private readonly List<Command> commands=[];
private double lastFit=double.NegativeInfinity;
public AxisResponse Response { get; private set; }=AxisResponse.Unknown;
public void Relearn(){BreakObservation();Response=AxisResponse.Unknown;}
public void BreakObservation(){samples.Clear();commands.Clear();lastFit=double.NegativeInfinity;}
public void Acknowledge(double time,double command)
{
if(!double.IsFinite(time)||!double.IsFinite(command)||Math.Abs(command)>1)throw new ArgumentException("Invalid acknowledged steering.");
if(commands.Count>0&&time<commands[^1].Time)throw new ArgumentException("Steering acknowledgement went backwards.");
commands.Add(new(time,command));
}
public void Observe(double time,double rate)
{
if(!double.IsFinite(time)||!double.IsFinite(rate)||Math.Abs(rate)>600)throw new ArgumentException("Invalid measured angular rate.");
if(samples.Count>0&&(time<=samples[^1].Time||time-samples[^1].Time>.3))BreakObservation();
samples.Add(new(time,rate));
samples.RemoveAll(s=>s.Time<time-5);
if(commands.Count>1){var keep=commands.FindLastIndex(c=>c.Time<time-5.5);if(keep>0)commands.RemoveRange(0,keep);}
if(samples.Count<16||commands.Count<2||time-samples[0].Time<.7||time-lastFit<.4)return;
lastFit=time;
Fit();
}
private double InputAt(double time)
{
var lo=0;var hi=commands.Count-1;
if(hi<0||commands[0].Time>time)return double.NaN;
while(lo<hi){var mid=(lo+hi+1)/2;if(commands[mid].Time<=time)lo=mid;else hi=mid-1;}
return commands[lo].Value;
}
public (double Rate,double Angle) PredictQueuedInputs(double time,double rate,double horizon)
{
double angle=0;
for(double elapsed=0;elapsed<horizon;)
{
var dt=Math.Min(.01,horizon-elapsed);
var input=InputAt(time+elapsed+dt*.5-Response.InputDelay);
if(!double.IsFinite(input))input=0;
var desired=Response.MaximumRate*input;var decay=Math.Exp(-dt/Response.TimeConstant);
angle+=desired*dt+(rate-desired)*Response.TimeConstant*(1-decay);
rate=desired+(rate-desired)*decay;elapsed+=dt;
}
return(rate,angle);
}
private void Fit()
{
var minimum=samples.Min(s=>s.Rate);var maximum=samples.Max(s=>s.Rate);
if(maximum-minimum<.025||commands.Max(c=>Math.Abs(c.Value))<.006)return;
var best=double.PositiveInfinity;AxisResponse? fitted=null;
// The interval is deliberately fitted as well: IPC latency and the original
// physics input consumer can vary independently of a ship's turn speed.
foreach(var delay in new[]{0,.025,.05,.075,.1,.15,.2,.25})
{
var rows=new List<(double Dt,double Before,double After,double Input)>();
for(var i=1;i<samples.Count;i++)
{
var before=samples[i-1];var after=samples[i];var dt=after.Time-before.Time;
var input=InputAt((before.Time+after.Time)*.5-delay);
if(dt is >=.005 and <=.2&&double.IsFinite(input))rows.Add((dt,before.Rate,after.Rate,input));
}
if(rows.Count<12)continue;
foreach(var tau in new[]{.025,.04,.06,.08,.12,.18,.25,.35,.5,.75,1.0,1.25})
{
double numerator=0,denominator=0;
foreach(var row in rows)
{
var decay=Math.Exp(-row.Dt/tau);var a=row.Input*(1-decay);var b=row.After-row.Before*decay;
numerator+=a*b;denominator+=a*a;
}
if(denominator<1e-7)continue;
var rate=numerator/denominator;if(rate is <.5 or >600)continue;
double square=0;
foreach(var row in rows)
{
var decay=Math.Exp(-row.Dt/tau);var residual=row.After-row.Before*decay-rate*row.Input*(1-decay);
square+=residual*residual;
}
var error=Math.Sqrt(square/rows.Count);
// Prefer a smaller delay when fits are indistinguishable; a
// stationary segment alone must not invent a large input lag.
var score=error+delay*.0001;
if(score<best){best=score;fitted=new(rate,tau,delay,error,rows.Count,true);}
}
}
if(fitted is {} value&&value.FitError<Math.Max(.15,(maximum-minimum)*.08))Response=value;
}
}
/// <summary>Predictive rate control with a measured stopping angle and a quiet alignment band.</summary>
internal sealed class AdaptiveAttitudeAxis
{
public AxisResponseEstimator Model { get; }=new();
private bool settled;
public void BreakObservation(){settled=false;Model.BreakObservation();}
public double Control(double error,double rate,double time,double dt,bool enabled=true)
{
if(!enabled){settled=false;error=0;}
if(Math.Abs(error)<.10&&Math.Abs(rate)<.16)settled=true;
else if(Math.Abs(error)>.28||Math.Abs(rate)>.4)settled=false;
if(settled)return 0;
var model=Model.Response;
if(!model.Calibrated)return Math.Clamp((Math.Clamp(error/.7,-8,8)-rate*2)/model.MaximumRate,-.1,.1);
var delay=model.InputDelay+Math.Clamp(dt*.5,.005,.06);
var prediction=Model.PredictQueuedInputs(time,rate,delay);
var predictedRate=prediction.Rate;var predictedError=error-prediction.Angle;
var responseSeconds=Math.Max(.55,delay*3+.3);
var wantedRate=predictedError/responseSeconds;
var speedLimit=model.Calibrated?model.MaximumRate*.9:8;
// Reserve angular stopping distance before reaching the selected heading.
speedLimit=Math.Min(speedLimit,Math.Sqrt(2*model.Acceleration*Math.Abs(predictedError))*.7);
wantedRate=Math.Clamp(wantedRate,-speedLimit,speedLimit);
var horizon=Math.Max(.10,dt*2);
var decay=Math.Exp(-horizon/model.TimeConstant);
return Math.Clamp((wantedRate-predictedRate*decay)/(model.MaximumRate*(1-decay)),-1,1);
}
}
namespace XFEEDToolBox.Core.Navigation;
/// <summary>A live, ship/axis-specific first-order angular response, in degrees and seconds.</summary>
public sealed record AxisResponse(double MaximumRate,double TimeConstant,double InputDelay,double FitError,int Samples,bool Calibrated)
{
// An unmeasured ship starts with low authority; this is a bound, not a ship specification.
public static AxisResponse Unknown { get; }=new(400,.08,.12,0,0,false);
public double Acceleration=>MaximumRate/TimeConstant;
public double StoppingAngle(double rate)=>InputDelay*Math.Abs(rate)+TimeConstant*(Math.Abs(rate)-MaximumRate*Math.Log(1+Math.Abs(rate)/MaximumRate));
}
/// <summary>
/// Fits rate(t+dt)=rate(t)*exp(-dt/tau)+K*u(t-delay)*(1-exp(-dt/tau)).
/// Uses only ordinary, acknowledged steering: it never injects calibration manoeuvres.
/// Each axis and ship/flight-mode has its own fit. No shared yaw/pitch/roll gains.
/// </summary>
public sealed class AxisResponseEstimator
{
private readonly record struct Sample(double Time,double Rate);
private readonly record struct Command(double Time,double Value);
private readonly List<Sample> samples=[];
private readonly List<Command> commands=[];
private double lastFit=double.NegativeInfinity;
public AxisResponse Response { get; private set; }=AxisResponse.Unknown;
public void Relearn(){BreakObservation();Response=AxisResponse.Unknown;}
public void BreakObservation(){samples.Clear();commands.Clear();lastFit=double.NegativeInfinity;}
public void Acknowledge(double time,double command)
{
if(!double.IsFinite(time)||!double.IsFinite(command)||Math.Abs(command)>1)throw new ArgumentException("Invalid acknowledged steering.");
if(commands.Count>0&&time<commands[^1].Time)throw new ArgumentException("Steering acknowledgement went backwards.");
commands.Add(new(time,command));
}
public void Observe(double time,double rate)
{
if(!double.IsFinite(time)||!double.IsFinite(rate)||Math.Abs(rate)>600)throw new ArgumentException("Invalid measured angular rate.");
if(samples.Count>0&&(time<=samples[^1].Time||time-samples[^1].Time>.3))BreakObservation();
samples.Add(new(time,rate));
samples.RemoveAll(s=>s.Time<time-5);
if(commands.Count>1){var keep=commands.FindLastIndex(c=>c.Time<time-5.5);if(keep>0)commands.RemoveRange(0,keep);}
if(samples.Count<16||commands.Count<2||time-samples[0].Time<.7||time-lastFit<.4)return;
lastFit=time;
Fit();
}
private double InputAt(double time)
{
var lo=0;var hi=commands.Count-1;
if(hi<0||commands[0].Time>time)return double.NaN;
while(lo<hi){var mid=(lo+hi+1)/2;if(commands[mid].Time<=time)lo=mid;else hi=mid-1;}
return commands[lo].Value;
}
public (double Rate,double Angle) PredictQueuedInputs(double time,double rate,double horizon)
{
double angle=0;
for(double elapsed=0;elapsed<horizon;)
{
var dt=Math.Min(.01,horizon-elapsed);
var input=InputAt(time+elapsed+dt*.5-Response.InputDelay);
if(!double.IsFinite(input))input=0;
var desired=Response.MaximumRate*input;var decay=Math.Exp(-dt/Response.TimeConstant);
angle+=desired*dt+(rate-desired)*Response.TimeConstant*(1-decay);
rate=desired+(rate-desired)*decay;elapsed+=dt;
}
return(rate,angle);
}
private void Fit()
{
var minimum=samples.Min(s=>s.Rate);var maximum=samples.Max(s=>s.Rate);
if(maximum-minimum<.025||commands.Max(c=>Math.Abs(c.Value))<.006)return;
var best=double.PositiveInfinity;AxisResponse? fitted=null;
// The interval is deliberately fitted as well: IPC latency and the original
// physics input consumer can vary independently of a ship's turn speed.
foreach(var delay in new[]{0,.025,.05,.075,.1,.15,.2,.25})
{
var rows=new List<(double Dt,double Before,double After,double Input)>();
for(var i=1;i<samples.Count;i++)
{
var before=samples[i-1];var after=samples[i];var dt=after.Time-before.Time;
var input=InputAt((before.Time+after.Time)*.5-delay);
if(dt is >=.005 and <=.2&&double.IsFinite(input))rows.Add((dt,before.Rate,after.Rate,input));
}
if(rows.Count<12)continue;
foreach(var tau in new[]{.025,.04,.06,.08,.12,.18,.25,.35,.5,.75,1.0,1.25})
{
double numerator=0,denominator=0;
foreach(var row in rows)
{
var decay=Math.Exp(-row.Dt/tau);var a=row.Input*(1-decay);var b=row.After-row.Before*decay;
numerator+=a*b;denominator+=a*a;
}
if(denominator<1e-7)continue;
var rate=numerator/denominator;if(rate is <.5 or >600)continue;
double square=0;
foreach(var row in rows)
{
var decay=Math.Exp(-row.Dt/tau);var residual=row.After-row.Before*decay-rate*row.Input*(1-decay);
square+=residual*residual;
}
var error=Math.Sqrt(square/rows.Count);
// Prefer a smaller delay when fits are indistinguishable; a
// stationary segment alone must not invent a large input lag.
var score=error+delay*.0001;
if(score<best){best=score;fitted=new(rate,tau,delay,error,rows.Count,true);}
}
}
if(fitted is {} value&&value.FitError<Math.Max(.15,(maximum-minimum)*.08))Response=value;
}
}
/// <summary>Predictive rate control with a measured stopping angle and a quiet alignment band.</summary>
internal sealed class AdaptiveAttitudeAxis
{
public AxisResponseEstimator Model { get; }=new();
private bool settled;
public void BreakObservation(){settled=false;Model.BreakObservation();}
public double Control(double error,double rate,double time,double dt,bool enabled=true)
{
if(!enabled){settled=false;error=0;}
if(Math.Abs(error)<.10&&Math.Abs(rate)<.16)settled=true;
else if(Math.Abs(error)>.28||Math.Abs(rate)>.4)settled=false;
if(settled)return 0;
var model=Model.Response;
if(!model.Calibrated)return Math.Clamp((Math.Clamp(error/.7,-8,8)-rate*2)/model.MaximumRate,-.1,.1);
var delay=model.InputDelay+Math.Clamp(dt*.5,.005,.06);
var prediction=Model.PredictQueuedInputs(time,rate,delay);
var predictedRate=prediction.Rate;var predictedError=error-prediction.Angle;
var responseSeconds=Math.Max(.55,delay*3+.3);
var wantedRate=predictedError/responseSeconds;
var speedLimit=model.Calibrated?model.MaximumRate*.9:8;
// Reserve angular stopping distance before reaching the selected heading.
speedLimit=Math.Min(speedLimit,Math.Sqrt(2*model.Acceleration*Math.Abs(predictedError))*.7);
wantedRate=Math.Clamp(wantedRate,-speedLimit,speedLimit);
var horizon=Math.Max(.10,dt*2);
var decay=Math.Exp(-horizon/model.TimeConstant);
return Math.Clamp((wantedRate-predictedRate*decay)/(model.MaximumRate*(1-decay)),-1,1);
}
}