use h3o::{CellIndex, Resolution};
use crate::raster::algebra::{transform, Industry};
use crate::raster::color::heat;
use crate::raster::h3::{aggregate_by_parent, industry_cell, origin_cell, Extensives};
use crate::raster::{Face, Node3, Rgb, SceneGraph3D, Strut, Vertex3};
use crate::viz::NodeStyle;
const FINE_RES: Resolution = Resolution::Eight;
const COARSE_RES: Resolution = Resolution::Seven;
pub const S: f64 = 0.15;
pub const HEX_R_FINE: f64 = S * 0.92;
pub const HEX_R_COARSE: f64 = S * 1.9;
pub const GROUND_Y: f64 = -0.95;
pub const RIBBON_LIFT: f64 = 0.32;
pub const RENDER_THRESHOLD: f64 = 0.4;
const NODE_RADIUS_SCALE: f64 = 0.05;
const OUTLINE_GOLD: &str = "#F2C56B";
const OUTLINE_CRIMSON: &str = "#C43A2E";
const GROUND_HEX_COLOR: Rgb = Rgb(217, 164, 65);
const RIBBON_COLOR: Rgb = Rgb(196, 58, 46);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Zoom {
Fine,
Coarse,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SankeyEntity {
pub name: String,
pub cell: CellIndex,
pub c: f64,
pub v: f64,
pub s: f64,
pub t: f64,
pub n: u32,
pub hx: f64,
pub hz: f64,
}
impl SankeyEntity {
pub fn e(&self) -> f64 {
self.s / self.v
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RibbonFlow {
pub donor: String,
pub absorber: String,
pub flow: f64,
pub rendered: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SankeyScene {
pub scene: SceneGraph3D,
pub entities: Vec<SankeyEntity>,
pub ribbons: Vec<RibbonFlow>,
pub phi: f64,
pub r: f64,
}
impl SankeyScene {
pub fn net_t(&self) -> f64 {
self.entities.iter().map(|e| e.t).sum()
}
}
pub fn hex_xz(q: f64, r: f64, s: f64) -> (f64, f64) {
(s * 1.732_050_8 * (q + r / 2.0), s * 1.5 * r)
}
pub fn occ_y(c: f64, v: f64) -> f64 {
let q = (c / v).ln();
-0.8 + 1.55 * ((q + 0.3) / 2.6).clamp(0.0, 1.0)
}
fn industry_hex_offsets(inds: &[Industry]) -> Vec<(i32, i32)> {
const CLUSTER: [(i32, i32); 4] = [(-6, 0), (-2, 0), (1, -1), (4, 0)];
const OFF: [(i32, i32); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)];
let mut cnt = [0usize; 4];
inds.iter()
.map(|i| {
let lane = i.lane as usize;
let k = cnt[lane] % OFF.len();
cnt[lane] += 1;
(CLUSTER[lane].0 + OFF[k].0, CLUSTER[lane].1 + OFF[k].1)
})
.collect()
}
fn fine_entities(inds: &[Industry]) -> Vec<(CellIndex, SankeyEntity)> {
let economy = transform(inds);
let offsets = industry_hex_offsets(inds);
let origin = origin_cell(FINE_RES);
inds.iter()
.zip(offsets.iter())
.zip(economy.t.iter())
.map(|((ind, &(hq, hr)), &t)| {
let cell = industry_cell(origin, hq, hr).unwrap_or_else(|e| {
panic!(
"industry hex ({hq},{hr}) hit h3o::LocalIjError::{e:?} — the deck fixture's \
fixed axial offsets are pentagon-free at FINE_RES from the (0,0) origin"
)
});
let (hx, hz) = hex_xz(hq as f64, hr as f64, S);
let s = ind.v * ind.e;
let entity = SankeyEntity {
name: ind.name.clone(),
cell,
c: ind.c,
v: ind.v,
s,
t,
n: 1,
hx,
hz,
};
(cell, entity)
})
.collect()
}
fn coarse_entities(inds: &[Industry]) -> Vec<(CellIndex, SankeyEntity)> {
let fine = fine_entities(inds);
let extensive_pairs: Vec<(CellIndex, Extensives)> = fine
.iter()
.map(|(cell, e)| {
(
*cell,
Extensives {
c: e.c,
v: e.v,
s: e.s,
t: e.t,
n: e.n,
hx: e.hx,
hz: e.hz,
},
)
})
.collect();
aggregate_by_parent(&extensive_pairs, COARSE_RES)
.into_iter()
.map(|(parent, ext)| {
let n = ext.n.max(1) as f64;
let entity = SankeyEntity {
name: format!("cell {:x}", u64::from(parent)),
cell: parent,
c: ext.c,
v: ext.v,
s: ext.s,
t: ext.t,
n: ext.n,
hx: ext.hx / n,
hz: ext.hz / n,
};
(parent, entity)
})
.collect()
}
fn allocate_ribbons(entities: &[SankeyEntity]) -> Vec<RibbonFlow> {
let mut donors: Vec<&SankeyEntity> = entities.iter().filter(|e| e.t < 0.0).collect();
donors.sort_by(|a, b| a.t.partial_cmp(&b.t).unwrap_or(core::cmp::Ordering::Equal));
let raw_neg_sum: f64 = donors.iter().map(|e| -e.t).sum();
let neg_sum = if raw_neg_sum == 0.0 { 1.0 } else { raw_neg_sum };
let mut ribbons = Vec::with_capacity(donors.len() * entities.len());
for j in entities.iter().filter(|e| e.t > 0.0) {
for i in &donors {
let flow = j.t * (-i.t) / neg_sum;
ribbons.push(RibbonFlow {
donor: i.name.clone(),
absorber: j.name.clone(),
flow,
rendered: flow >= RENDER_THRESHOLD,
});
}
}
ribbons
}
fn ground_hex(cx: f64, cz: f64, r: f64, fill: Rgb) -> (Vec<Face>, Vec<Strut>) {
let mut corners = Vec::with_capacity(7);
for k in 0..=6 {
let a = std::f64::consts::PI / 180.0 * (60.0 * k as f64 + 30.0);
corners.push(Vertex3 {
x: cx + r * a.cos(),
y: GROUND_Y,
z: cz + r * a.sin(),
});
}
let center = Vertex3 {
x: cx,
y: GROUND_Y,
z: cz,
};
let mut faces = Vec::with_capacity(6);
let mut struts = Vec::with_capacity(6);
for w in corners.windows(2) {
faces.push(Face {
verts: [center, w[0], w[1]],
fill,
opacity: 0.05,
});
struts.push(Strut {
a: w[0],
b: w[1],
color: fill,
});
}
(faces, struts)
}
pub fn build_sankey(inds: &[Industry], zoom: Zoom) -> SankeyScene {
let economy = transform(inds);
let (entity_pairs, hex_r) = match zoom {
Zoom::Fine => (fine_entities(inds), HEX_R_FINE),
Zoom::Coarse => (coarse_entities(inds), HEX_R_COARSE),
};
let entities: Vec<SankeyEntity> = entity_pairs.into_iter().map(|(_, e)| e).collect();
let ribbons = allocate_ribbons(&entities);
let mut faces = Vec::new();
let mut struts = Vec::new();
let mut nodes = Vec::with_capacity(entities.len());
let mut labels = Vec::with_capacity(entities.len());
for e in &entities {
let (hex_faces, hex_struts) = ground_hex(e.hx, e.hz, hex_r, GROUND_HEX_COLOR);
faces.extend(hex_faces);
struts.extend(hex_struts);
let y = occ_y(e.c, e.v);
let base = Vertex3 {
x: e.hx,
y: GROUND_Y,
z: e.hz,
};
let top = Vertex3 {
x: e.hx,
y,
z: e.hz,
};
struts.push(Strut {
a: base,
b: top,
color: GROUND_HEX_COLOR,
});
let style = NodeStyle {
stroke: if e.t > 0.0 {
OUTLINE_GOLD.to_string()
} else {
OUTLINE_CRIMSON.to_string()
},
..NodeStyle::default()
};
let q = e.c / e.v;
let label = format!(
"{} q={:.1} {}{:.1}",
e.name,
q,
if e.t >= 0.0 { "+" } else { "" },
e.t
);
nodes.push(Node3 {
id: format!("sankey-{}", e.name),
pos: top,
radius: NODE_RADIUS_SCALE * (e.c + e.v).sqrt(),
color: heat((e.e() / 4.0).min(1.0)),
style,
attrs: serde_json::json!({
"c": e.c, "v": e.v, "s": e.s, "t": e.t, "n": e.n,
"q": q, "e": e.e(), "label": label,
}),
});
labels.push(serde_json::json!({ "name": e.name, "q": q, "t": e.t }));
}
for f in ribbons.iter().filter(|f| f.rendered) {
let a_entity = entities
.iter()
.find(|e| e.name == f.donor)
.expect("donor entity exists");
let b_entity = entities
.iter()
.find(|e| e.name == f.absorber)
.expect("absorber entity exists");
let a = Vertex3 {
x: a_entity.hx,
y: occ_y(a_entity.c, a_entity.v),
z: a_entity.hz,
};
let b = Vertex3 {
x: b_entity.hx,
y: occ_y(b_entity.c, b_entity.v),
z: b_entity.hz,
};
let mid = Vertex3 {
x: (a.x + b.x) / 2.0,
y: a.y.max(b.y) + RIBBON_LIFT,
z: (a.z + b.z) / 2.0,
};
struts.push(Strut {
a,
b: mid,
color: RIBBON_COLOR,
});
struts.push(Strut {
a: mid,
b,
color: RIBBON_COLOR,
});
}
let bbox = bounding_box(&faces, &struts, &nodes);
let mut metadata = serde_json::Map::new();
metadata.insert("entities".to_string(), serde_json::json!(labels));
metadata.insert(
"conservation".to_string(),
serde_json::json!({
"phi": economy.phi,
"r": economy.r,
"zoom": match zoom { Zoom::Fine => "fine", Zoom::Coarse => "coarse" },
}),
);
SankeyScene {
scene: SceneGraph3D {
nodes,
faces,
struts,
bounding_box: bbox,
metadata,
},
entities,
ribbons,
phi: economy.phi,
r: economy.r,
}
}
fn bounding_box(
faces: &[Face],
struts: &[Strut],
nodes: &[Node3],
) -> (f64, f64, f64, f64, f64, f64) {
let mut min = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
let mut max = (f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut fold = |v: &Vertex3| {
min.0 = min.0.min(v.x);
min.1 = min.1.min(v.y);
min.2 = min.2.min(v.z);
max.0 = max.0.max(v.x);
max.1 = max.1.max(v.y);
max.2 = max.2.max(v.z);
};
for f in faces {
for v in &f.verts {
fold(v);
}
}
for s in struts {
fold(&s.a);
fold(&s.b);
}
for n in nodes {
fold(&n.pos);
}
if !min.0.is_finite() {
return (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
}
(min.0, min.1, min.2, max.0, max.1, max.2)
}