1#pragma once
2#include "../Modules/OrbitTrace.h"
3#include <map>
4
5using TraceTable=std::vector<std::map<std::string,std::string>>;
6TraceTable ReadFlightTrace(const std::filesystem::path& path)
7{
8 std::ifstream file(path,std::ios::binary);Check(bool(file),"CSV exists and can be read while open");
9 std::string text((std::istreambuf_iterator<char>(file)),{}),field;
10 std::vector<std::string> fields,header;TraceTable result;bool quoted=false;
11 for(size_t i=0;i<text.size();++i) {
12 const char ch=text[i];
13 if(ch=='"') {
14 if(quoted&&i+1<text.size()&&text[i+1]=='"') {field+='"';++i;}
15 else quoted=!quoted;
16 } else if(!quoted&&(ch==','||ch=='\n')) {
17 fields.push_back(field);field.clear();
18 if(ch=='\n') {
19 if(header.empty()) header=fields;
20 else {
21 Check(fields.size()==header.size(),"every trace row has exactly the header width");
22 std::map<std::string,std::string> row;
23 for(size_t j=0;j<fields.size();++j) row.emplace(header[j],fields[j]);
24 Check(row.size()==fields.size(),"trace headers are unique");result.push_back(std::move(row));
25 }
26 fields.clear();
27 }
28 } else field+=ch;
29 }
30 Check(!quoted&&field.empty()&&fields.empty(),"CSV ends at a complete row");return result;
31}
32void OrbitTraceTests()
33{
34 namespace fs=std::filesystem;
35 const fs::path directory="outputs/orbit-pass/trace-tests";
36
37 const auto run=directory/std::to_string(std::chrono::steady_clock::now().time_since_epoch().count());
38 auto in=Fixture();
auto r=Settings(in);
const auto s=
Solve(in,r);
39 in.targetName=L"TAC, \"test\"\n\u00c9\U0001f680";
40 Executor executor;auto g=executor.Begin(in,r,s);
41 Check(g.valid,"trace fixture is a real executable plan");
42 const auto command=g.deltaVelocity;
43 TraceContext c;c.dor=c.executorActive=true;c.programTime=100;c.moduleDt=.02;c.reference=-1;
44 c.rotation.frame.forward=
Unit(command);c.engineCount=3;
45 ActuationTelemetry a;a.Accumulate(1,{0,0,.02},{.001,0,0});
46 a.mainFuelKg=10;a.translationFuelKg=20;a.rotationFuelKg=30;a.idleFuelKg=40;
47 {
48 const auto restricted=run/L"not-admin";
49 FlightTrace gated;
50 for(bool manual:{false,true}) {
51 auto settings=r;settings.recordPreview=manual;
52 gated.Begin(restricted,in,settings,s,a);gated.Write(in,settings,s,g,c,a);
53 Check(!gated.Active()&&!fs::exists(restricted),"non-admin automatic and manual capture create no files");
54 }
55 for(Mode mode:{Mode::Target,Mode::Adjust,Mode::Rendezvous,Mode::Overfly,Mode::Return,Mode::Ascent})
56 for(bool ascent:{false,true}) {
57 const auto hidden=
Rows(r,mode,
false,ascent,
false),shown=
Rows(r,mode,
false,ascent,
true);
58 Check(std::find(hidden.begin(),hidden.end(),Row::Record)==hidden.end()&&
59 std::find(shown.begin(),shown.end(),Row::Record)!=shown.end(),"REC row is admin-only in every mission leg");
60 }
61 auto denied=r;
Edit(denied,Row::Record,1,s,in.now);
62 Check(!denied.recordPreview&&denied.revision==r.revision,"hidden REC action cannot enable recording without permission");
63 gated.Allow(true);gated.Begin(restricted,in,r,s,a);gated.Write(in,r,s,g,c,a);
64 const auto recorded=gated.Path();const auto count=ReadFlightTrace(recorded).size();
65 gated.Allow(false);gated.Write(in,r,s,g,c,a);
66 Check(!gated.Active()&&ReadFlightTrace(recorded).size()==count,"losing admin permission closes capture without another flight sample");
67 gated.Allow(true);gated.Write(in,r,s,g,c,a);
68 Check(!gated.Active()&&ReadFlightTrace(recorded).size()==count,"regaining permission does not resume an old capture");
69 Check(executor.Active()&&g.valid&&
Norm(g.deltaVelocity-command)==0,
"recording permission leaves active DOR guidance unchanged");
70 }
71 FlightTrace trace;trace.Allow(
true);trace.Begin(run,in,r,s,a);
const auto path=trace.Path();
72 trace.Write(in,r,s,g,c,a);
73 auto rows=ReadFlightTrace(path);Check(rows.size()==1&&rows[0]["event"]=="BEGIN","engagement immediately flushes initial sample");
74 Check(rows[0][
"target_name"]==
TraceUtf8(in.targetName),
"UTF-8 target name and CSV quotes/newlines round trip");
75 Check(std::stod(rows[0]["meet_in_s"])==s.plan.end,"capture holds original committed arrival");
76 Check(std::stod(rows[0]["arrival_duration_s"])==r.arrivalSeconds&&rows[0]["surface_duration_held"]=="0",
77 "trace distinguishes selected duration from the committed arrival deadline");
78 Check(std::stod(rows[0]["delivered_main_scalar_dv_mps"])==0,"impulse starts at engagement rather than process launch");
79 Check(std::stod(rows[0]["main_fuel_integrated_kg"])==0&&std::isnan(std::stod(rows[0]["meco_estimate_s"])),
80 "component fuel starts at capture and unknown MECO is NaN");
81 Check(std::abs(std::stod(rows[0]["terminal_lead_s"])-g.terminalLeadSeconds)<1e-9,"arrival lead is actual executor decision");
82 Check(
Norm(g.deltaVelocity-command)==0&&executor.Active(),
"trace does not mutate flight control");
83 const auto geometry=ReadFlightTrace(
path.parent_path()/(
path.stem().wstring()+L
"-plan.csv"));
84 Check(geometry.size()==s.ownPath.size()+s.targetPath.size()+s.plan.path.size()+s.plan.coast.size()+s.plan.goalPath.size()+s.plan.burns.size(),
85 "companion CSV retains all committed path points and burn locations");
86 Check(geometry.front().at("session")==rows[0]["session"],"plan and telemetry share a capture identity");
87
88 for(int i=0;i<5;++i) {a.Accumulate(.02,{0,0,.02},{.001,0,0});a.sequence++;c.programTime+=.02;trace.Write(in,r,s,g,c,a);}
89 Check(ReadFlightTrace(path).size()==1,"unchanged updates are throttled without dropping impulses");
90 a.mainFuelKg+=3;a.translationFuelKg+=2;a.rotationFuelKg+=1;a.idleFuelKg+=.1;
91 g.phase=Phase::Align;g.thrust=false;c.programTime+=.01;trace.Write(in,r,s,g,c,a);
92 rows=ReadFlightTrace(path);Check(rows.size()==2&&rows.back()["phase"]=="ALIGN","sub-sample phase change recorded immediately");
93 Check(std::abs(std::stod(rows.back()["delivered_main_scalar_dv_mps"])-2)<1e-9,"integrates all physics updates between rows");
94 Check(std::stod(rows.back()["main_fuel_integrated_kg"])==3&&
95 std::stod(rows.back()["translation_fuel_integrated_kg"])==2&&
96 std::stod(rows.back()["rotation_fuel_integrated_kg"])==1&&
97 std::abs(std::stod(rows.back()["idle_fuel_integrated_kg"])-.1)<1e-12,
98 "fuel components retain every physics update without pre-engagement consumption");
99 c.freeze=true;trace.Write(in,r,s,g,c,a);Check(ReadFlightTrace(path).back()["freeze"]=="1","freeze event retained at same simulation time");
100 c.freeze=false;c.reference=2;trace.Write(in,r,s,g,c,a);
101 Check(ReadFlightTrace(path).back()["reference"]=="2","bubble transition is recorded independently of docking");
102
103
104 in.now+=s.plan.end+1;c.programTime+=s.plan.end+1;g.phase=Phase::Arrive;g.maneuverPhase=Phase::Arrive;
105 g.remainingDeltaV=.0315;g.status=L"DOR ARRIVAL";a.valid=true;a.programTime=c.programTime-1;a.output[0]=.05;
106 trace.Write(in,r,s,g,c,a);rows=ReadFlightTrace(path);
107 Check(std::stod(rows.back()["meet_in_s"])==-1&&std::stod(rows.back()["range_km"])>100,
108 "missed encounter visible even when remaining command delta-V is small");
109 Check(rows.back()["coast_prediction_valid"]=="0"&&std::stod(rows.back()["physics_age_s"])==1,
110 "expired prediction and stale physics explicitly distinguished from zero miss");
111 ++r.revision;g=executor.Step(in,r);c.dor=c.executorActive=false;
112 trace.Write(in,r,s,g,c,a,true);rows=ReadFlightTrace(path);
113 Check(rows.back()["event"]=="END"&&rows.back()["guidance_status"]=="DOR: PLAN CHANGED"&&!trace.Active(),
114 "disconnect flushes its actual abort reason");
115 const auto summaryFixture=directory/L"synthetic-missed-encounter.csv";
116 fs::copy_file(path,summaryFixture,fs::copy_options::overwrite_existing);
117 const auto closedRows=rows.size();trace.Write(in,r,s,g,c,a);
118 Check(ReadFlightTrace(path).size()==closedRows,"disengaged recorder writes nothing");
119 for(int attempt=0;attempt<6;++attempt) {
120 trace.Begin(run,in,r,s,a);trace.Write(in,r,s,g,c,a,true);
121 Check(!trace.Failed()&&!trace.Active(),"repeated engagements get independent captures");
122 Check(ReadFlightTrace(trace.Path()).back()["event"]=="REJECTED","rejected engagement retains a terminal record");
123 Check(ReadFlightTrace(trace.Path()).front()["previous_phase"]=="OFF","new attempt does not inherit prior flight phase");
124 }
125 size_t samples=0,plans=0;
126 for(const auto& entry:fs::directory_iterator(run)) {
127 if(!entry.is_regular_file()) continue;
128 if(entry.path().stem().string().find("-plan")!=std::string::npos) ++plans;else ++samples;
129 }
130 Check(samples==4&&plans==4,"flight slot retention is bounded without touching unrelated files");
131 FlightTrace capped(65536);capped.Allow(true);c.dor=true;c.programTime=0;
132 capped.Begin(run/L"limit",in,r,s,a);const auto cappedPath=capped.Path();
133 for(int i=0;i<1000&&!capped.Limited();++i) {c.programTime+=1;g.thrust=!g.thrust;capped.Write(in,r,s,g,c,a);}
134 Check(capped.Limited()&&!capped.Failed()&&fs::file_size(cappedPath)<=65536,"size cap preserves departure and stops on complete row");
135 rows=ReadFlightTrace(cappedPath);Check(rows.front()["event"]=="BEGIN"&&rows.back()["event"]=="LIMIT","size cap is explicit in file");
136 capped.Write(in,r,s,g,c,a,true);Check(!capped.Active(),"limit does not prevent clean disarm");
137 const auto blocked=run/L"not-a-directory";{std::ofstream(blocked)<<"test";}
138 FlightTrace unavailable;unavailable.Allow(true);unavailable.Begin(blocked,in,r,s,a);unavailable.Write(in,r,s,g,c,a,true);
139 Check(unavailable.Failed()&&!unavailable.Active(),"file open failure is isolated from flight control");
140
141 const double impulse=a.totalImpulseKms;
142 a.Accumulate(-1,{0,0,1},{});a.Accumulate(NAN,{0,0,1},{});a.Accumulate(1,{NAN,0,0},{});
143 Check(a.totalImpulseKms==impulse,"invalid physics samples do not corrupt accumulated impulses");
144 {
145 auto launch=Fixture();launch.onGround=true;launch.freeFlight=false;
146 launch.own={{launch.radius,0,0},{0,launch.radius*launch.spin,0}};
147 auto capture=Settings(launch);
const auto noPlan=
Solve(launch,capture);
148 Check(noPlan.plan.path.empty()&&!noPlan.plan.valid&&noPlan.status==L"ASCENT DATA / CONFIG",
149 "ascent REC fixture without vehicle performance has no launch solution");
150 for(Mode mode:{Mode::Target,Mode::Adjust,Mode::Rendezvous,Mode::Overfly,Mode::Return}) {
151 const auto controls=
Rows(capture,mode,
false,
false,
true);
152 Check(std::find(controls.begin(),controls.end(),Row::Record)!=controls.end(),"REC is reachable in every objective");
153 }
154 Edit(capture,Row::Record,1,noPlan,launch.now,
false,
true);
155 Check(capture.recordPreview&&capture.recordFlightOnly&&
RowText(Row::Record,capture,noPlan,launch.now)==L
"REC ON (FLIGHT)",
156 "REC starts telemetry-only when no planned path exists");
157 const auto revision=capture.revision;
158 Edit(capture,Row::Arrival,1,noPlan,launch.now);
159 Check(capture.recordPreview&&!
EndManualCapture(capture,revision,
true,
false,
true),
160 "flight capture survives ATC target edits, planning edits and later DOR engagement");
161 Check(
EndManualCapture(capture,revision,
false,
true,
false),
"vehicle or simulation reset ends flight capture");
162 TraceContext context;context.programTime=10;context.pitchRad=15*
Pi/180;context.aoaRad=3*
Pi/180;
163 context.gear=1;context.flaps=.5;context.measuredLoadG={0,1,0};
164 context.rotation.frame={{0,0,1},{1,0,0},{0,1,0}};
165 ActuationTelemetry physics;physics.airSampleTime=10;physics.airVelocityBodyKms={0,0,.2};
166 physics.lever[0]=.5;physics.output[0]=.45;
167 FlightTrace ascent;ascent.Allow(true);ascent.Begin(run/L"ascent",launch,capture,noPlan,physics);
168 Guidance passive;ascent.Write(launch,capture,noPlan,passive,context,physics);
169 const auto ascentPath=ascent.Path();auto flightRows=ReadFlightTrace(ascentPath);
170 Check(flightRows[0]["schema"]=="6"&&flightRows[0]["capture_kind"]=="MANUAL_FLIGHT"&&flightRows[0]["plan_reference_available"]=="0",
171 "unplanned ascent has explicit flight-only identity");
172 Check(std::isnan(std::stod(flightRows[0]["meet_in_s"]))&&flightRows[0]["coast_prediction_valid"]=="0"&&flightRows[0]["entry_reference_valid"]=="0",
173 "no plan means no fictional arrival deadline or reference error");
174 Check(std::abs(std::stod(flightRows[0]["pitch_actual_deg"])-15)<1e-9&&
175 std::abs(std::stod(flightRows[0]["aoa_deg"])-3)<1e-9&&flightRows[0]["flap_fraction"]=="0.5",
176 "actual pitch, AoA and configuration are recorded independently");
177 const auto startGeometry=ReadFlightTrace(ascentPath.parent_path()/(ascentPath.stem().wstring()+L"-plan.csv"));
178 Check(startGeometry.front().at("path")=="capture_start","plan-less companion retains capture origin rather than an empty file");
179 for(double altitude:{.1,30.,99.9,100.1,500.}) {
180 launch.now+=60;context.programTime+=60;launch.onGround=false;launch.freeFlight=true;
181 launch.own={{launch.radius+altitude,0,0},{.1,4,0}};
182 ++launch.targetId;physics.airSampleTime=context.programTime;
183 const auto live=
Solve(launch,capture);ascent.Write(launch,capture,live,passive,context,physics);
184 Check(ascent.Active(),"manual capture continues through liftoff, atmospheric climb and insertion");
185 }
186 context.dor=context.executorActive=true;passive.phase=Phase::Depart;passive.valid=passive.thrust=true;
187 context.programTime+=1;launch.now+=1;
188 ascent.Write(launch,capture,
Solve(launch,capture),passive,context,physics);
189 flightRows=ReadFlightTrace(ascentPath);
190 Check(flightRows.back()["dor"]=="1"&&flightRows.back()["capture_kind"]=="MANUAL_FLIGHT"&&
191 flightRows.back()["plan_reference_available"]=="0","insertion guidance is observed without replacing the ascent recording");
192 Check(flightRows.back()["air_sample_fresh"]=="0"&&std::isnan(std::stod(flightRows.back()["aoa_deg"])),
193 "stale air data is distinguishable from current aerodynamic evidence");
194 Check(std::abs(std::stod(flightRows.back()["vertical_speed_kms"])-.1)<1e-9&&
195 std::abs(std::stod(flightRows.back()["tangential_inertial_speed_kms"])-4)<1e-9,"radial and tangential velocities have explicit units");
196 Edit(capture,Row::Record,1,noPlan,launch.now,
false,
true);
197 Check(
EndManualCapture(capture,revision,
false,
false,
false),
"REC OFF ends the continuous flight capture");
198 ascent.Write(launch,capture,noPlan,passive,context,physics,true);
199 Check(!ascent.Active()&&ReadFlightTrace(ascentPath).back()["event"]=="END","ascent log is flushed on explicit stop");
200 fs::copy_file(ascentPath,directory/L"synthetic-ascent.csv",fs::copy_options::overwrite_existing);
201 Request reference;reference.recordPreview=true;
203 "reference capture still stops for target changes or automatic execution");
204
205 BusState display;display.snapshot=s;display.snapshot.mode=Mode::Adjust;display.request=r;
206 display.request.adjust=true;display.request.lock=Lock::None;display.request.start=Start::Time;
207 for(Start start:{Start::Now,Start::Time}) {
208 display.request.start=start;
209 for(
const auto& label:
Readouts(display,
Rows(display.request,Mode::Adjust,
false,
false,
true),0,
false))
210 if(label.text.find(L"FUEL ")==0) Check(label.y+12<=266,"REC row does not overlap the orbital fuel/caution readouts");
211 }
212 }
213
214
215 {
216 auto launch=Fixture();Request ascentRequest;ascentRequest.ascent=true;
217 Snapshot ascentSnapshot;ascentSnapshot.mode=Mode::Ascent;
218 Guidance ascentGuidance;ascentGuidance.valid=ascentGuidance.thrust=ascentGuidance.ascentControl=true;
219 ascentGuidance.phase=Phase::Depart;ascentGuidance.ascentMain=.5;ascentGuidance.ascentNormal=.12;
220 TraceContext context;context.dor=context.executorActive=true;context.programTime=20;context.verticalMode=2;
221 ActuationTelemetry physics;FlightTrace ascent;ascent.Allow(true);
222 physics.ascentPitchActive=true;physics.elevator=.23;physics.pitchExternalMoment=-2500000;
223 physics.pitchTailMoment=1000000;physics.pitchRcsMoment=1600000;physics.pitchResidualMoment=0;
224 physics.aeroBodyKms2={0,.004,-.001};physics.aeroSampleTime=19.9;
225 ascent.Begin(run,launch,ascentRequest,ascentSnapshot,physics);
226 ascent.Write(launch,ascentRequest,ascentSnapshot,ascentGuidance,context,physics);
227 auto ascentRows=ReadFlightTrace(ascent.Path());
228 Check(ascentRows.back()["ascent_controller"]=="1"&&ascentRows.back()["afcs_vertical_name"]=="FPA",
229 "automated ascent and renumbered FPA are explicit in CSV");
230 Check(std::stod(ascentRows.back()["ascent_main_command"])==.5&&
231 std::stod(ascentRows.back()["ascent_normal_command"])==.12,"ascent main and vertical commands remain distinct");
232 Check(ascentRows.back()["ascent_pitch_surfaces"]=="1"&&std::stod(ascentRows.back()["elevator_deflection"])==.23&&
233 std::stod(ascentRows.back()["pitch_external_lb_m"])==-2500000&&std::stod(ascentRows.back()["pitch_rcs_lb_m"])==1600000&&
234 std::stod(ascentRows.back()["aero_body_kms2_y"])==.004,"CSV records actual lift and surface/RCS pitch allocation");
235 context.programTime+=1;context.dor=context.executorActive=false;ascentGuidance.phase=Phase::Complete;
236 ascentGuidance.status=L"INSERTION COMPLETE / REPLAN";
237 ascent.Write(launch,ascentRequest,ascentSnapshot,ascentGuidance,context,physics,true);
238 fs::copy_file(ascent.Path(),directory/L"synthetic-automated-ascent.csv",fs::copy_options::overwrite_existing);
239 }
240 std::cout<<"Trace tests: "<<run.string()<<"\n";
241}
Plan Solve(const Input &in, const Request &r, bool geometry)
bool EndManualCapture(const Request &r, std::uint64_t revision, bool changed, bool reset, bool begin)
std::wstring RowText(Row row, const Request &r, const Snapshot &s, double now)
std::vector< Row > Rows(const Request &r, Mode mode, bool entry=false, bool ascent=false, bool recordingAllowed=false)
std::vector< Label > Readouts(const BusState &data, const std::vector< Row > &rows, int uiRow, bool dorActive, bool showKeys=true)
void Edit(Request &r, Row row, int direction, const Snapshot &s, double now, bool circularize=false, bool recordingAllowed=false)
std::string TraceUtf8(const std::wstring &value)