SGYWFTP/src/server/gmat_runner.ts
2026-11-15 13:02:03 +03:00

320 lines
7.5 KiB
TypeScript

// Runs GMAT console trajectories asynchronously with analytic Keplerian ephemeris fallback.
// So like.
import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import { config } from "./config.js";
import {
enrichTrajectoryPoint,
generateTrajectory,
orbitForTarget,
} from "../shared/ephemeris.js";
import type { TrajectoryPoint, TrajectoryResult } from "../shared/types.js";
const execFileAsync = promisify(execFile);
interface GmatTargetDef {
sma: number;
ecc: number;
inc: number;
raan: number;
aop: number;
ta: number;
days: number;
body: "Earth" | "Sun";
}
const TARGET_ORBITS: Record<string, GmatTargetDef> = {
vleo: {
sma: 6611,
ecc: 0.002,
inc: 51.6,
raan: 120,
aop: 80,
ta: 0,
days: 0.35,
body: "Earth",
},
leo: {
sma: 6791,
ecc: 0.002,
inc: 51.6,
raan: 120,
aop: 80,
ta: 0,
days: 0.45,
body: "Earth",
},
sso: {
sma: 7076,
ecc: 0.001,
inc: 98.2,
raan: 100,
aop: 80,
ta: 0,
days: 0.5,
body: "Earth",
},
geo: {
sma: 42164,
ecc: 0.0005,
inc: 0.5,
raan: 0,
aop: 0,
ta: 0,
days: 1.0,
body: "Earth",
},
l1: {
sma: 750000,
ecc: 0.985,
inc: 28.5,
raan: 45,
aop: 160,
ta: 0,
days: 12,
body: "Earth",
},
lunar: {
sma: 192000,
ecc: 0.96,
inc: 28.5,
raan: 60,
aop: 180,
ta: 0,
days: 10,
body: "Earth",
},
mars: {
sma: 188800000,
ecc: 0.21,
inc: 1.85,
raan: 49.5,
aop: 336.06,
ta: 0,
days: 180,
body: "Sun",
},
asteroid: {
sma: 158500000,
ecc: 0.14,
inc: 6.0,
raan: 2.0,
aop: 66.2,
ta: 0,
days: 150,
body: "Sun",
},
jupiter: {
sma: 463700000,
ecc: 0.68,
inc: 1.3,
raan: 100.5,
aop: 273.8,
ta: 0,
days: 420,
body: "Sun",
},
solar: {
sma: 83800000,
ecc: 0.78,
inc: 3.4,
raan: 45,
aop: 120,
ta: 0,
days: 120,
body: "Sun",
},
};
const N_CHUNKS = 200;
function buildGmatScript(def: GmatTargetDef): string {
const isHelio = def.body === "Sun";
const coordSys = isHelio ? "SunMJ2000Eq" : "EarthMJ2000Eq";
const pointMasses = isHelio
? "{Earth, Luna, Mars, Jupiter, Sun}"
: "{Earth, Luna, Sun}";
const lines = [
"% Auto-generated Space Gaem trajectory script",
...(isHelio
? [
"Create CoordinateSystem SunMJ2000Eq;",
"SunMJ2000Eq.Origin = Sun;",
"SunMJ2000Eq.Axes = MJ2000Eq;",
"",
]
: []),
"Create Spacecraft SC;",
"SC.DateFormat = UTCGregorian;",
"SC.Epoch = '01 Jan 2026 00:00:00.000';",
`SC.CoordinateSystem = ${coordSys};`,
"SC.DisplayStateType = Keplerian;",
"SC.AnomalyType = TA;",
`SC.SMA = ${def.sma};`,
`SC.ECC = ${def.ecc};`,
`SC.INC = ${def.inc};`,
`SC.RAAN = ${def.raan};`,
`SC.AOP = ${def.aop};`,
`SC.TA = ${def.ta};`,
"SC.DryMass = 1000;",
"",
"Create ForceModel FM;",
`FM.CentralBody = ${def.body};`,
`FM.PointMasses = ${pointMasses};`,
"FM.Drag = None;",
"FM.SRP = Off;",
"FM.ErrorControl = RSSStep;",
"",
"Create Propagator PROP;",
"PROP.FM = FM;",
"PROP.Type = RungeKutta89;",
"PROP.InitialStepSize = 60;",
"PROP.Accuracy = 1e-10;",
"PROP.MinStep = 0.001;",
"PROP.MaxStep = 86400;",
"PROP.MaxStepAttempts = 50;",
"",
"BeginMissionSequence",
"",
];
const chunkDays = def.days / N_CHUNKS;
for (let i = 0; i < N_CHUNKS; i++) {
lines.push(`Propagate PROP(SC) {SC.ElapsedDays = ${chunkDays.toFixed(8)}}`);
lines.push(
`Write SC.UTCGregorian SC.${coordSys}.X SC.${coordSys}.Y SC.${coordSys}.Z`,
);
}
lines.push("");
return lines.join("\n");
}
function parseGmatStdout(stdout: string): TrajectoryPoint[] {
const lines = stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const points: TrajectoryPoint[] = [];
for (let i = 0; i + 3 < lines.length; i++) {
const x = Number(lines[i + 1]);
const y = Number(lines[i + 2]);
const z = Number(lines[i + 3]);
if (
Number.isFinite(x) &&
Number.isFinite(y) &&
Number.isFinite(z) &&
/[A-Z][a-z]{2}/.test(lines[i])
) {
points.push({ t: points.length, x, y, z });
i += 3;
}
}
return points;
}
export function resolveGmatConsoleBin(): string | null {
if (config.gmatConsoleBin) {
return fs.existsSync(config.gmatConsoleBin) ? config.gmatConsoleBin : null;
}
const gmatDir = path.dirname(config.gmatBin);
if (fs.existsSync(gmatDir)) {
const found = fs
.readdirSync(gmatDir)
.find((f) => /^GmatConsole/.test(f) && !f.includes(".so"));
if (found) return path.join(gmatDir, found);
}
return null;
}
export async function runTrajectory(
target: string,
opts: { altKm?: number; incDeg?: number } = {},
): Promise<TrajectoryResult> {
const key = target === "moon-landing" ? "lunar" : target;
const baseDef = TARGET_ORBITS[key] ?? TARGET_ORBITS.leo;
const def: GmatTargetDef = {
...baseDef,
sma:
baseDef.body === "Earth" &&
opts.altKm &&
key !== "lunar" &&
key !== "l1" &&
key !== "geo"
? 6371 + opts.altKm
: baseDef.sma,
inc: opts.incDeg ?? baseDef.inc,
};
const durationSec = def.days * 86400;
const analytic = generateTrajectory(key, durationSec, 280, opts);
const consoleBin = resolveGmatConsoleBin();
if (!consoleBin) {
return {
...analytic,
source: "analytic",
reason: "GMAT console binary not available",
};
}
const gmatDir = path.dirname(consoleBin);
fs.mkdirSync(config.gmatWorkDir, { recursive: true });
const baseName = `${key}-${Date.now()}-${Math.floor(Math.random() * 999)}`;
const scriptPath = path.join(config.gmatWorkDir, `${baseName}.script`);
const logPath = path.join(config.gmatWorkDir, `${baseName}.log`);
const cleanup = () => {
fs.unlink(scriptPath, () => {});
fs.unlink(logPath, () => {});
};
try {
fs.writeFileSync(scriptPath, buildGmatScript(def));
const { stdout } = await execFileAsync(
consoleBin,
["-l", logPath, "-r", scriptPath],
{
cwd: gmatDir,
timeout: 30_000,
maxBuffer: 32 * 1024 * 1024,
},
);
cleanup();
const points = parseGmatStdout(stdout);
if (points.length > 10) {
const orb = orbitForTarget(key, opts);
const enriched = points.map((p, idx) => {
const t = (idx / (points.length - 1)) * durationSec;
const analyticPt =
analytic.points[
Math.min(
analytic.points.length - 1,
Math.round(
(idx / (points.length - 1)) * (analytic.points.length - 1),
),
)
];
const rGmat = Math.hypot(p.x, p.y, p.z);
const rAnalytic = analyticPt
? Math.hypot(analyticPt.x, analyticPt.y, analyticPt.z)
: rGmat;
const radialDrift = Math.abs(rGmat - rAnalytic);
return enrichTrajectoryPoint(orb, t, p.x, p.y, p.z, radialDrift);
});
return {
points: enriched,
period: analytic.period,
target: key,
source: "gmat",
};
}
return {
...analytic,
source: "analytic",
reason: `GMAT returned ${points.length} points`,
};
} catch (err) {
cleanup();
return {
...analytic,
source: "analytic",
reason: String((err as Error).message ?? err).slice(0, 160),
};
}
}