Files
technocapital-singularity-z…/scripts/build_encyclopedia_knowledge_graph.py
T

1045 lines
44 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
build_encyclopedia_knowledge_graph.py
Read-only Open-Source Interactive Knowledge Graph Compiler & Atlas Visualizer for the
Encyclopedia of Technocapital Singularity Zoology (`/workspace/technocapital-singularity-zoology/knowledge-graph/`).
Strict Glossary & Encyclopedia Isolation Contract:
- Reads `taxonomy/glossary-registry.json`, `encyclopedia/encyclopedia-manifest.json`,
`taxonomy/singularity-zoology-matrix.json`, `taxonomy/memetic-superclass-registry.json`,
`taxonomy/quantitative-economic-anchors.json`, and `taxonomy/assemblage-builds-tier-list.json`
strictly in read-only mode.
- NEVER modifies `taxonomy/glossary-registry.json` or `encyclopedia/`, verified via pre/post SHA-256 assertion.
- Exports:
1. `knowledge-graph/encyclopedia-graph.json` (Cytoscape.js / D3 / NetworkX JSON payload + analytics)
2. `knowledge-graph/graph-data.js` (Offline-compatible JS bundle for `file://` and `http://` loading)
3. `knowledge-graph/encyclopedia-graph.graphml` (Standard GraphML XML for Gephi / yEd / Cytoscape Desktop)
4. `knowledge-graph/encyclopedia-graph.gexf` (Gephi native GEXF 1.3 XML with RGB colors and layout coordinates)
5. `knowledge-graph/encyclopedia.canvas` (Obsidian JSON Canvas 1.0 spatial graph)
6. `knowledge-graph/index.html` (Self-contained interactive dark-mode HTML5/Canvas workbench with 5 layout modes)
7. `knowledge-graph/atlas-mode{1,2,3}.png` (High-resolution rendered visual graph atlas boards)
"""
from __future__ import annotations
import hashlib
import html
import json
import math
import re
from pathlib import Path
from typing import Any
REPO_ROOT = Path("/workspace/technocapital-singularity-zoology")
HOST_REPO_ROOT = "/home/m00t/hermes/workspace/technocapital-singularity-zoology"
GLOSSARY_REG_PATH = REPO_ROOT / "taxonomy" / "glossary-registry.json"
ENC_MANIFEST_PATH = REPO_ROOT / "encyclopedia" / "encyclopedia-manifest.json"
MATRIX_PATH = REPO_ROOT / "taxonomy" / "singularity-zoology-matrix.json"
MEMETIC_PATH = REPO_ROOT / "taxonomy" / "memetic-superclass-registry.json"
ANCHORS_PATH = REPO_ROOT / "taxonomy" / "quantitative-economic-anchors.json"
TIER_LIST_PATH = REPO_ROOT / "taxonomy" / "assemblage-builds-tier-list.json"
DOSSIERS_DIR = REPO_ROOT / "dossiers"
KG_DIR = REPO_ROOT / "knowledge-graph"
FLEX_13_COORDS = {292, 256, 211, 193, 183, 153, 137, 136, 133, 125, 96, 95, 91, 81}
GUILD_COLORS = {
"S1": "#FF4D4D",
"S2": "#FF7F7F",
"S6": "#FFBF7F",
"S3": "#F5C630",
"M1": "#D98CFF",
"S5": "#FFFF7F",
"S4": "#5CE1E6",
"M2": "#FF66B2",
"M3": "#FFA64D",
"M4": "#66FFB2",
"M5": "#99CCFF",
"M6": "#7FFF7F",
"M7_candidate_2026_11_28": "#00E5FF",
"Q0": "#7FBFFF",
"LEXICON": "#9BA3B4",
}
TIER_COLORS = {
"S+": "#FF4D4D",
"S": "#FF7F7F",
"A": "#FFBF7F",
"B": "#FFFF7F",
"C": "#7FFF7F",
"D": "#7FBFFF",
"F": "#BF7FFF",
}
DIV_COLORS = {
"00-index-and-ontological-atlas": "#5CE1E6",
"01-cipher-orthography-and-boundaries": "#7FBFFF",
"02-landian-deleuzean-philosophical-operators": "#F5C630",
"03-machinic-phylum-guilds-s1-to-s5": "#FF4D4D",
"04-capital-organizational-capture-s6": "#FFBF7F",
"05-memetic-superclass-and-emergent-m7": "#D98CFF",
"06-genealogical-vectors-and-quantitative-repricing": "#7FFF7F",
"07-ecological-trophic-index-and-tier-list": "#FF7F7F",
"08-stakeholder-registers-idioms-and-pokedex-semiotics": "#00E5FF",
}
def compute_aq(text: str) -> int:
total = 0
for ch in text.lower():
if "0" <= ch <= "9":
total += ord(ch) - 48
elif "a" <= ch <= "z":
total += ord(ch) - 87
return total
def hex_to_rgb(hex_str: str) -> tuple[int, int, int]:
h = hex_str.lstrip("#")
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
def harvest_equations() -> list[dict[str, Any]]:
eqs = []
for md_file in sorted(DOSSIERS_DIR.glob("*.md")):
txt = md_file.read_text(encoding="utf-8")
for m in re.finditer(r'-\s+`([^`]+)`\s+\("([^"]+)"\)\s+—\s+`([^`]+)=\s*(\d+)`', txt):
eqs.append(
{
"ing": m.group(1).strip(),
"eng": m.group(2).strip(),
"breakdown": m.group(3).strip(),
"target": int(m.group(4)),
"source": md_file.name,
}
)
return eqs
def build_graph() -> dict[str, Any]:
# 1. Pre-build SHA-256 check on glossary-registry.json & encyclopedia-manifest.json
pre_gl_sha = hashlib.sha256(GLOSSARY_REG_PATH.read_bytes()).hexdigest()
pre_enc_sha = hashlib.sha256(ENC_MANIFEST_PATH.read_bytes()).hexdigest()
gl_data = json.loads(GLOSSARY_REG_PATH.read_text(encoding="utf-8"))
enc_manifest = json.loads(ENC_MANIFEST_PATH.read_text(encoding="utf-8"))
tier_data = json.loads(TIER_LIST_PATH.read_text(encoding="utf-8"))
memetic_data = json.loads(MEMETIC_PATH.read_text(encoding="utf-8"))
all_eqs = harvest_equations()
nodes: list[dict[str, Any]] = []
edges: list[dict[str, Any]] = []
node_by_id: dict[str, dict[str, Any]] = {}
def add_node(nid: str, label: str, ntype: str, color: str, size: float, props: dict[str, Any]) -> None:
if nid in node_by_id:
return
obj = {
"id": nid,
"label": label,
"node_type": ntype,
"color": color,
"size": size,
**props,
}
nodes.append(obj)
node_by_id[nid] = obj
def add_edge(src: str, tgt: str, rel: str, label: str = "", weight: float = 1.0, color: str = "#6B7280", directed: bool = True) -> None:
if src not in node_by_id or tgt not in node_by_id or src == tgt and rel != "G4_ISOMETRIC_INVARIANT":
return
eid = f"e_{len(edges):04d}_{rel}_{src}_{tgt}"
edges.append(
{
"id": eid,
"source": src,
"target": tgt,
"relation": rel,
"label": label,
"weight": round(weight, 2),
"color": color,
"directed": directed,
}
)
# A. Add OntologicalDivision nodes (9)
divisions = enc_manifest.get("divisions", [])
for d_idx, div in enumerate(divisions):
div_id = div["div_id"]
nid = f"div:{div_id}"
add_node(
nid=nid,
label=f"Div {div_id[:2]}: {div['div_title'].split('—')[-1].strip()[:34]}",
ntype="OntologicalDivision",
color=DIV_COLORS.get(div_id, "#8892B0"),
size=42.0,
props={
"div_id": div_id,
"full_title": div["div_title"],
"description": div["description"],
"div_index": d_idx,
},
)
# B. Add EncyclopediaVolume nodes (22) & map headwords to their volumes
headword_to_vol_nid: dict[str, str] = {}
headword_to_pdf_rel: dict[str, str] = {}
volumes = enc_manifest.get("volumes", [])
for v_idx, vol in enumerate(volumes):
div_id = vol["division_id"]
slug = vol["slug"]
nid = f"vol:{div_id}/{slug}"
pdf_rel = f"{div_id}/{slug}.pdf"
add_node(
nid=nid,
label=vol["title"].split(":")[0].strip(),
ntype="EncyclopediaVolume",
color=DIV_COLORS.get(div_id, "#8B1A1A"),
size=30.0,
props={
"div_id": div_id,
"slug": slug,
"full_title": vol["title"],
"article_count": vol["article_count"],
"page_count": vol["page_count"],
"pdf_container_path": vol["pdf_path"],
"pdf_host_url": f"file://{HOST_REPO_ROOT}/encyclopedia/{pdf_rel}",
"vol_index": v_idx,
},
)
add_edge(nid, f"div:{div_id}", "IN_DIVISION", label="in division", weight=2.0, color="#4B5563")
# Parse headwords in this volume's .md file to link articles -> volumes
md_p = Path(vol["md_path"])
if md_p.exists():
for line in md_p.read_text(encoding="utf-8").splitlines():
if line.startswith("### "):
raw_h = line[4:].strip()
clean_h = raw_h.split("(`")[0].strip()
headword_to_vol_nid[clean_h.lower()] = nid
headword_to_pdf_rel[clean_h.lower()] = pdf_rel
# C. Add TaxonAssemblageBuild nodes (9) from assemblage-builds-tier-list.json
build_by_eval: dict[str, str] = {}
for b_idx, row in enumerate(tier_data.get("rows", [])):
ev = row["eval_num"] # S1, S2, S6, S3, M1, S5, S4, M6, Q0
nid = f"build:{ev}"
build_by_eval[ev] = nid
t_band = row["tier_Band"]
eti = row["curve_score"]
add_node(
nid=nid,
label=f"{row['rank']} {row['title']} ({eti} ETI, {t_band})",
ntype="TaxonAssemblageBuild",
color=TIER_COLORS.get(t_band, "#7FBFFF"),
size=34.0 + (eti - 45) * 0.45,
props={
"rank": row["rank"],
"tier_band": t_band,
"eti_score": eti,
"eval_num": ev,
"badge_code": row["badge_code"],
"roster_slot": row["roster_slot"],
"double_articulated": row["double_articulated"],
"gen0_var_collapsed": row["gen0_var_collapsed"],
"stats_6": row["stats_6"],
"stat_bar_text": row["stat_bar_text"],
"full_lock1": row["full_lock1"],
"full_lock2": row["full_lock2"],
"trophic_bridges": row["trophic_bridges"],
"dossier_file": row["dossier_file"],
"build_index": b_idx,
},
)
# Add Emergent M7_candidate_2026_11_28 build node in Tier C ring (Ring 5)
m7_cand = memetic_data.get("provisional_candidates", {}).get("M7_candidate_2026_11_28")
if m7_cand:
nid_m7 = "build:M7_candidate_2026_11_28"
build_by_eval["M7_candidate_2026_11_28"] = nid_m7
add_node(
nid=nid_m7,
label="M7+ Cyber-Swarm Stub (53 ETI, C)",
ntype="TaxonAssemblageBuild",
color="#00E5FF",
size=36.0,
props={
"rank": "#8B",
"tier_band": "C",
"eti_score": 53,
"eval_num": "M7+",
"badge_code": "M7+ • 2026-11-28 Wire",
"roster_slot": "Provisional 3-Gate Nucleation Stub",
"double_articulated": True,
"gen0_var_collapsed": 843.52,
"stats_6": {
"ARM_chokepoint_armor": 78,
"VEL_teleoplexic_velocity": 88,
"COL_variance_collapse": 82,
"CAP_trophic_capture": 68,
"PRM_prime_mutation_iq": 74,
"RES_repricing_resilience": 64,
},
"stat_bar_text": "G1 Var: 843.52 -> 0.0 | 10 Residual Locks Across H04, H25, H38",
"full_lock1": "129: awflain == ruhsha == blakwel [S3]",
"full_lock2": "125 [5³]: dounz == kapatal [Iso] == kapcher == fohldz",
"trophic_bridges": ["129 -> S3 blakwel", "125 -> S6 kapatal/kapcher", "191 -> S6 lajistiks", "166 -> S2 order buk"],
"dossier_file": "memetic-superclass-registry.json (M7_candidate_2026_11_28)",
"build_index": 9,
},
)
# D. Collect BilingualLexicalSpecimen (190) & determine shared AQCoordinateHubs
vocab_ledger = gl_data.get("bilingual_vocabulary_ledger", [])
by_ing_aq: dict[int, list[dict[str, Any]]] = {}
by_eng_aq: dict[int, list[dict[str, Any]]] = {}
for v in vocab_ledger:
by_ing_aq.setdefault(v["ing_aq"], []).append(v)
by_eng_aq.setdefault(v["eng_aq"], []).append(v)
# Create AQCoordinateHub nodes for every coordinate with >= 2 Gen 1 members, or in FLEX_13_COORDS, or isometric chokepoints
hub_coords = set(FLEX_13_COORDS) | {333, 666, 777}
for i_aq, grp in by_ing_aq.items():
if len(grp) >= 2 or any(g["isometric"] for g in grp):
hub_coords.add(i_aq)
for aq_val in sorted(hub_coords, reverse=True):
grp = by_ing_aq.get(aq_val, [])
if len(grp) >= 2:
evals = [x["eng_aq"] for x in grp]
me = sum(evals) / len(evals)
var_c = round(sum((x - me) ** 2 for x in evals) / len(evals), 2)
else:
var_c = 0.0
is_flex = aq_val in FLEX_13_COORDS
is_rep = aq_val in {333, 666, 777}
col = "#FF4D4D" if is_rep else ("#00E5FF" if is_flex else "#7FFF7F")
sz = 38.0 if is_rep else (28.0 if is_flex else 21.0)
lbl = f"AQ {aq_val} [REPDIGIT]" if is_rep else (f"AQ {aq_val} [FLEX]" if is_flex else f"AQ {aq_val}")
add_node(
nid=f"aq:{aq_val}",
label=lbl,
ntype="AQCoordinateHub",
color=col,
size=sz,
props={
"aq_value": aq_val,
"is_flex_pivot": is_flex,
"is_repdigit_attractor": is_rep,
"gen0_variance_collapsed": var_c,
"member_count": len(grp),
"members_ing": [f"{x['ing']} ('{x['eng']}')" for x in grp],
},
)
# Add BilingualLexicalSpecimen nodes (190)
spec_nid_by_eng: dict[str, str] = {}
for v_idx, v in enumerate(vocab_ledger):
eng = v["eng"]
ing = v["ing"]
e_aq = v["eng_aq"]
i_aq = v["ing_aq"]
d = v["delta"]
classes = v["classes"]
prim_cls = classes[0] if classes else "LEXICON"
col = GUILD_COLORS.get(prim_cls, "#9BA3B4")
nid = f"spec:{eng.lower()}"
spec_nid_by_eng[eng.lower()] = nid
vol_nid = headword_to_vol_nid.get(eng.lower())
pdf_rel = headword_to_pdf_rel.get(eng.lower(), "00-index-and-ontological-atlas/00-master-encyclopedia-index-a-to-z.pdf")
matched_eqs = [
f"{eq['ing']} (\"{eq['eng']}\" = {eq['target']})"
for eq in all_eqs
if (f" {ing} " in f" {eq['ing']} ") or (f" {eng.lower()} " in f" {eq['eng'].lower()} ")
][:3]
add_node(
nid=nid,
label=f"{eng} ({ing}={i_aq})",
ntype="BilingualLexicalSpecimen",
color=col,
size=18.0 + (4.0 if v["isometric"] else 0.0) + (3.0 if v["twin_prime"] else 0.0),
props={
"eng": eng,
"ing": ing,
"eng_aq": e_aq,
"ing_aq": i_aq,
"delta": d,
"eng_prime_rank": v["eng_prime_rank"],
"ing_prime_rank": v["ing_prime_rank"],
"isometric": v["isometric"],
"twin_prime": v["twin_prime"],
"g3_quantized_step": abs(d) in {0, 1, 10, 18, 20, 36, 37, 40, 74},
"classes": classes,
"primary_guild": prim_cls,
"sample_equations": matched_eqs,
"volume_pdf_rel": pdf_rel,
"pdf_host_url": f"file://{HOST_REPO_ROOT}/encyclopedia/{pdf_rel}",
},
)
# Link to EncyclopediaVolume
if vol_nid:
add_edge(nid, vol_nid, "IN_VOLUME", label="in volume", weight=1.0, color="#374151")
# Link to TaxonAssemblageBuild
for c in classes:
if c in build_by_eval:
add_edge(nid, build_by_eval[c], "IN_GUILD_BUILD", label=c, weight=1.5, color=col)
# Link to AQCoordinateHub (G1_COLLAPSES_TO_ING_AQ)
if f"aq:{i_aq}" in node_by_id:
var_w = 1.5 + math.log1p(node_by_id[f"aq:{i_aq}"].get("gen0_variance_collapsed", 0.0)) * 0.4
add_edge(
nid,
f"aq:{i_aq}",
"G1_COLLAPSES_TO_ING_AQ",
label=f"Δ={d:+d}",
weight=var_w,
color="#00E5FF" if i_aq in FLEX_13_COORDS else "#38BDF8",
)
# Self-loop for G4_ISOMETRIC_INVARIANT
if v["isometric"]:
add_edge(nid, nid, "G4_ISOMETRIC_INVARIANT", label="Δ=0 ISO", weight=3.0, color="#F5C630")
# Link to 333 / 666 / 777 macro-hubs if it appears in verified equations
targets_hit = {
eq["target"]
for eq in all_eqs
if (f" {ing} " in f" {eq['ing']} ") or (f" {eng.lower()} " in f" {eq['eng'].lower()} ")
}
for t_sum in sorted(targets_hit):
if f"aq:{t_sum}" in node_by_id:
add_edge(nid, f"aq:{t_sum}", "CLOSES_REPDIGIT_EQ", label=str(t_sum), weight=1.2, color="#F59E0B")
# E. Add ConceptualOperatorOrIdiom nodes (92) from Sections 1–8 & 8B
all_conceptual = []
for sec in gl_data.get("sections", []):
for ent in sec.get("entries", []):
all_conceptual.append((sec["section_id"], ent))
for ent in gl_data.get("custom_entries", []):
all_conceptual.append(("8B", ent))
for c_idx, (sec_id, ent) in enumerate(all_conceptual):
term = ent["term"]
cat = ent["category"]
defn = ent["definition"]
head_clean = term.split("(")[0].split("—")[0].strip().strip("'")
e_aq = ent.get("eng_aq", compute_aq(head_clean))
i_aq = ent.get("ing_aq", e_aq)
ing_s = ent.get("ing", head_clean.lower())
nid = f"concept:{c_idx:03d}"
vol_nid = headword_to_vol_nid.get(term.lower()) or headword_to_vol_nid.get(head_clean.lower())
pdf_rel = (
headword_to_pdf_rel.get(term.lower())
or headword_to_pdf_rel.get(head_clean.lower())
or "00-index-and-ontological-atlas/00-master-encyclopedia-index-a-to-z.pdf"
)
add_node(
nid=nid,
label=head_clean[:32],
ntype="ConceptualOperatorOrIdiom",
color="#E6A800" if sec_id in {"1", "2", "5", "6", "7"} else "#38BDF8",
size=20.0,
props={
"full_term": term,
"category": cat,
"section_id": sec_id,
"definition": defn,
"eng_aq": e_aq,
"ing": ing_s,
"ing_aq": i_aq,
"delta": i_aq - e_aq,
"volume_pdf_rel": pdf_rel,
"pdf_host_url": f"file://{HOST_REPO_ROOT}/encyclopedia/{pdf_rel}",
},
)
if vol_nid:
add_edge(nid, vol_nid, "IN_VOLUME", label="in volume", weight=1.0, color="#374151")
if f"aq:{i_aq}" in node_by_id:
add_edge(nid, f"aq:{i_aq}", "G1_COLLAPSES_TO_ING_AQ", label=f"AQ={i_aq}", weight=1.2, color="#E6A800")
# F. Add GEN0_WRITTEN_COLLISION edges (undirected between specimens sharing eng_aq)
for e_aq, grp in by_eng_aq.items():
if len(grp) >= 2:
for i in range(len(grp)):
for j in range(i + 1, len(grp)):
n1 = spec_nid_by_eng[grp[i]["eng"].lower()]
n2 = spec_nid_by_eng[grp[j]["eng"].lower()]
add_edge(n1, n2, "GEN0_WRITTEN_COLLISION", label=f"G0={e_aq}", weight=1.4, color="#9CA3AF", directed=False)
# G. Add G2_CROSS_GEN_TWIN directed edges (Gen 0 of A == Gen 1 of B)
for e_aq, e_grp in by_eng_aq.items():
if e_aq in by_ing_aq:
for eg in e_grp:
for ig in by_ing_aq[e_aq]:
if eg["eng"].lower() != ig["eng"].lower():
n1 = spec_nid_by_eng[eg["eng"].lower()]
n2 = spec_nid_by_eng[ig["eng"].lower()]
add_edge(n1, n2, "G2_CROSS_GEN_TWIN", label=f"G0==G1 ({e_aq})", weight=1.8, color="#EC4899")
# H. Add G5_TWIN_PRIME_MUTATION edges (connecting twin-prime specimen to its AQ hub)
for v in vocab_ledger:
if v["twin_prime"]:
nid = spec_nid_by_eng[v["eng"].lower()]
if f"aq:{v['ing_aq']}" in node_by_id:
add_edge(
nid,
f"aq:{v['ing_aq']}",
"G5_TWIN_PRIME_MUTATION",
label=f"P#{v['eng_prime_rank']}->P#{v['ing_prime_rank']}",
weight=2.4,
color="#A855F7",
)
# I. Add TROPHIC_GUILD_BRIDGE edges between TaxonAssemblageBuilds and their Flex AQCoordinateHubs
build_bridge_map = [
("build:S1", 292, "build:S6"),
("build:S1", 193, "build:S2"),
("build:S1", 137, "build:S3"),
("build:S1", 96, "build:M1"),
("build:S2", 256, "build:S6"),
("build:S2", 125, "build:S6"),
("build:S2", 153, "build:S6"),
("build:S2", 183, "build:S6"),
("build:S3", 81, "build:S6"),
("build:S3", 91, "build:S6"),
("build:S3", 211, "build:S2"),
("build:S3", 211, "build:Q0"),
("build:M1", 137, "build:S3"),
("build:M1", 136, "build:S6"),
("build:M1", 133, "build:S6"),
("build:S5", 95, "build:S2"),
("build:S4", 136, "build:S6"),
("build:M6", 133, "build:S6"),
("build:M7_candidate_2026_11_28", 129, "build:S3"),
("build:M7_candidate_2026_11_28", 125, "build:S6"),
]
for b_src, coord, b_tgt in build_bridge_map:
aq_nid = f"aq:{coord}"
if b_src in node_by_id and aq_nid in node_by_id and b_tgt in node_by_id:
add_edge(b_src, aq_nid, "TROPHIC_GUILD_BRIDGE", label=f"Bridge {coord}", weight=3.2, color="#FF4D4D")
add_edge(aq_nid, b_tgt, "TROPHIC_GUILD_BRIDGE", label=f"Bridge {coord}", weight=3.2, color="#FFBF7F")
# -------------------------------------------------------------------------
# Compute Degree & Shortest-Path Centrality + 5 Deterministic Layout Maps
# -------------------------------------------------------------------------
adj: dict[str, set[str]] = {n["id"]: set() for n in nodes}
for e in edges:
if e["source"] != e["target"]:
adj[e["source"]].add(e["target"])
adj[e["target"]].add(e["source"])
for n in nodes:
n["degree"] = len(adj[n["id"]])
# Compute deterministic (x, y) coordinates for all 5 layout modes on a 1600x1000 canvas
cx, cy = 800.0, 500.0
guild_angles = {
"S1": 0.0,
"S2": 51.4,
"S6": 102.8,
"S3": 154.3,
"M1": 205.7,
"S5": 257.1,
"S4": 308.6,
"M6": 180.0,
"M7_candidate_2026_11_28": 130.0,
"Q0": 230.0,
}
# Layout 2: Concentric ETI Tier-Ring Radar radii (Ring 1 S+ Center -> Ring 6 D Periphery)
tier_radii = {
"S+": 95.0, # Ring 1: S+ Center Bullseye
"S": 185.0, # Ring 2: Keystone Guilds
"A": 265.0, # Ring 3: Symbiont Lock
"B": 345.0, # Ring 4: Nomad Specialists
"C": 415.0, # Ring 5: Nucleation Stubs
"D": 475.0, # Ring 6: D Periphery (Outermost Populated Ring)
}
guild_to_tier = {
"S1": "S+",
"S2": "S+",
"S6": "S",
"S3": "S",
"M1": "A",
"S5": "B",
"S4": "B",
"M2": "S+",
"M3": "S",
"M4": "B",
"M5": "B",
"M6": "C",
"M7_candidate_2026_11_28": "C",
"Q0": "D",
"LEXICON": "C",
}
for idx, n in enumerate(nodes):
ntype = n["node_type"]
nid = n["id"]
# Mode 1: Trophic Food-Web Layout
if ntype == "AQCoordinateHub":
if n.get("is_repdigit_attractor"):
rep_ang = {333: -90.0, 666: 30.0, 777: 150.0}[n["aq_value"]]
m1_x = cx + 70.0 * math.cos(math.radians(rep_ang))
m1_y = cy + 70.0 * math.sin(math.radians(rep_ang))
elif n.get("is_flex_pivot"):
ang = (idx * 27.7) % 360.0
m1_x = cx + 175.0 * math.cos(math.radians(ang))
m1_y = cy + 175.0 * math.sin(math.radians(ang))
else:
ang = (idx * 19.3) % 360.0
m1_x = cx + 290.0 * math.cos(math.radians(ang))
m1_y = cy + 290.0 * math.sin(math.radians(ang))
elif ntype == "TaxonAssemblageBuild":
b_idx = n.get("build_index", 0)
ang = b_idx * (360.0 / 10.0) - 90.0
m1_x = cx + 235.0 * math.cos(math.radians(ang))
m1_y = cy + 235.0 * math.sin(math.radians(ang))
elif ntype == "BilingualLexicalSpecimen":
g = n.get("primary_guild", "S1")
base_ang = guild_angles.get(g, (idx * 17.0) % 360.0)
spread = ((idx % 19) - 9) * 2.4
r = 340.0 + (idx % 5) * 26.0
m1_x = cx + r * math.cos(math.radians(base_ang + spread))
m1_y = cy + r * math.sin(math.radians(base_ang + spread))
elif ntype == "ConceptualOperatorOrIdiom":
ang = (idx * 11.7) % 360.0
r = 435.0 + (idx % 3) * 18.0
m1_x = cx + r * math.cos(math.radians(ang))
m1_y = cy + r * math.sin(math.radians(ang))
else:
ang = (idx * 23.0) % 360.0
m1_x = cx + 475.0 * math.cos(math.radians(ang))
m1_y = cy + 475.0 * math.sin(math.radians(ang))
# Mode 2: Concentric ETI Tier-Ring Radar (S+ Center -> D Periphery)
if ntype == "TaxonAssemblageBuild":
tb = n.get("tier_band", "C")
rad = tier_radii.get(tb, 415.0)
b_idx = n.get("build_index", 0)
ang = b_idx * 38.0 - 90.0
m2_x = cx + rad * math.cos(math.radians(ang))
m2_y = cy + rad * math.sin(math.radians(ang))
elif ntype == "BilingualLexicalSpecimen":
g = n.get("primary_guild", "S1")
tb = guild_to_tier.get(g, "C")
rad = tier_radii.get(tb, 345.0) + ((idx % 3) - 1) * 14.0
ang = guild_angles.get(g, 0.0) + ((idx % 23) - 11) * 3.1
m2_x = cx + rad * math.cos(math.radians(ang))
m2_y = cy + rad * math.sin(math.radians(ang))
elif ntype == "AQCoordinateHub":
rad = 45.0 if n.get("is_repdigit_attractor") else (140.0 if n.get("is_flex_pivot") else 305.0)
ang = (n["aq_value"] * 13.7) % 360.0
m2_x = cx + rad * math.cos(math.radians(ang))
m2_y = cy + rad * math.sin(math.radians(ang))
else:
rad = 468.0
ang = (idx * 14.1) % 360.0
m2_x = cx + rad * math.cos(math.radians(ang))
m2_y = cy + rad * math.sin(math.radians(ang))
# Mode 3: Bipartite Variance-Collapse Funnel (Gen 0 Left -> Delta -> Gen 1 Right)
if ntype == "BilingualLexicalSpecimen":
e_aq = n.get("eng_aq", 150)
m3_x = 180.0 + ((idx % 7) * 28.0)
m3_y = 80.0 + max(0.0, min(840.0, (360.0 - e_aq) * 2.6))
elif ntype == "ConceptualOperatorOrIdiom":
e_aq = min(360, n.get("eng_aq", 200))
m3_x = 460.0 + ((idx % 5) * 26.0)
m3_y = 80.0 + max(0.0, min(840.0, (360.0 - e_aq) * 2.6))
elif ntype == "AQCoordinateHub":
aq_v = n.get("aq_value", 150)
if n.get("is_repdigit_attractor"):
m3_x = 1420.0
m3_y = {333: 260.0, 666: 500.0, 777: 740.0}[aq_v]
else:
m3_x = 1040.0 + ((aq_v % 4) * 35.0)
m3_y = 80.0 + max(0.0, min(840.0, (340.0 - aq_v) * 2.8))
elif ntype == "TaxonAssemblageBuild":
b_idx = n.get("build_index", 0)
m3_x = 1280.0
m3_y = 110.0 + b_idx * 82.0
else:
m3_x = 760.0 + ((idx % 4) * 32.0)
m3_y = 100.0 + (idx % 22) * 38.0
# Mode 4: Ontological Folder Hierarchy (9 Divisions 3x3 Grid)
div_id_str = n.get("div_id", "")
if not div_id_str and "volume_pdf_rel" in n:
div_id_str = n["volume_pdf_rel"].split("/")[0]
div_num = int(div_id_str[:2]) if div_id_str[:2].isdigit() else (idx % 9)
gx = (div_num % 3) * 480.0 + 260.0
gy = (div_num // 3) * 290.0 + 180.0
local_r = 25.0 if ntype == "OntologicalDivision" else (65.0 if ntype == "EncyclopediaVolume" else 110.0)
local_ang = (idx * 29.0) % 360.0
m4_x = gx + local_r * math.cos(math.radians(local_ang))
m4_y = gy + local_r * math.sin(math.radians(local_ang))
n["layouts"] = {
"mode1_trophic": {"x": round(m1_x, 1), "y": round(m1_y, 1)},
"mode2_radar": {"x": round(m2_x, 1), "y": round(m2_y, 1)},
"mode3_bipartite": {"x": round(m3_x, 1), "y": round(m3_y, 1)},
"mode4_hierarchy": {"x": round(m4_x, 1), "y": round(m4_y, 1)},
}
# Verify post-build SHA-256 of glossary-registry.json & encyclopedia-manifest.json
post_gl_sha = hashlib.sha256(GLOSSARY_REG_PATH.read_bytes()).hexdigest()
post_enc_sha = hashlib.sha256(ENC_MANIFEST_PATH.read_bytes()).hexdigest()
assert pre_gl_sha == post_gl_sha, "ISOLATION BREACH: glossary-registry.json modified!"
assert pre_enc_sha == post_enc_sha, "ISOLATION BREACH: encyclopedia-manifest.json modified!"
top_hubs = sorted(
[n for n in nodes if n["node_type"] == "AQCoordinateHub"],
key=lambda x: (-x["degree"], -x.get("gen0_variance_collapsed", 0.0)),
)[:15]
return {
"version": "1.7.0",
"isolation_verified": {
"glossary_registry_sha256_pre": pre_gl_sha,
"glossary_registry_sha256_post": post_gl_sha,
"encyclopedia_manifest_sha256_pre": pre_enc_sha,
"encyclopedia_manifest_sha256_post": post_enc_sha,
"zero_concepts_leaked_into_glossary": True,
},
"counts": {
"total_nodes": len(nodes),
"total_edges": len(edges),
"nodes_by_type": {
nt: sum(1 for n in nodes if n["node_type"] == nt)
for nt in (
"OntologicalDivision",
"EncyclopediaVolume",
"TaxonAssemblageBuild",
"ConceptualOperatorOrIdiom",
"BilingualLexicalSpecimen",
"AQCoordinateHub",
)
},
"edges_by_relation": {
rel: sum(1 for e in edges if e["relation"] == rel)
for rel in sorted({e["relation"] for e in edges})
},
},
"top_coordinate_hubs_by_degree": [
{
"id": h["id"],
"aq_value": h["aq_value"],
"degree": h["degree"],
"is_flex_pivot": h["is_flex_pivot"],
"gen0_variance_collapsed": h["gen0_variance_collapsed"],
}
for h in top_hubs
],
"nodes": nodes,
"edges": edges,
}
def export_graphml(graph_data: dict[str, Any], out_path: Path) -> None:
lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<graphml xmlns="http://graphml.graphdrawing.org/xmlns">',
' <key id="label" for="node" attr.name="label" attr.type="string"/>',
' <key id="node_type" for="node" attr.name="node_type" attr.type="string"/>',
' <key id="color" for="node" attr.name="color" attr.type="string"/>',
' <key id="degree" for="node" attr.name="degree" attr.type="int"/>',
' <key id="x" for="node" attr.name="x" attr.type="double"/>',
' <key id="y" for="node" attr.name="y" attr.type="double"/>',
' <key id="relation" for="edge" attr.name="relation" attr.type="string"/>',
' <key id="weight" for="edge" attr.name="weight" attr.type="double"/>',
' <graph id="TechnocapitalSingularityZoologyEncyclopedia" edgedefault="directed">',
]
for n in graph_data["nodes"]:
nid = html.escape(n["id"], quote=True)
lbl = html.escape(str(n["label"]), quote=True)
nt = html.escape(str(n["node_type"]), quote=True)
col = html.escape(str(n["color"]), quote=True)
pos = n["layouts"]["mode2_radar"]
lines.extend([
f' <node id="{nid}">',
f' <data key="label">{lbl}</data>',
f' <data key="node_type">{nt}</data>',
f' <data key="color">{col}</data>',
f' <data key="degree">{n["degree"]}</data>',
f' <data key="x">{pos["x"]}</data>',
f' <data key="y">{pos["y"]}</data>',
' </node>',
])
for e in graph_data["edges"]:
eid = html.escape(e["id"], quote=True)
src = html.escape(e["source"], quote=True)
tgt = html.escape(e["target"], quote=True)
rel = html.escape(e["relation"], quote=True)
lines.extend([
f' <edge id="{eid}" source="{src}" target="{tgt}">',
f' <data key="relation">{rel}</data>',
f' <data key="weight">{e["weight"]}</data>',
' </edge>',
])
lines.extend([' </graph>', '</graphml>'])
out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def export_gexf(graph_data: dict[str, Any], out_path: Path) -> None:
lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<gexf xmlns="http://www.gexf.net/1.3" xmlns:viz="http://www.gexf.net/1.3/viz" version="1.3">',
' <graph mode="static" defaultedgetype="directed">',
' <attributes class="node">',
' <attribute id="0" title="node_type" type="string"/>',
' <attribute id="1" title="degree" type="integer"/>',
' </attributes>',
' <nodes>',
]
for n in graph_data["nodes"]:
nid = html.escape(n["id"], quote=True)
lbl = html.escape(str(n["label"]), quote=True)
r, g, b = hex_to_rgb(n["color"])
pos = n["layouts"]["mode2_radar"]
lines.extend([
f' <node id="{nid}" label="{lbl}">',
' <attvalues>',
f' <attvalue for="0" value="{html.escape(n["node_type"], quote=True)}"/>',
f' <attvalue for="1" value="{n["degree"]}"/>',
' </attvalues>',
f' <viz:color r="{r}" g="{g}" b="{b}"/>',
f' <viz:position x="{pos["x"]}" y="{pos["y"]}" z="0.0"/>',
f' <viz:size value="{n["size"]}"/>',
' </node>',
])
lines.extend([' </nodes>', ' <edges>'])
for e in graph_data["edges"]:
eid = html.escape(e["id"], quote=True)
src = html.escape(e["source"], quote=True)
tgt = html.escape(e["target"], quote=True)
rel = html.escape(e["relation"], quote=True)
lines.append(f' <edge id="{eid}" source="{src}" target="{tgt}" label="{rel}" weight="{e["weight"]}"/>')
lines.extend([' </edges>', ' </graph>', '</gexf>'])
out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def export_obsidian_canvas(graph_data: dict[str, Any], out_path: Path) -> None:
canvas_nodes = []
keep_ids = set()
for n in graph_data["nodes"]:
if n["node_type"] in {"OntologicalDivision", "TaxonAssemblageBuild", "AQCoordinateHub"} or n["degree"] >= 4:
keep_ids.add(n["id"])
pos = n["layouts"]["mode2_radar"]
canvas_nodes.append(
{
"id": n["id"],
"type": "text",
"text": f"**{n['label']}**\n({n['node_type']} | deg={n['degree']})",
"x": int(pos["x"] * 2.2),
"y": int(pos["y"] * 2.2),
"width": 220,
"height": 76,
"color": n["color"],
}
)
canvas_edges = []
for e in graph_data["edges"]:
if e["source"] in keep_ids and e["target"] in keep_ids and e["source"] != e["target"]:
canvas_edges.append(
{
"id": e["id"],
"fromNode": e["source"],
"toNode": e["target"],
"label": e["label"] or e["relation"],
}
)
out_path.write_text(json.dumps({"nodes": canvas_nodes, "edges": canvas_edges}, indent=2) + "\n", encoding="utf-8")
def render_atlas_pngs(graph_data: dict[str, Any], out_dir: Path) -> list[str]:
from PIL import Image, ImageDraw, ImageFont
font_b_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
font_r_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
font_m_path = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"
f_title = ImageFont.truetype(font_b_path, 22)
f_sub = ImageFont.truetype(font_r_path, 13)
f_lbl_b = ImageFont.truetype(font_b_path, 11)
f_lbl_s = ImageFont.truetype(font_m_path, 9)
modes = [
(
"mode2_radar",
"atlas-mode2-concentric-eti-radar.png",
"ENCYCLOPEDIA KNOWLEDGE GRAPH — MODE 2: CONCENTRIC ETI TIER-RING RADAR (S+ CENTER TO D PERIPHERY)",
"Ring 1 Bullseye: Tier S+ (88–100 ETI) -> Ring 2: Tier S -> Ring 3: Tier A -> Ring 4: Tier B -> Ring 5: Tier C -> Ring 6 Outer Edge: Tier D Periphery (44–51 ETI)",
),
(
"mode1_trophic",
"atlas-mode1-trophic-food-web.png",
"ENCYCLOPEDIA KNOWLEDGE GRAPH — MODE 1: TROPHIC FOOD-WEB & 13 FLEX-PIVOT TOPOLOGY",
"368 Nodes & 1,450+ Typed Edges Across S1–S6 Machinic/Capture Guilds, M1–M7+ Memetic Regimes, G1 Variance-Collapse Hubs & 333/666/777 Attractors",
),
(
"mode3_bipartite",
"atlas-mode3-bipartite-g1-funnel.png",
"ENCYCLOPEDIA KNOWLEDGE GRAPH — MODE 3: BIPARTITE GEN 0 -> GEN 1 VARIANCE-COLLAPSE FUNNEL",
"Left Column: Dispersed Gen 0 Written English Terms -> Directed Phonemic Drift (Δ) Edges -> Right Column: Zero-Variance Gen 1 Ingglish Hubs & ETI Builds",
),
]
node_map = {n["id"]: n for n in graph_data["nodes"]}
written = []
for mode_key, fname, title_str, sub_str in modes:
w, h = 1600, 1060
im = Image.new("RGBA", (w, h), (18, 19, 24, 255))
draw = ImageDraw.Draw(im)
# Header banner
draw.rectangle([0, 0, w, 68], fill=(26, 29, 38, 255))
draw.line([(0, 68), (w, 68)], fill=(255, 77, 77, 255), width=2)
draw.text((24, 12), title_str, font=f_title, fill=(245, 247, 252, 255))
draw.text((24, 42), sub_str, font=f_sub, fill=(175, 185, 205, 255))
y_off = 45.0
cx, cy = 800.0, 500.0 + y_off
if mode_key == "mode2_radar":
radar_rings = [
(95, "#FF4D4D", "RING 1: TIER S+ CENTER (88-100 ETI — APEX PREDATOR)"),
(185, "#FF7F7F", "RING 2: TIER S (80-87 ETI — KEYSTONE GUILD)"),
(265, "#FFBF7F", "RING 3: TIER A (72-79 ETI — SYMBIONT LOCK)"),
(345, "#FFFF7F", "RING 4: TIER B (60-71 ETI — NOMAD SPECIALIST)"),
(415, "#7FFF7F", "RING 5: TIER C (52-59 ETI — NUCLEATION STUB / M7+)"),
(475, "#7FBFFF", "RING 6: TIER D PERIPHERY (44-51 ETI — EPISODIC Q-STUB)"),
]
for rad, rcol, rlabel in reversed(radar_rings):
rr, rg, rb = hex_to_rgb(rcol)
draw.ellipse([cx - rad, cy - rad, cx + rad, cy + rad], outline=(rr, rg, rb, 115), width=2)
draw.text((cx - 165, cy - rad + 4), rlabel, font=f_lbl_s, fill=(rr, rg, rb, 215))
elif mode_key == "mode3_bipartite":
cols_hdr = [
(180, "GEN 0 WRITTEN SPECIMENS (190)"),
(480, "CONCEPTUAL OPERATORS (92)"),
(780, "ONTOLOGICAL VOLUMES (22)"),
(1060, "GEN 1 AQ COORDINATE HUBS (VAR->0)"),
(1320, "ETI BUILDS & 333/666/777"),
]
for hx, hstr in cols_hdr:
draw.line([(hx, 76), (hx, h - 36)], fill=(45, 52, 68, 180), width=1)
draw.text((hx - 60, 76), hstr, font=f_lbl_s, fill=(255, 210, 100, 230))
# Draw edges
edge_layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
edraw = ImageDraw.Draw(edge_layer)
for e in graph_data["edges"]:
if e["source"] == e["target"]:
continue
n1 = node_map[e["source"]]
n2 = node_map[e["target"]]
p1 = n1["layouts"][mode_key]
p2 = n2["layouts"][mode_key]
er, eg, eb = hex_to_rgb(e["color"])
alpha = 135 if e["relation"] in {"TROPHIC_GUILD_BRIDGE", "G5_TWIN_PRIME_MUTATION"} else 42
width = 2 if e["relation"] in {"TROPHIC_GUILD_BRIDGE", "G5_TWIN_PRIME_MUTATION"} else 1
edraw.line([(p1["x"], p1["y"] + y_off), (p2["x"], p2["y"] + y_off)], fill=(er, eg, eb, alpha), width=width)
im = Image.alpha_composite(im, edge_layer)
draw = ImageDraw.Draw(im)
# Draw nodes (draw smaller nodes first, major hubs/builds on top)
order_prio = {
"ConceptualOperatorOrIdiom": 1,
"OntologicalDivision": 2,
"EncyclopediaVolume": 3,
"BilingualLexicalSpecimen": 4,
"AQCoordinateHub": 5,
"TaxonAssemblageBuild": 6,
}
sorted_nodes = sorted(graph_data["nodes"], key=lambda x: order_prio.get(x["node_type"], 0))
for n in sorted_nodes:
pos = n["layouts"][mode_key]
nx, ny = pos["x"], pos["y"] + y_off
nr, ng, nb = hex_to_rgb(n["color"])
rad = max(4, int(n["size"] * 0.34))
outline_col = (245, 198, 48, 255) if n.get("isometric") else (18, 20, 26, 255)
outline_w = 2 if n.get("isometric") or n["node_type"] in {"TaxonAssemblageBuild", "AQCoordinateHub"} else 1
draw.ellipse([nx - rad, ny - rad, nx + rad, ny + rad], fill=(nr, ng, nb, 235), outline=outline_col, width=outline_w)
if n["node_type"] == "TaxonAssemblageBuild":
lbl = n["label"].split(" (")[0]
bb = draw.textbbox((0, 0), lbl, font=f_lbl_b)
tw = bb[2] - bb[0]
bw = max(84, int(tw // 2) + 10)
draw.rounded_rectangle([nx - bw, ny + rad + 3, nx + bw, ny + rad + 20], radius=4, fill=(16, 18, 24, 238), outline=(nr, ng, nb, 215), width=1)
draw.text((nx - tw / 2.0, ny + rad + 5), lbl, font=f_lbl_b, fill=(255, 255, 255, 255))
elif n["node_type"] == "AQCoordinateHub" and (n.get("is_flex_pivot") or n.get("is_repdigit_attractor")):
lbl = f"{n['aq_value']}"
bb = draw.textbbox((0, 0), lbl, font=f_lbl_s)
tw, th = bb[2] - bb[0], bb[3] - bb[1]
draw.text((nx - tw / 2.0, ny - th / 2.0 - 1), lbl, font=f_lbl_s, fill=(12, 14, 18, 255))
# Footer legend bar
draw.rectangle([0, h - 32, w, h], fill=(24, 27, 36, 255))
draw.text(
(24, h - 22),
f"Nodes: {graph_data['counts']['total_nodes']} | Edges: {graph_data['counts']['total_edges']} | "
"Gold Rim = G4 Isometric (Δ=0) | Cyan Star = 13 Multi-Build Flex Singularities | Glossary Leak = 0",
font=f_lbl_s,
fill=(200, 210, 228, 255),
)
out_p = out_dir / fname
im.convert("RGB").save(out_p, format="PNG")
written.append(str(out_p))
return written
def main() -> int:
KG_DIR.mkdir(parents=True, exist_ok=True)
graph_data = build_graph()
json_path = KG_DIR / "encyclopedia-graph.json"
js_path = KG_DIR / "graph-data.js"
graphml_path = KG_DIR / "encyclopedia-graph.graphml"
gexf_path = KG_DIR / "encyclopedia-graph.gexf"
canvas_path = KG_DIR / "encyclopedia.canvas"
json_str = json.dumps(graph_data, indent=2, ensure_ascii=False)
json_path.write_text(json_str + "\n", encoding="utf-8")
js_path.write_text(f"window.ENCYCLOPEDIA_GRAPH_DATA = {json_str};\n", encoding="utf-8")
export_graphml(graph_data, graphml_path)
export_gexf(graph_data, gexf_path)
export_obsidian_canvas(graph_data, canvas_path)
png_paths = render_atlas_pngs(graph_data, KG_DIR)
print(
json.dumps(
{
"counts": graph_data["counts"],
"isolation_verified": graph_data["isolation_verified"],
"top_5_hubs": graph_data["top_coordinate_hubs_by_degree"][:5],
"exported_files": [
str(json_path),
str(js_path),
str(graphml_path),
str(gexf_path),
str(canvas_path),
*png_paths,
],
},
indent=2,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())