In this section
- Test Positron test · cosmic / tools/explore/periodic/furnace/positron/test_positron.py lines 1–199
- Periodic — Furnace render · cosmic / tools/explore/periodic/furnace/run.py lines 1–501
Test Positron
A test in the furnace folder of Cosmic that checks Positron Core. It sets up (`setUp`) and sets up class (`setUpClass`).
testcosmic / tools/explore/periodic/furnace/positron/test_positron.py · lines 1–199 of 199 · Entry point · pattern RealGraph (shared by 2 files)
- What it does
- It tests its inputs. Defines 28 functions or classes, including f, tiny, Fixtures, setUp, v. Uses libraries __future__, importlib.util, json, math, os. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file elements118.json.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for the POSITRON (ANTIPODE-26).
- Why it matters
- Guards the behaviour of Positron Core.
- Application
- cosmic · tools/explore/periodic/furnace/positron · test
- Uses
- Positron Core (import), __future__, importlib.util, json, math, os, re, sys, unittest
- Used by
- none found
- Produces
- f, tiny, Fixtures, Independence, RealGraph
- Defines here
- f, tiny, Fixtures, setUp, v, test_unique_pairs_and_self_loops, test_fan, test_forward_reach_excludes_seeds, test_impact_rank_and_ties, test_components, test_cycles, test_folder_measures, test_role_measures, test_gini_matches_ranked_formula, test_median, test_param_count, test_vocabulary_counts_files_once, test_layout_fallback, Independence, test_no_electron_import, test_all_118_modules, RealGraph, setUpClass, load, test_interface_and_determinism, test_matches_grid_published_table, test_sensitive_boundaries_pinned, test_injected_mismatch_is_detected
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/periodic/furnace/positron/test_positron.py:1-199 · blob 60b684cea403e9ecbbc17770debd8aea70e62c78 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Tests for the POSITRON (ANTIPODE-26). Run: python -m pytest positron/test_positron.py (or python test_positron.py)."""
from __future__ import annotations
import importlib.util
import json
import math
import os
import re
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
FURNACE = os.path.dirname(HERE)
sys.path.insert(0, HERE)
import positron_core as pc # noqa: E402
GRAPH = pc.DEFAULT_GRAPH
def f(i, repo="r", path=(), role="render", lang="JavaScript", lines=10, defines=(), pure=False,
reachable=True, dup=None, status="production_core", stage="unknown", sigs=(), words=()):
return {"id": i, "repo": repo, "folder_hierarchy": [repo, *path], "role": role, "lang": lang,
"lines": lines, "defines": list(defines), "pure": pure, "reachable": reachable,
"duplicate_of": dup, "canonical_status": status, "domain_stage": stage,
"signatures": list(sigs), "name_words": list(words)}
def tiny():
"""6 files. run edges: 0->1, 1->0 (2-cycle), 1->2, 2->3; page loads: 4->5, 4->5 (dup), 5->5 (self)."""
files = [
f(0, path=("a",), role="geodesy", lines=10, defines=("x",), pure=True, sigs=("f(a, b)",), words=("alpha", "beta")),
f(1, path=("a", "b"), role="geodesy", lines=20, lang="Python", sigs=("g(x, (y, z), w)",), words=("alpha",)),
f(2, path=("c",), role="electrical", lines=30, reachable=False, dup=0, words=("beta", "v2")),
f(3, repo="s", role="electrical", lines=40, status="unknown", words=("alpha", "alpha")),
f(4, role="render", lines=50, sigs=("h(a > 0 ? x : y, z)",)),
f(5, role="render", lines=60, sigs=("noparens",)),
]
edges = [[0, 1, "workflow-run", ""], [1, 0, "script-call", ""], [1, 2, "workflow-run", ""],
[2, 3, "workflow-run", ""], [4, 5, "script-src", ""], [4, 5, "stylesheet", ""],
[5, 5, "script-src", ""]]
return {"files": files, "edges": edges,
"roles": [{"id": r} for r in ("geodesy", "electrical", "energy-data", "ingest", "transform", "render", "interaction")],
"domain_stages": [{"id": "unknown"}],
"canonical_statuses": ["production_core", "supporting_data", "duplicate_candidate", "unreached_review", "unknown"]}
class Fixtures(unittest.TestCase):
def setUp(self):
self.g = tiny()
pc._CACHE.clear()
def v(self, block):
return pc.View(self.g, block)
def test_unique_pairs_and_self_loops(self):
self.assertEqual(self.v("s").pairs, [(4, 5)])
self.assertEqual(self.v("d").pairs, [(0, 1), (1, 0), (1, 2), (2, 3)])
def test_fan(self):
v = self.v("d")
self.assertEqual(pc.fam_fanout(self.g, v, 1), 3)
self.assertEqual(pc.fam_fanout(self.g, v, 2), 1)
self.assertEqual(pc.fam_fanin(self.g, v, 1), 4)
def test_forward_reach_excludes_seeds(self):
v = self.v("d")
# z=1: seed = file 1 (out 2); 1 hop -> {0, 2}; 2 hops adds 3
self.assertEqual(pc.fam_forward_reach(self.g, v, 1, z=1), 2)
self.assertEqual(pc.fam_forward_reach(self.g, v, 2, z=1), 3)
def test_impact_rank_and_ties(self):
v = self.v("d")
# in-degree: 0:1, 1:1, 2:1, 3:1 -> rank 1 = file 0 (tie by id); reverse reach of 0 within 4 hops = {1}
self.assertEqual(pc.fam_impact(self.g, v, 4), 1)
def test_components(self):
v = self.v("d")
self.assertEqual(pc.fam_weak_components(self.g, v, 3), 1) # {0,1,2,3}
self.assertEqual(pc.fam_weak_components(self.g, v, 0), 3) # + singletons 4, 5
def test_cycles(self):
v = self.v("d")
self.assertEqual(pc.fam_short_cycles(self.g, v, 4), 2)
def test_folder_measures(self):
v = self.v("d")
# lv=1 (repo): only 2->3 crosses (r vs s)
self.assertAlmostEqual(pc.fam_folder_crossing(self.g, v, 3), 0.25)
# distances: 0-1: [r,a] vs [r,a,b] = 1; 1-0 = 1; 1-2: [r,a,b] vs [r,c] = 3; 2-3: [r,c] vs [s] = 3
self.assertAlmostEqual(pc.fam_folder_distance(self.g, v, 1), 0.5)
self.assertAlmostEqual(pc.fam_folder_distance(self.g, v, 3), 1.0)
def test_role_measures(self):
v = self.v("d")
self.assertAlmostEqual(pc.fam_role_cohesion(self.g, v, 1), 2 / 3) # from geodesy: 0->1,1->0,1->2
self.assertAlmostEqual(pc.fam_dup_by_role(self.g, v, 2), 0.5)
self.assertAlmostEqual(pc.fam_isolation(self.g, v, 6), 1.0) # render files have no run edges
def test_gini_matches_ranked_formula(self):
for xs in ([1, 2, 3, 4], [5], [3, 3, 3], [1, 100, 7, 7, 2]):
s = sorted(xs)
m = len(s)
ranked = 2 * sum((i + 1) * x for i, x in enumerate(s)) / (m * sum(s)) - (m + 1) / m
self.assertTrue(math.isclose(pc.gini_pairwise(xs), ranked, abs_tol=1e-12))
self.assertEqual(pc.gini_pairwise([]), 0.0)
def test_median(self):
self.assertEqual(pc.median_fraction([3, 1, 2]), 2.0)
self.assertEqual(pc.median_fraction([4, 1, 2, 3]), 2.5)
def test_param_count(self):
self.assertEqual(pc.param_count("f()"), 0)
self.assertEqual(pc.param_count("f(a, b)"), 2)
self.assertEqual(pc.param_count("g(x, (y, z), w)"), 3)
self.assertEqual(pc.param_count("noparens"), 0)
# A7: literal reading, '>' drives depth negative and hides the next comma
self.assertEqual(pc.param_count("h(a > 0 ? x : y, z)"), 1)
def test_vocabulary_counts_files_once(self):
words, counts = pc.word_rank(self.g)
self.assertEqual(words[0], "alpha")
self.assertEqual(counts["alpha"], 3)
self.assertNotIn("v2", counts)
def test_layout_fallback(self):
self.assertEqual(pc._layout_from_z(1), {"period": 1, "group": 1, "block": "s"})
self.assertEqual(pc._layout_from_z(2)["group"], 18)
self.assertEqual(pc._layout_from_z(57)["group"], None)
self.assertEqual(pc._layout_from_z(71), {"period": 6, "group": 3, "block": "d"})
self.assertEqual(pc._layout_from_z(103), {"period": 7, "group": 3, "block": "d"})
self.assertEqual(pc._layout_from_z(118), {"period": 7, "group": 18, "block": "p"})
self.assertEqual(pc._layout_from_z(13), {"period": 3, "group": 13, "block": "p"})
class Independence(unittest.TestCase):
def test_no_electron_import(self):
for name in os.listdir(HERE):
if name.endswith(".py") and name != "test_positron.py":
src = open(os.path.join(HERE, name), encoding="utf-8").read()
self.assertNotRegex(src, r"^\s*(from|import)\s+(common|electron|e\d+)\b", name)
self.assertNotIn("numpy", src.replace("no numpy", ""), name)
def test_all_118_modules(self):
for z in range(1, 119):
self.assertTrue(os.path.exists(os.path.join(HERE, "p%d.py" % z)), z)
@unittest.skipUnless(os.path.exists(GRAPH), "build_graph.json not present")
class RealGraph(unittest.TestCase):
@classmethod
def setUpClass(cls):
raw = json.load(open(os.path.join(FURNACE, "elements118.json")))
cls.els = {e["Z"]: e for e in (raw["elements"] if isinstance(raw, dict) else raw)}
cls.grid = {}
gpath = os.path.join(FURNACE, "electron", "GRID.md")
if os.path.exists(gpath): # published numbers only; the electron's code is not read
for line in open(gpath, encoding="utf-8"):
m = re.match(r"\| (\d+) \| \w+ \|.*\| ([-\d.]+) \|$", line.strip())
if m:
cls.grid[int(m.group(1))] = float(m.group(2))
def load(self, z):
spec = importlib.util.spec_from_file_location("p%d" % z, os.path.join(HERE, "p%d.py" % z))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def test_interface_and_determinism(self):
for z in (1, 24, 57, 89, 118):
mod = self.load(z)
a = mod.run({"element": self.els[z]}, None)
b = mod.run({"element": self.els[z]}, None)
self.assertEqual(a["value"], b["value"])
self.assertIsInstance(a["value"], (int, float))
self.assertLessEqual(len(a["picture"]), 400)
def test_matches_grid_published_table(self):
if not self.grid:
self.skipTest("GRID.md table not present")
for z in range(1, 119):
v = pc.run_element(z, {"element": self.els[z]})["value"]
e = self.grid[z] # table rounded to 6 decimals
self.assertTrue(abs(v - e) <= 1e-6 + 1e-6 * abs(e), (z, v, e))
def test_sensitive_boundaries_pinned(self):
g = pc.load_graph({})
v = pc._view(g, "d")
order = pc.ranked(range(v.n), v.indeg)
self.assertEqual([v.indeg(i) for i in order[2:6]], [9, 9, 9, 9]) # A4 tie at hub ranks 3..6
def test_injected_mismatch_is_detected(self):
"""An off-by-one in d must change a value: the comparison is not vacuous."""
g = pc.load_graph({})
v = pc._view(g, "s")
self.assertNotEqual(pc.fam_fanout(g, v, 1), pc.fam_fanout(g, v, 2))
if __name__ == "__main__":
unittest.main()Periodic — Furnace
A Python command-line tool in the explore folder of Cosmic that reads elements118, build graph, identity and receipts, using SHA-256.
rendercosmic / tools/explore/periodic/furnace/run.py · lines 1–501 of 742 · Entry point · pattern render_page (shared by 2 files)
- What it does
- It loads elements118, build graph, identity and receipts. Defines 32 functions or classes, including get_xp, to_host, sha256_bytes, sha256_file, digest. Uses libraries __future__, argparse, hashlib, html, importlib.util. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file elements118.json; JSON file build_graph.json; JSON file identity.json; JSON file periodic.json; JSON file receipts.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Extras (cosmic); Test Run (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
- What it achieves
- It gets xp (`get_xp`), builds elements (`build_elements`) and writes elements (`write_elements`). FURNACE: batched runner for the 118 periodic code experiments. It accepts `--xp`, `--batch` and `--out`.
- Why it matters
- Run by Extras. Checked by Test Run.
- Application
- cosmic · tools/explore/periodic/furnace · Python CLI
- Uses
- __future__, argparse, hashlib, html, importlib.util, json, math, os
- Used by
- run by Extras (script call), imported by Test Run (import)
- Produces
- get_xp, to_host, sha256_bytes, sha256_file, digest, roman, position, category, valence, build_elements, write_elements, load_elements
- Defines here
- get_xp, to_host, sha256_bytes, sha256_file, digest, roman, position, category, valence, build_elements, write_elements, load_elements, _index, build_base, ln, element_ctx, _enter_side, _forget_sides, load_module, clean_picture, compare, num_ok, walk, rel_name
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/periodic/furnace/run.py:1-501 · blob 24bb78698c8df9d9d9f9a6a259705d09e9f3f417 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""FURNACE: batched runner for the 118 periodic code experiments.
Each real element Z has an ELECTRON (electron/e<Z>.py, the primary computation)
and a POSITRON (positron/p<Z>.py, an independent second method). Both expose
run(ctx, xp) -> {"value": ..., "picture": [...]}. The furnace loads the Explore
Code graph into arrays ONCE, runs every available pair in batches, compares the
two values within a tolerance and writes receipts:
/tmp/vk/periodic/furnace/receipts.json (machine receipts)
/tmp/vk/periodic/furnace/index.html (gallery, + gallery.css/js, data.js)
furnace/RECEIPTS.md (human summary)
A disagreement is an ANNIHILATION: it is recorded, never hidden.
Backend: --xp numpy (default) or --xp cupy; experiments must only use the xp
module they are given on ctx arrays, so CuPy is a drop-in replacement.
Usage:
python3 run.py # run once
python3 run.py --every 600 --until-minutes 75
python3 run.py --elements # rebuild elements118.json from the cited source
"""
from __future__ import annotations
import argparse
import hashlib
import html
import importlib.util
import json
import math
import os
import re
import shutil
import sys
import time
import traceback
from pathlib import Path
import numpy as np
sys.dont_write_bytecode = True # never drop __pycache__ into electron/ or positron/
HERE = Path(__file__).resolve().parent
ELECTRON_DIR = HERE / "electron"
POSITRON_DIR = HERE / "positron"
PAGE_DIR = HERE / "page"
ELEMENTS_JSON = HERE / "elements118.json"
RECEIPTS_MD = HERE / "RECEIPTS.md"
GRAPH = Path("/tmp/site8/explore-code/build_graph.json")
OUT = Path("/tmp/vk/periodic/furnace")
OPTIONAL_INPUTS = [
Path("/tmp/vk/7/identity.json"),
Path("/tmp/vk/clean/manifest.json"),
Path("/tmp/vk/periodic/periodic.json"),
]
SCHEMA = "periodic-furnace-receipts-v1"
DEFAULT_TOL = {"rtol": 1e-9, "atol": 1e-9}
MAX_PICTURE = 400
MAX_LIST = 64
COLOURS = {"cyan": "#00ffff", "blue": "#66ccff", "grey": "#a6adbb",
"white": "#ffffff", "line": "#2f343d"}
BLOCK_KINDS = {
"s": ["import", "python-relative", "sys-path", "require", "dynamic-import",
"url-import-meta", "worker", "import-map"],
"p": ["script-src", "stylesheet", "modulepreload", "iframe", "script-call", "fetch"],
"d": ["link", "estate-url", "comment-url"],
"f": ["workflow-run"],
}
# --------------------------------------------------------------------------- backend
def get_xp(name: str = "numpy"):
"""Return the array module. 'cupy' needs CuPy installed (CUDA). A module
object is passed through (tests use an array-module stand-in)."""
if not isinstance(name, str) and name is not None:
return name
if name in ("numpy", "np", None):
return np
if name in ("cupy", "cp"):
try:
import cupy # type: ignore
except ImportError as exc: # pragma: no cover - depends on host
raise SystemExit("--xp cupy requested but CuPy is not installed: %s" % exc)
return cupy
raise SystemExit("unknown --xp backend %r (use numpy or cupy)" % name)
def to_host(v):
"""Convert xp arrays / numpy scalars to plain python (json-safe)."""
if hasattr(v, "get") and callable(getattr(v, "get")) and not isinstance(v, dict):
try: # CuPy ndarray / scalar
v = v.get()
except TypeError:
pass
if isinstance(v, np.ndarray):
return to_host(v.tolist())
if isinstance(v, np.generic):
return to_host(v.item())
if isinstance(v, dict):
return {str(k): to_host(x) for k, x in v.items()}
if isinstance(v, (list, tuple)):
return [to_host(x) for x in v]
if isinstance(v, bool) or v is None or isinstance(v, str):
return v
if isinstance(v, int):
return v
if isinstance(v, float):
if math.isnan(v) or math.isinf(v):
return str(v)
return v
return str(v)
def sha256_bytes(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def digest(obj) -> str:
return sha256_bytes(json.dumps(obj, sort_keys=True, separators=(",", ":")).encode())
# --------------------------------------------------------------------------- elements
PGF_DATA = Path("/usr/share/texlive/texmf-dist/tex/latex/pgf-periodictable/pgfPT.data.tex")
PGF_NAMES = Path("/usr/share/texlive/texmf-dist/tex/latex/pgf-periodictable/pgfPT.names.tex")
PGF_STY = Path("/usr/share/texlive/texmf-dist/tex/latex/pgf-periodictable/pgf-PeriodicTable.sty")
_ROMAN = [(100, "c"), (90, "xc"), (50, "l"), (40, "xl"), (10, "x"), (9, "ix"),
(5, "v"), (4, "iv"), (1, "i")]
def roman(n: int) -> str:
out = ""
for v, s in _ROMAN:
while n >= v:
out += s
n -= v
return out
def position(z: int):
"""(group or None, period, block, layout row, layout col) for the IUPAC form
with Lu/Lr in group 3 and La-Yb / Ac-No in the separate f rows."""
starts = [(1, 1), (3, 2), (11, 3), (19, 4), (37, 5), (55, 6), (87, 7), (119, 8)]
period = max(p for s, p in starts if z >= s)
first = dict((p, s) for s, p in starts)[period]
i = z - first # 0-based index in the period
if period == 1:
group = 1 if z == 1 else 18
elif period in (2, 3):
group = i + 1 if i < 2 else i + 11
elif period in (4, 5):
group = i + 1
else: # 6, 7: 32 elements, f run at index 2..15
if i < 2:
group = i + 1
elif i < 16:
group = None
else:
group = i - 13 # index 16 (Lu/Lr) -> group 3
if group is None:
block = "f"
elif z == 2:
block = "s"
elif group <= 2:
block = "s"
elif group <= 12:
block = "d"
else:
block = "p"
if group is None:
row = 9 if period == 6 else 10
col = i + 1 # La/Ac at col 3 .. Yb/No at col 16
else:
row, col = period, group
return group, period, block, row, col
METALLOIDS = {5, 14, 32, 33, 51, 52}
REACTIVE_NONMETALS = {1, 6, 7, 8, 9, 15, 16, 17, 34, 35, 53}
NOBLE = {2, 10, 18, 36, 54, 86}
POST_TRANSITION = {13, 31, 49, 50, 81, 82, 83, 84, 85}
def category(z: int, group, block) -> str:
if z >= 109:
return "unknown chemical properties"
if z in NOBLE:
return "noble gas"
if z in REACTIVE_NONMETALS:
return "reactive nonmetal"
if z in METALLOIDS:
return "metalloid"
if z in POST_TRANSITION:
return "post-transition metal"
if group == 1:
return "alkali metal"
if group == 2:
return "alkaline earth metal"
if 57 <= z <= 71:
return "lanthanide"
if 89 <= z <= 103:
return "actinide"
return "transition metal"
def valence(z: int, group, block) -> int:
"""Valence electron count by the group convention: s/p main group = group (1,2)
or group-10 (13-18), He = 2; d block = group number; f block = 3."""
if z == 2:
return 2
if block == "f":
return 3
if group <= 12:
return group
return group - 10
def build_elements(data_path: Path = PGF_DATA, names_path: Path = PGF_NAMES):
data_txt = data_path.read_text(encoding="latin-1")
names_txt = names_path.read_text(encoding="latin-1")
out = []
for z in range(1, 119):
r = roman(z)
m = re.search(r"\\def\\pgfPT@data@%s\{(.*)\}%%" % r, data_txt)
if not m:
raise ValueError("no pgfPT data for Z=%d" % z)
fields = {}
for item in m.group(1).split(","):
if "/" in item:
val, key = item.rsplit("/", 1)
fields[key.strip()] = val.strip()
nm = re.search(r"\\def\\pgfPT@nomes@%s\{(.*)\}%%" % r, names_txt)
name = None
if nm:
for item in nm.group(1).split(","):
if item.endswith("/en"):
name = item[:-3]
sym = fields["CS"]
ar = fields.get("Ar", "")
mass_number = ar.startswith("[")
weight = float(ar.strip("[] "))
en_raw = fields.get("eneg", "---")
try:
en = float(en_raw)
except ValueError:
en = None
group, period, block, row, col = position(z)
out.append({
"Z": z, "symbol": sym, "name": name, "group": group, "period": period,
"block": block, "weight": weight, "weight_is_mass_number": mass_number,
"en": en, "valence": valence(z, group, block),
"category": category(z, group, block), "row": row, "col": col,
})
return out
def write_elements(path: Path = ELEMENTS_JSON):
els = build_elements()
sty = PGF_STY.read_text(encoding="latin-1")
ver = re.search(r"\\ProvidesPackage\{pgf-PeriodicTable\}\[([^\]]*)\]", sty)
doc = {
"schema": "elements118-v1",
"source": {
"dataset": "pgf-PeriodicTable LaTeX package (CTAN), %s" % (ver.group(1) if ver else "?"),
"files": {
str(PGF_DATA): sha256_file(PGF_DATA),
str(PGF_NAMES): sha256_file(PGF_NAMES),
},
"url": "https://ctan.org/pkg/pgf-periodictable",
"fields_from_source": {
"symbol": "CS", "name": "English name (pgfPT.names.tex /en)",
"weight": "Ar (relative atomic mass; [n] = mass number of the longest-lived isotope, flagged weight_is_mass_number)",
"en": "eneg (Pauling electronegativity; '---' -> null)",
},
"fields_derived": {
"group/period/block/row/col": "from Z by the IUPAC layout with Lu and Lr in group 3 and La-Yb, Ac-No in the f rows (group null)",
"valence": "group convention: groups 1-2 -> group, 13-18 -> group-10, He -> 2, d block -> group number, f block -> 3",
"category": "common periodic-table colour classes: metalloids B Si Ge As Sb Te; reactive nonmetals H C N O F P S Se Cl Br I; noble gases He-Rn; post-transition Al Ga In Sn Tl Pb Bi Po At; Z>=109 'unknown chemical properties'",
},
"built_by": "furnace/run.py --elements",
},
"elements": els,
}
path.write_text(json.dumps(doc, indent=1, ensure_ascii=False) + "\n")
return doc
def load_elements(path: Path = ELEMENTS_JSON):
return json.loads(path.read_text())["elements"]
# --------------------------------------------------------------------------- context
def _index(values):
names = sorted({"" if v is None else str(v) for v in values})
lut = {n: i for i, n in enumerate(names)}
return names, np.array([lut["" if v is None else str(v)] for v in values], dtype=np.int16)
def build_base(graph: dict, xp=np, inputs: dict | None = None) -> dict:
"""Load the graph into arrays once. Returns the shared part of ctx."""
files = graph["files"]
edges = graph["edges"]
n = len(files)
by_id = {f["id"]: i for i, f in enumerate(files)}
kinds = [k["id"] for k in graph.get("edge_kinds", [])]
for e in edges:
if e[2] not in kinds:
kinds.append(e[2])
klut = {k: i for i, k in enumerate(kinds)}
res_names, res_idx = _index([e[3] if len(e) > 3 else "" for e in edges])
src = np.array([by_id[e[0]] for e in edges], dtype=np.int32)
dst = np.array([by_id[e[1]] for e in edges], dtype=np.int32)
ekind = np.array([klut[e[2]] for e in edges], dtype=np.int16)
def ln(f, key):
v = f.get(key)
return len(v) if isinstance(v, (list, dict)) else 0
host = {}
for key, listname in [("role", "roles"), ("stage", "stages"),
("domain_stage", "domain_stages"), ("lang", "langs"),
("repo", "repos"), ("kind", "kinds"),
("canonical_status", "canonical_statuses")]:
names, idx = _index([f.get(key) for f in files])
host[listname] = names
host[key] = idx
for key, src_key in [("n_defines", "defines"), ("n_imports", "imports"),
("n_dependents", "dependents"), ("n_mentions", "mentions"),
("n_mentioned_by", "mentioned_by"),
("n_reached", "reached_from_entries"),
("n_signatures", "signatures")]:
host[key] = np.array([ln(f, src_key) for f in files], dtype=np.int32)
host["lines"] = np.array([int(f.get("lines") or 0) for f in files], dtype=np.int32)
host["section"] = np.array([int(f.get("section") or 0) for f in files], dtype=np.int32)
host["block_no"] = np.array([int(f.get("block") or 0) for f in files], dtype=np.int32)
host["depth"] = np.array([len(f.get("folder_hierarchy") or []) for f in files], dtype=np.int32)
for key in ("entry", "reachable", "pure"):
host[key] = np.array([bool(f.get(key)) for f in files], dtype=bool)
dup = [f.get("duplicate_of") for f in files]
host["duplicate_of"] = np.array([by_id.get(d, -1) if d is not None else -1 for d in dup], dtype=np.int32)
host["is_duplicate"] = host["duplicate_of"] >= 0
base = {"np": np, "xp": xp, "N": n, "E": len(edges),
"edge_kinds": kinds, "edge_resolutions": res_names,
"block_kinds": BLOCK_KINDS,
"paths": ["%s/%s" % (f.get("repo"), f.get("path")) for f in files],
"titles": [f.get("title") or "" for f in files],
"name_words": [list(f.get("name_words") or []) for f in files],
"inputs": dict(inputs or {}),
"graph_cut": graph.get("cut"), "graph_schema": graph.get("schema")}
base["src"], base["dst"] = xp.asarray(src), xp.asarray(dst)
base["edge_kind"], base["edge_res"] = xp.asarray(ekind), xp.asarray(res_idx)
for k, v in host.items():
base[k] = xp.asarray(v) if isinstance(v, np.ndarray) else v
# host copy of edge kinds for block masks
base["_ekind_host"] = ekind
return base
def element_ctx(base: dict, el: dict, xp=np) -> dict:
ctx = dict(base)
ctx.pop("_ekind_host", None)
ctx["element"] = {k: el[k] for k in ("Z", "symbol", "name", "group", "period", "block",
"weight", "en", "valence", "category")}
ctx["seed"] = el["Z"]
wanted = {i for i, k in enumerate(base["edge_kinds"]) if k in BLOCK_KINDS[el["block"]]}
mask = np.isin(base["_ekind_host"], sorted(wanted)) if wanted else np.zeros(base["E"], bool)
ctx["block_mask"] = xp.asarray(mask)
return ctx
# --------------------------------------------------------------------------- experiments
_SIDE_DIRS: set = set()
_STASH: dict = {}
def _enter_side(d: Path):
"""Make d importable (e.g. electron/common.py) while keeping helper modules of
the electron and positron dirs apart, even if both name a module 'common'."""
d = str(Path(d).resolve())
_SIDE_DIRS.add(d)
for name, m in list(sys.modules.items()):
f = getattr(m, "__file__", None) or ""
owner = os.path.dirname(os.path.abspath(f)) if f else ""
if owner in _SIDE_DIRS and owner != d:
_STASH.setdefault(owner, {})[name] = sys.modules.pop(name)
sys.modules.update(_STASH.pop(d, {}))
while d in sys.path:
sys.path.remove(d)
sys.path.insert(0, d)
def _forget_sides(dirs):
"""Drop cached helper modules so a re-run sees files edited since the last tick."""
dirs = {str(Path(d).resolve()) for d in dirs} | _SIDE_DIRS
_STASH.clear()
for name, m in list(sys.modules.items()):
f = getattr(m, "__file__", None) or ""
if f and os.path.dirname(os.path.abspath(f)) in dirs:
del sys.modules[name]
importlib.invalidate_caches()
def load_module(path: Path):
path = Path(path)
_enter_side(path.parent)
name = "periodic_%s_%s" % (path.parent.name, path.stem)
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def clean_picture(pic):
"""Keep only known primitives with numeric geometry and palette colours."""
out = []
if not isinstance(pic, list):
return out
num = ("x", "y", "r", "x1", "y1", "x2", "y2", "w", "h")
for p in pic[:MAX_PICTURE]:
if not isinstance(p, dict) or p.get("t") not in ("circle", "line", "rect", "poly", "text"):
continue
q = {"t": p["t"]}
for k in num:
if k in p:
try:
v = float(to_host(p[k]))
if math.isfinite(v):
q[k] = round(v, 3)
except (TypeError, ValueError):
pass
c = p.get("c", "grey")
q["c"] = c if c in COLOURS else "grey"
if p["t"] == "poly":
pts = []
for pt in to_host(p.get("pts") or [])[:200]:
try:
pts.append([round(float(pt[0]), 3), round(float(pt[1]), 3)])
except (TypeError, ValueError, IndexError):
pass
q["pts"] = pts
if p["t"] == "text":
q["s"] = str(p.get("s", ""))[:40]
if "fill" in p:
q["fill"] = bool(p["fill"])
out.append(q)
return out
def compare(e, p, tol=None):
"""Return (agree, max_abs_diff, reason)."""
tol = dict(DEFAULT_TOL, **(tol or {}))
rtol, atol = float(tol["rtol"]), float(tol["atol"])
worst = [0.0]
def num_ok(a, b):
if isinstance(a, bool) or isinstance(b, bool):
return a == b
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
d = abs(float(a) - float(b))
worst[0] = max(worst[0], d)
return d <= atol + rtol * abs(float(a))
return a == b
def walk(a, b, where):
if isinstance(a, dict) and isinstance(b, dict):
if set(a) != set(b):
return "keys differ at %s: %s" % (where or "value", sorted(set(a) ^ set(b))[:6])
for k in sorted(a):
r = walk(a[k], b[k], "%s.%s" % (where, k) if where else k)
if r:
return r
return None
if isinstance(a, list) and isinstance(b, list):
if len(a) != len(b):
return "length differs at %s: %d vs %d" % (where or "value", len(a), len(b))
for i, (x, y) in enumerate(zip(a, b)):
r = walk(x, y, "%s[%d]" % (where, i))
if r:
return r
return None
if not num_ok(a, b):
return "differs at %s: %r vs %r" % (where or "value", a, b)
return None
reason = walk(e, p, "")
return reason is None, worst[0], reason
def rel_name(path: Path) -> str:
"""'electron/e1.py': the side folder and file name, never an absolute path."""
path = Path(path)