CosmosLaboratory
Reproducible astrophysics experiments. The laboratory is strictly separate from the reference universe: an
experiment is a self-contained, versioned, Codable document that never reads or mutates catalogue or ephemeris
data. Depends on CosmosCore and CosmosMath only. CPU, double precision, Swift 6 strict concurrency.
Plain statements first
- Gravity is Newtonian. There is no general-relativistic solver. The single optional relativistic ingredient is a first-order post-Newtonian perihelion term (§2.4), validated against Mercury and labelled as such.
- There is no GPU solver. Both solvers (direct summation and Barnes–Hut) run on the CPU.
- The point-mass lens (§6) is a set of optics formulas, not a simulation.
- The galaxy "merger" is a restricted toy model (§5); its cores never merge.
1. Files and API
| File | Contents |
|---|---|
Experiment.swift |
Experiment, LabBody, UnitSystem (.si, .nBody), ForceSolver, IntegratorChoice, CollisionPolicy, GravityModel, validate(), JSON (jsonData(), init(jsonData:)), LabJSON |
LabRandom.swift |
LabRandom (SplitMix64 seeding + xoshiro256**), uniform, normal, direction |
Forces.swift |
direct-summation kernel (SIMD4, threads), BarnesHutTree, exact pair diagnostics, public ForceProbe |
NBodyEngine.swift |
NBodyEngine: SimulationEngine, EngineSnapshot, Diagnostics, CollisionEvent, RunTermination |
Runner.swift |
Laboratory.run / .resume (synchronous), ExperimentRunner (actor), RunOptions, FrameDelivery, Frame, RunProgress, ExperimentResult, TrajectorySample |
Analytic.swift |
TwoBody (elements, vis-viva, universal-variable propagation), HohmannTransfer, Flyby, PointMassLens |
Library.swift |
ExperimentLibrary (the experiments of §5), LibraryExperiment, ExpectedQuantity, StabilityScan, Laboratory.closestApproach |
LabExport.swift |
LabExport.diagnosticsCSV, .trajectoriesCSV, .json, .result(fromJSON:) |
Build and run an experiment
// 1. Describe (or take one from the library; every library call also returns the analytic expectation).
let lib = try ExperimentLibrary.binary(mass1: 1, mass2: 1, semiMajorAxis: 1, eccentricity: 0.5, orbits: 10,
integrator: .yoshida4(timeStep: 0.001), units: .nBody)
let exp: Experiment = lib.experiment // Codable document; exp.jsonData() / Experiment(jsonData:)
lib["period"]; lib.expectations; lib.modelNotes // what theory predicts, what the model leaves out
// 2a. Synchronously (scripting, tests, command line). Honours Swift task cancellation.
let result = try Laboratory.run(exp) { frame in /* every output, index 0 = initial state */ }
// 2b. From the UI: an actor with pause / resume / cancel / progress / snapshots and a frame stream.
let runner = try ExperimentRunner(experiment: exp, options: RunOptions(frameDelivery: .backpressure(buffer: 2)))
await runner.start()
for await frame in runner.frames { draw(frame.positions); show(frame.diagnostics) } // the run waits for the consumer
await runner.pause(); await runner.resume(); await runner.cancel()
let p = await runner.progress // state, fraction, time, stepCount, outputCount, wallClockSeconds
let checkpoint = await runner.snapshot() // EngineSnapshot (Codable); ExperimentRunner(snapshot:) continues it
let result = try await runner.result() // ExperimentResult, or throws CosmosError.cancelled / the engine error
// 3. Results and export.
result.diagnostics; result.maxRelativeEnergyError; result.events; result.finalBodies; result.finalSnapshot
let csv = LabExport.diagnosticsCSV(result) // units in headers
let traj = try LabExport.trajectoriesCSV(result) // needs RunOptions.storeTrajectories
let json = try LabExport.json(result) // experiment + results + events + final snapshot + versionsNBodyEngine can also be driven directly: init(experiment:), init(snapshot:), step() -> StepOutcome
(.stepped, .outputReached, .finished), advance(by:) (the CosmosCore.SimulationEngine requirement),
diagnostics(), frame(), snapshot(), and read-only state (time, stepCount, ids, positions,
velocities, masses, bodies, events, termination).
2. Models and equations
2.1 Experiment record
Experiment stores: schemaVersion (currently 1), engineID (orix.cosmos.laboratory.nbody), engineVersion
(1.0.0), title, seed, units (unit symbols and the value of G in those units — the engine is unit-agnostic),
bodies (id, name, mass, position, velocity, optional radius, isTestParticle), solver,
integrator with its parameters, softeningLength, collisionPolicy, gravity, duration, outputInterval,
notes, and a ScientificStatus (hypothetical by default and for every modified universe; the
caller-supplied-states experiments default to estimated, see §5).
- JSON is canonical: sorted keys, pretty printed, every
Doublein shortest round-trip form, so decode → encode gives the same bytes and every number is restored bit for bit (tested, including −0.0 and values near the subnormal range). validate()runs before anything is encoded, decoded or simulated and throwsCosmosError.invalidInput(never crashes) on: no bodies; NaN/∞ anywhere; mass ≤ 0 for a massive body; non-zero mass for a test particle; radius ≤ 0; duplicate identifiers; a massive body sharing its position with any other body; non-positive step, tolerance, duration or output interval; more than 9·10¹⁵ steps; negative softening; opening angle outside [0, 2]; leaf capacity outside 1…1024; a post-Newtonian term without a valid central body or with a fixed-step integrator; a schema version newer than this build.- A test particle feels gravity and exerts none. It must be declared (
isTestParticle, mass exactly 0) so that a zero mass is never accepted by accident. Two test particles may coincide.
2.2 Forces
Pair acceleration with Plummer softening ε (ε = 0: pure Newton):
a_i = Σ_{j≠i} G m_j (r_j − r_i) / (|r_j − r_i|² + ε²)^{3/2} U = −Σ_{i<j} G m_i m_j / √(|r_i − r_j|² + ε²)- Direct summation (
.direct): exact pair sum over the massive bodies, O(N·N_massive) per evaluation. Kernel: sources packed four perSIMD4<Double>, one division and one square root per pair; targets are partitioned across threads withDispatchQueue.concurrentPerformwhen N·N_massive ≥ 65 536. Each target's sum has a fixed order, so the result does not depend on the number of cores or on scheduling. What SIMD and threads actually buy is measured in §8 (kernel table). No Accelerate/vDSP call is used: the kernel is a single fused loop and vDSP would need several passes over temporary arrays. - Barnes–Hut (
.barnesHut(openingAngle: θ, leafCapacity:)): octree over the massive bodies rebuilt at every force evaluation; cells carry total mass and centre of mass (monopole only, no quadrupole); a cell of side s at distance d from its centre of mass is accepted when s/d < θ, otherwise opened; leaves (≤leafCapacitybodies) are summed directly. θ = 0 reproduces direct summation to rounding. The force error versus θ is measured in §7. Barnes–Hut forces are not exactly antisymmetric, so linear momentum is conserved only approximately.
2.3 Integrators
| Choice | Method | Order | Properties |
|---|---|---|---|
.leapfrog(timeStep:) |
kick–drift–kick (velocity Verlet) | 2 | symplectic, time-reversible, 1 force evaluation per step |
.yoshida4(timeStep:) |
composition of three leapfrogs, w₁ = 1/(2 − 2^{1/3}), w₀ = −2^{1/3} w₁ (Yoshida 1990; Forest & Ruth 1990) | 4 | symplectic, 3 force evaluations per step, one backward sub-step |
.dormandPrince54(…) / .adaptive(relativeTolerance:) |
Dormand & Prince (1980) RK5(4)7M embedded pair, FSAL, step-size control h ← 0.9·h·err^{−1/5} clamped to [0.2, 5] | 5 | adaptive, not symplectic (energy drifts secularly at the tolerance level), 6 force evaluations per step, resolves close encounters |
Adaptive error control: a step is accepted when max_i|Δx_i| ≤ atol_x + rtol·max_i|x_i| and max_i|Δv_i| ≤ atol_v + rtol·max_i|v_i| (Δ = difference between the 5th- and 4th-order solutions; maxima over bodies). The scale is global, not per body, and not translation-invariant: use a barycentric frame.
Only integrators validated in §7 are shipped. IAS15 and DOP853 are not implemented.
Output plan. Fixed-step runs take ⌈duration/dt⌉ steps and output every round(outputInterval/dt) steps (and
at the last step): the output interval is rounded to a whole number of steps and time is stepCount·dt, never an
accumulated sum. Adaptive runs land exactly on k·outputInterval and on the duration (the step is shortened to hit
them; the controller's preferred step is kept for the next step).
2.4 Gravity model: Newtonian, plus one optional post-Newtonian term
GravityModel.postNewtonianPerihelion(centralBody:speedOfLight:) adds to every other body the 1PN Schwarzschild
acceleration in the test-particle limit, with r, v relative to the central body of mass M:
a_1PN = GM / (c² r³) · [ (4GM/r − v²) r + 4 (r·v) v ]It reproduces the perihelion advance Δω = 6πGM / (c² a (1 − e²)) per orbit — and nothing else: no mutual 1PN terms between planets, no reaction on the central body (momentum is not conserved by this term), no light bending, no frame dragging, no gravitational radiation. It is velocity dependent, so it is only accepted with the adaptive integrator. The energy reported in the diagnostics remains the Newtonian energy.
2.5 Collisions
Detection by radii after every step: bodies i, j with known radii collide when |r_i − r_j| < R_i + R_j (at least one of them massive). Detection is discrete: a pair that crosses and separates within one step is missed, and the contact is recorded up to one step late.
| Policy | Behaviour |
|---|---|
.ignore |
radii unused |
.merge |
perfectly inelastic: m = m₁ + m₂, r and v of the pair's barycentre (mass and linear momentum conserved to rounding), R = (R₁³ + R₂³)^{1/3} (volumes add: equal mean densities assumed), identifier of the more massive progenitor, name "A+B". Energy is lost: ΔE = −(½ μ v_rel² − G m₁m₂/√(d² + ε²)) with μ the reduced mass (kinetic energy of the relative motion minus the pair's mutual binding energy); it would become heat and deformation, which are not modelled. The pair's angular momentum about its own barycentre (μ r_rel × v_rel, the would-be spin) is dropped as well. Every merger is recorded as a CollisionEvent with the measured energyChange. |
.stopOnContact |
the run ends (termination == .stoppedOnContact) and reports the pair, separation and relative speed |
2.6 Diagnostics (every output)
Diagnostics: time, step count, body count, kinetic, potential and total energy, linear momentum, angular
momentum vector (about the frame origin), barycentre position and velocity, relativeEnergyError,
mergerEnergyChange, closest pair distance and identifiers, potentialIsApproximate, wall-clock seconds.
relativeEnergyError = (E − E₀ − ΣΔE_mergers) / |E₀|: the integration error alone; energy deliberately removed by mergers is reported separately. It isnilwhen E₀ = 0 exactly, and meaningless when E₀ ≈ 0 (parabolic encounters): compare the absolute drift with the kinetic energy instead.- Sums use Neumaier compensation (
CosmosMath.CompensatedSum). - Cost O(N·N_massive) per output (exact pair sum and closest-pair search). For a Barnes–Hut run with more than
20 000 massive bodies the potential is the tree estimate ½Σ m_i φ_i (
potentialIsApproximate == true) and the closest pair is not computed (nil). - Drift is reported as measured; nothing is renormalised or corrected.
2.7 Run control, memory and reproducibility
ExperimentRunner(actor):start,pause,resume,cancel(Swift task cancellation;result()then throwsCosmosError.cancelled),progress,snapshot,currentDiagnostics,result,frames,detachFrames. The computation runs in slices ofRunOptions.sliceSeconds(default 10 ms) of wall-clock time; control requests are served between slices, so the latency of pause/cancel/snapshot is one slice plus one integrator step (a step of a 10⁵-body run is not interruptible).- Frames:
.backpressure(buffer: n)— at most n frames wait and the simulation suspends until the consumer takes one (nothing is dropped; a consumer that stops reading stalls the run until it is cancelled ordetachFrames()is called);.dropOldest(buffer: n)— the simulation never waits;.none. - Bounded memory: at most
maxStoredSamples(default 4096) diagnostics samples are kept. When the bound is reached every other stored sample is discarded and the storage stride doubles (decimation by powers of two; the initial and final outputs are always kept;ExperimentResult.sampleStriderecords the stride). Trajectories (storeTrajectories) use the same scheme, additionally bounded bymaxTrajectoryBytes(24 bytes per body per sample, default 256 MiB). Frames themselves are never accumulated by the runner. - Reproducibility — guaranteed (tested): on the same machine and build, the same experiment gives bit-identical states (a) from run to run, (b) whether it is run synchronously or through the actor, (c) with any pattern of pause/resume, any slice length and any frame delivery, (d) when stopped at an arbitrary step, checkpointed to JSON and continued from the decoded snapshot, (e) with any number of cores. Snapshots are refused by a different engine version.
- Reproducibility — not guaranteed: across CPU architectures, operating-system versions, compiler versions or
optimisation levels. Reasons: the adaptive controller calls
pow, the samplers calllog,cos,sin, and none of these is correctly rounded by IEEE 754; the compiler may contract a·b + c differently between builds. The integer stream ofLabRandom(next(),uniform()) is identical everywhere. Wall-clock fields are measurements and never reproducible.
3. Random numbers
LabRandom(seed:): xoshiro256** (Blackman & Vigna 2018) with the four state words produced by SplitMix64 from the
seed. uniform() = (next() >> 11)·2⁻⁵³ ∈ [0, 1); normal() by Box–Muller (second variate discarded, no hidden
cache); direction() uniform on the sphere. The run itself draws no random numbers: the seed only shapes the
initial conditions and is stored in the experiment.
4. Analytic references (Analytic.swift)
TwoBody.propagate(mu:position:velocity:dt:): exact Kepler propagation for any conic with the universal variable χ and Stumpff functions, solved by Laguerre–Conway iteration; bound orbits are first reduced modulo the period.TwoBody.elements,stateAtTrueAnomaly,timeSincePeriapsis,period,visVivaSpeed,circularSpeed.HohmannTransfer(mu:r1:r2:): a_t = (r₁ + r₂)/2, Δv₁ = |√(μ(2/r₁ − 1/a_t)) − √(μ/r₁)|, Δv₂ = |√(μ/r₂) − √(μ(2/r₂ − 1/a_t))|, T = π√(a_t³/μ), phase angle π − n₂T.Flyby(mu:vInfinity:periapsis:)/(…impactParameter:): e = 1 + r_p v∞²/μ, turn angle δ = 2 asin(1/e), b = r_p√(1 + 2μ/(r_p v∞²)), |Δv| = 2 v∞ sin(δ/2).PointMassLens: see §6.
5. Experiment library (ExperimentLibrary)
Each function returns a LibraryExperiment: the Experiment, the analytic expectations (name, value, unit,
formula) when one exists, and modelNotes that the UI must show with the result.
| Function | System | Analytic expectation |
|---|---|---|
twoBody(primaryMass:secondaryMass:periapsis:eccentricity:initialTrueAnomaly:duration:…) |
two-body problem, any eccentricity (ellipse, parabola, hyperbola) | period, energy, angular momentum, exact final relative state |
binary(mass1:mass2:semiMajorAxis:eccentricity:orbits:…) |
equal and unequal binaries | same |
system(title:bodies:…), sunEarthMoon(sun:earth:moon:…), solarSystem(bodies:…) |
N-body from caller-supplied states (LabBody(id:name:mass:state:) takes a CosmosCore.StateVector); the module does not import ephemerides |
none. Status estimated: real initial conditions, Newtonian point-mass dynamics |
changingMass(in:of:factor:), addingBody(to:_:) |
any experiment with one mass changed / one body added (status hypothetical) |
none |
changedStarMass(starMass:planetMass:orbitRadius:massFactor:…) |
circular planet whose star's mass is multiplied by f at t = 0 | k = (fM + m)/(M + m): e′ = |1/k − 1|, a′ = r/(2 − 1/k), unbound for k ≤ ½ |
stabilityScan(…testSemiMajorAxes:planetOrbits:…) + StabilityScan.survival(of:) |
star, planet, massless test planets; survival time versus semi-major axis | Hill radius; Wisdom (1980) resonance-overlap half-width 1.3 μ^{2/7} a_p (indicative) |
meanMotionResonance(…p:q:…) |
particles at and around the interior p:q resonance | a_res = a_p (q/p)^{2/3}, period ratio |
hohmannTransfer(centralMass:r1:r2:…) |
spacecraft coasting on the transfer ellipse, target marker at the rendezvous phase | Δv₁, Δv₂, total, transfer time, arrival distance and speed, phase angle |
gravityAssist(planetMass:planetVelocity:vInfinity:periapsis:startDistance:…) |
hyperbolic flyby of a moving planet (patched-conic encounter phase) | turn angle, |Δv|, exact conic velocity at the end distance, asymptotic inertial speed change |
plummerCluster(count:totalMass:scaleRadius:seed:…) |
Plummer sphere in virial equilibrium (sampling below) | W = −3πGM²/(32a), T = −W/2, half-mass radius a/√(2^{2/3} − 1) |
galaxyMerger(…) |
restricted toy model: two softened cores, rings of test particles | pericentre time and distance of the point-mass orbit only |
asteroidDeflection(deltaV:leadTime:…) + Laboratory.closestApproach(in:between:and:) |
asteroid built to hit a target marker; impulsive along-track Δv at t = 0 | exact two-body miss distance; rule of thumb 3Δv·t |
figureEight(periods:…) |
Chenciner–Montgomery three-body choreography | period 6.32591398, zero angular momentum |
Details that matter:
- Plummer sampling (Aarseth, Hénon & Wielen 1974): X uniform → r = a (X^{−2/3} − 1)^{−1/2}, resampled beyond
truncationRadius·a (default 20a, which encloses 99.6 % of the mass); isotropic direction; speed v = q·v_esc(r), v_esc = √(2GM/a)(1 + r²/a²)^{−1/4}, q by von Neumann rejection from g(q) = q²(1 − q²)^{7/2} (bound 0.1); the sample is shifted to its barycentre at rest. Default units are Hénon units (G = M = 1, a = 3π/16, E = −¼). Default softening a·N^{−1/3}. Equal masses, no primordial binaries, no stellar evolution, no tidal field. - Stability scan: all test planets ride in one run (they do not interact).
StabilityScan.survivaldeclares a particle lost when its osculating orbit about the star becomes unbound, when its osculating semi-major axis departs from the initial one by more thanmaxFractionalDrift(default 20 %), or when it enters the planet's Hill sphere. These are conventions.survivalTime == nilmeans "survived the whole run", i.e. only a lower bound; a finite run proves nothing about long-term stability. - Galaxy "merger" (after Toomre & Toomre 1972): explicitly approximate. No gas, no star formation, no dark-matter halo, no self-gravity of the discs, no dynamical friction — the cores follow a softened two-body orbit and do not merge; the test particles only trace tidal bridges and tails.
- Asteroid deflection: heliocentric two-body motion; the target has no gravity (no gravitational focusing,
no keyholes); impulsive and perfectly along-track Δv; no momentum-enhancement factor. The target is a point:
compare the miss distance with its radius yourself.
closestApproachinterpolates the relative trajectory inside each integrator step with a cubic Hermite polynomial and minimises it with Brent's method. - Hohmann: the first impulse is in the initial velocity; the second impulse is the analytic value (the run ends at arrival and verifies distance, speed, zero radial velocity and rendezvous with the target).
- Gravity assist: only the planet's gravity acts (no star, no curvature of the planet's path).
6. Point-mass gravitational lens (pedagogical)
Weak-field, thin-lens, small-angle formulas — optics, not a GR simulation (no ray tracing in a metric, no strong field, no extended lens, no time delay):
α = 4GM/(c² b) θ_E = √(4GM/c² · D_LS/(D_L D_S))
θ± = (β ± √(β² + 4θ_E²))/2 μ± = ½ ± (u² + 2)/(2u√(u² + 4)), u = β/θ_E μ_tot = (u² + 2)/(u√(u² + 4))deflectionAngle refuses impact parameters inside the Schwarzschild radius. Perfect alignment (u = 0) returns
the Einstein ring positions and nil magnifications (formally infinite for a point source). Distances are
angular-diameter distances; take them from CosmosCosmology in a cosmological setting.
7. Validation (Swift Testing, 42 tests in 5 suites; numbers printed by the tests as MEASURED …)
Measured in a debug build on the machine of §8. Tolerances asserted in the tests are 1.5–10× the measured values.
Kepler problem (equal masses, a = 1, G = 1, T = 2π/√2; error = |relative position − analytic| in units of a)
| Check | Measured | Asserted |
|---|---|---|
| leapfrog, e = 0.5, dt = T/4000, 10 orbits: position / max |ΔE/E| / max |ΔL/L| | 1.11e-3 / 6.7e-6 / 1.0e-14 | 3e-3 / 2e-5 / 1e-13 |
| Yoshida 4, same: position / energy / angular momentum | 1.02e-8 / 5.8e-11 / 2.4e-14 | 3e-8 / 2e-10 / 1e-13 |
| Dormand–Prince rtol 1e-12, same (5341 steps): position / energy / angular momentum | 2.0e-9 / 2.4e-11 / 8.3e-12 | 1e-8 / 1e-10 / 5e-11 |
| period from axis crossings (m = 3 + 1, e = 0.3) vs Kepler III | 5.9e-12 relative | 2e-5 |
| convergence order, leapfrog (T/500 … T/4000, e = 0.3) | 2.0003, 2.0001, 2.0000 | 2 ± 0.05 |
| convergence order, Yoshida 4 (T/250 … T/2000) | 3.997, 3.999, 4.000 | 4 ± 0.1 |
| convergence order, Dormand–Prince at fixed step (T/100 … T/800) | 5.15, 5.18, 5.14 | 5 ± 0.3 |
| adaptive, e = 0.9, 1 orbit, rtol 1e-6 / 1e-8 / 1e-10 / 1e-12: position error (steps) | 8.4e-4 (85) / 6.7e-6 (147) / 4.3e-8 (343) / 3.0e-10 (826) | monotone, < 1e-8 at 1e-12 |
| close encounter e = 0.99, 1 orbit: adaptive rtol 1e-11 vs leapfrog with the same number of force evaluations (4675) | 1.0e-7 vs 57 (leapfrog fails) | adaptive < 1e-6 and 100× better |
| unbound, e = 1 / 1.5 / 3 through periapsis, vs universal-variable solution | 2.0e-12 / 6.4e-13 / 5.3e-14 relative | 1e-9 |
TwoBody.propagate vs conic formulas, e = 0 … 5 |
< 1e-12 relative | 1e-12 |
Three-body and relativity
| Check | Measured | Asserted |
|---|---|---|
| figure-eight (Simó's 8-digit initial conditions), closure after one period, Dormand–Prince rtol 1e-12 | 4.1e-8 (energy 4.6e-12) | 5e-7 |
| figure-eight, cyclic exchange of positions at T/3 | exact permutation to 5e-7 | 5e-7 |
| figure-eight after 10 periods, leapfrog T/20000 / Yoshida T/2000 | 4.1e-6 / 4.2e-7 | 2e-4 |
| Mercury perihelion advance with the 1PN term (a = 0.38709893 au, e = 0.20563069, 415 orbits) | 42.9809″/century | 42.98 ± 0.01 and formula 42.9805 ± 0.01 |
| same run without the term | 2.4e-4″/century | < 0.002 |
Forces
| Check | Measured | Asserted |
|---|---|---|
| SIMD/threaded kernel vs scalar reference, N = 2 … 700, max relative difference | ≤ 2.5e-15 | 1e-12; call-to-call bit identity |
| Barnes–Hut vs direct, Plummer N = 4000, leaf 8, rms / max relative force error (interactions per body) | see table below | bounds below |
| Barnes–Hut potential energy, N = 3000, θ = 0.5, leaf 1 / 8 / 32 | 9.7e-6 / 2.4e-5 / 2.0e-5 relative | 2e-3 |
| Barnes–Hut run vs direct run, N = 500, θ = 0.4, 256 steps: max position difference; energy error BH / direct; momentum drift BH / direct | 4.0e-4; 2.1e-5 / 1.3e-6; 1.3e-5 / 2e-17 | 1e-3 / 1e-4; 1e-3 / 1e-14 |
| θ | rms force error | max force error | interactions per body (direct = 3999) | asserted rms bound |
|---|---|---|---|---|
| 0 | 2.1e-15 | 9.7e-15 | 3999 | 1e-12 |
| 0.2 | 1.0e-4 | 5.8e-4 | 3260 | 1e-3 |
| 0.3 | 3.7e-4 | 1.2e-3 | 2628 | 1e-3 |
| 0.5 | 2.0e-3 | 1.6e-2 | 1583 | 1e-2 |
| 0.7 | 5.8e-3 | 8.4e-2 | 970 | 1e-2 |
| 1.0 | 2.0e-2 | 1.5e-1 | 507 | 5e-2 |
With monopole cells the maximum error is an order of magnitude above the rms: a few bodies sit next to a cell whose centre of mass is far from its centre. Use θ ≤ 0.5 for anything quantitative.
Collisions, conservation, sampling
| Check | Measured | Asserted |
|---|---|---|
| merge: change of total linear momentum | 6.2e-15 | 1e-13 |
| merge: energy change vs −(½μv_rel² − Gm₁m₂/d) | agree | 1e-3 relative |
| merge: energy error once the merger loss is accounted for | 7.6e-6 | 1e-5 |
| direct cluster N = 200, leapfrog dt = 1/128, 128 steps: energy / momentum / angular momentum / barycentre drift | 5.3e-6 / 5e-17 / 9e-16 / 2e-17 | 1e-4 / 1e-14 / 1e-13 / 1e-13 |
| Plummer N = 2000: T, W, half-mass radius over model values; virial ratio | 1.0026, 0.99997, 0.989; 0.5013 | ±6 %, ±6 %, ±8 % |
Library experiments
| Check | Reference | Measured | Asserted |
|---|---|---|---|
| Hohmann 191.34411 km → 35 781.34857 km | Vallado (2013) Example 6-1: 2.457038, 1.478187, 3.935224 km/s, 315.403 min | reproduced | 5e-7 km/s, 5e-4 min |
| Earth → Mars (1 → 1.524 au) | classroom values ≈ 2.94 + 2.65 km/s, ≈ 259 d | 2.946, 2.650 km/s, 258.9 d | 0.01 km/s, 0.5 d |
| circular speed and period at 1 au | 29.78 km/s; Gaussian year 365.2569 d | reproduced | 0.01 km/s; 1e-3 d |
| Hohmann, simulated: arrival distance / speed / rendezvous offset (outward; inward) | analytic | 3.9e-11 / 3.5e-11 / 4.4e-11; 1.4e-12 / 1.4e-12 / 2.3e-9 | 1e-9 / 1e-9 / 1e-8 |
| gravity assist (GM = 1.2668653e17 m³/s², v∞ = 10 km/s, r_p = 3 × 71 492 km; δ = 117.567°, Δv = 17 104 m/s): simulation vs conic at the same distance | exact conic | ≤ 1.1e-10 relative | 1e-8 |
| same: simulated turn angle vs asymptotic δ, start at 100 / 1000 / 10 000 r_p | δ = 2 asin(1/e) | 9.2e-4 / 1.0e-5 / 1.0e-7 relative | decreasing; < 1e-3 at 10⁴ r_p |
| changed star mass (f = 0.8): e′ and a′ of the simulated orbit | energy argument | agree | 1e-9 |
| asteroid deflection, Δv = 1 cm/s, 5 and 10 years ahead: simulated vs analytic miss distance | two-body minimum | 4387.5815 vs 4387.5826 km; 8071.775 vs 8071.877 km | 1e-3 relative |
| same: rule of thumb 3Δv·t | Ahrens & Harris (1992) | 4734 km; 9467 km (order of magnitude only) | within ×10 |
| asteroid without deflection: miss distance | 0 by construction | 1.3 m (of 1.5e11 m) | < 1 km |
| stability scan, μ = 1e-3, 300 planet orbits | Wisdom half-width 0.18 a_p | lost: a = 0.9 (2.7 orbits), 0.95 (24.7), 1.05 (49.2), 1.1 (1.7); survived: 0.3, 0.4, 0.5, 2.0, 2.5 | lost inside 0.6 Δa, survive beyond 3 Δa |
| 2:1 resonance, m_p/M = 1e-5: return offset after 4 planet orbits | a_res = a_p·2^{−2/3} | 1.3e-3 a | 5e-3 |
| Sun–Earth–Moon from supplied (synthetic test) states, 1 year, rtol 1e-11 | — | month 27.05 d, distance 373 802 … 388 207 km, energy error 3.0e-13 | bound orbit, 27.3 ± 0.5 d, 1e-9 |
| toy galaxy encounter: isolated disc radius drift; pericentre distance and time vs Kepler | circular orbits in a Plummer potential; point-mass orbit | 7.8e-4; 1.001, 1.001 | 1e-3; 5 %, 10 % |
| solar-limb light deflection | 1.75″ | 1.7512″ | 0.005″ |
| Einstein radius, 1 M☉ at 4 kpc, source at 8 kpc | formula | 1.009 mas | 0.01 mas |
| lens equation, θ₊θ₋ = −θ_E², μ₊ + μ₋ = 1, μ_tot(u = 1) = 3/√5, magnification vs finite differences | identities | hold | 1e-12 … 1e-6 |
Run control and records — bit-identical restart from a JSON snapshot taken at an arbitrary step, and
bit-identical actor run with repeated pause/resume, for five experiments (adaptive figure-eight, Yoshida
figure-eight, direct leapfrog cluster, Barnes–Hut cluster, cluster with mergers); backpressure (the producer stops
at the buffer size until the consumer reads; 301 of 301 frames delivered in order); dropOldest and none;
cancellation of a running and of a paused actor run, of Laboratory.run and of advance(by:); decimation
(1001 outputs → 64 stored, stride 16, kept samples identical to the undecimated run); output plan; JSON round
trip byte-stable with sorted keys; 28 pathological inputs rejected by validate, the engine, the runner and the
encoder; a singular run fails with an error; generator determinism and moments; CSV/JSON export round trips.
Sources of the reference numbers are listed in §10. The Sun–Earth–Moon states used by the test are synthetic (circular coplanar orbits) and are labelled as such: that test checks plumbing and sanity, not ephemeris accuracy.
8. Benchmarks
swift run -c release cosmos-bench lab.direct lab.kernel lab.barneshut lab.integrators (cosmos-bench list
shows every benchmark; --quick shortens them). The program prints the machine, OS, build configuration and
load average it reads from the system, and only numbers it measured.
Output obtained on 2026-11-24 (release build; MacBook Pro, Apple M5 Max, 18 cores, 48 GB, macOS 27.0). The machine was shared with other builds and test runs while this was measured (see the load averages in the output): throughputs, the multi-threaded ones above all, are pessimistic and fluctuate from run to run.
# cosmos-bench
machine: Mac17,6 — Apple M5 Max, 18 active cores, 48 GB
os: Version 27.0 (Build 26A5425a)
build: release
load average at start (1 min): 46.9 — other processes were competing for the CPU; timings are pessimistic
## lab.direct — direct N-body, leapfrog: steps/s, pair interactions/s, energy error (N = 2 … 10 000) [1-min load average now: 46.9]
leapfrog KDK, dt = 1/256 Hénon time units, Plummer softening a·N^(-1/3); N = 2 is an unsoftened circular binary; best of 3 runs
N steps wall [s] steps/s pair interactions/s |dE/E| at end
2 2000000 0.363 5.507e+06 1.101e+07 5.2e-11
10 400000 0.127 3.147e+06 2.833e+08 1.36e-06
100 20000 0.176 1.138e+05 1.127e+09 3.65e-06
1000 400 0.08 5003 5.01e+09 3.34e-07
10000 12 0.0845 142 1.538e+10 5.51e-08
## lab.kernel — force kernel: scalar reference vs SIMD4 vs SIMD4 + threads [1-min load average now: 43.7]
one force evaluation of a Plummer cluster, best of several repetitions; speed-up relative to the scalar reference
N kernel wall [ms] pair interactions/s speed-up max rel. diff vs scalar
100 scalar, 1 thread 0.01171 8.456e+08 1 0
100 simd4, 1 thread 0.008542 1.159e+09 1.37 7e-16
100 simd4 + threads 0.008541 1.159e+09 1.37 7e-16
1000 scalar, 1 thread 1.198 8.339e+08 1 0
1000 simd4, 1 thread 0.803 1.244e+09 1.49 2.7e-15
1000 simd4 + threads 0.1196 8.354e+09 10 2.7e-15
10000 scalar, 1 thread 123.5 8.093e+08 1 0
10000 simd4, 1 thread 81.17 1.232e+09 1.52 9.8e-15
10000 simd4 + threads 6.458 1.548e+10 19.1 9.8e-15
## lab.barneshut — Barnes–Hut (θ = 0.5): steps/s, interactions/s, force and energy error (N = 10⁴ … 10⁵) [1-min load average now: 43.7]
leapfrog KDK, dt = 1/256, θ = 0.5, leaf capacity 8, monopole cells; force error measured against direct summation of the same state
energy error: exact pair sum for N ≤ 20 000, tree estimate (approximate) above; timings: best of 3 runs; a tree is rebuilt at every force evaluation
N steps wall [s] steps/s interactions/s interactions/body/step rms force err max force err |dE/E| at end
10000 40 0.2 199.6 4.923e+09 2405.9 0.00216 0.0631 7.72e-07
30000 16 0.335 47.75 4.766e+09 3131.7 0.00156 0.0386 2.17e-05
100000 6 0.709 8.466 3.417e+09 3459.4 0.00127 0.0534 8.35e-06
## lab.integrators — integrators on a Kepler orbit (e = 0.5, 100 orbits): cost and accuracy [1-min load average now: 42.6]
equal-mass binary, a = 1, e = 0.5, 100 orbits; position error against the analytic Kepler solution (units of a)
integrator steps force evals wall [s] steps/s position error max |dE/E|
leapfrog, T/1000 100000 100001 0.0288 3.469e+06 0.176 0.000107
leapfrog, T/10000 1000000 1000001 0.315 3.173e+06 0.00177 1.06e-06
yoshida4, T/1000 100000 300000 0.0539 1.857e+06 2.62e-05 1.49e-08
yoshida4, T/10000 1000000 3000000 0.488 2.047e+06 2.36e-09 1.51e-12
dopri54, rtol 1e-8 8601 51607 0.0124 6.926e+05 7.71e-05 5.77e-08
dopri54, rtol 1e-12 51801 310807 0.0763 6.788e+05 1.96e-07 2.39e-10Reading the numbers:
- Direct summation: 1.5·10¹⁰ pair interactions per second at N = 10⁴ (142 leapfrog steps/s); 5.0·10⁹ at N = 10³ (5.0·10³ steps/s). Below N ≈ 100 the per-step overhead (array bookkeeping, no threads) dominates: 5.5·10⁶ steps/s for two bodies.
- What SIMD and threads buy (kernel table): the SIMD4 kernel is 1.4–1.5× faster than the scalar loop on one thread — a modest but measured gain, limited by the double-precision divide and square root of each pair; threads bring the N = 10⁴ evaluation to 19× the scalar reference on this 18-core machine under load. Results agree with the scalar reference to ≤ 1e-14 relative.
- Barnes–Hut (θ = 0.5, leaf 8): 200, 48 and 8.5 steps/s at N = 10⁴, 3·10⁴ and 10⁵, with an rms force error of 0.13–0.22 % and a maximum of 4–6 % on single bodies. At N = 10⁴ it is only 1.4× faster than direct summation (2406 interactions per body instead of 9999, in a scalar tree walk); the gain grows with N (3459 interactions per body at 10⁵, where direct summation would need 10⁵).
- Energy errors are those of the short benchmark runs (12–2·10⁶ steps) and are quoted to show that the timed code is the validated code, not as a statement about long-term accuracy.
- Integrators: per step, Yoshida costs 3 force evaluations and Dormand–Prince 6. For the same position error after 100 orbits of an e = 0.5 binary, Yoshida with T/1000 (3·10⁵ evaluations, 2.6e-5) beats leapfrog with T/10000 (10⁶ evaluations, 1.8e-3); the adaptive integrator at rtol 1e-12 reaches 2.0e-7 with 3.1·10⁵ evaluations but its energy error (2.4e-10 after 100 orbits, 2.4e-11 after 10) grows with time, unlike the symplectic ones.
9. Numerical limits and what is not modelled
- Double precision throughout. Direct summation costs O(N²): about 10⁴ bodies is the practical interactive limit (see §8); Barnes–Hut extends this to ~10⁵ with percent-level force errors.
- Fixed-step integrators do not resolve close encounters: use softening, a smaller step, or the adaptive integrator. An unsoftened singular encounter makes the adaptive integrator stop with a step-underflow error; a fixed step goes through it with a large, honestly reported energy error or a non-finite-state error.
- The adaptive integrator is not symplectic: over very long integrations its energy error grows roughly linearly with time at the tolerance level. It uses one global step for all bodies (no individual or block time steps, no regularisation of binaries).
- Barnes–Hut: monopole only, tree rebuilt at every evaluation, no individual softening, approximate momentum conservation, O(N²) exact diagnostics below 20 000 bodies and tree-estimated potential above.
- Collisions: discrete detection at step ends; mergers are point-mass mergers (no spin, no fragmentation, no
heat); the O(N·N_massive) overlap test runs every step when a policy other than
.ignoreis set and radii exist. - Softening is a single Plummer length for all pairs.
- Not modelled at all: general relativity beyond the single 1PN term of §2.4, gas dynamics, radiation pressure, tides, oblateness (J2), non-gravitational forces, stellar evolution, dark-matter haloes, cosmological expansion or periodic boundaries, GPU acceleration, individual time steps, regularisation, IAS15/DOP853.
- The library experiments with caller-supplied states are Newtonian point-mass propagations of real initial
conditions; they drift away from a real ephemeris and are labelled
estimated.
10. References
- S. J. Aarseth, M. Hénon, R. Wielen, "A comparison of numerical methods for the study of star cluster dynamics", A&A 37, 183 (1974) — Plummer sampling.
- T. J. Ahrens, A. W. Harris, "Deflection and fragmentation of near-Earth asteroids", Nature 360, 429 (1992) — Δs ≈ 3Δv·t.
- J. Barnes, P. Hut, "A hierarchical O(N log N) force-calculation algorithm", Nature 324, 446 (1986).
- R. R. Bate, D. D. Mueller, J. E. White, Fundamentals of Astrodynamics, Dover (1971) — universal variables.
- D. Blackman, S. Vigna, "Scrambled linear pseudorandom number generators", ACM TOMS 47, 36 (2021; arXiv:1805.01407) — xoshiro256**; SplitMix64 reference code at prng.di.unimi.it.
- A. Chenciner, R. Montgomery, "A remarkable periodic solution of the three-body problem in the case of equal masses", Ann. Math. 152, 881 (2000) — figure-eight, with C. Simó's numerical initial conditions; C. Moore, Phys. Rev. Lett. 70, 3675 (1993).
- B. A. Conway, "An improved algorithm due to Laguerre for the solution of Kepler's equation", Celest. Mech. 39, 199 (1986).
- H. D. Curtis, Orbital Mechanics for Engineering Students, Elsevier — universal Kepler equation, Hohmann transfer, flyby.
- J. R. Dormand, P. J. Prince, "A family of embedded Runge–Kutta formulae", J. Comput. Appl. Math. 6, 19 (1980); E. Hairer, S. P. Nørsett, G. Wanner, Solving Ordinary Differential Equations I, Springer (1993) — step-size control.
- E. Forest, R. D. Ruth, "Fourth-order symplectic integration", Physica D 43, 105 (1990); H. Yoshida, "Construction of higher order symplectic integrators", Phys. Lett. A 150, 262 (1990).
- D. C. Heggie, R. D. Mathieu, "Standardised units and time scales", in The Use of Supercomputers in Stellar Dynamics, Springer (1986) — N-body (Hénon) units.
- B. Paczyński, "Gravitational microlensing by the galactic halo", ApJ 304, 1 (1986); P. Schneider, J. Ehlers, E. E. Falco, Gravitational Lenses, Springer (1992) — point-mass lens.
- H. C. Plummer, MNRAS 71, 460 (1911) — Plummer model.
- A. Toomre, J. Toomre, "Galactic bridges and tails", ApJ 178, 623 (1972) — restricted encounter model.
- D. A. Vallado, Fundamentals of Astrodynamics and Applications, 4th ed., Microcosm Press (2013), Example 6-1 — Hohmann reference numbers.
- C. M. Will, "The confrontation between general relativity and experiment", Living Rev. Relativ. 17, 4 (2014) — 1PN equations of motion, Mercury's 42.98″/century; Mercury's a and e: Explanatory Supplement to the Astronomical Almanac (mean elements at J2000).
- J. Wisdom, "The resonance overlap criterion and the onset of stochastic behavior in the restricted three-body problem", AJ 85, 1122 (1980).
- IAU 2015 Resolution B3 (nominal GM☉, R☉, GM of Jupiter) and CODATA 2018 G via
CosmosCore.Constants.
11. Changes requested outside this module
None required. Benchmarks/Sources/main.swift is now a dispatcher: a module adds its benchmarks by declaring a
[Benchmark] array in its own file and appending it to registry in main.swift.