1189 lines
49 KiB
Python
Executable File
1189 lines
49 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""
|
||
build_encyclopedia_knowledge_graph.py
|
||
Standalone Open-Source Interactive Knowledge Graph Compiler & Atlas Visualizer
|
||
in `/workspace/encyclopedia-knowledge-graph`.
|
||
|
||
Reads upstream domain data strictly in READ-ONLY mode from the sibling repository
|
||
`/workspace/technocapital-singularity-zoology`:
|
||
- `taxonomy/glossary-registry.json`
|
||
- `encyclopedia/encyclopedia-manifest.json`
|
||
- `taxonomy/singularity-zoology-matrix.json`
|
||
- `taxonomy/memetic-superclass-registry.json`
|
||
- `taxonomy/quantitative-economic-anchors.json`
|
||
- `taxonomy/assemblage-builds-tier-list.json`
|
||
- `dossiers/65..69-dossier-*.md`
|
||
|
||
Enforces pre/post SHA-256 verification on `glossary-registry.json` and `encyclopedia-manifest.json`
|
||
so zero knowledge-graph concepts ever leak into the upstream glossary or encyclopedia.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import html
|
||
import json
|
||
import math
|
||
import re
|
||
import shutil
|
||
import sys
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
KG_REPO_ROOT = Path(__file__).resolve().parent.parent
|
||
WORKSPACE_ROOT = KG_REPO_ROOT.parent
|
||
_CORE_SRC = WORKSPACE_ROOT / "hyperstitionstudio-core" / "src"
|
||
if _CORE_SRC.is_dir() and str(_CORE_SRC) not in sys.path:
|
||
sys.path.insert(0, str(_CORE_SRC))
|
||
|
||
try:
|
||
from hyperstitionstud_io.ciphers import compute_aq as _hs_compute_aq
|
||
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
|
||
from hyperstitionstud_io.graph import URN_GRAPH_NS, URN_SCHEMA_GRAPH, make_entity_urn
|
||
from hyperstitionstud_io.publishing.fonts import load_pillow_font
|
||
except ImportError:
|
||
_hs_compute_aq = None
|
||
ReadOnlyIsolationGuard = None
|
||
load_pillow_font = None
|
||
URN_GRAPH_NS = "urn:io:hyperstitionstud:ns:kg:1.0"
|
||
URN_SCHEMA_GRAPH = "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph"
|
||
def make_entity_urn(domain: str, entity_type: str, entity_id: str | int) -> str:
|
||
return f"urn:io:hyperstitionstud:{domain}:{entity_type}:{entity_id}"
|
||
|
||
UPSTREAM_REPO_DEFAULT = WORKSPACE_ROOT / "technocapital-singularity-zoology"
|
||
PUBLIC_WEB_ORIGIN = "https://hyperstitionstud.io"
|
||
|
||
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(dossiers_dir: Path) -> 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(upstream_repo: Path = UPSTREAM_REPO_DEFAULT) -> dict[str, Any]:
|
||
gl_reg_path = upstream_repo / "taxonomy" / "glossary-registry.json"
|
||
enc_man_path = upstream_repo / "encyclopedia" / "encyclopedia-manifest.json"
|
||
tier_path = upstream_repo / "taxonomy" / "assemblage-builds-tier-list.json"
|
||
memetic_path = upstream_repo / "taxonomy" / "memetic-superclass-registry.json"
|
||
dossiers_dir = upstream_repo / "dossiers"
|
||
|
||
pre_gl_sha = hashlib.sha256(gl_reg_path.read_bytes()).hexdigest()
|
||
pre_enc_sha = hashlib.sha256(enc_man_path.read_bytes()).hexdigest()
|
||
|
||
gl_data = json.loads(gl_reg_path.read_text(encoding="utf-8"))
|
||
enc_manifest = json.loads(enc_man_path.read_text(encoding="utf-8"))
|
||
tier_data = json.loads(tier_path.read_text(encoding="utf-8"))
|
||
memetic_data = json.loads(memetic_path.read_text(encoding="utf-8"))
|
||
all_eqs = harvest_equations(dossiers_dir)
|
||
|
||
nodes: list[dict[str, Any]] = []
|
||
edges: list[dict[str, Any]] = []
|
||
node_by_id: dict[str, dict[str, Any]] = {}
|
||
seen_edges: set[tuple[str, str, str]] = set()
|
||
|
||
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
|
||
key = (src, tgt, rel) if directed else (min(src, tgt), max(src, tgt), rel)
|
||
if key in seen_edges:
|
||
return
|
||
seen_edges.add(key)
|
||
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"{PUBLIC_WEB_ORIGIN}/encyclopedia/{pdf_rel}",
|
||
"vol_index": v_idx,
|
||
},
|
||
)
|
||
add_edge(nid, f"div:{div_id}", "IN_DIVISION", label="in division", weight=2.0, color="#4B5563")
|
||
|
||
rel_md = upstream_repo / "encyclopedia" / div_id / f"{slug}.md"
|
||
md_p = rel_md if rel_md.is_file() else 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 (10)
|
||
build_by_eval: dict[str, str] = {}
|
||
for b_idx, row in enumerate(tier_data.get("rows", [])):
|
||
ev = row["eval_num"]
|
||
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,
|
||
},
|
||
)
|
||
|
||
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) & AQCoordinateHubs (65)
|
||
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)
|
||
|
||
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],
|
||
},
|
||
)
|
||
|
||
spec_nid_by_eng: dict[str, str] = {}
|
||
for v in 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"{PUBLIC_WEB_ORIGIN}/encyclopedia/{pdf_rel}",
|
||
},
|
||
)
|
||
|
||
if vol_nid:
|
||
add_edge(nid, vol_nid, "IN_VOLUME", label="in volume", weight=1.0, color="#374151")
|
||
|
||
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)
|
||
|
||
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",
|
||
)
|
||
|
||
if v["isometric"]:
|
||
add_edge(nid, nid, "G4_ISOMETRIC_INVARIANT", label="Δ=0 ISO", weight=3.0, color="#F5C630")
|
||
|
||
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)
|
||
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"{PUBLIC_WEB_ORIGIN}/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
|
||
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 edges
|
||
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
|
||
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
|
||
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")
|
||
|
||
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"]])
|
||
|
||
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,
|
||
}
|
||
|
||
tier_radii = {
|
||
"S+": 95.0,
|
||
"S": 185.0,
|
||
"A": 265.0,
|
||
"B": 345.0,
|
||
"C": 415.0,
|
||
"D": 475.0,
|
||
}
|
||
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"]
|
||
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))
|
||
|
||
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))
|
||
|
||
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
|
||
|
||
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)},
|
||
}
|
||
|
||
post_gl_sha = hashlib.sha256(gl_reg_path.read_bytes()).hexdigest()
|
||
post_enc_sha = hashlib.sha256(enc_man_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 {
|
||
"$schema": "./schemas/v1/encyclopedia-graph.schema.json",
|
||
"$id": URN_SCHEMA_GRAPH,
|
||
"namespace_urn": URN_GRAPH_NS,
|
||
"version": "2.14.0",
|
||
"encyclopedia_base_path": "../technocapital-singularity-zoology/encyclopedia",
|
||
"upstream_repository": str(upstream_repo),
|
||
"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"?>',
|
||
f'<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:hs="{URN_GRAPH_NS}">',
|
||
' <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"?>',
|
||
f'<gexf xmlns="http://www.gexf.net/1.3" xmlns:viz="http://www.gexf.net/1.3/viz" xmlns:hs="{URN_GRAPH_NS}" 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
|
||
|
||
if load_pillow_font is not None:
|
||
f_title = load_pillow_font("DejaVuSans-Bold.ttf", 22)
|
||
f_sub = load_pillow_font("DejaVuSans.ttf", 13)
|
||
f_lbl_b = load_pillow_font("DejaVuSans-Bold.ttf", 11)
|
||
f_lbl_s = load_pillow_font("DejaVuSansMono-Bold.ttf", 9)
|
||
else:
|
||
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",
|
||
"388 Nodes & 1,282 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)
|
||
|
||
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))
|
||
|
||
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)
|
||
|
||
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))
|
||
|
||
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 verify_published_artifacts(kg_dir: Path, upstream_repo: Path, pre_gl_sha: str, pre_enc_sha: str) -> dict[str, Any]:
|
||
import xml.etree.ElementTree as ET
|
||
from PIL import Image
|
||
|
||
gl_reg_path = upstream_repo / "taxonomy" / "glossary-registry.json"
|
||
enc_man_path = upstream_repo / "encyclopedia" / "encyclopedia-manifest.json"
|
||
post_gl_sha = hashlib.sha256(gl_reg_path.read_bytes()).hexdigest()
|
||
post_enc_sha = hashlib.sha256(enc_man_path.read_bytes()).hexdigest()
|
||
|
||
json_p = kg_dir / "encyclopedia-graph.json"
|
||
js_p = kg_dir / "graph-data.js"
|
||
gml_p = kg_dir / "encyclopedia-graph.graphml"
|
||
gexf_p = kg_dir / "encyclopedia-graph.gexf"
|
||
canv_p = kg_dir / "encyclopedia.canvas"
|
||
html_p = (kg_dir / "index.html") if (kg_dir / "index.html").exists() else (KG_REPO_ROOT / "index.html")
|
||
|
||
j_obj = json.loads(json_p.read_text(encoding="utf-8"))
|
||
c_obj = json.loads(canv_p.read_text(encoding="utf-8"))
|
||
gml_root = ET.parse(gml_p).getroot()
|
||
gexf_root = ET.parse(gexf_p).getroot()
|
||
|
||
png_checks = {}
|
||
for m_name in ("atlas-mode1-trophic-food-web.png", "atlas-mode2-concentric-eti-radar.png", "atlas-mode3-bipartite-g1-funnel.png"):
|
||
p = kg_dir / m_name
|
||
with Image.open(p) as im:
|
||
png_checks[m_name] = {"size": list(im.size), "mode": im.mode, "bytes": p.stat().st_size}
|
||
|
||
return {
|
||
"all_gates_passed": (
|
||
pre_gl_sha == post_gl_sha
|
||
and pre_enc_sha == post_enc_sha
|
||
and len(j_obj["nodes"]) >= 388
|
||
and len(j_obj["edges"]) >= 1282
|
||
and gml_root.tag.endswith("graphml")
|
||
and gexf_root.tag.endswith("gexf")
|
||
and len(c_obj["nodes"]) > 0
|
||
and js_p.stat().st_size > 100000
|
||
and html_p.exists()
|
||
),
|
||
"gate1_glossary_sha256_unchanged": pre_gl_sha == post_gl_sha,
|
||
"gate2_encyclopedia_sha256_unchanged": pre_enc_sha == post_enc_sha,
|
||
"gate3_json_schema_counts": {"nodes": len(j_obj["nodes"]), "edges": len(j_obj["edges"])},
|
||
"gate4_xml_well_formed": {"graphml_root": gml_root.tag, "gexf_root": gexf_root.tag},
|
||
"gate5_obsidian_canvas_counts": {"canvas_nodes": len(c_obj["nodes"]), "canvas_edges": len(c_obj["edges"])},
|
||
"gate6_atlas_pngs": png_checks,
|
||
}
|
||
|
||
|
||
def query_node_ego(graph_data: dict[str, Any], query: str) -> dict[str, Any]:
|
||
q = query.strip().lower()
|
||
matches = []
|
||
for n in graph_data["nodes"]:
|
||
if (
|
||
n["id"].lower() == q
|
||
or q in n["label"].lower()
|
||
or q == str(n.get("ing_aq", ""))
|
||
or q == str(n.get("aq_value", ""))
|
||
or q == (n.get("eng", "") or "").lower()
|
||
or q == (n.get("ing", "") or "").lower()
|
||
):
|
||
matches.append(n)
|
||
if not matches:
|
||
return {"query": query, "match_count": 0, "matched_node_ids": [], "matches": []}
|
||
primary = matches[0]
|
||
nid = primary["id"]
|
||
incident = [
|
||
{"relation": e["relation"], "source": e["source"], "target": e["target"], "label": e["label"], "weight": e["weight"]}
|
||
for e in graph_data["edges"]
|
||
if e["source"] == nid or e["target"] == nid
|
||
]
|
||
return {
|
||
"query": query,
|
||
"match_count": len(matches),
|
||
"matched_node_ids": [m["id"] for m in matches],
|
||
"primary_node": {k: v for k, v in primary.items() if k != "layouts"},
|
||
"layouts": primary.get("layouts"),
|
||
"incident_edge_count": len(incident),
|
||
"sample_incident_edges": incident[:15],
|
||
}
|
||
|
||
|
||
def main() -> int:
|
||
import argparse
|
||
|
||
ap = argparse.ArgumentParser(description="Build, verify, and query the Encyclopedia of Technocapital Singularity Zoology Knowledge Graph.")
|
||
ap.add_argument("--upstream-repo", default=str(UPSTREAM_REPO_DEFAULT), help="Path to upstream technocapital-singularity-zoology repository (read-only).")
|
||
ap.add_argument("--out-dir", default=str(KG_REPO_ROOT), help="Target output directory for generated graph artifacts (default: /workspace/encyclopedia-knowledge-graph).")
|
||
ap.add_argument("--bundle-encyclopedia", action="store_true", help="Copy/bundle ./encyclopedia/ into --out-dir and set encyclopedia_base_path='./encyclopedia' for single-folder static HTTP hosting.")
|
||
ap.add_argument("--verify-only", action="store_true", help="Run 6-gate verification on existing knowledge-graph artifacts without rebuilding.")
|
||
ap.add_argument("--check-isolation", action="store_true", help="Print upstream glossary and encyclopedia SHA-256 digests and verify zero modifications.")
|
||
ap.add_argument("--query-node", default=None, help="Query a node by ID, headword, Ingglish token, or integer AQ coordinate and inspect its ego-network.")
|
||
args = ap.parse_args()
|
||
|
||
upstream_repo = Path(args.upstream_repo)
|
||
gl_reg_path = upstream_repo / "taxonomy" / "glossary-registry.json"
|
||
enc_man_path = upstream_repo / "encyclopedia" / "encyclopedia-manifest.json"
|
||
pre_gl_sha = hashlib.sha256(gl_reg_path.read_bytes()).hexdigest()
|
||
pre_enc_sha = hashlib.sha256(enc_man_path.read_bytes()).hexdigest()
|
||
|
||
if args.check_isolation:
|
||
print(
|
||
json.dumps(
|
||
{
|
||
"glossary_registry_path": str(gl_reg_path),
|
||
"glossary_registry_sha256": pre_gl_sha,
|
||
"encyclopedia_manifest_path": str(enc_man_path),
|
||
"encyclopedia_manifest_sha256": pre_enc_sha,
|
||
},
|
||
indent=2,
|
||
)
|
||
)
|
||
return 0
|
||
|
||
out_dir = Path(args.out_dir)
|
||
if args.verify_only:
|
||
ver = verify_published_artifacts(out_dir, upstream_repo, pre_gl_sha, pre_enc_sha)
|
||
print(json.dumps(ver, indent=2))
|
||
return 0 if ver["all_gates_passed"] else 1
|
||
|
||
graph_data = build_graph(upstream_repo=upstream_repo)
|
||
if args.query_node:
|
||
res = query_node_ego(graph_data, args.query_node)
|
||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||
return 0
|
||
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
if args.bundle_encyclopedia:
|
||
src_enc = upstream_repo / "encyclopedia"
|
||
dst_enc = out_dir / "encyclopedia"
|
||
if src_enc.is_dir():
|
||
shutil.copytree(src_enc, dst_enc, dirs_exist_ok=True)
|
||
graph_data["encyclopedia_base_path"] = "./encyclopedia"
|
||
|
||
json_path = out_dir / "encyclopedia-graph.json"
|
||
js_path = out_dir / "graph-data.js"
|
||
graphml_path = out_dir / "encyclopedia-graph.graphml"
|
||
gexf_path = out_dir / "encyclopedia-graph.gexf"
|
||
canvas_path = out_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(
|
||
"window.HyperstitionStudio = window.HyperstitionStudio || {};\n"
|
||
f"window.HyperstitionStudio.EncyclopediaGraphData = {json_str};\n"
|
||
"window.ENCYCLOPEDIA_GRAPH_DATA = window.HyperstitionStudio.EncyclopediaGraphData;\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, out_dir)
|
||
ver = verify_published_artifacts(out_dir, upstream_repo, pre_gl_sha, pre_enc_sha)
|
||
|
||
print(
|
||
json.dumps(
|
||
{
|
||
"counts": graph_data["counts"],
|
||
"isolation_verified": graph_data["isolation_verified"],
|
||
"six_gate_verification": ver,
|
||
"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())
|