hypergraph_rs/raster/deck.rs
1//! `mulberry32` deck RNG port + `buildWorld` fixture + o(C) organization degree
2//! (`topology-deck.html:120-121, 129-179, 196-208`). Task 6.
3//!
4//! `mulberry32` is a fixture-only RNG that never enters the general
5//! layout/community API (`Pcg64Mcg` remains the crate's canonical
6//! generator) — see the plan's CRITICAL REFERENCE CORRECTION on
7//! mulberry32 vs Pcg64Mcg.
8
9use std::collections::HashSet;
10
11use serde_json::Value;
12
13use crate::algorithms::connected::connected_components;
14use crate::Hypergraph;
15
16use super::algebra::{deck_industries, Industry};
17
18/// Byte-exact Rust port of the deck's `mulberry32(a)` closure
19/// (`topology-deck.html:120-121`). State is a wrapping `u32`; `next()`
20/// reproduces the JS `Math.imul`/`>>>`/`|0` arithmetic bit-for-bit (pure
21/// wrapping-integer arithmetic — no float-tolerance concern, user CLAUDE.md
22/// §4).
23#[derive(Debug, Clone)]
24pub struct Mulberry32 {
25 a: u32,
26}
27
28impl Mulberry32 {
29 /// Seed the generator (the deck's `mulberry32(seed)` call).
30 pub fn new(seed: u32) -> Self {
31 Self { a: seed }
32 }
33
34 /// Advance the generator and return the next `[0,1)` draw. Named `next`
35 /// (not `Iterator`) to match the Step-1 golden-vector test contract and
36 /// the deck's own `rnd()` call shape; it is a fixture RNG, not a
37 /// general-purpose iterator.
38 #[allow(clippy::should_implement_trait)]
39 pub fn next(&mut self) -> f64 {
40 self.a = self.a.wrapping_add(0x6D2B79F5);
41 let mut t = self.a;
42 t = (t ^ (t >> 15)).wrapping_mul(t | 1);
43 t ^= t.wrapping_add((t ^ (t >> 7)).wrapping_mul(t | 61));
44 ((t ^ (t >> 14)) as f64) / 4294967296.0
45 }
46}
47
48/// One of the 28 seeded agents (`topology-deck.html:129-134`).
49#[derive(Debug, Clone, PartialEq)]
50pub struct Agent {
51 pub id: usize,
52 pub bloc: u8,
53 pub wealth: f64,
54 pub subsistence: f64,
55}
56
57/// An organizing community: a member set plus internal cohesion links
58/// (`topology-deck.html:135-143`).
59#[derive(Debug, Clone, PartialEq)]
60pub struct Community {
61 pub name: String,
62 pub members: Vec<usize>,
63 pub links: Vec<(usize, usize)>,
64}
65
66/// A multilateral extraction hyperedge: deduped periphery tails -> one
67/// capital head (`topology-deck.html:145-149`).
68#[derive(Debug, Clone, PartialEq)]
69pub struct Extraction {
70 pub tails: Vec<usize>,
71 pub head: usize,
72 pub mass: f64,
73}
74
75/// The instrument input bundle — everything `instruments::build` reads to
76/// render a scene. `build_world(seed)` (below) is the **seeded deck
77/// fixture** producer (`topology-deck.html:151-179`'s `buildWorld` return
78/// value); `raster::ingest::to_world` (Phase I) is the **real-graph**
79/// producer for an arbitrary `Hypergraph`. Both paths converge on this one
80/// struct so the frozen render path (`instruments::build` → `rasterize` /
81/// `render_pixels`) never has to know which producer built its input —
82/// this is the adapter-into-struct design (`plans/phase-I-topology-ingest.md`
83/// CRITICAL DESIGN RULING), chosen over a `WorldSource` trait so the golden
84/// path is edited by neither producer, ever.
85///
86/// `seed`/`tick` are deck-fixture provenance: no instrument builder reads
87/// them (only `build_world`/`do_tick` do). `ingest::to_world` sets both to
88/// `0` as documented sentinels and reports its own real provenance on
89/// `IngestReport` instead of mutating this struct.
90#[derive(Debug, Clone, PartialEq)]
91pub struct DeckWorld {
92 pub seed: u32,
93 pub agents: Vec<Agent>,
94 pub communities: Vec<Community>,
95 pub extraction: Vec<Extraction>,
96 pub industries: Vec<Industry>,
97 pub repression: f64,
98 pub tick: u32,
99 pub zoom: u8,
100}
101
102/// Agent ids of the given bloc, in `agents` order.
103fn agents_in_bloc(agents: &[Agent], bloc: u8) -> Vec<usize> {
104 agents
105 .iter()
106 .filter(|a| a.bloc == bloc)
107 .map(|a| a.id)
108 .collect()
109}
110
111/// The deck's `mk(pool,size,name)`: seeded Fisher-Yates shuffle of the full
112/// pool, then take the first `size` (`topology-deck.html:137-138`). Bounded:
113/// `pool.len()` is at most 14 (the largest bloc).
114fn shuffle_take(rnd: &mut Mulberry32, pool: Vec<usize>, size: usize, name: &str) -> Community {
115 let mut m = pool;
116 for i in (1..m.len()).rev() {
117 let j = (rnd.next() * (i as f64 + 1.0)) as usize;
118 m.swap(i, j);
119 }
120 m.truncate(size);
121 Community {
122 name: name.to_string(),
123 members: m,
124 links: Vec::new(),
125 }
126}
127
128/// Port `buildWorld(seed)` (`topology-deck.html:129-179`): 28 agents in 3
129/// blocs, 4 organizing communities (capital δ fully cohesive, the rest
130/// atomized with 1 link), 4 extraction hyperedges, and the 13-industry
131/// table.
132pub fn build_world(seed: u32) -> DeckWorld {
133 let mut rnd = Mulberry32::new(seed);
134 let mut agents = Vec::new();
135 let blocs: [(usize, u8, f64); 3] = [(5, 0, 8.5), (9, 1, 5.6), (14, 2, 2.1)];
136 let mut id = 0usize;
137 for (n, bloc, w) in blocs {
138 for _ in 0..n {
139 agents.push(Agent {
140 id,
141 bloc,
142 wealth: w + rnd.next() * 1.4 - 0.7,
143 subsistence: 3.0,
144 });
145 id += 1;
146 }
147 }
148
149 let mut communities = vec![
150 shuffle_take(&mut rnd, agents_in_bloc(&agents, 2), 6, "cell \u{3b1}"),
151 shuffle_take(&mut rnd, agents_in_bloc(&agents, 2), 6, "cell \u{3b2}"),
152 shuffle_take(&mut rnd, agents_in_bloc(&agents, 1), 6, "union \u{3b3}"),
153 shuffle_take(&mut rnd, agents_in_bloc(&agents, 0), 4, "capital \u{3b4}"),
154 ];
155
156 for c in communities.iter_mut() {
157 let full = c.name == "capital \u{3b4}";
158 let want = if full { c.members.len() - 1 } else { 1 };
159 for i in 0..want {
160 c.links.push((c.members[i], c.members[i + 1]));
161 }
162 }
163
164 let per = agents_in_bloc(&agents, 2);
165 let cap = agents_in_bloc(&agents, 0);
166 let mut extraction = Vec::new();
167 for e in 0..4usize {
168 let mut tails_raw = Vec::new();
169 for _ in 0..4 {
170 let idx = (rnd.next() * per.len() as f64) as usize;
171 tails_raw.push(per[idx]);
172 }
173 // JS `new Set([...])` dedupes preserving first-seen order.
174 let mut seen: HashSet<usize> = HashSet::new();
175 let mut tails = Vec::new();
176 for t in tails_raw {
177 if seen.insert(t) {
178 tails.push(t);
179 }
180 }
181 let head = cap[e % cap.len()];
182 let mass = 1.4 + rnd.next() * 1.2;
183 extraction.push(Extraction { tails, head, mass });
184 }
185
186 DeckWorld {
187 seed,
188 agents,
189 communities,
190 extraction,
191 industries: deck_industries(),
192 repression: 2.6,
193 tick: 0,
194 zoom: 0,
195 }
196}
197
198/// Port of `doTick()` (`topology-deck.html:243-252`, Task 10). Order
199/// verbatim (Finding 1): (1) wealth extraction over `world.extraction` —
200/// `take = mass·0.12`; each tail loses `take/|tails|` under a
201/// `Math.max(0.2, …)` floor; the head gains `take·0.8`; every bloc-1
202/// (core-labor) agent gains `take·0.2/9`; THEN (2) c-accumulation — each
203/// industry's `c ×= 1.035` if `lane>=2` else `×= 1.015` (`v,e` untouched).
204/// Does not itself call `transform` — callers compute readouts from the
205/// mutated `world.industries` afterward (the crate's `transform` is a pure
206/// fn with no `Industry`-side effects to "re-run", unlike the deck's
207/// closure-captured `W.industries`). Bounded:
208/// `world.extraction.len() * (max tails + agents.len()) + world.industries.len()`.
209pub fn do_tick(world: &mut DeckWorld) {
210 world.tick += 1;
211
212 for e in &world.extraction {
213 let take = e.mass * 0.12;
214 let per_tail = take / e.tails.len() as f64;
215 for &t in &e.tails {
216 world.agents[t].wealth = (world.agents[t].wealth - per_tail).max(0.2);
217 }
218 world.agents[e.head].wealth += take * 0.8;
219 for a in world.agents.iter_mut().filter(|a| a.bloc == 1) {
220 a.wealth += take * 0.2 / 9.0;
221 }
222 }
223
224 for ind in world.industries.iter_mut() {
225 ind.c *= if ind.lane >= 2 { 1.035 } else { 1.015 };
226 }
227}
228
229/// Weight quantum of the deck's spectral adjacency: every weight the deck
230/// uses (`.25` intra-community, `.5` extraction, `1` community link,
231/// `topology-deck.html:216-220`) is an exact integer multiple of `0.25`,
232/// so multiplicity encodes weight exactly (see [`deck_hypergraph`]).
233const SPECTRAL_WEIGHT_QUANTUM: f64 = 0.25;
234
235/// Add the 2-node edge `(a,b)` `round(w / 0.25)` times — the multiplicity
236/// encoding of a weighted edge (see [`deck_hypergraph`]). Bounded: `w` comes
237/// from the deck's three literal constants, so the count is 1, 2 or 4.
238fn add_weighted_pair(h: &mut Hypergraph<Value, Value, Value>, a: usize, b: usize, w: f64) {
239 let reps = (w / SPECTRAL_WEIGHT_QUANTUM).round() as u32;
240 for _ in 0..reps {
241 let _ = h.add_edge(vec![a.to_string(), b.to_string()], None, Value::Null);
242 }
243}
244
245/// The shared `DeckWorld -> &Hypergraph` adapter (Finding 6): 28 agents
246/// become nodes keyed by their id. The single bridge from `DeckWorld` to the
247/// shipped `&Hypergraph` APIs (`subhypergraph`, `connected_components`,
248/// Task 7's `normalized_laplacian`), none of which take `DeckWorld` directly.
249///
250/// **Review MINOR 8 correction (2026-07-22).** This adapter previously built
251/// edges from community *links* only. That is NOT the graph the deck's
252/// `spectral()` diagonalizes (`topology-deck.html:216-220`), which is:
253///
254/// * all-pairs intra-community coupling at weight `.25`,
255/// * each community link at weight `1`,
256/// * each extraction tail -> head at weight `.5`,
257///
258/// accumulated symmetrically (`A[a][b] += w`), so a pair appearing in
259/// several roles sums its weights. Deviation 2 sanctions a *different
260/// eigensolver* producing different eigenvector VALUES; it does not sanction
261/// a structurally different input graph. This fn now builds the deck's
262/// actual adjacency.
263///
264/// **Weight encoding (declared deviation).** The shipped `Hypergraph` has no
265/// per-edge weight and `communities::normalized_laplacian` builds a 0/1
266/// incidence, so weights are encoded by **edge multiplicity**: one 2-node
267/// edge per `0.25` of weight (`.25` -> x1, `.5` -> x2, `1` -> x4). This is
268/// exact, not approximate — every deck weight is an integer multiple of
269/// `0.25`. It is also exactly faithful to the spectrum: for 2-node edges
270/// (`De = 2`) the hypergraph normalized Laplacian reduces to
271/// `L = ½·(I − D^{-1/2} W D^{-1/2})` with `W[i,k]` the multiplicity and
272/// `D[i] = Σ_k W[i,k]`, i.e. exactly one half of the standard weighted
273/// normalized Laplacian — a uniform positive scale, which leaves every
274/// eigenVECTOR unchanged (only eigenvalues halve). The spectral layout reads
275/// eigenvectors only.
276///
277/// **Isolated nodes (retained, narrowed).** Even under the deck's full
278/// adjacency, 5 of the 28 agents at seed 1917 (ids 7, 9, 11, 15, 27) belong
279/// to no community and appear in no extraction hyperedge, so their degree is
280/// 0 — verified directly against the reference implementation, whose own
281/// `deg` array carries five zeros. `normalized_laplacian` divides by node
282/// degree and rejects those with `SpectralError::IsolatedNode`, so each such
283/// agent still gets an inert singleton self-edge (`add_edge(vec![id])`):
284/// degree 1, zero coupling to any other node (`L[i,i] = 0`, its row/column
285/// otherwise zero). The deck reaches the same place by a different route —
286/// an isolated row of its shifted operator is `shift·v[i]`, i.e. eigenvalue
287/// 0 of `L`, decoupled from everything — so this is a representational
288/// necessity of the shipped API, not a structural difference. The count of
289/// affected agents drops from 18 to 5 under this correction.
290pub fn deck_hypergraph(w: &DeckWorld) -> Hypergraph<Value, Value, Value> {
291 let mut h: Hypergraph<Value, Value, Value> = Hypergraph::new();
292 for a in &w.agents {
293 h.add_node(&a.id.to_string(), Value::Null);
294 }
295 let mut degree = vec![0u32; w.agents.len()];
296 let link = |h: &mut Hypergraph<Value, Value, Value>,
297 degree: &mut Vec<u32>,
298 a: usize,
299 b: usize,
300 weight: f64| {
301 add_weighted_pair(h, a, b, weight);
302 degree[a] += 1;
303 degree[b] += 1;
304 };
305
306 // All-pairs intra-community coupling at .25 (`:217-218`). Bounded:
307 // Σ_C |C|·(|C|−1)/2 over a fixed 4-community fixture.
308 for c in &w.communities {
309 for i in 0..c.members.len() {
310 for j in (i + 1)..c.members.len() {
311 link(&mut h, &mut degree, c.members[i], c.members[j], 0.25);
312 }
313 }
314 }
315 // Community cohesion links at 1 (`:219`).
316 for c in &w.communities {
317 for &(a, b) in &c.links {
318 link(&mut h, &mut degree, a, b, 1.0);
319 }
320 }
321 // Extraction tails -> head at .5 (`:220`).
322 for e in &w.extraction {
323 for &t in &e.tails {
324 link(&mut h, &mut degree, t, e.head, 0.5);
325 }
326 }
327
328 for a in &w.agents {
329 if degree[a.id] == 0 {
330 let _ = h.add_edge(vec![a.id.to_string()], None, Value::Null);
331 }
332 }
333 h
334}
335
336/// Organization degree `o(C) = 1` if `|C|<2` else `1 - (|Π₀(C)|-1)/(|C|-1)`
337/// (`topology-deck.html:206-208`). Built as an isolated per-community graph
338/// (own members as nodes, own links as edges) rather than a slice of the
339/// shared `deck_hypergraph`: the deck's `orgOf` walks only `c.links`, and
340/// the periphery communities draw from an overlapping pool (`cell α`/`cell
341/// β` both shuffle the full 14-agent bloc), so filtering a shared multi-
342/// community graph by node membership alone (`subhypergraph`) could admit
343/// another community's edge whose endpoints happen to fall inside this
344/// community's member set — this isolated construction is immune to that
345/// and reproduces `orgOf` exactly. Reuses `connected_components`
346/// (`algorithms::connected`) for `|Π₀(C)|`, per Task 6.
347pub fn org_degree(c: &Community) -> f64 {
348 let n = c.members.len();
349 if n < 2 {
350 return 1.0;
351 }
352 let mut h: Hypergraph<Value, Value, Value> = Hypergraph::new();
353 for m in &c.members {
354 h.add_node(&m.to_string(), Value::Null);
355 }
356 for (a, b) in &c.links {
357 let _ = h.add_edge(vec![a.to_string(), b.to_string()], None, Value::Null);
358 }
359 let comps = connected_components(&h).len();
360 1.0 - (comps as f64 - 1.0) / (n as f64 - 1.0)
361}
362
363/// Path-halving union-find over `[0, n)`, bounded by `n` unions (Power-of-10
364/// rule 2: no loop here is unbounded — `find`'s `while` shrinks the parent
365/// chain toward the root every step and terminates once `parent[x] == x`,
366/// which every union eventually establishes over a graph of `n` nodes).
367struct UnionFind {
368 parent: Vec<usize>,
369}
370
371impl UnionFind {
372 fn new(n: usize) -> Self {
373 Self {
374 parent: (0..n).collect(),
375 }
376 }
377
378 fn find(&mut self, mut x: usize) -> usize {
379 while self.parent[x] != x {
380 self.parent[x] = self.parent[self.parent[x]];
381 x = self.parent[x];
382 }
383 x
384 }
385
386 fn union(&mut self, a: usize, b: usize) {
387 let (ra, rb) = (self.find(a), self.find(b));
388 if ra != rb {
389 self.parent[ra] = rb;
390 }
391 }
392}
393
394/// Global Π₀: union all community links and all extraction tails→head over
395/// the full 28-agent population (`topology-deck.html:196-204`'s
396/// `globalPi0`), hand-rolled (not `algorithms::connected_components`,
397/// which walks a `&Hypergraph` — `DeckWorld`'s extraction hyperedges are
398/// directed tails→head, not the crate's undirected membership shape).
399pub fn global_pi0(w: &DeckWorld) -> usize {
400 let mut uf = UnionFind::new(w.agents.len());
401 for c in &w.communities {
402 for &(a, b) in &c.links {
403 uf.union(a, b);
404 }
405 }
406 for e in &w.extraction {
407 for &t in &e.tails {
408 uf.union(t, e.head);
409 }
410 }
411 let mut roots: HashSet<usize> = HashSet::new();
412 for a in &w.agents {
413 roots.insert(uf.find(a.id));
414 }
415 roots.len()
416}
417
418/// `sigmoid(x) = 1/(1+e^-x)` (`topology-deck.html:122`). Routes through
419/// `exp` — not byte-exact across libm implementations (Finding 3, user
420/// CLAUDE.md §4); callers golden-test it tolerance-bounded (`< 1e-12`).
421pub fn sigmoid(x: f64) -> f64 {
422 1.0 / (1.0 + (-x).exp())
423}
424
425/// Mean wealth of the bloc-2 (periphery) agents, in `agents` order
426/// (`topology-deck.html:439-440`'s `pw`). Pure arithmetic — byte-exact.
427pub fn periphery_mean_wealth(w: &DeckWorld) -> f64 {
428 let per: Vec<&Agent> = w.agents.iter().filter(|a| a.bloc == 2).collect();
429 per.iter().map(|a| a.wealth).sum::<f64>() / per.len() as f64
430}
431
432/// `psa = sigmoid(pw − per[0].subsistence)` (`topology-deck.html:443`) — the
433/// periphery's assimilation survival probability. Tolerance-bounded golden
434/// (routes through `sigmoid`'s `exp`, Finding 3), NOT byte-exact.
435pub fn psa(w: &DeckWorld) -> f64 {
436 let subsistence = w
437 .agents
438 .iter()
439 .find(|a| a.bloc == 2)
440 .map_or(3.0, |a| a.subsistence);
441 sigmoid(periphery_mean_wealth(w) - subsistence)
442}
443
444/// `psr = min(1, (org(cell α)+org(cell β))/2 / (repression/2.6·0.9))`
445/// (`topology-deck.html:444`) — the deck's *calibrated* rupture-survival
446/// form; diverges from the textbook `P(S|R)=Org/Repression` (see OPEN
447/// DECISION D-R7). Pure division — byte-exact. `communities[0]`/`[1]` are
448/// `cell α`/`cell β` by `build_world`'s push order.
449pub fn psr(w: &DeckWorld) -> f64 {
450 let org0 = org_degree(&w.communities[0]);
451 let org1 = org_degree(&w.communities[1]);
452 let mean_org = (org0 + org1) / 2.0;
453 (mean_org / (w.repression / 2.6 * 0.9)).min(1.0)
454}