Skip to main content

hypergraph_rs/raster/instruments/
sankey.rs

1//! Instrument III — the OCC hyper-Sankey over the invariant u64 H3 grid
2//! (`topology-deck.html:361-435`, Task 9). Every industry snaps to a real
3//! `h3o::CellIndex`; ribbons are the transformation-algebra `T` transfers
4//! (Task 5) reified as a proportional bipartite (multi-donor -> absorber)
5//! allocation — a directed hyperedge, PHASE-R-MAP §3. FINE/COARSE zoom is
6//! the coarse-graining functor `GROUP BY parent(h3_index)` (`h3::
7//! aggregate_by_parent`): extensives sum, `Φ` and `r` are invariant.
8
9use h3o::{CellIndex, Resolution};
10
11use crate::raster::algebra::{transform, Industry};
12use crate::raster::color::heat;
13use crate::raster::h3::{aggregate_by_parent, industry_cell, origin_cell, Extensives};
14use crate::raster::{Face, Node3, Rgb, SceneGraph3D, Strut, Vertex3};
15use crate::viz::NodeStyle;
16
17/// The fixed resolution industries snap to (Task 9 Interfaces: "pick a
18/// res-8 origin").
19const FINE_RES: Resolution = Resolution::Eight;
20/// One level coarser — the `parent()` target for `Zoom::Coarse`.
21const COARSE_RES: Resolution = Resolution::Seven;
22
23/// Ground-plane hex scale (`topology-deck.html:373`, `S=.15`) — shared by
24/// `hexXZ` position AND the fine/coarse `hexR` outline radius below.
25pub const S: f64 = 0.15;
26/// Fine-level hex outline radius: `S*.92` (`:374`).
27pub const HEX_R_FINE: f64 = S * 0.92;
28/// Coarse-level hex outline radius: `S*1.9` (`:374`).
29pub const HEX_R_COARSE: f64 = S * 1.9;
30/// The ground plane's world-space `y` (`:373`, `GROUNDY=-.95`).
31pub const GROUND_Y: f64 = -0.95;
32/// Bezier ribbon midpoint raise (`:427`, `mid.y = max(a.y,b.y)+.32`).
33pub const RIBBON_LIFT: f64 = 0.32;
34/// Sub-threshold flows are skipped from rendering only (Deviation 5).
35pub const RENDER_THRESHOLD: f64 = 0.4;
36/// Node radius `∝ √(c+v)` (world-space scale; the deck's own `.62` factor
37/// additionally divides by a camera-dependent `top.s/300` foreshortening
38/// term that has no meaning in a camera-independent `SceneGraph3D`,
39/// mirroring the D-R6 world-space-hull precedent in `cylinder.rs`).
40const NODE_RADIUS_SCALE: f64 = 0.05;
41
42/// `#F2C56B` / `#C43A2E` — the deck's literal outline hex strings
43/// (`:417`), distinct from `color::heat`'s own gold/crimson RGB endpoints.
44const OUTLINE_GOLD: &str = "#F2C56B";
45const OUTLINE_CRIMSON: &str = "#C43A2E";
46const GROUND_HEX_COLOR: Rgb = Rgb(217, 164, 65);
47const RIBBON_COLOR: Rgb = Rgb(196, 58, 46);
48
49/// FINE = 13 industries; COARSE = `h3o::CellIndex::parent()` aggregation
50/// (`topology-deck.html:373`, `W.zoom`).
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Zoom {
53    Fine,
54    Coarse,
55}
56
57/// One rendered grid entity — an industry (FINE) or an aggregated H3 parent
58/// cell (COARSE). `s = v·e` (recomputed as `s/v` from summed extensives on
59/// aggregation, mirroring `aggregateCells`'s `e=gr.s/gr.v`).
60#[derive(Debug, Clone, PartialEq)]
61pub struct SankeyEntity {
62    pub name: String,
63    pub cell: CellIndex,
64    pub c: f64,
65    pub v: f64,
66    pub s: f64,
67    pub t: f64,
68    pub n: u32,
69    pub hx: f64,
70    pub hz: f64,
71}
72
73impl SankeyEntity {
74    /// `e = s/v` (the industry/cell's rate of exploitation).
75    pub fn e(&self) -> f64 {
76        self.s / self.v
77    }
78}
79
80/// One donor->absorber value transfer in the FULL (unrendered) allocation
81/// (Deviation 5). `rendered` marks whether it cleared `RENDER_THRESHOLD`
82/// and therefore has ribbon `Strut`s in the scene.
83#[derive(Debug, Clone, PartialEq)]
84pub struct RibbonFlow {
85    pub donor: String,
86    pub absorber: String,
87    pub flow: f64,
88    pub rendered: bool,
89}
90
91/// The built instrument: the camera-independent `SceneGraph3D` plus the
92/// entities/ribbons/`(Φ,r)` the scene was derived from — golden-testable
93/// without re-deriving the algebra from the scene geometry.
94#[derive(Debug, Clone, PartialEq)]
95pub struct SankeyScene {
96    pub scene: SceneGraph3D,
97    pub entities: Vec<SankeyEntity>,
98    pub ribbons: Vec<RibbonFlow>,
99    pub phi: f64,
100    pub r: f64,
101}
102
103impl SankeyScene {
104    /// `Σ T_i` over rendered entities — `0` by construction of `r=S/CV`
105    /// (`r·CV − S = 0`), partition-independent (Deviation 7).
106    pub fn net_t(&self) -> f64 {
107        self.entities.iter().map(|e| e.t).sum()
108    }
109}
110
111/// `hexXZ(q,r,s) = {x: s·√3·(q+r/2), z: s·1.5·r}` (`:361`).
112pub fn hex_xz(q: f64, r: f64, s: f64) -> (f64, f64) {
113    (s * 1.732_050_8 * (q + r / 2.0), s * 1.5 * r)
114}
115
116/// `occY(c,v) = -0.8 + 1.55·clamp((ln(c/v)+0.3)/2.6, 0, 1)` (`:362`).
117pub fn occ_y(c: f64, v: f64) -> f64 {
118    let q = (c / v).ln();
119    -0.8 + 1.55 * ((q + 0.3) / 2.6).clamp(0.0, 1.0)
120}
121
122/// The deck's `CLUSTER`/`OFF` axial-offset snap (`:169-177`): each
123/// industry, in `inds` order, gets `(hq,hr) = CLUSTER[lane] + OFF[k]` where
124/// `k` is that lane's running count mod 4. Bounded: `inds.len()`.
125fn industry_hex_offsets(inds: &[Industry]) -> Vec<(i32, i32)> {
126    const CLUSTER: [(i32, i32); 4] = [(-6, 0), (-2, 0), (1, -1), (4, 0)];
127    const OFF: [(i32, i32); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)];
128    let mut cnt = [0usize; 4];
129    inds.iter()
130        .map(|i| {
131            let lane = i.lane as usize;
132            let k = cnt[lane] % OFF.len();
133            cnt[lane] += 1;
134            (CLUSTER[lane].0 + OFF[k].0, CLUSTER[lane].1 + OFF[k].1)
135        })
136        .collect()
137}
138
139/// The 13 fine-level entities, each snapped to a real `h3o::CellIndex`
140/// (Deviation 7). Bounded: `inds.len()`.
141fn fine_entities(inds: &[Industry]) -> Vec<(CellIndex, SankeyEntity)> {
142    let economy = transform(inds);
143    let offsets = industry_hex_offsets(inds);
144    let origin = origin_cell(FINE_RES);
145
146    inds.iter()
147        .zip(offsets.iter())
148        .zip(economy.t.iter())
149        .map(|((ind, &(hq, hr)), &t)| {
150            let cell = industry_cell(origin, hq, hr).unwrap_or_else(|e| {
151                panic!(
152                    "industry hex ({hq},{hr}) hit h3o::LocalIjError::{e:?} — the deck fixture's \
153                     fixed axial offsets are pentagon-free at FINE_RES from the (0,0) origin"
154                )
155            });
156            let (hx, hz) = hex_xz(hq as f64, hr as f64, S);
157            let s = ind.v * ind.e;
158            let entity = SankeyEntity {
159                name: ind.name.clone(),
160                cell,
161                c: ind.c,
162                v: ind.v,
163                s,
164                t,
165                n: 1,
166                hx,
167                hz,
168            };
169            (cell, entity)
170        })
171        .collect()
172}
173
174/// The COARSE-level entities: `fine_entities` grouped `BY parent(h3_index)`
175/// (`h3::aggregate_by_parent`) — extensives summed, position averaged, `e`
176/// recomputed (Deviation 7). Bounded: `inds.len()`.
177fn coarse_entities(inds: &[Industry]) -> Vec<(CellIndex, SankeyEntity)> {
178    let fine = fine_entities(inds);
179    let extensive_pairs: Vec<(CellIndex, Extensives)> = fine
180        .iter()
181        .map(|(cell, e)| {
182            (
183                *cell,
184                Extensives {
185                    c: e.c,
186                    v: e.v,
187                    s: e.s,
188                    t: e.t,
189                    n: e.n,
190                    hx: e.hx,
191                    hz: e.hz,
192                },
193            )
194        })
195        .collect();
196
197    aggregate_by_parent(&extensive_pairs, COARSE_RES)
198        .into_iter()
199        .map(|(parent, ext)| {
200            let n = ext.n.max(1) as f64;
201            let entity = SankeyEntity {
202                name: format!("cell {:x}", u64::from(parent)),
203                cell: parent,
204                c: ext.c,
205                v: ext.v,
206                s: ext.s,
207                t: ext.t,
208                n: ext.n,
209                hx: ext.hx / n,
210                hz: ext.hz / n,
211            };
212            (parent, entity)
213        })
214        .collect()
215}
216
217/// The FULL (unrendered) donor->absorber allocation (Deviation 5): donors
218/// (`T<0`) sorted ascending, `negSum = Σ(−T_donor)`; for each absorber `j`
219/// and donor `i`, `flow = j.T·(−i.T)/negSum` (`:429-431`). Conserves to `Φ`
220/// regardless of the `RENDER_THRESHOLD` cutoff. Bounded:
221/// `donors.len() * absorbers.len()`.
222fn allocate_ribbons(entities: &[SankeyEntity]) -> Vec<RibbonFlow> {
223    let mut donors: Vec<&SankeyEntity> = entities.iter().filter(|e| e.t < 0.0).collect();
224    // NaN-safe comparator (review MINOR 6): the plan forbids `.unwrap()` on
225    // `partial_cmp` absolutely — same pattern as `camera.rs`'s depth sort.
226    donors.sort_by(|a, b| a.t.partial_cmp(&b.t).unwrap_or(core::cmp::Ordering::Equal));
227    // The deck's `negSum = donors.reduce(...) || 1` (`:429`) substitutes 1
228    // for EXACTLY zero — JS `||` tests falsiness, not magnitude. Review
229    // MAJOR 2: `.max(1.0)` also substituted 1 for any `0 < Σ(−T) < 1`,
230    // silently breaking `Σflow == Φ` on any scaled-down industry table.
231    let raw_neg_sum: f64 = donors.iter().map(|e| -e.t).sum();
232    let neg_sum = if raw_neg_sum == 0.0 { 1.0 } else { raw_neg_sum };
233
234    let mut ribbons = Vec::with_capacity(donors.len() * entities.len());
235    for j in entities.iter().filter(|e| e.t > 0.0) {
236        for i in &donors {
237            let flow = j.t * (-i.t) / neg_sum;
238            ribbons.push(RibbonFlow {
239                donor: i.name.clone(),
240                absorber: j.name.clone(),
241                flow,
242                rendered: flow >= RENDER_THRESHOLD,
243            });
244        }
245    }
246    ribbons
247}
248
249/// Fan-triangulate a regular hexagon (7 corners, closed) at ground `y` into
250/// filled `Face`s, plus the 6 perimeter edges as outline `Struts`. Bounded:
251/// fixed 6-corner hex.
252fn ground_hex(cx: f64, cz: f64, r: f64, fill: Rgb) -> (Vec<Face>, Vec<Strut>) {
253    let mut corners = Vec::with_capacity(7);
254    for k in 0..=6 {
255        let a = std::f64::consts::PI / 180.0 * (60.0 * k as f64 + 30.0);
256        corners.push(Vertex3 {
257            x: cx + r * a.cos(),
258            y: GROUND_Y,
259            z: cz + r * a.sin(),
260        });
261    }
262    let center = Vertex3 {
263        x: cx,
264        y: GROUND_Y,
265        z: cz,
266    };
267    let mut faces = Vec::with_capacity(6);
268    let mut struts = Vec::with_capacity(6);
269    for w in corners.windows(2) {
270        faces.push(Face {
271            verts: [center, w[0], w[1]],
272            fill,
273            opacity: 0.05,
274        });
275        struts.push(Strut {
276            a: w[0],
277            b: w[1],
278            color: fill,
279        });
280    }
281    (faces, struts)
282}
283
284/// Build Instrument III (`topology-deck.html:363-433`).
285pub fn build_sankey(inds: &[Industry], zoom: Zoom) -> SankeyScene {
286    let economy = transform(inds);
287    let (entity_pairs, hex_r) = match zoom {
288        Zoom::Fine => (fine_entities(inds), HEX_R_FINE),
289        Zoom::Coarse => (coarse_entities(inds), HEX_R_COARSE),
290    };
291    let entities: Vec<SankeyEntity> = entity_pairs.into_iter().map(|(_, e)| e).collect();
292    let ribbons = allocate_ribbons(&entities);
293
294    let mut faces = Vec::new();
295    let mut struts = Vec::new();
296    let mut nodes = Vec::with_capacity(entities.len());
297    let mut labels = Vec::with_capacity(entities.len());
298
299    // Ground hexes + stems + OCC-altitude node per entity (bounded:
300    // entities.len()).
301    for e in &entities {
302        let (hex_faces, hex_struts) = ground_hex(e.hx, e.hz, hex_r, GROUND_HEX_COLOR);
303        faces.extend(hex_faces);
304        struts.extend(hex_struts);
305
306        let y = occ_y(e.c, e.v);
307        let base = Vertex3 {
308            x: e.hx,
309            y: GROUND_Y,
310            z: e.hz,
311        };
312        let top = Vertex3 {
313            x: e.hx,
314            y,
315            z: e.hz,
316        };
317        struts.push(Strut {
318            a: base,
319            b: top,
320            color: GROUND_HEX_COLOR,
321        });
322
323        let style = NodeStyle {
324            stroke: if e.t > 0.0 {
325                OUTLINE_GOLD.to_string()
326            } else {
327                OUTLINE_CRIMSON.to_string()
328            },
329            ..NodeStyle::default()
330        };
331
332        let q = e.c / e.v;
333        let label = format!(
334            "{} q={:.1} {}{:.1}",
335            e.name,
336            q,
337            if e.t >= 0.0 { "+" } else { "" },
338            e.t
339        );
340        nodes.push(Node3 {
341            id: format!("sankey-{}", e.name),
342            pos: top,
343            radius: NODE_RADIUS_SCALE * (e.c + e.v).sqrt(),
344            color: heat((e.e() / 4.0).min(1.0)),
345            style,
346            attrs: serde_json::json!({
347                "c": e.c, "v": e.v, "s": e.s, "t": e.t, "n": e.n,
348                "q": q, "e": e.e(), "label": label,
349            }),
350        });
351        labels.push(serde_json::json!({ "name": e.name, "q": q, "t": e.t }));
352    }
353
354    // Ribbon Struts, rendered allocation only (Deviation 5). Bounded:
355    // ribbons.len().
356    for f in ribbons.iter().filter(|f| f.rendered) {
357        let a_entity = entities
358            .iter()
359            .find(|e| e.name == f.donor)
360            .expect("donor entity exists");
361        let b_entity = entities
362            .iter()
363            .find(|e| e.name == f.absorber)
364            .expect("absorber entity exists");
365        let a = Vertex3 {
366            x: a_entity.hx,
367            y: occ_y(a_entity.c, a_entity.v),
368            z: a_entity.hz,
369        };
370        let b = Vertex3 {
371            x: b_entity.hx,
372            y: occ_y(b_entity.c, b_entity.v),
373            z: b_entity.hz,
374        };
375        let mid = Vertex3 {
376            x: (a.x + b.x) / 2.0,
377            y: a.y.max(b.y) + RIBBON_LIFT,
378            z: (a.z + b.z) / 2.0,
379        };
380        struts.push(Strut {
381            a,
382            b: mid,
383            color: RIBBON_COLOR,
384        });
385        struts.push(Strut {
386            a: mid,
387            b,
388            color: RIBBON_COLOR,
389        });
390    }
391
392    let bbox = bounding_box(&faces, &struts, &nodes);
393
394    let mut metadata = serde_json::Map::new();
395    metadata.insert("entities".to_string(), serde_json::json!(labels));
396    metadata.insert(
397        "conservation".to_string(),
398        serde_json::json!({
399            "phi": economy.phi,
400            "r": economy.r,
401            "zoom": match zoom { Zoom::Fine => "fine", Zoom::Coarse => "coarse" },
402        }),
403    );
404
405    SankeyScene {
406        scene: SceneGraph3D {
407            nodes,
408            faces,
409            struts,
410            bounding_box: bbox,
411            metadata,
412        },
413        entities,
414        ribbons,
415        phi: economy.phi,
416        r: economy.r,
417    }
418}
419
420/// Min/max over every vertex the scene actually produced. Bounded:
421/// `faces.len()*3 + struts.len()*2 + nodes.len()`.
422fn bounding_box(
423    faces: &[Face],
424    struts: &[Strut],
425    nodes: &[Node3],
426) -> (f64, f64, f64, f64, f64, f64) {
427    let mut min = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
428    let mut max = (f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
429    let mut fold = |v: &Vertex3| {
430        min.0 = min.0.min(v.x);
431        min.1 = min.1.min(v.y);
432        min.2 = min.2.min(v.z);
433        max.0 = max.0.max(v.x);
434        max.1 = max.1.max(v.y);
435        max.2 = max.2.max(v.z);
436    };
437    for f in faces {
438        for v in &f.verts {
439            fold(v);
440        }
441    }
442    for s in struts {
443        fold(&s.a);
444        fold(&s.b);
445    }
446    for n in nodes {
447        fold(&n.pos);
448    }
449    if !min.0.is_finite() {
450        return (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
451    }
452    (min.0, min.1, min.2, max.0, max.1, max.2)
453}