use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::raster::deck::DeckWorld;
#[cfg(feature = "cells3d")]
use crate::raster::instruments::{self, Instrument, InstrumentOpts};
#[cfg(feature = "cells3d")]
use crate::raster::SceneGraph3D;
use crate::Hypergraph;
mod edges;
mod nodes;
pub use edges::{ingest_edges, IngestedEdges};
pub(crate) use nodes::index_of;
pub use nodes::{ingest_nodes, IngestedNodes};
pub const ATTR_CONTRACT_VERSION: u32 = 1;
pub const K_WEALTH: &str = "wealth";
pub const K_SUBSISTENCE: &str = "subsistence";
pub const K_BLOC: &str = "bloc";
pub const K_TENSION: &str = "tension";
pub const K_H3_CELL: &str = "h3_cell";
pub const K_KIND: &str = "kind";
pub const K_NAME: &str = "name";
pub const K_LINKS: &str = "links";
pub const K_HEAD: &str = "head";
pub const K_MASS: &str = "mass";
pub const K_LANE: &str = "lane";
pub const K_C: &str = "c";
pub const K_V: &str = "v";
pub const K_E: &str = "e";
pub const K_REPRESSION: &str = "repression";
pub const K_ZOOM: &str = "zoom";
pub const KIND_COMMUNITY: &str = "community";
pub const KIND_EXTRACTION: &str = "extraction";
pub const KIND_INDUSTRY: &str = "industry";
pub const DEFAULT_BLOC: u8 = 1;
pub const PERIPHERY_BLOC: u8 = 2;
pub const DEFAULT_LANE: u8 = 0;
pub const DEFAULT_MASS: f64 = 1.0;
pub const DEFAULT_REPRESSION: f64 = 1.0;
pub const DEFAULT_ZOOM: u8 = 0;
pub const DEFAULT_COMMUNITY_NAME: &str = "community-";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AttrContract {
pub version: u32,
pub wealth: String,
pub subsistence: String,
pub bloc: String,
pub tension: String,
pub h3_cell: String,
pub kind: String,
pub name: String,
pub links: String,
pub head: String,
pub mass: String,
pub lane: String,
pub c: String,
pub v: String,
pub e: String,
pub repression: String,
pub zoom: String,
}
impl Default for AttrContract {
fn default() -> Self {
Self {
version: ATTR_CONTRACT_VERSION,
wealth: K_WEALTH.to_string(),
subsistence: K_SUBSISTENCE.to_string(),
bloc: K_BLOC.to_string(),
tension: K_TENSION.to_string(),
h3_cell: K_H3_CELL.to_string(),
kind: K_KIND.to_string(),
name: K_NAME.to_string(),
links: K_LINKS.to_string(),
head: K_HEAD.to_string(),
mass: K_MASS.to_string(),
lane: K_LANE.to_string(),
c: K_C.to_string(),
v: K_V.to_string(),
e: K_E.to_string(),
repression: K_REPRESSION.to_string(),
zoom: K_ZOOM.to_string(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TensionSource {
Derived,
Attr,
}
#[derive(Debug, Clone, PartialEq)]
pub struct IngestReport {
pub contract_version: u32,
pub node_ids: Vec<String>,
pub agent_count: usize,
pub community_count: usize,
pub extraction_count: usize,
pub industry_count: usize,
pub skipped_edges: Vec<String>,
pub bloc_defaulted: usize,
pub lane_defaulted: bool,
pub repression_defaulted: bool,
pub tension_source: TensionSource,
pub h3_cells: Vec<Option<u64>>,
}
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum IngestError {
#[error("node `{node}` is missing required attribute `{key}`")]
MissingNodeAttr { node: String, key: String },
#[error("edge `{edge}` (kind `{kind}`) is missing required attribute `{key}`")]
MissingEdgeAttr {
edge: String,
kind: String,
key: String,
},
#[error("attribute `{key}` on `{owner}` has the wrong shape or is not finite")]
BadAttrType { owner: String, key: String },
#[error("graph attribute `{key}` is invalid: {reason}")]
BadGraphAttr { key: String, reason: String },
#[error("community edge `{edge}` links node `{node}`, which is not one of its members")]
LinkOutsideCommunity { edge: String, node: String },
#[error("extraction edge `{edge}` names head `{node}`, which is not one of its members")]
HeadNotMember { edge: String, node: String },
#[error("industry edge `{edge}` has v == 0 (rate of exploitation would divide by zero)")]
DegenerateIndustry { edge: String },
#[error("edge `{edge}` references node `{node}`, which is not in the hypergraph")]
UnknownNode { edge: String, node: String },
#[error("at least 2 agent nodes are required for a spectral embedding, found {found}")]
TooFewAgents { found: usize },
#[error(
"a world with {communities} communities computes psa over the periphery bloc ({bloc}), but no node carries it"
)]
NoPeripheryBloc { communities: usize, bloc: u8 },
}
fn read_repression(
h: &Hypergraph<Value, Value, Value>,
key: &str,
defaulted: &mut bool,
) -> Result<f64, IngestError> {
match h.graph_attr(key) {
None => {
*defaulted = true;
Ok(DEFAULT_REPRESSION)
}
Some(v) => v.as_f64().ok_or_else(|| IngestError::BadGraphAttr {
key: key.to_string(),
reason: "must be a finite number".to_string(),
}),
}
}
fn read_zoom(h: &Hypergraph<Value, Value, Value>, key: &str) -> Result<u8, IngestError> {
match h.graph_attr(key) {
None => Ok(DEFAULT_ZOOM),
Some(v) => {
let n = v.as_u64().ok_or_else(|| IngestError::BadGraphAttr {
key: key.to_string(),
reason: "must be an unsigned integer".to_string(),
})?;
u8::try_from(n).map_err(|_| IngestError::BadGraphAttr {
key: key.to_string(),
reason: "must fit in a u8".to_string(),
})
}
}
}
pub fn to_world(
h: &Hypergraph<Value, Value, Value>,
c: &AttrContract,
) -> Result<(DeckWorld, IngestReport), IngestError> {
let mut repression_defaulted = false;
let repression = read_repression(h, &c.repression, &mut repression_defaulted)?;
if !repression.is_finite() || repression <= 0.0 {
return Err(IngestError::BadGraphAttr {
key: c.repression.clone(),
reason: "must be finite and > 0.0".to_string(),
});
}
let zoom = read_zoom(h, &c.zoom)?;
let IngestedNodes {
agents,
node_ids,
h3_cells,
bloc_defaulted,
tension_source,
} = ingest_nodes(h, c, repression)?;
if agents.len() < 2 {
return Err(IngestError::TooFewAgents {
found: agents.len(),
});
}
let index = index_of(&node_ids);
let edges = ingest_edges(h, c, &index)?;
if edges.communities.len() >= 2 && !agents.iter().any(|a| a.bloc == PERIPHERY_BLOC) {
return Err(IngestError::NoPeripheryBloc {
communities: edges.communities.len(),
bloc: PERIPHERY_BLOC,
});
}
let world = DeckWorld {
seed: 0,
agents,
communities: edges.communities,
extraction: edges.extraction,
industries: edges.industries,
repression,
tick: 0,
zoom,
};
let report = IngestReport {
contract_version: c.version,
agent_count: world.agents.len(),
community_count: world.communities.len(),
extraction_count: world.extraction.len(),
industry_count: world.industries.len(),
skipped_edges: edges.skipped,
bloc_defaulted,
lane_defaulted: edges.lane_defaulted,
repression_defaulted,
tension_source,
node_ids,
h3_cells,
};
Ok((world, report))
}
#[cfg(feature = "cells3d")]
pub fn build_scene(
h: &Hypergraph<Value, Value, Value>,
c: &AttrContract,
inst: Instrument,
opts: &InstrumentOpts,
) -> Result<(SceneGraph3D, IngestReport), IngestError> {
let (world, report) = to_world(h, c)?;
if inst == Instrument::Sankey && world.industries.is_empty() {
return Ok((SceneGraph3D::empty(), report));
}
let scene = instruments::build(inst, &world, opts);
Ok((scene, report))
}