Projects
Projects / space_state

space_state

A spacecraft trajectory simulator written from scratch in Python, plus the start of a real-time guidance computer on a Teensy 4.1. It plans maneuvers with classical orbital mechanics, then flies them as finite burns through the real solar system's gravity.

November–December 2025 Personal research project Python · C++ / FreeRTOS wjhdfnmf/space_state
7.9 daysEarth-to-Moon flight, captured in lunar orbit
7 bodiesat real NASA JPL DE440 positions
±0.1 km100 km lunar orbit held over 24 h
~3,800lines: 3,500 Python + 300 C++

Overview

space_state is a personal research project I built in my spare time in late 2025: about 3,500 lines of Python and 300 lines of C++. The simulator flies a spacecraft through the real solar system:

  • Gravity from the Sun, Earth, Moon, Venus, Mars, Jupiter and Saturn, at their true positions from NASA JPL's DE440 ephemeris.
  • Maneuvers planned with classical orbital mechanics: Hohmann transfers, plane changes, a departure-window search for Moon intercept.
  • Burns flown as finite burns with real engine models, with the ship's mass draining as it burns.
  • Hardware: a Teensy 4.1 running FreeRTOS that receives the simulated state over 2 Mbaud USB serial and logs it to SD — the first step toward hardware-in-the-loop guidance.

Re-run in November 2026, the full mission works. A simulated SpaceX Starship leaves a 400 km Earth orbit, changes plane, burns for the Moon and is captured into a stable lunar orbit after a 7.9-day flight. A second scenario holds a 100 km lunar orbit to within 0.1 km of altitude for a full day of N-body simulation.

Timeline

From first commit to a working Earth-to-Moon mission took 11 days, November 21 to December 1, 2025, in eight commits. The first commit already held 2,440 lines, so earlier work came before it.

DateLines + / −What changed
Dec 1+1,004 / −259Lunar orbit insertion and the full Earth-to-Moon scenario; lunar-orbit test; 3D and orbital-plane views
Nov 29+21 / −25Fixes; departure-vs-distance plot
Nov 28+127 / −168Maneuver-planning cleanup
Nov 28+468 / −117Orbital-element tools; LaTeX formula reference
Nov 27+230 / −73Departure-window search with a progress bar
Nov 27+1,498 / −1,492Guidance rewritten: ZEM/ZEV finite-burn guidance v2 and orbital-mechanics tools
Nov 23+901 / −438Reorganized into base / guidance / visual packages; 3D plots; firmware quaternion test
Nov 21+2,440First commit: propagator, ship model, guidance, tests, 2D plots, Teensy firmware

Architecture

Each maneuver is planned analytically, turned into a timed finite burn, then flown by numerical integration through real solar-system gravity.

Flow: mission script orders the burns, maneuver planner computes them, burn controller turns delta-v into a burn window, propagator integrates with DOP853 calling the 7-body dynamics every step, and results feed the plots
How one maneuver flows through the simulator.
PartWhat it does
State & dynamics
base/star_dynamics.py
Position, velocity and mass in the Solar System Barycentric frame (AU, AU/day, kg). Gravity summed over 7 bodies at their DE440 positions, plus thrust and mass flow.
Propagator
base/star_propagator.py
SciPy solve_ivp with DOP853 (8th-order Runge–Kutta) at 1e-9 tolerance; step capped at 1 minute, 2 s during burns. Appends each leg into one result across mission phases.
Spacecraft & engines
base/star_ship.py
Throttleable thrusters with thrust, specific impulse and mass flow. Presets: Starship (3 Raptor Vacuum), Centaur III (RL10), Agena (Bell 8096).
Maneuver planning
base/star_states.py
Circular orbits around any body, Hohmann transfers, circularization at apoapsis, plane change at the ascending node, a departure-time sweep for Moon intercept, lunar orbit insertion.
Orbital-element tools
guidance/star_tools.py
Inclination, eccentricity, energy, semi-major axis, vis-viva, period, nodes, time to apoapsis, burn duration from the rocket equation.
Guidance
guidance/
A burn controller that turns a maneuver (Δv, centre time, direction) into a burn window and thrust commands; plus experimental ZEM/ZEV closed-loop guidance.
Flight computer
src/
Teensy 4.1 firmware on FreeRTOS: a receive task reads 56-byte state packets (7 doubles) over 2 Mbaud USB serial; a guidance task logs them to SD every 100 ms.
Reference
document/document.tex
A LaTeX write-up of every orbital-mechanics formula the code uses.

The Earth-to-Moon mission

Starship with three Raptor Vacuum engines: 1,220 t at start (120 t dry, 1,100 t propellant), beginning in a 400 km circular Earth orbit, with seven-body gravity throughout. Simulating 7.9 days takes 237 s.

BurnMission timeΔvLengthResult
1. Plane change at the ascending node0.03 d3,762 m/s370 sInclination changed 28.4° to match the Moon's plane
2. Trans-lunar injection0.07 d3,086 m/s120 sApoapsis raised from 6,772 km to near the Moon's distance
3. Lunar orbit insertion5.14 d—21 s36,249 km from the Moon, 0.51 km/s relative
4. Circularization at closest approach5.89 d312 m/s6 s6,424 km above the Moon at circular speed

Outcome: for the final two days of coasting the ship stays between 6,417 and 6,449 km above the Moon, and its energy relative to the Moon stays negative (−0.30 km²/s²), so it is captured. The mission used 1,082 t of propellant, 98.4% of the tank — most of it on the 28.4° plane change, which costs more than the trans-lunar injection itself.

Diagram of the plane change: the equatorial starting orbit rotated into the Moon's orbital plane at the ascending node
Burn 1, the plane change. The equatorial starting orbit (dashed) is rotated into the Moon's orbital plane (shaded) at the ascending node. The simulation flies 28.2° of the planned 28.4°, leaving the orbit within 1° of the Moon's plane. Earth is drawn at half size so the 400 km orbits show.
Earth-centred view: the spacecraft leaves a small orbit at Earth, follows a transfer ellipse to the Moon's path and loops with the Moon
Earth-centred view. From the 400 km orbit (the small loop, Earth drawn 4× size) along the transfer ellipse, then looping with the Moon once captured.
3D trajectory in the solar-system barycentric frame
3D, solar-system frame. Positions relative to the solar-system barycentre, so Earth's motion shifts the whole path; the waves at the end are the ship circling the moving Moon.
Moon-centred view of the arrival: the ship comes in from the right, kinks at the insertion burn, and closes into an orbit
Arrival, Moon-centred. The ship comes in from the right; the kink is the insertion burn 36,000 km out; the closed loop is the final orbit about 6,400 km above the surface.
Simulator dashboard: altitude above Earth and Moon, eccentricity, inclination, apsides, energy, propellant and throttle over the mission
The simulator's own dashboard. Altitude above Earth and Moon, eccentricity, inclination, apsides, energy, propellant and throttle. The four burns show as throttle spikes; propellant falls from 1,100 t to 18 t. (The time axis says hours; the values are days.)

Departure timing

The planner sweeps candidate times to minimize the miss distance at the Moon, up to 1,000 per search. The first sweep found a 16,476 km miss; after the first insertion burn a second, full N-body sweep picked the 6,424 km closest approach used for circularization.

Miss distance at apoapsis plotted against coast time, with a minimum of 6,424 km at 5.89 days
Searching for the insertion point. Miss distance against coast time; the minimum, 6,424 km at 5.89 days, is where the circularization burn happens.

Holding lunar orbit

A ship placed in a 100 km circular lunar orbit was propagated for 24 hours under seven-body gravity. Its altitude stayed between 99.9 and 100.0 km — a check that the integrator and the frame conversions are consistent. It runs in 24 s.

Twelve revolutions around the Moon in 24 hours, traced in the solar-system frame as the Moon moves
Twelve orbits of the Moon in 24 hours, traced in the solar-system frame while the Moon itself moves along its path.

What didn't run as committed

  • validation/test_ship.py calls ship.set_throttle(), but the class now uses a throttle property — the test is stale, not the model.
  • tests/porkchop_earth_moon.py is an earlier experiment that calls an old function signature.
  • The Teensy firmware needs the board itself; it wasn't built or flashed for this re-run.

Code review

The physics foundation is solid: real ephemerides, a high-order integrator, consistent units and finite burns with mass flow. The gaps are speed, closed-loop guidance and project hygiene.

What holds up

Real-world fidelity

JPL DE440 positions and NAIF gravity constants for 7 bodies, not a two-body approximation.

Numerics done right

DOP853 at 1e-9, a 2 s step cap during burns so a short burn is never skipped, and terminal events for ignition, cutoff and depletion.

Clean separation

Planning (what Δv, when), guidance (how to fly it) and propagation (what physically happens) are separate; any controller implementing update(t, y) plugs in.

Realistic vehicles

Engines with thrust, Isp and mass flow; burn durations from the rocket equation, centred on the ideal impulsive time.

Documentation

A LaTeX derivation of every orbital formula used, kept beside the code.

Full-stack ambition

The same project reaches down to a real-time FreeRTOS microcontroller with separate receive and guidance tasks.

Limitations, and what I'd do now

IssueEffectWhat I'd do now
Every gravity evaluation queries Skyfield for 7 body positions237 s to simulate 7.9 days; slow for sweeps and optimizationInterpolate the ephemeris once per run (Chebyshev or spline cache) — likely 10–100× faster
Burns are open-loop: fixed direction and durationArrival at 6,424 km instead of a chosen low orbitFinish the ZEM/ZEV closed-loop guidance; add a mid-course correction
The plane change happens in low Earth orbit3,762 m/s — more than the trans-lunar burnCombine it with TLI, or do it far from Earth where speed is low
No pinned dependenciesBreaks on current astropy and numpyA versioned requirements.txt
Stale unit test and porkchop scriptTests don't guard the codeUpdate the tests and run them in CI
The dynamics function also updates throttle and propellantSide effects inside an integrator's derivative are fragileKeep the derivative pure; apply commands between steps
Python-to-Teensy streaming isn't in the code yetThe hardware-in-the-loop loop isn't closedAdd the serial sender and a round-trip latency test

The main lesson: planning and flying are different problems. An analytic plan is a starting guess; the simulator shows how far reality drifts from it, and guidance is what closes that gap.

The physics and math

The approach: plan each maneuver with closed-form two-body orbital mechanics (fast, exact for one body), fly it with numerical N-body integration (accurate, no shortcuts), then plan the next maneuver from wherever the ship actually ended up.

1. Equations of motion

The state is position, velocity and mass in the Solar System Barycentric frame. Each body's position rk(t) comes from DE440 and its gravitational parameter μk from NAIF; T is total thrust, τ the throttle and û the thrust direction.

\dot{\mathbf{r}} = \mathbf{v}, \qquad \dot{\mathbf{v}} = -\sum_{k=1}^{7} \mu_k \frac{\mathbf{r}-\mathbf{r}_k(t)}{\lVert \mathbf{r}-\mathbf{r}_k(t) \rVert^{3}} + \frac{T\,\tau}{m}\,\hat{\mathbf{u}}, \qquad \dot{m} = -\frac{T\,\tau}{I_{sp}\, g_0}

2. Integration

SciPy solve_ivp with DOP853, an 8th-order Runge–Kutta method with an embedded error estimate; a step is accepted only if its estimated error is below rtol·|y| + atol, with both at 1e-9. Steps are capped at 60 s while coasting and 2 s during burns, and propagation is split at each burn's start and end so thrust never switches inside a step.

3. Describing an orbit

Orbital elements are computed from position and velocity relative to the body being orbited. A negative specific energy ε means the ship is bound — the capture test used above.

\mathbf{h} = \mathbf{r}\times\mathbf{v}, \qquad \mathbf{e} = \frac{\mathbf{v}\times\mathbf{h}}{\mu} - \hat{\mathbf{r}}, \qquad i = \arccos\frac{h_z}{h}, \qquad \varepsilon = \frac{v^2}{2} - \frac{\mu}{r}, \qquad a = -\frac{\mu}{2\varepsilon}

Time to apoapsis, needed to schedule burns there, goes through the eccentric and mean anomalies:

E = 2\arctan\!\left(\sqrt{\tfrac{1-e}{1+e}}\,\tan\tfrac{\nu}{2}\right), \qquad M = E - e\sin E, \qquad n = \sqrt{\mu/a^{3}}, \qquad t_{apo} = \frac{\pi - M}{n}

4. Plane change at the ascending node

The ship's orbit is integrated until it crosses the Moon's orbital plane; there, rotating the velocity about the line of nodes tilts the orbit without changing its size.

\Delta i = \arccos(\hat{\mathbf{h}}_{ship}\cdot\hat{\mathbf{h}}_{Moon}), \qquad \mathbf{v}' = R(\hat{\mathbf{k}},\Delta i)\,\mathbf{v}, \qquad \Delta v = 2v\sin\frac{\Delta i}{2}

Here Δi = 28.4° at 7.67 km/s gives 3,762 m/s, matching the simulated burn.

5. Trans-lunar injection

A Hohmann transfer from r₁ = 6,772 km to r₂ = 369,034 km, burned prograde, with the speed from the vis-viva equation (3,086 m/s). The departure time is a search: 1,000 candidates, each checked against the Moon's DE440 position at the predicted apoapsis time.

a_t = \frac{r_1 + r_2}{2}, \qquad v(r) = \sqrt{\mu\left(\frac{2}{r} - \frac{1}{a}\right)}, \qquad \Delta v_{TLI} = v(r_1)\big|_{a=a_t} - v_{now}

6. Capture at the Moon

At closest approach the velocity relative to the Moon is replaced with circular speed in the same orbital plane (a 312 m/s burn):

v_{circ} = \sqrt{\frac{\mu_{Moon}}{r}}, \qquad \hat{\mathbf{v}}_{circ} = \frac{\hat{\mathbf{h}}\times\mathbf{r}}{\lVert\hat{\mathbf{h}}\times\mathbf{r}\rVert}, \qquad \Delta\mathbf{v} = v_{circ}\hat{\mathbf{v}}_{circ} - \mathbf{v}_{rel}

7. Turning a Δv into a real burn

Plans assume instant velocity changes; real engines take seconds to minutes while the ship gets lighter. The rocket equation gives the propellant and the mass flow gives the time, and the burn is centred on the ideal impulse time.

m_f = m_0\, e^{-\Delta v / v_e}, \qquad v_e = I_{sp}\, g_0, \qquad \dot m = \frac{T}{v_e}, \qquad t_{burn} = \frac{m_0 - m_f}{\dot m}, \qquad t_{start} = t_c - \frac{t_{burn}}{2}

8. Why the result differs from the plan

Each plan uses two-body formulas and instantaneous burns, but the flight uses seven bodies and finite burns, and the differences add up: the predicted 16,476 km miss became a 6,424 km closest approach. Re-planning from the propagated state at each step is why the mission still ends in a bound lunar orbit; closing the loop continuously with ZEM/ZEV guidance is the next step toward hitting a chosen orbit such as 100 km.

How the results were made

Re-run on November 17, 2026 from a fresh clone of main (last code commit December 1, 2025) with Python 3.12 in a separate virtual environment. No project code was changed.

  • Packages: numpy 2.3.5, scipy 1.18.1, matplotlib 3.11.2, skyfield 1.55, astropy 7.1.1, tqdm, pytest and plotly. astropy 7.2+ dropped a module the code imports, and astropy 7.1 needs numpy below 2.5.
  • Ephemeris: de440.bsp from JPL SSD, plus gm_de440.tpc and pck00011.tpc from NAIF.
  • Headless capture: a small wrapper imports each scenario and runs it unchanged, saving figures to files instead of windows; a separate script draws the Earth- and Moon-centred views and checks capture.
cd space_state/space_state
python run_capture.py tests.guidance_controller test_guided_insertion out_mission   # 237 s
python run_capture.py tests.orbit_moon test_guided_insertion out_moon               # 24 s
python analyze_mission.py out_mission
wjhdfnmf/space_statePython · C++ · main branch
View the code on GitHub

Previous project: ← ProjectZero — a from-scratch C++ machine-learning framework