Repository Public
1<!--2ORIX Cosmos3File: Documentation/modules/CosmosSpatial.md4Description: What CosmosSpatial implements (scale bands, floating origin, HEALPix, octree, sky index), file formats, why these indices, how they were validated and measured, known limits.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# CosmosSpatial910Scale hierarchy of the atlas, loss-free floating origin, and the two spatial indices. Depends on `CosmosCore`11(and `simd`) only. No third-party code.1213## What is implemented1415| File | API | Notes |16|---|---|---|17| `ScaleBands.swift` | `ScaleBand` (8 bands), `ScaleHierarchy.bands`, `band(forViewDistance:)`, `band(forViewDistance:current:hysteresis:)`, `blendTowardsNext`, `LengthUnit`, `LengthDisplay.unit/value/meters/string` | Band limits are conventions of the atlas, not physical boundaries. |18| `FloatingOrigin.swift` | `AnchoredPosition` (Int64 cell on a 2³² m grid + Double offset), `FloatingOrigin.relative`, `relativeFloat`, `rebased`, `rebase`, `needsRebase` | ≤ 1 µm resolution out to ±3.96e28 m. |19| `HEALPix.swift` | `HEALPix(order:)`, `pixel(theta:phi:)`, `pixel(longitude:latitude:)`, `pixel(direction:)`, `center(of:)`, `centerLonLat`, `centerVector`, `neighbours(of:)`, `ancestor`, `descendants`, `maxPixelRadius`, `queryDisc(center:radius:inclusive:)`, `queryDiscRanges` | NESTED scheme, orders 0…29. |20| `Octree.swift` | `OctreeBuilder.build/write`, `OctreeFile` (memory-mapped), `OctreeRegion` (`all`, `sphere`, `cone`, `frustum`), `Frustum.perspective`, `forEachPoint`, `points(in:)`, `selectLOD(viewpoint:region:pointBudget:minAngularSize:)` | LOD by brightness. |21| `SkyIndex.swift` | `SkyIndexBuilder.build/write`, `SkyIndexFile` (memory-mapped), `forEachPoint(center:radius:maxMagnitude:)`, `points` | HEALPix-ordered points for direction-only data. |2223### Scale bands2425| Band | View distance (m) | Characteristic length | Origin | Axes | Unit |26|---|---|---|---|---|---|27| surface | 0 – 1e6 | 10 km | focus body | body-fixed | km |28| planetSystem | 1e6 – 5e9 | 3.844e8 m (Earth–Moon) | focus body | ICRF | km |29| solarSystem | 5e9 – 1.5e16 | 1 au | Solar-System barycentre | ecliptic J2000 | au |30| stellarNeighbourhood | 1.5e16 – 3.0857e19 (1 kpc) | 10 pc | Solar-System barycentre | ICRF | pc |31| milkyWay | 1 kpc – 100 kpc | 8.2 kpc (Sun–centre) | Galactic Centre | galactic | kpc |32| localGroup | 100 kpc – 3 Mpc | 780 kpc (M 31) | Galactic Centre | galactic | Mpc |33| largeScaleStructure | 3 Mpc – 1 Gpc | 16.5 Mpc (Virgo) | observer | ICRF | Mpc |34| observableUniverse | > 1 Gpc | ≈ 14 Gpc comoving (model-dependent) | observer | ICRF | Gpc |3536Transition rule: the band containing the camera–focus distance; with a current band, it is kept until the37distance leaves its interval widened by 20 % (hysteresis), so the frame and origin do not flicker on a limit.38`blendTowardsNext` gives a 0…1 cross-fade weight over the last half decade below the upper limit.39Display units: m (< 1 km), km (< 0.01 au), au (< 10⁴ au), pc or ly (< 1 kpc), kpc, Mpc, Gpc.4041### Floating origin4243A Double in metres resolves |p|·2⁻⁵²: 7 m at 1 pc, 7 000 km at 1 Gpc. `AnchoredPosition` keeps an Int64 cell index44on a 2³² m grid plus a Double offset inside the cell; differences are formed exactly in the integer part, so45`relative(to:)` has the relative accuracy of a Double *of the difference*. Rebasing a set of camera-relative46vectors to a new origin adds one exactly formed shift. Tested: a 1 m step at 1 Gpc is preserved exactly; 2 00047integer-metre offsets rebased by 5e12 m at 1.4 Gpc and back are bit-identical.4849## Why these two indices5051* **Octree for 3D positions** (stars with distances, galaxies): the atlas flies through the data, so queries are52 volumes (sphere around the camera, view frustum, cone) and the density varies by orders of magnitude; an octree53 adapts its depth to the density and gives level of detail for free. Points are inserted brightest first; a node54 keeps the first `nodeCapacity` points reaching it. Every node therefore holds the brightest points of its cube55 that no ancestor holds, and `selectLOD` (refinement by apparent node size under a hard point budget, closed56 under ancestors) can draw any view from a bounded number of points with the most luminous objects always57 present. A k-d tree would query as fast but has no natural LOD levels; a uniform grid cannot cope with the58 density contrast between the solar neighbourhood and 1 kpc.59* **HEALPix for directions** (objects without a usable distance, sky tiles): equal-area pixels (so tile60 populations follow the sky density, not the latitude), hierarchical nested numbering (children of p are61 4p…4p+3, so multi-resolution tiles and range scans are trivial), and it is the tiling of the astronomical62 archives themselves (Gaia `source_id` encodes a HEALPix index). The star files of CosmosCatalog are tiled with63 it by the pipeline.6465## File formats (little-endian, versioned, validated on open)6667**Octree** (`octree.bin` in star packs), magic `COSMOCT1`, version 1: header 80 bytes (counts, root cube,68capacity, depth, record sizes); nodes × 40 bytes breadth-first (`firstPoint u64, subtreePointCount u64, pointCount69u32, firstChild u32, maxBrightness f32, minBrightness f32, childMask u8, level u8`), children of a node contiguous;70points × 40 bytes (`x, y, z f64, brightness f32, payload u64`), grouped by node, brightest first. Positions are71absolute Doubles (exact round trip). Opening checks magic, version, sizes, the exact file length and every node's72point range and child range; a truncated or foreign file is rejected.7374**Sky index**, magic `COSMHPX1`, version 1: header 32 bytes, `12·4^order + 1` pixel offsets (u64), points × 3275bytes (`longitude f64, latitude f64, magnitude f32, payload u64`) sorted by nested pixel then magnitude. No76installed pack uses it yet (star packs carry their own tile directory): it is the index for direction-only77layers built later (sky-survey tiles, galaxies without distance).7879## Validation (tests: `Packages/CosmosSpatial/Tests`, 26 tests)8081| Check | Reference | Result asserted |82|---|---|---|83| ang2pix NESTED, 630 directions, orders 0…29 incl. poles and region limits | healpy 1.20.1 (`Tests/Fixtures/healpix_reference.json`, generator script beside it) | identical pixel |84| pix2ang, 9 orders | healpy | ≤ 1e-13 rad |85| 8 neighbours incl. face corners (missing neighbour = nil) | healpy `get_all_neighbours` | identical |86| disc query, pixel centres inside, 60 discs | healpy `query_disc(inclusive=False)` | identical lists |87| `maxPixelRadius` | healpy `max_pixrad` | relative 1e-7 |88| inclusive disc | 300 random points per disc must fall in a returned pixel; ranges = pixels | holds |89| equal area | 480 000 uniform directions over 48 pixels | within 6 σ |90| octree sphere / cone / frustum / brightness cut | brute force on 6 000 clustered random points at scales 1 m, 100 pc, 1 Gpc | identical sets |91| LOD | root = the `capacity` brightest; children never brighter than the parent's faintest; budget never exceeded; ancestor-closed | holds |92| determinism, identical positions, NaN input, corrupted/truncated files | — | as specified |93| sky index cone + magnitude cut | brute force on 8 000 points, orders 0, 3, 5, poles included | identical sets |94| floating origin | 1 m at 1 Gpc; lossless rebasing; µm near the origin | exact |9596The pipeline's Python `ang2pix` (`DataPipeline/catalogs/healpix.py`) was compared with healpy on 160 00097directions: 0 mismatches.9899## Measured (2026-11-24, MacBook Pro M5 Max, release build, 1-min load average 15: other builds were running)100101| Operation | Result |102|---|---|103| HEALPix ang2pix | 38–41 M directions/s (orders 5, 12, 29) |104| HEALPix inclusive disc query | 0.010 ms (order 5, 0.1 rad, 54 px); 0.084 ms (order 8, 0.1 rad, 2 134 px); 5.4 ms (order 8, 1 rad, 182 153 px) |105| Octree build, 477 502 points (stars-gaia-g10) | 0.21 s, 1 482 nodes, 19.2 MB |106| Open + structural check of that file | 0.27 ms |107| Sphere 10 pc around the Sun / 50 pc off-centre | 0.28 ms (149 pts) / 0.45 ms (1 853 pts) |108| Cone 0.1 rad to 1 kpc / frustum 60° to 2 kpc | 2.1 ms (587 pts) / 2.6 ms (26 033 pts) |109| LOD selection, budget 10 000 / 100 000 | 0.03 ms (9 078 pts, 9 nodes) / 0.06 ms (99 965 pts, 170 nodes) |110111Reproduce: `swift run -c release cosmos-bench spatial.indices` (needs the packs; `COSMOS_PACKS_DIR` overrides the112location).113114## Known limits115116- `OctreeBuilder` and `SkyIndexBuilder` hold all points in memory (pipeline use); the readers do not.117- The cone test of the octree prunes with the bounding sphere of a node (conservative); half-angles ≥ 90° are118 pruned by distance only. Results are exact in all cases (points are tested individually).119- `selectLOD` returns nodes; a node partly outside the region is returned whole (the caller clips or accepts it).120- `queryDisc(inclusive: true)` is a superset (pixels whose centre is within radius + pixel radius); filter points121 exactly, as `SkyIndexFile` does. No polygon or strip queries, no RING scheme.122- The octree stores one position per point at one epoch (J2016.0 in the star packs); stellar motion over123 centuries must be applied from the star records.124- `ScaleOrigin.galacticCenter` names the origin; the Sun–centre vector and its uncertainty come from125 `MilkyWayModel` (CosmosCatalog). There is no supergalactic frame in `CosmosCore.ReferenceFrame` yet.126