Skip to main content

hypergraph_rs/raster/
h3.rs

1//! `h3o` u64 boundary (PHASE-R-MAP §4 / divergence D7): all bitwise spatial
2//! algebra for the raster crate lives here, never leaking into graph
3//! semantics. `CellIndex` (u64-backed `NonZeroU64`) is the spatial index
4//! domain type end-to-end; it is stringified only when it crosses the
5//! graph's stringly-typed ID boundary. Feature-gated `cells3d`. Task 9.
6
7use h3o::error::LocalIjError;
8use h3o::{CellIndex, CoordIJ, LatLng, LocalIJ, Resolution};
9
10/// A fixed, deterministic origin cell for the deck's invariant industry hex
11/// grid, at `resolution`. The deck's own grid (`topology-deck.html:169-172`)
12/// is a synthetic axial-coordinate mock with no geographic meaning; `h3o`
13/// requires a real anchor, so `(0,0)` lat/lng is used — arbitrary but fixed,
14/// making every `industry_cell` call a pure function of `(hq,hr)`.
15pub fn origin_cell(resolution: Resolution) -> CellIndex {
16    LatLng::new(0.0, 0.0)
17        .expect("(0.0, 0.0) is always a valid lat/lng")
18        .to_cell(resolution)
19}
20
21/// Snap an industry's axial `(hq, hr)` offset to a real `h3o::CellIndex`,
22/// anchored at `origin` — the **inverse** of `to_local_ij` (Finding 10):
23/// `CellIndex::try_from(LocalIJ::new(origin, CoordIJ::new(hq, hr)))`.
24/// Returns `Err(LocalIjError::Pentagon)` explicitly when the offset crosses
25/// pentagon distortion (12 of 122 base cells are pentagons) — callers MUST
26/// handle it, never `.unwrap()` (Power-of-10 rule 4).
27pub fn industry_cell(origin: CellIndex, hq: i32, hr: i32) -> Result<CellIndex, LocalIjError> {
28    CellIndex::try_from(LocalIJ::new(origin, CoordIJ::new(hq, hr)))
29}
30
31/// Extensive (summable) quantities carried per grid cell (`aggregateCells`,
32/// `topology-deck.html:371-380`): `c`, `v`, `s`, `t` (transformation
33/// transfer), and `n` (member count) all sum under aggregation; `hx`/`hz`
34/// (ground position) sum too, then are divided by `n` at the call site to
35/// recover the mean position (mirrors the deck's `hx/=n; hz/=n`).
36#[derive(Debug, Clone, Copy, PartialEq)]
37pub struct Extensives {
38    pub c: f64,
39    pub v: f64,
40    pub s: f64,
41    pub t: f64,
42    pub n: u32,
43    pub hx: f64,
44    pub hz: f64,
45}
46
47impl Extensives {
48    /// Componentwise sum — the zoom functor's `GROUP BY parent` reducer.
49    fn merge(self, other: Self) -> Self {
50        Self {
51            c: self.c + other.c,
52            v: self.v + other.v,
53            s: self.s + other.s,
54            t: self.t + other.t,
55            n: self.n + other.n,
56            hx: self.hx + other.hx,
57            hz: self.hz + other.hz,
58        }
59    }
60}
61
62/// `GROUP BY parent(h3_index)` (Deviation 7): coarse-grains `cells` — each
63/// `(CellIndex, Extensives)` pair rolls up to `parent(coarse_res)`, extensives
64/// summed. Output order is the order each parent is FIRST encountered while
65/// scanning `cells` (deterministic, independent of any hash order — no
66/// `HashMap` iteration order leaks into the returned `Vec`). Bounded:
67/// `cells.len()` iterations, `cells.len()` worst-case output rows.
68pub fn aggregate_by_parent(
69    cells: &[(CellIndex, Extensives)],
70    coarse_res: Resolution,
71) -> Vec<(CellIndex, Extensives)> {
72    let mut order: Vec<CellIndex> = Vec::with_capacity(cells.len());
73    let mut by_parent: std::collections::HashMap<CellIndex, Extensives> =
74        std::collections::HashMap::with_capacity(cells.len());
75
76    for &(cell, ext) in cells {
77        let parent = cell
78            .parent(coarse_res)
79            .expect("coarse_res must be <= the fine cell's resolution");
80        match by_parent.get_mut(&parent) {
81            Some(acc) => *acc = acc.merge(ext),
82            None => {
83                by_parent.insert(parent, ext);
84                order.push(parent);
85            }
86        }
87    }
88
89    order
90        .into_iter()
91        .map(|parent| (parent, by_parent[&parent]))
92        .collect()
93}