use std::collections::HashMap;
use serde_json::json;
use crate::communities::{normalized_laplacian, smallest_k_eigenvectors};
use crate::layout::convex_hull;
use crate::raster::color::heat;
use crate::raster::deck::{deck_hypergraph, org_degree, psa, psr, Community, DeckWorld};
use crate::raster::{Face, Node3, Rgb, SceneGraph3D, Strut, Vertex3};
use crate::viz::NodeStyle;
use super::{CylinderHeight, InstrumentOpts};
pub const R: f64 = 1.05;
pub const H: f64 = 1.55;
pub const SPECTRAL_SEED: u64 = 22_928;
const AGENT_RADIUS: f64 = 0.03;
const COMMUNITY_NODE_RADIUS: f64 = 0.04;
const GHOST_STRUT_COLOR: Rgb = Rgb(217, 164, 65);
fn community_height_scalar(c: &Community, opts: &InstrumentOpts) -> f64 {
match opts.cylinder_height {
CylinderHeight::OrgDegree => org_degree(c),
CylinderHeight::HullFill => {
let n = c.members.len();
if n < 2 {
1.0
} else {
let max_links = (n * (n - 1) / 2) as f64;
(c.links.len() as f64 / max_links).clamp(0.0, 1.0)
}
}
}
}
const SPECTRAL_INSET: f64 = 0.92;
fn scale_column(col: &mut [f64]) {
let mut mx = 0.0_f64;
for v in col.iter() {
let a = v.abs();
if a > mx {
mx = a;
}
}
if mx.is_nan() || mx <= 0.0 {
mx = 1.0;
}
for v in col.iter_mut() {
*v = *v / mx * SPECTRAL_INSET;
}
}
pub(crate) fn spectral_positions(world: &DeckWorld) -> Vec<(f64, f64)> {
let hg = deck_hypergraph(world);
let (l, ids) = normalized_laplacian(&hg)
.expect("deck_hypergraph guarantees every agent has degree >= 1 (Task 7 deviation)");
let ev = smallest_k_eigenvectors(&l, 2, Some(SPECTRAL_SEED));
let mut row_of: HashMap<String, usize> = HashMap::new();
for (row, id) in ids.iter().enumerate() {
row_of.insert(id.clone(), row);
}
let mut xs: Vec<f64> = Vec::with_capacity(world.agents.len());
let mut ys: Vec<f64> = Vec::with_capacity(world.agents.len());
for a in &world.agents {
let row = row_of[&a.id.to_string()];
xs.push(ev[[row, 0]]);
ys.push(ev[[row, 1]]);
}
scale_column(&mut xs);
scale_column(&mut ys);
xs.into_iter().zip(ys).collect()
}
fn hull_faces(hull: &[(f64, f64)], y: f64, fill: Rgb, opacity: f64) -> Vec<Face> {
if hull.len() < 3 {
return Vec::new();
}
let v0 = Vertex3 {
x: hull[0].0,
y,
z: hull[0].1,
};
let mut faces = Vec::with_capacity(hull.len() - 2);
for i in 1..hull.len() - 1 {
let v1 = Vertex3 {
x: hull[i].0,
y,
z: hull[i].1,
};
let v2 = Vertex3 {
x: hull[i + 1].0,
y,
z: hull[i + 1].1,
};
faces.push(Face {
verts: [v0, v1, v2],
fill,
opacity,
});
}
faces
}
const RING_SEGMENTS: usize = 64;
const BODY_STRUTS: usize = 12;
const RING_BOTTOM_COLOR: Rgb = Rgb(138, 122, 97);
const RING_TOP_COLOR: Rgb = Rgb(217, 164, 65);
const BODY_STRUT_COLOR: Rgb = Rgb(74, 62, 44);
fn ring(y: f64, color: Rgb) -> Vec<Strut> {
let point = |i: usize| -> Vertex3 {
let a = i as f64 / RING_SEGMENTS as f64 * std::f64::consts::TAU;
Vertex3 {
x: a.cos() * R,
y,
z: a.sin() * R,
}
};
(0..RING_SEGMENTS)
.map(|i| Strut {
a: point(i),
b: point(i + 1),
color,
})
.collect()
}
pub fn build_cylinder(world: &DeckWorld, opts: &InstrumentOpts) -> SceneGraph3D {
let pos = spectral_positions(world);
let mut nodes = Vec::with_capacity(world.agents.len());
let mut faces = Vec::new();
let mut struts = Vec::new();
let mut community_labels = Vec::with_capacity(world.communities.len());
struts.extend(ring(-H / 2.0, RING_BOTTOM_COLOR));
struts.extend(ring(H / 2.0, RING_TOP_COLOR));
for i in 0..BODY_STRUTS {
let a = i as f64 / BODY_STRUTS as f64 * std::f64::consts::TAU;
let (x, z) = (a.cos() * R, a.sin() * R);
struts.push(Strut {
a: Vertex3 { x, y: -H / 2.0, z },
b: Vertex3 { x, y: H / 2.0, z },
color: BODY_STRUT_COLOR,
});
}
for a in &world.agents {
let (sx, sy) = pos[a.id];
nodes.push(Node3 {
id: format!("agent-{}", a.id),
pos: Vertex3 {
x: sx * R * 0.85,
y: -H / 2.0,
z: sy * R * 0.85,
},
radius: AGENT_RADIUS,
color: Rgb(233, 223, 201),
style: NodeStyle::default(),
attrs: json!({ "agent_id": a.id, "bloc": a.bloc }),
});
}
for c in &world.communities {
let o = community_height_scalar(c, opts);
let y = -H / 2.0 + o * H;
let col = heat(1.0 - o);
let member_pts: Vec<(f64, f64)> = c
.members
.iter()
.map(|&m| {
let (sx, sy) = pos[m];
(sx * R * 0.85, sy * R * 0.85)
})
.collect();
let hull = convex_hull(&member_pts);
faces.extend(hull_faces(&hull, y, col, 0.12 + 0.3 * o));
for &m in &c.members {
let (sx, sy) = pos[m];
let bottom = Vertex3 {
x: sx * R * 0.85,
y: -H / 2.0,
z: sy * R * 0.85,
};
let top = Vertex3 {
x: sx * R * 0.85,
y,
z: sy * R * 0.85,
};
struts.push(Strut {
a: bottom,
b: top,
color: GHOST_STRUT_COLOR,
});
nodes.push(Node3 {
id: format!("agent-{}@{}", m, c.name),
pos: top,
radius: COMMUNITY_NODE_RADIUS,
color: col,
style: NodeStyle::default(),
attrs: json!({ "agent_id": m, "community": c.name }),
});
}
community_labels.push(json!({ "name": c.name, "o": o }));
}
let mut metadata = serde_json::Map::new();
metadata.insert("communities".to_string(), json!(community_labels));
if world.communities.len() >= 2 {
metadata.insert("psa".to_string(), json!(psa(world)));
metadata.insert("psr".to_string(), json!(psr(world)));
}
SceneGraph3D {
nodes,
faces,
struts,
bounding_box: (-R, -H / 2.0, -R, R, H / 2.0, R),
metadata,
}
}