use std::collections::HashSet;
use serde_json::Value;
use crate::algorithms::connected::connected_components;
use crate::Hypergraph;
use super::algebra::{deck_industries, Industry};
#[derive(Debug, Clone)]
pub struct Mulberry32 {
a: u32,
}
impl Mulberry32 {
pub fn new(seed: u32) -> Self {
Self { a: seed }
}
#[allow(clippy::should_implement_trait)]
pub fn next(&mut self) -> f64 {
self.a = self.a.wrapping_add(0x6D2B79F5);
let mut t = self.a;
t = (t ^ (t >> 15)).wrapping_mul(t | 1);
t ^= t.wrapping_add((t ^ (t >> 7)).wrapping_mul(t | 61));
((t ^ (t >> 14)) as f64) / 4294967296.0
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Agent {
pub id: usize,
pub bloc: u8,
pub wealth: f64,
pub subsistence: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Community {
pub name: String,
pub members: Vec<usize>,
pub links: Vec<(usize, usize)>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Extraction {
pub tails: Vec<usize>,
pub head: usize,
pub mass: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DeckWorld {
pub seed: u32,
pub agents: Vec<Agent>,
pub communities: Vec<Community>,
pub extraction: Vec<Extraction>,
pub industries: Vec<Industry>,
pub repression: f64,
pub tick: u32,
pub zoom: u8,
}
fn agents_in_bloc(agents: &[Agent], bloc: u8) -> Vec<usize> {
agents
.iter()
.filter(|a| a.bloc == bloc)
.map(|a| a.id)
.collect()
}
fn shuffle_take(rnd: &mut Mulberry32, pool: Vec<usize>, size: usize, name: &str) -> Community {
let mut m = pool;
for i in (1..m.len()).rev() {
let j = (rnd.next() * (i as f64 + 1.0)) as usize;
m.swap(i, j);
}
m.truncate(size);
Community {
name: name.to_string(),
members: m,
links: Vec::new(),
}
}
pub fn build_world(seed: u32) -> DeckWorld {
let mut rnd = Mulberry32::new(seed);
let mut agents = Vec::new();
let blocs: [(usize, u8, f64); 3] = [(5, 0, 8.5), (9, 1, 5.6), (14, 2, 2.1)];
let mut id = 0usize;
for (n, bloc, w) in blocs {
for _ in 0..n {
agents.push(Agent {
id,
bloc,
wealth: w + rnd.next() * 1.4 - 0.7,
subsistence: 3.0,
});
id += 1;
}
}
let mut communities = vec![
shuffle_take(&mut rnd, agents_in_bloc(&agents, 2), 6, "cell \u{3b1}"),
shuffle_take(&mut rnd, agents_in_bloc(&agents, 2), 6, "cell \u{3b2}"),
shuffle_take(&mut rnd, agents_in_bloc(&agents, 1), 6, "union \u{3b3}"),
shuffle_take(&mut rnd, agents_in_bloc(&agents, 0), 4, "capital \u{3b4}"),
];
for c in communities.iter_mut() {
let full = c.name == "capital \u{3b4}";
let want = if full { c.members.len() - 1 } else { 1 };
for i in 0..want {
c.links.push((c.members[i], c.members[i + 1]));
}
}
let per = agents_in_bloc(&agents, 2);
let cap = agents_in_bloc(&agents, 0);
let mut extraction = Vec::new();
for e in 0..4usize {
let mut tails_raw = Vec::new();
for _ in 0..4 {
let idx = (rnd.next() * per.len() as f64) as usize;
tails_raw.push(per[idx]);
}
let mut seen: HashSet<usize> = HashSet::new();
let mut tails = Vec::new();
for t in tails_raw {
if seen.insert(t) {
tails.push(t);
}
}
let head = cap[e % cap.len()];
let mass = 1.4 + rnd.next() * 1.2;
extraction.push(Extraction { tails, head, mass });
}
DeckWorld {
seed,
agents,
communities,
extraction,
industries: deck_industries(),
repression: 2.6,
tick: 0,
zoom: 0,
}
}
pub fn do_tick(world: &mut DeckWorld) {
world.tick += 1;
for e in &world.extraction {
let take = e.mass * 0.12;
let per_tail = take / e.tails.len() as f64;
for &t in &e.tails {
world.agents[t].wealth = (world.agents[t].wealth - per_tail).max(0.2);
}
world.agents[e.head].wealth += take * 0.8;
for a in world.agents.iter_mut().filter(|a| a.bloc == 1) {
a.wealth += take * 0.2 / 9.0;
}
}
for ind in world.industries.iter_mut() {
ind.c *= if ind.lane >= 2 { 1.035 } else { 1.015 };
}
}
const SPECTRAL_WEIGHT_QUANTUM: f64 = 0.25;
fn add_weighted_pair(h: &mut Hypergraph<Value, Value, Value>, a: usize, b: usize, w: f64) {
let reps = (w / SPECTRAL_WEIGHT_QUANTUM).round() as u32;
for _ in 0..reps {
let _ = h.add_edge(vec![a.to_string(), b.to_string()], None, Value::Null);
}
}
pub fn deck_hypergraph(w: &DeckWorld) -> Hypergraph<Value, Value, Value> {
let mut h: Hypergraph<Value, Value, Value> = Hypergraph::new();
for a in &w.agents {
h.add_node(&a.id.to_string(), Value::Null);
}
let mut degree = vec![0u32; w.agents.len()];
let link = |h: &mut Hypergraph<Value, Value, Value>,
degree: &mut Vec<u32>,
a: usize,
b: usize,
weight: f64| {
add_weighted_pair(h, a, b, weight);
degree[a] += 1;
degree[b] += 1;
};
for c in &w.communities {
for i in 0..c.members.len() {
for j in (i + 1)..c.members.len() {
link(&mut h, &mut degree, c.members[i], c.members[j], 0.25);
}
}
}
for c in &w.communities {
for &(a, b) in &c.links {
link(&mut h, &mut degree, a, b, 1.0);
}
}
for e in &w.extraction {
for &t in &e.tails {
link(&mut h, &mut degree, t, e.head, 0.5);
}
}
for a in &w.agents {
if degree[a.id] == 0 {
let _ = h.add_edge(vec![a.id.to_string()], None, Value::Null);
}
}
h
}
pub fn org_degree(c: &Community) -> f64 {
let n = c.members.len();
if n < 2 {
return 1.0;
}
let mut h: Hypergraph<Value, Value, Value> = Hypergraph::new();
for m in &c.members {
h.add_node(&m.to_string(), Value::Null);
}
for (a, b) in &c.links {
let _ = h.add_edge(vec![a.to_string(), b.to_string()], None, Value::Null);
}
let comps = connected_components(&h).len();
1.0 - (comps as f64 - 1.0) / (n as f64 - 1.0)
}
struct UnionFind {
parent: Vec<usize>,
}
impl UnionFind {
fn new(n: usize) -> Self {
Self {
parent: (0..n).collect(),
}
}
fn find(&mut self, mut x: usize) -> usize {
while self.parent[x] != x {
self.parent[x] = self.parent[self.parent[x]];
x = self.parent[x];
}
x
}
fn union(&mut self, a: usize, b: usize) {
let (ra, rb) = (self.find(a), self.find(b));
if ra != rb {
self.parent[ra] = rb;
}
}
}
pub fn global_pi0(w: &DeckWorld) -> usize {
let mut uf = UnionFind::new(w.agents.len());
for c in &w.communities {
for &(a, b) in &c.links {
uf.union(a, b);
}
}
for e in &w.extraction {
for &t in &e.tails {
uf.union(t, e.head);
}
}
let mut roots: HashSet<usize> = HashSet::new();
for a in &w.agents {
roots.insert(uf.find(a.id));
}
roots.len()
}
pub fn sigmoid(x: f64) -> f64 {
1.0 / (1.0 + (-x).exp())
}
pub fn periphery_mean_wealth(w: &DeckWorld) -> f64 {
let per: Vec<&Agent> = w.agents.iter().filter(|a| a.bloc == 2).collect();
per.iter().map(|a| a.wealth).sum::<f64>() / per.len() as f64
}
pub fn psa(w: &DeckWorld) -> f64 {
let subsistence = w
.agents
.iter()
.find(|a| a.bloc == 2)
.map_or(3.0, |a| a.subsistence);
sigmoid(periphery_mean_wealth(w) - subsistence)
}
pub fn psr(w: &DeckWorld) -> f64 {
let org0 = org_degree(&w.communities[0]);
let org1 = org_degree(&w.communities[1]);
let mean_org = (org0 + org1) / 2.0;
(mean_org / (w.repression / 2.6 * 0.9)).min(1.0)
}