Repository Public
1<!--2ORIX Cosmos3File: Documentation/modules/CosmosLaboratory.md4Description: What CosmosLaboratory implements (experiment record, N-body solvers and integrators, collisions, diagnostics, run control, experiment library, export), the equations and references, measured validation and benchmark numbers, reproducibility guarantees, numerical limits and what is not modelled.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# CosmosLaboratory910Reproducible astrophysics experiments. The laboratory is strictly separate from the reference universe: an11experiment is a self-contained, versioned, `Codable` document that never reads or mutates catalogue or ephemeris12data. Depends on `CosmosCore` and `CosmosMath` only. CPU, double precision, Swift 6 strict concurrency.1314**Plain statements first**1516- Gravity is **Newtonian**. There is **no general-relativistic solver**. The single optional relativistic17 ingredient is a first-order post-Newtonian perihelion term (§2.4), validated against Mercury and labelled as such.18- There is **no GPU solver**. Both solvers (direct summation and Barnes–Hut) run on the CPU.19- The point-mass lens (§6) is a set of **optics formulas**, not a simulation.20- The galaxy "merger" is a **restricted toy model** (§5); its cores never merge.2122## 1. Files and API2324| File | Contents |25|---|---|26| `Experiment.swift` | `Experiment`, `LabBody`, `UnitSystem` (`.si`, `.nBody`), `ForceSolver`, `IntegratorChoice`, `CollisionPolicy`, `GravityModel`, `validate()`, JSON (`jsonData()`, `init(jsonData:)`), `LabJSON` |27| `LabRandom.swift` | `LabRandom` (SplitMix64 seeding + xoshiro256**), `uniform`, `normal`, `direction` |28| `Forces.swift` | direct-summation kernel (SIMD4, threads), `BarnesHutTree`, exact pair diagnostics, public `ForceProbe` |29| `NBodyEngine.swift` | `NBodyEngine: SimulationEngine`, `EngineSnapshot`, `Diagnostics`, `CollisionEvent`, `RunTermination` |30| `Runner.swift` | `Laboratory.run` / `.resume` (synchronous), `ExperimentRunner` (actor), `RunOptions`, `FrameDelivery`, `Frame`, `RunProgress`, `ExperimentResult`, `TrajectorySample` |31| `Analytic.swift` | `TwoBody` (elements, vis-viva, universal-variable propagation), `HohmannTransfer`, `Flyby`, `PointMassLens` |32| `Library.swift` | `ExperimentLibrary` (the experiments of §5), `LibraryExperiment`, `ExpectedQuantity`, `StabilityScan`, `Laboratory.closestApproach` |33| `LabExport.swift` | `LabExport.diagnosticsCSV`, `.trajectoriesCSV`, `.json`, `.result(fromJSON:)` |3435### Build and run an experiment3637```swift38// 1. Describe (or take one from the library; every library call also returns the analytic expectation).39let lib = try ExperimentLibrary.binary(mass1: 1, mass2: 1, semiMajorAxis: 1, eccentricity: 0.5, orbits: 10,40 integrator: .yoshida4(timeStep: 0.001), units: .nBody)41let exp: Experiment = lib.experiment // Codable document; exp.jsonData() / Experiment(jsonData:)42lib["period"]; lib.expectations; lib.modelNotes // what theory predicts, what the model leaves out4344// 2a. Synchronously (scripting, tests, command line). Honours Swift task cancellation.45let result = try Laboratory.run(exp) { frame in /* every output, index 0 = initial state */ }4647// 2b. From the UI: an actor with pause / resume / cancel / progress / snapshots and a frame stream.48let runner = try ExperimentRunner(experiment: exp, options: RunOptions(frameDelivery: .backpressure(buffer: 2)))49await runner.start()50for await frame in runner.frames { draw(frame.positions); show(frame.diagnostics) } // the run waits for the consumer51await runner.pause(); await runner.resume(); await runner.cancel()52let p = await runner.progress // state, fraction, time, stepCount, outputCount, wallClockSeconds53let checkpoint = await runner.snapshot() // EngineSnapshot (Codable); ExperimentRunner(snapshot:) continues it54let result = try await runner.result() // ExperimentResult, or throws CosmosError.cancelled / the engine error5556// 3. Results and export.57result.diagnostics; result.maxRelativeEnergyError; result.events; result.finalBodies; result.finalSnapshot58let csv = LabExport.diagnosticsCSV(result) // units in headers59let traj = try LabExport.trajectoriesCSV(result) // needs RunOptions.storeTrajectories60let json = try LabExport.json(result) // experiment + results + events + final snapshot + versions61```6263`NBodyEngine` can also be driven directly: `init(experiment:)`, `init(snapshot:)`, `step() -> StepOutcome`64(`.stepped`, `.outputReached`, `.finished`), `advance(by:)` (the `CosmosCore.SimulationEngine` requirement),65`diagnostics()`, `frame()`, `snapshot()`, and read-only state (`time`, `stepCount`, `ids`, `positions`,66`velocities`, `masses`, `bodies`, `events`, `termination`).6768## 2. Models and equations6970### 2.1 Experiment record7172`Experiment` stores: `schemaVersion` (currently 1), `engineID` (`orix.cosmos.laboratory.nbody`), `engineVersion`73(`1.0.0`), `title`, `seed`, `units` (unit symbols and the value of G in those units — the engine is unit-agnostic),74`bodies` (`id`, `name`, `mass`, `position`, `velocity`, optional `radius`, `isTestParticle`), `solver`,75`integrator` with its parameters, `softeningLength`, `collisionPolicy`, `gravity`, `duration`, `outputInterval`,76`notes`, and a `ScientificStatus` (`hypothetical` by default and for every modified universe; the77caller-supplied-states experiments default to `estimated`, see §5).7879- JSON is canonical: sorted keys, pretty printed, every `Double` in shortest round-trip form, so80 decode → encode gives the same bytes and every number is restored bit for bit (tested, including −0.0 and81 values near the subnormal range).82- `validate()` runs before anything is encoded, decoded or simulated and throws `CosmosError.invalidInput`83 (never crashes) on: no bodies; NaN/∞ anywhere; mass ≤ 0 for a massive body; non-zero mass for a test particle;84 radius ≤ 0; duplicate identifiers; a massive body sharing its position with any other body; non-positive85 step, tolerance, duration or output interval; more than 9·10¹⁵ steps; negative softening; opening angle86 outside [0, 2]; leaf capacity outside 1…1024; a post-Newtonian term without a valid central body or with a87 fixed-step integrator; a schema version newer than this build.88- A **test particle** feels gravity and exerts none. It must be declared (`isTestParticle`, mass exactly 0) so89 that a zero mass is never accepted by accident. Two test particles may coincide.9091### 2.2 Forces9293Pair acceleration with Plummer softening ε (ε = 0: pure Newton):9495```96a_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|² + ε²)97```9899- **Direct summation** (`.direct`): exact pair sum over the massive bodies, O(N·N_massive) per evaluation. Kernel:100 sources packed four per `SIMD4<Double>`, one division and one square root per pair; targets are partitioned101 across threads with `DispatchQueue.concurrentPerform` when N·N_massive ≥ 65 536. Each target's sum has a fixed102 order, so the result does not depend on the number of cores or on scheduling. What SIMD and threads actually103 buy is measured in §8 (kernel table). No Accelerate/vDSP call is used: the kernel is a single fused loop and104 vDSP would need several passes over temporary arrays.105- **Barnes–Hut** (`.barnesHut(openingAngle: θ, leafCapacity:)`): octree over the massive bodies rebuilt at every106 force evaluation; cells carry total mass and centre of mass (**monopole only**, no quadrupole); a cell of side107 s at distance d from its centre of mass is accepted when s/d < θ, otherwise opened; leaves (≤ `leafCapacity`108 bodies) are summed directly. θ = 0 reproduces direct summation to rounding. The force error versus θ is measured109 in §7. Barnes–Hut forces are not exactly antisymmetric, so linear momentum is conserved only approximately.110111### 2.3 Integrators112113| Choice | Method | Order | Properties |114|---|---|---|---|115| `.leapfrog(timeStep:)` | kick–drift–kick (velocity Verlet) | 2 | symplectic, time-reversible, 1 force evaluation per step |116| `.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 |117| `.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 |118119Adaptive error control: a step is accepted when max_i|Δx_i| ≤ atol_x + rtol·max_i|x_i| and120max_i|Δv_i| ≤ atol_v + rtol·max_i|v_i| (Δ = difference between the 5th- and 4th-order solutions; maxima over121bodies). The scale is global, not per body, and not translation-invariant: use a barycentric frame.122123Only integrators validated in §7 are shipped. IAS15 and DOP853 are **not** implemented.124125**Output plan.** Fixed-step runs take ⌈duration/dt⌉ steps and output every round(outputInterval/dt) steps (and126at the last step): the output interval is rounded to a whole number of steps and time is `stepCount·dt`, never an127accumulated sum. Adaptive runs land exactly on k·outputInterval and on the duration (the step is shortened to hit128them; the controller's preferred step is kept for the next step).129130### 2.4 Gravity model: Newtonian, plus one optional post-Newtonian term131132`GravityModel.postNewtonianPerihelion(centralBody:speedOfLight:)` adds to every other body the 1PN Schwarzschild133acceleration in the test-particle limit, with r, v relative to the central body of mass M:134135```136a_1PN = GM / (c² r³) · [ (4GM/r − v²) r + 4 (r·v) v ]137```138139It reproduces the perihelion advance Δω = 6πGM / (c² a (1 − e²)) per orbit — and nothing else: no mutual 1PN140terms between planets, no reaction on the central body (momentum is not conserved by this term), no light141bending, no frame dragging, no gravitational radiation. It is velocity dependent, so it is only accepted with the142adaptive integrator. The energy reported in the diagnostics remains the Newtonian energy.143144### 2.5 Collisions145146Detection by radii after every step: bodies i, j with known radii collide when |r_i − r_j| < R_i + R_j (at least147one of them massive). Detection is discrete: a pair that crosses and separates within one step is missed, and the148contact is recorded up to one step late.149150| Policy | Behaviour |151|---|---|152| `.ignore` | radii unused |153| `.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`. |154| `.stopOnContact` | the run ends (`termination == .stoppedOnContact`) and reports the pair, separation and relative speed |155156### 2.6 Diagnostics (every output)157158`Diagnostics`: time, step count, body count, kinetic, potential and total energy, linear momentum, angular159momentum vector (about the frame origin), barycentre position and velocity, `relativeEnergyError`,160`mergerEnergyChange`, closest pair distance and identifiers, `potentialIsApproximate`, wall-clock seconds.161162- `relativeEnergyError = (E − E₀ − ΣΔE_mergers) / |E₀|`: the integration error alone; energy deliberately163 removed by mergers is reported separately. It is `nil` when E₀ = 0 exactly, and **meaningless when E₀ ≈ 0**164 (parabolic encounters): compare the absolute drift with the kinetic energy instead.165- Sums use Neumaier compensation (`CosmosMath.CompensatedSum`).166- Cost O(N·N_massive) per output (exact pair sum and closest-pair search). For a Barnes–Hut run with more than167 20 000 massive bodies the potential is the tree estimate ½Σ m_i φ_i (`potentialIsApproximate == true`) and the168 closest pair is **not computed** (`nil`).169- Drift is reported as measured; nothing is renormalised or corrected.170171### 2.7 Run control, memory and reproducibility172173- `ExperimentRunner` (actor): `start`, `pause`, `resume`, `cancel` (Swift task cancellation; `result()` then174 throws `CosmosError.cancelled`), `progress`, `snapshot`, `currentDiagnostics`, `result`, `frames`,175 `detachFrames`. The computation runs in slices of `RunOptions.sliceSeconds` (default 10 ms) of wall-clock time;176 control requests are served between slices, so the latency of pause/cancel/snapshot is one slice plus one177 integrator step (a step of a 10⁵-body run is not interruptible).178- **Frames**: `.backpressure(buffer: n)` — at most n frames wait and the simulation suspends until the consumer179 takes one (nothing is dropped; a consumer that stops reading stalls the run until it is cancelled or180 `detachFrames()` is called); `.dropOldest(buffer: n)` — the simulation never waits; `.none`.181- **Bounded memory**: at most `maxStoredSamples` (default 4096) diagnostics samples are kept. When the bound is182 reached every other stored sample is discarded and the storage stride doubles (decimation by powers of two;183 the initial and final outputs are always kept; `ExperimentResult.sampleStride` records the stride).184 Trajectories (`storeTrajectories`) use the same scheme, additionally bounded by `maxTrajectoryBytes`185 (24 bytes per body per sample, default 256 MiB). Frames themselves are never accumulated by the runner.186- **Reproducibility — guaranteed** (tested): on the same machine and build, the same experiment gives187 bit-identical states (a) from run to run, (b) whether it is run synchronously or through the actor, (c) with188 any pattern of pause/resume, any slice length and any frame delivery, (d) when stopped at an arbitrary step,189 checkpointed to JSON and continued from the decoded snapshot, (e) with any number of cores.190 Snapshots are refused by a different engine version.191- **Reproducibility — not guaranteed**: across CPU architectures, operating-system versions, compiler versions or192 optimisation levels. Reasons: the adaptive controller calls `pow`, the samplers call `log`, `cos`, `sin`, and193 none of these is correctly rounded by IEEE 754; the compiler may contract a·b + c differently between builds.194 The integer stream of `LabRandom` (`next()`, `uniform()`) *is* identical everywhere. Wall-clock fields are195 measurements and never reproducible.196197## 3. Random numbers198199`LabRandom(seed:)`: xoshiro256** (Blackman & Vigna 2018) with the four state words produced by SplitMix64 from the200seed. `uniform()` = (next() >> 11)·2⁻⁵³ ∈ [0, 1); `normal()` by Box–Muller (second variate discarded, no hidden201cache); `direction()` uniform on the sphere. The run itself draws no random numbers: the seed only shapes the202initial conditions and is stored in the experiment.203204## 4. Analytic references (`Analytic.swift`)205206- `TwoBody.propagate(mu:position:velocity:dt:)`: exact Kepler propagation for any conic with the universal variable207 χ and Stumpff functions, solved by Laguerre–Conway iteration; bound orbits are first reduced modulo the period.208- `TwoBody.elements`, `stateAtTrueAnomaly`, `timeSincePeriapsis`, `period`, `visVivaSpeed`, `circularSpeed`.209- `HohmannTransfer(mu:r1:r2:)`: a_t = (r₁ + r₂)/2, Δv₁ = |√(μ(2/r₁ − 1/a_t)) − √(μ/r₁)|,210 Δv₂ = |√(μ/r₂) − √(μ(2/r₂ − 1/a_t))|, T = π√(a_t³/μ), phase angle π − n₂T.211- `Flyby(mu:vInfinity:periapsis:)` / `(…impactParameter:)`: e = 1 + r_p v∞²/μ, turn angle δ = 2 asin(1/e),212 b = r_p√(1 + 2μ/(r_p v∞²)), |Δv| = 2 v∞ sin(δ/2).213- `PointMassLens`: see §6.214215## 5. Experiment library (`ExperimentLibrary`)216217Each function returns a `LibraryExperiment`: the `Experiment`, the analytic `expectations` (name, value, unit,218formula) when one exists, and `modelNotes` that the UI must show with the result.219220| Function | System | Analytic expectation |221|---|---|---|222| `twoBody(primaryMass:secondaryMass:periapsis:eccentricity:initialTrueAnomaly:duration:…)` | two-body problem, any eccentricity (ellipse, parabola, hyperbola) | period, energy, angular momentum, exact final relative state |223| `binary(mass1:mass2:semiMajorAxis:eccentricity:orbits:…)` | equal and unequal binaries | same |224| `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 |225| `changingMass(in:of:factor:)`, `addingBody(to:_:)` | any experiment with one mass changed / one body added (status `hypothetical`) | none |226| `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 ≤ ½ |227| `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) |228| `meanMotionResonance(…p:q:…)` | particles at and around the interior p:q resonance | a_res = a_p (q/p)^{2/3}, period ratio |229| `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 |230| `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 |231| `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) |232| `galaxyMerger(…)` | **restricted toy model**: two softened cores, rings of test particles | pericentre time and distance of the point-mass orbit only |233| `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 |234| `figureEight(periods:…)` | Chenciner–Montgomery three-body choreography | period 6.32591398, zero angular momentum |235236Details that matter:237238- **Plummer sampling** (Aarseth, Hénon & Wielen 1974): X uniform → r = a (X^{−2/3} − 1)^{−1/2}, resampled beyond239 `truncationRadius`·a (default 20a, which encloses 99.6 % of the mass); isotropic direction; speed v = q·v_esc(r),240 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);241 the sample is shifted to its barycentre at rest. Default units are Hénon units (G = M = 1, a = 3π/16, E = −¼).242 Default softening a·N^{−1/3}. Equal masses, no primordial binaries, no stellar evolution, no tidal field.243- **Stability scan**: all test planets ride in one run (they do not interact). `StabilityScan.survival`244 declares a particle lost when its osculating orbit about the star becomes unbound, when its osculating245 semi-major axis departs from the initial one by more than `maxFractionalDrift` (default 20 %), or when it enters246 the planet's Hill sphere. These are conventions. `survivalTime == nil` means "survived the whole run", i.e.247 only a lower bound; a finite run proves nothing about long-term stability.248- **Galaxy "merger"** (after Toomre & Toomre 1972): explicitly approximate. No gas, no star formation, no249 dark-matter halo, no self-gravity of the discs, no dynamical friction — the cores follow a softened two-body250 orbit and **do not merge**; the test particles only trace tidal bridges and tails.251- **Asteroid deflection**: heliocentric two-body motion; the target has no gravity (no gravitational focusing,252 no keyholes); impulsive and perfectly along-track Δv; no momentum-enhancement factor. The target is a point:253 compare the miss distance with its radius yourself. `closestApproach` interpolates the relative trajectory254 inside each integrator step with a cubic Hermite polynomial and minimises it with Brent's method.255- **Hohmann**: the first impulse is in the initial velocity; the second impulse is the analytic value (the run256 ends at arrival and verifies distance, speed, zero radial velocity and rendezvous with the target).257- **Gravity assist**: only the planet's gravity acts (no star, no curvature of the planet's path).258259## 6. Point-mass gravitational lens (pedagogical)260261Weak-field, thin-lens, small-angle formulas — optics, not a GR simulation (no ray tracing in a metric, no strong262field, no extended lens, no time delay):263264```265α = 4GM/(c² b) θ_E = √(4GM/c² · D_LS/(D_L D_S))266θ± = (β ± √(β² + 4θ_E²))/2 μ± = ½ ± (u² + 2)/(2u√(u² + 4)), u = β/θ_E μ_tot = (u² + 2)/(u√(u² + 4))267```268269`deflectionAngle` refuses impact parameters inside the Schwarzschild radius. Perfect alignment (u = 0) returns270the Einstein ring positions and `nil` magnifications (formally infinite for a point source). Distances are271angular-diameter distances; take them from CosmosCosmology in a cosmological setting.272273## 7. Validation (Swift Testing, 42 tests in 5 suites; numbers printed by the tests as `MEASURED …`)274275Measured in a debug build on the machine of §8. Tolerances asserted in the tests are 1.5–10× the measured values.276277**Kepler problem** (equal masses, a = 1, G = 1, T = 2π/√2; error = |relative position − analytic| in units of a)278279| Check | Measured | Asserted |280|---|---|---|281| 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 |282| Yoshida 4, same: position / energy / angular momentum | 1.02e-8 / 5.8e-11 / 2.4e-14 | 3e-8 / 2e-10 / 1e-13 |283| 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 |284| period from axis crossings (m = 3 + 1, e = 0.3) vs Kepler III | 5.9e-12 relative | 2e-5 |285| convergence order, leapfrog (T/500 … T/4000, e = 0.3) | 2.0003, 2.0001, 2.0000 | 2 ± 0.05 |286| convergence order, Yoshida 4 (T/250 … T/2000) | 3.997, 3.999, 4.000 | 4 ± 0.1 |287| convergence order, Dormand–Prince at fixed step (T/100 … T/800) | 5.15, 5.18, 5.14 | 5 ± 0.3 |288| 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 |289| 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 |290| unbound, e = 1 / 1.5 / 3 through periapsis, vs universal-variable solution | 2.0e-12 / 6.4e-13 / 5.3e-14 relative | 1e-9 |291| `TwoBody.propagate` vs conic formulas, e = 0 … 5 | < 1e-12 relative | 1e-12 |292293**Three-body and relativity**294295| Check | Measured | Asserted |296|---|---|---|297| 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 |298| figure-eight, cyclic exchange of positions at T/3 | exact permutation to 5e-7 | 5e-7 |299| figure-eight after 10 periods, leapfrog T/20000 / Yoshida T/2000 | 4.1e-6 / 4.2e-7 | 2e-4 |300| 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 |301| same run without the term | 2.4e-4″/century | < 0.002 |302303**Forces**304305| Check | Measured | Asserted |306|---|---|---|307| SIMD/threaded kernel vs scalar reference, N = 2 … 700, max relative difference | ≤ 2.5e-15 | 1e-12; call-to-call bit identity |308| Barnes–Hut vs direct, Plummer N = 4000, leaf 8, rms / max relative force error (interactions per body) | see table below | bounds below |309| Barnes–Hut potential energy, N = 3000, θ = 0.5, leaf 1 / 8 / 32 | 9.7e-6 / 2.4e-5 / 2.0e-5 relative | 2e-3 |310| 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 |311312| θ | rms force error | max force error | interactions per body (direct = 3999) | asserted rms bound |313|---|---|---|---|---|314| 0 | 2.1e-15 | 9.7e-15 | 3999 | 1e-12 |315| 0.2 | 1.0e-4 | 5.8e-4 | 3260 | 1e-3 |316| 0.3 | 3.7e-4 | 1.2e-3 | 2628 | 1e-3 |317| 0.5 | 2.0e-3 | 1.6e-2 | 1583 | 1e-2 |318| 0.7 | 5.8e-3 | 8.4e-2 | 970 | 1e-2 |319| 1.0 | 2.0e-2 | 1.5e-1 | 507 | 5e-2 |320321With monopole cells the maximum error is an order of magnitude above the rms: a few bodies sit next to a cell322whose centre of mass is far from its centre. Use θ ≤ 0.5 for anything quantitative.323324**Collisions, conservation, sampling**325326| Check | Measured | Asserted |327|---|---|---|328| merge: change of total linear momentum | 6.2e-15 | 1e-13 |329| merge: energy change vs −(½μv_rel² − Gm₁m₂/d) | agree | 1e-3 relative |330| merge: energy error once the merger loss is accounted for | 7.6e-6 | 1e-5 |331| 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 |332| Plummer N = 2000: T, W, half-mass radius over model values; virial ratio | 1.0026, 0.99997, 0.989; 0.5013 | ±6 %, ±6 %, ±8 % |333334**Library experiments**335336| Check | Reference | Measured | Asserted |337|---|---|---|---|338| 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 |339| 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 |340| circular speed and period at 1 au | 29.78 km/s; Gaussian year 365.2569 d | reproduced | 0.01 km/s; 1e-3 d |341| 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 |342| 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 |343| 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 |344| changed star mass (f = 0.8): e′ and a′ of the simulated orbit | energy argument | agree | 1e-9 |345| 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 |346| same: rule of thumb 3Δv·t | Ahrens & Harris (1992) | 4734 km; 9467 km (order of magnitude only) | within ×10 |347| asteroid without deflection: miss distance | 0 by construction | 1.3 m (of 1.5e11 m) | < 1 km |348| 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 |349| 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 |350| 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 |351| 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 % |352| solar-limb light deflection | 1.75″ | 1.7512″ | 0.005″ |353| Einstein radius, 1 M☉ at 4 kpc, source at 8 kpc | formula | 1.009 mas | 0.01 mas |354| lens equation, θ₊θ₋ = −θ_E², μ₊ + μ₋ = 1, μ_tot(u = 1) = 3/√5, magnification vs finite differences | identities | hold | 1e-12 … 1e-6 |355356**Run control and records** — bit-identical restart from a JSON snapshot taken at an arbitrary step, and357bit-identical actor run with repeated pause/resume, for five experiments (adaptive figure-eight, Yoshida358figure-eight, direct leapfrog cluster, Barnes–Hut cluster, cluster with mergers); backpressure (the producer stops359at the buffer size until the consumer reads; 301 of 301 frames delivered in order); `dropOldest` and `none`;360cancellation of a running and of a paused actor run, of `Laboratory.run` and of `advance(by:)`; decimation361(1001 outputs → 64 stored, stride 16, kept samples identical to the undecimated run); output plan; JSON round362trip byte-stable with sorted keys; 28 pathological inputs rejected by `validate`, the engine, the runner and the363encoder; a singular run fails with an error; generator determinism and moments; CSV/JSON export round trips.364365Sources of the reference numbers are listed in §10. The Sun–Earth–Moon states used by the test are synthetic366(circular coplanar orbits) and are labelled as such: that test checks plumbing and sanity, not ephemeris accuracy.367368## 8. Benchmarks369370`swift run -c release cosmos-bench lab.direct lab.kernel lab.barneshut lab.integrators` (`cosmos-bench list`371shows every benchmark; `--quick` shortens them). The program prints the machine, OS, build configuration and372load average it reads from the system, and only numbers it measured.373374Output obtained on 2026-11-24 (release build; MacBook Pro, Apple M5 Max, 18 cores, 48 GB, macOS 27.0).375**The machine was shared with other builds and test runs while this was measured** (see the load averages in376the output): throughputs, the multi-threaded ones above all, are pessimistic and fluctuate from run to run.377378```379# cosmos-bench380machine: Mac17,6 — Apple M5 Max, 18 active cores, 48 GB381os: Version 27.0 (Build 26A5425a)382build: release383load average at start (1 min): 46.9 — other processes were competing for the CPU; timings are pessimistic384385## lab.direct — direct N-body, leapfrog: steps/s, pair interactions/s, energy error (N = 2 … 10 000) [1-min load average now: 46.9]386leapfrog KDK, dt = 1/256 Hénon time units, Plummer softening a·N^(-1/3); N = 2 is an unsoftened circular binary; best of 3 runs387N steps wall [s] steps/s pair interactions/s |dE/E| at end3882 2000000 0.363 5.507e+06 1.101e+07 5.2e-1138910 400000 0.127 3.147e+06 2.833e+08 1.36e-06390100 20000 0.176 1.138e+05 1.127e+09 3.65e-063911000 400 0.08 5003 5.01e+09 3.34e-0739210000 12 0.0845 142 1.538e+10 5.51e-08393394## lab.kernel — force kernel: scalar reference vs SIMD4 vs SIMD4 + threads [1-min load average now: 43.7]395one force evaluation of a Plummer cluster, best of several repetitions; speed-up relative to the scalar reference396N kernel wall [ms] pair interactions/s speed-up max rel. diff vs scalar397100 scalar, 1 thread 0.01171 8.456e+08 1 0398100 simd4, 1 thread 0.008542 1.159e+09 1.37 7e-16399100 simd4 + threads 0.008541 1.159e+09 1.37 7e-164001000 scalar, 1 thread 1.198 8.339e+08 1 04011000 simd4, 1 thread 0.803 1.244e+09 1.49 2.7e-154021000 simd4 + threads 0.1196 8.354e+09 10 2.7e-1540310000 scalar, 1 thread 123.5 8.093e+08 1 040410000 simd4, 1 thread 81.17 1.232e+09 1.52 9.8e-1540510000 simd4 + threads 6.458 1.548e+10 19.1 9.8e-15406407## lab.barneshut — Barnes–Hut (θ = 0.5): steps/s, interactions/s, force and energy error (N = 10⁴ … 10⁵) [1-min load average now: 43.7]408leapfrog KDK, dt = 1/256, θ = 0.5, leaf capacity 8, monopole cells; force error measured against direct summation of the same state409energy error: exact pair sum for N ≤ 20 000, tree estimate (approximate) above; timings: best of 3 runs; a tree is rebuilt at every force evaluation410N steps wall [s] steps/s interactions/s interactions/body/step rms force err max force err |dE/E| at end41110000 40 0.2 199.6 4.923e+09 2405.9 0.00216 0.0631 7.72e-0741230000 16 0.335 47.75 4.766e+09 3131.7 0.00156 0.0386 2.17e-05413100000 6 0.709 8.466 3.417e+09 3459.4 0.00127 0.0534 8.35e-06414415## lab.integrators — integrators on a Kepler orbit (e = 0.5, 100 orbits): cost and accuracy [1-min load average now: 42.6]416equal-mass binary, a = 1, e = 0.5, 100 orbits; position error against the analytic Kepler solution (units of a)417integrator steps force evals wall [s] steps/s position error max |dE/E|418leapfrog, T/1000 100000 100001 0.0288 3.469e+06 0.176 0.000107419leapfrog, T/10000 1000000 1000001 0.315 3.173e+06 0.00177 1.06e-06420yoshida4, T/1000 100000 300000 0.0539 1.857e+06 2.62e-05 1.49e-08421yoshida4, T/10000 1000000 3000000 0.488 2.047e+06 2.36e-09 1.51e-12422dopri54, rtol 1e-8 8601 51607 0.0124 6.926e+05 7.71e-05 5.77e-08423dopri54, rtol 1e-12 51801 310807 0.0763 6.788e+05 1.96e-07 2.39e-10424```425426Reading the numbers:427428- **Direct summation**: 1.5·10¹⁰ pair interactions per second at N = 10⁴ (142 leapfrog steps/s); 5.0·10⁹ at429 N = 10³ (5.0·10³ steps/s). Below N ≈ 100 the per-step overhead (array bookkeeping, no threads) dominates:430 5.5·10⁶ steps/s for two bodies.431- **What SIMD and threads buy** (kernel table): the SIMD4 kernel is 1.4–1.5× faster than the scalar loop on one432 thread — a modest but measured gain, limited by the double-precision divide and square root of each pair;433 threads bring the N = 10⁴ evaluation to 19× the scalar reference on this 18-core machine under load. Results434 agree with the scalar reference to ≤ 1e-14 relative.435- **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 of436 0.13–0.22 % and a maximum of 4–6 % on single bodies. At N = 10⁴ it is only 1.4× faster than direct summation437 (2406 interactions per body instead of 9999, in a scalar tree walk); the gain grows with N (3459 interactions438 per body at 10⁵, where direct summation would need 10⁵).439- **Energy errors** are those of the short benchmark runs (12–2·10⁶ steps) and are quoted to show that the timed440 code is the validated code, not as a statement about long-term accuracy.441- **Integrators**: per step, Yoshida costs 3 force evaluations and Dormand–Prince 6. For the same position error442 after 100 orbits of an e = 0.5 binary, Yoshida with T/1000 (3·10⁵ evaluations, 2.6e-5) beats leapfrog with443 T/10000 (10⁶ evaluations, 1.8e-3); the adaptive integrator at rtol 1e-12 reaches 2.0e-7 with 3.1·10⁵ evaluations444 but its energy error (2.4e-10 after 100 orbits, 2.4e-11 after 10) grows with time, unlike the symplectic ones.445446## 9. Numerical limits and what is not modelled447448- Double precision throughout. Direct summation costs O(N²): about 10⁴ bodies is the practical interactive limit449 (see §8); Barnes–Hut extends this to ~10⁵ with percent-level force errors.450- Fixed-step integrators do not resolve close encounters: use softening, a smaller step, or the adaptive451 integrator. An unsoftened singular encounter makes the adaptive integrator stop with a step-underflow error;452 a fixed step goes through it with a large, honestly reported energy error or a non-finite-state error.453- The adaptive integrator is not symplectic: over very long integrations its energy error grows roughly454 linearly with time at the tolerance level. It uses one global step for all bodies (no individual or block time455 steps, no regularisation of binaries).456- Barnes–Hut: monopole only, tree rebuilt at every evaluation, no individual softening, approximate momentum457 conservation, O(N²) exact diagnostics below 20 000 bodies and tree-estimated potential above.458- Collisions: discrete detection at step ends; mergers are point-mass mergers (no spin, no fragmentation, no459 heat); the O(N·N_massive) overlap test runs every step when a policy other than `.ignore` is set and radii exist.460- Softening is a single Plummer length for all pairs.461- Not modelled at all: general relativity beyond the single 1PN term of §2.4, gas dynamics, radiation pressure,462 tides, oblateness (J2), non-gravitational forces, stellar evolution, dark-matter haloes, cosmological463 expansion or periodic boundaries, GPU acceleration, individual time steps, regularisation, IAS15/DOP853.464- The library experiments with caller-supplied states are Newtonian point-mass propagations of real initial465 conditions; they drift away from a real ephemeris and are labelled `estimated`.466467## 10. References468469- 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.470- T. J. Ahrens, A. W. Harris, "Deflection and fragmentation of near-Earth asteroids", Nature 360, 429 (1992) — Δs ≈ 3Δv·t.471- J. Barnes, P. Hut, "A hierarchical O(N log N) force-calculation algorithm", Nature 324, 446 (1986).472- R. R. Bate, D. D. Mueller, J. E. White, *Fundamentals of Astrodynamics*, Dover (1971) — universal variables.473- 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.474- 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).475- B. A. Conway, "An improved algorithm due to Laguerre for the solution of Kepler's equation", Celest. Mech. 39, 199 (1986).476- H. D. Curtis, *Orbital Mechanics for Engineering Students*, Elsevier — universal Kepler equation, Hohmann transfer, flyby.477- 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.478- 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).479- 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.480- 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.481- H. C. Plummer, MNRAS 71, 460 (1911) — Plummer model.482- A. Toomre, J. Toomre, "Galactic bridges and tails", ApJ 178, 623 (1972) — restricted encounter model.483- D. A. Vallado, *Fundamentals of Astrodynamics and Applications*, 4th ed., Microcosm Press (2013), Example 6-1 — Hohmann reference numbers.484- 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).485- J. Wisdom, "The resonance overlap criterion and the onset of stochastic behavior in the restricted three-body problem", AJ 85, 1122 (1980).486- IAU 2015 Resolution B3 (nominal GM☉, R☉, GM of Jupiter) and CODATA 2018 G via `CosmosCore.Constants`.487488## 11. Changes requested outside this module489490None required. `Benchmarks/Sources/main.swift` is now a dispatcher: a module adds its benchmarks by declaring a491`[Benchmark]` array in its own file and appending it to `registry` in `main.swift`.492