1use 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
17const FINE_RES: Resolution = Resolution::Eight;
20const COARSE_RES: Resolution = Resolution::Seven;
22
23pub const S: f64 = 0.15;
26pub const HEX_R_FINE: f64 = S * 0.92;
28pub const HEX_R_COARSE: f64 = S * 1.9;
30pub const GROUND_Y: f64 = -0.95;
32pub const RIBBON_LIFT: f64 = 0.32;
34pub const RENDER_THRESHOLD: f64 = 0.4;
36const NODE_RADIUS_SCALE: f64 = 0.05;
41
42const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Zoom {
53 Fine,
54 Coarse,
55}
56
57#[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 pub fn e(&self) -> f64 {
76 self.s / self.v
77 }
78}
79
80#[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#[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 pub fn net_t(&self) -> f64 {
107 self.entities.iter().map(|e| e.t).sum()
108 }
109}
110
111pub 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
116pub 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
122fn 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
139fn 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
174fn 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
217fn allocate_ribbons(entities: &[SankeyEntity]) -> Vec<RibbonFlow> {
223 let mut donors: Vec<&SankeyEntity> = entities.iter().filter(|e| e.t < 0.0).collect();
224 donors.sort_by(|a, b| a.t.partial_cmp(&b.t).unwrap_or(core::cmp::Ordering::Equal));
227 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
249fn 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
284pub 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 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 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
420fn 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}