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

| Part | What it does |
|---|---|
State & dynamicsbase/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. |
Propagatorbase/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 & enginesbase/star_ship.py | Throttleable thrusters with thrust, specific impulse and mass flow. Presets: Starship (3 Raptor Vacuum), Centaur III (RL10), Agena (Bell 8096). |
Maneuver planningbase/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 toolsguidance/star_tools.py | Inclination, eccentricity, energy, semi-major axis, vis-viva, period, nodes, time to apoapsis, burn duration from the rocket equation. |
Guidanceguidance/ | 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 computersrc/ | 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. |
Referencedocument/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.
| Burn | Mission time | Δv | Length | Result |
|---|---|---|---|---|
| 1. Plane change at the ascending node | 0.03 d | 3,762 m/s | 370 s | Inclination changed 28.4° to match the Moon's plane |
| 2. Trans-lunar injection | 0.07 d | 3,086 m/s | 120 s | Apoapsis raised from 6,772 km to near the Moon's distance |
| 3. Lunar orbit insertion | 5.14 d | — | 21 s | 36,249 km from the Moon, 0.51 km/s relative |
| 4. Circularization at closest approach | 5.89 d | 312 m/s | 6 s | 6,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.





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.

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.

What didn't run as committed
validation/test_ship.pycallsship.set_throttle(), but the class now uses a throttle property — the test is stale, not the model.tests/porkchop_earth_moon.pyis 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
| Issue | Effect | What I'd do now |
|---|---|---|
| Every gravity evaluation queries Skyfield for 7 body positions | 237 s to simulate 7.9 days; slow for sweeps and optimization | Interpolate the ephemeris once per run (Chebyshev or spline cache) — likely 10–100× faster |
| Burns are open-loop: fixed direction and duration | Arrival at 6,424 km instead of a chosen low orbit | Finish the ZEM/ZEV closed-loop guidance; add a mid-course correction |
| The plane change happens in low Earth orbit | 3,762 m/s — more than the trans-lunar burn | Combine it with TLI, or do it far from Earth where speed is low |
| No pinned dependencies | Breaks on current astropy and numpy | A versioned requirements.txt |
| Stale unit test and porkchop script | Tests don't guard the code | Update the tests and run them in CI |
| The dynamics function also updates throttle and propellant | Side effects inside an integrator's derivative are fragile | Keep the derivative pure; apply commands between steps |
| Python-to-Teensy streaming isn't in the code yet | The hardware-in-the-loop loop isn't closed | Add 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.bspfrom JPL SSD, plusgm_de440.tpcandpck00011.tpcfrom 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