"""The citation screen for route 27's comparison surface (rebuilt). Question: does every cited value on route 27's comparison surface resolve to an artifact that STATES it? Two layers, both mechanical: * CELL layer. Every artifact on the record that states cells of some row L(T_x, p) is parsed into (level, prime, value, source, locator) and grouped by cell. A cell carrying more than one value is a disagreement. No tile is computed and no published value is recomputed: the screen reads artifacts. * CITATION layer (`citations.py`, which consumes cells.json). A `cited_row` / `gate` / `corpus` structure, or a sentence of the form " ... (# ... published row)", names a source for a value; each is compared against the source's OWN artifact and classified OK / DRIFT / UNCHECKED. Three parser defects in the first run of this file are fixed here, and each was a false positive or a blind spot rather than a data problem: 1. `parse_md_table` treated any all-numeric DATA row as a table header, so #622's per-level summary row `| T_5 | 3 | 43 | 2 | 7 | 42 | 1 | 0 |` was read as the column key of the per-level table and produced seven phantom cells (T_11..T_23, p = 43). A header is now recognised only when the line BELOW it is a markdown separator. 2. `parse_report_rows` paired the prime line with the value line by position without checking that the primes it read were prime, inventing an impossible (T_29, p = 2). Primes are now verified and the arity must match exactly, or the row is reported unparsed. 3. Five sources parsed zero cells because their rows are nested (`#656`), are lists of records (`#645`'s level-29 cells), use a different key (`literal_vs_fold`), or are markdown tables whose columns are not primes (`#627`/`#637`'s row tables). Each is parsed by its own reader now. Nothing is dropped silently: every artifact parsed contributes a source row with its cell count, every table that yielded no cells is listed, and every row/statement that failed to parse is reported. """ import hashlib import json import os import re import sys HERE = os.path.dirname(os.path.abspath(__file__)) RUN = os.path.dirname(HERE) RAW = os.path.join(HERE, "raw") # fold prime -> level for the corpus's diagonal statements (L(T_x, p) with p the next prime after x) FOLD_TO_LEVEL = {7: 5, 11: 7, 13: 11, 17: 13, 19: 17, 23: 19, 29: 23, 31: 29, 37: 31} INT_RE = re.compile(r"^\d+$") SEP_RE = re.compile(r"^:?-{3,}:?$") def path(*parts): return os.path.join(RAW, *parts) def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True def intval(cell): """A markdown cell that is exactly one non-negative integer, else None. Deliberately strict: `72,150,222` and `-` are not values. The loose version of this helper read the witness-gap row of #637's table as three cells. """ s = (cell or "").strip().strip("*").strip("`").strip() return int(s) if INT_RE.match(s) else None def md_tables(text): """Every markdown table in `text`: header cells + data rows, with the header's 1-based line. A table is a `|`-row followed immediately by a separator row (`|---|---|`). Requiring the separator is what stops a data row from being mistaken for a header. """ lines = text.splitlines() out, i = [], 0 while i < len(lines): ln = lines[i].strip() if ln.startswith("|") and i + 1 < len(lines): sep = lines[i + 1].strip() if sep.startswith("|") and all( SEP_RE.match(c.strip()) for c in sep.strip("|").split("|") if c.strip()): rows, j = [], i + 2 while j < len(lines) and lines[j].strip().startswith("|"): rows.append([c.strip() for c in lines[j].strip().strip("|").split("|")]) j += 1 out.append({"header_line": i + 1, "header": [c.strip() for c in ln.strip("|").split("|")], "rows": rows}) i = j continue i += 1 return out def prime_grid_cells(table, label, at, allowed_levels=None, kind_for=None): """Cells from a table whose columns ARE primes and whose row label names a level (`T_31`).""" hdr = table["header"] if len(hdr) < 6 or not all(INT_RE.match(c) for c in hdr[1:]): return 0, None primes = [int(c) for c in hdr[1:]] n, skipped = 0, [] for r, row in enumerate(table["rows"]): if len(row) != len(hdr): skipped.append({"row": row[:2], "why": "cell count %d != header %d" % (len(row), len(hdr))}) continue m = re.search(r"T_?\{?(\d+)\}?", row[0].replace("*", "")) if not m: skipped.append({"row": row[0][:40], "why": "row label names no level"}) continue lvl = int(m.group(1)) if allowed_levels and lvl not in allowed_levels: skipped.append({"row": row[0][:40], "why": "level %d outside the artifact's domain" % lvl}) continue kind = kind_for(row[0]) if kind_for else {} got = 0 for p, cell in zip(primes, row[1:]): v = intval(cell) if v is None: continue at({"level": lvl, "p": p, "value": v, "source": label, "locator": "%s table@%d row '%s' col %d" % (label, table["header_line"], row[0][:24], p), **kind}) got += 1 n += got return n, (skipped or None) def prime_col_cells(table, label, level, at): """Cells from a table whose header names a `p` column and an `L` column (#627's T_29 row).""" hdr = [h.strip("*").strip() for h in table["header"]] if not hdr or hdr[0].lower() != "p" or "L" not in hdr: return 0, None li = hdr.index("L") n, skipped = 0, [] for row in table["rows"]: if len(row) <= li: skipped.append({"row": row[:2], "why": "shorter than its header"}) continue p, v = intval(row[0]), intval(row[li]) if p is None or v is None: skipped.append({"row": row[0][:24], "why": "p or L not an integer"}) continue at({"level": level, "p": p, "value": v, "source": label, "locator": "%s table@%d row p=%d col L" % (label, table["header_line"], p)}) n += 1 return n, (skipped or None) def bound_cells(level, m, label, locator, at, unparsed): """#656's `row_ge2_ge3`: `[x, y]` is min(L, 2) together with `L >= 3`, NOT the value of L. Read as a row this field invents four disagreements (T_29 p=31 and p=37, T_31 p=37, 41 and 53, where `[2, True]` is a cell with L >= 3). Read as what it is -- a two-verdict encoding -- it is exact wherever it is not a bound, and the bounds are consistent with every full row on the record. """ if not isinstance(m, dict): return 0 n = 0 for k, v in m.items(): if not INT_RE.match(str(k)) or not (isinstance(v, list) and len(v) == 2): unparsed.append({"source": label, "key": str(k), "why": "not a [value, flag] pair"}) continue first, second = v[0], v[1] if first == 1: at({"level": level, "p": int(k), "value": 1, "source": label, "locator": "%s[%s] first=1" % (locator, k), "kind": "own"}) n += 1 elif first == 2 and second is False: at({"level": level, "p": int(k), "value": 2, "source": label, "locator": "%s[%s] = [2, false]" % (locator, k), "kind": "own"}) n += 1 elif first == 2 and second is True: # a bound, not a value: recorded as such and deliberately kept OUT of the cell layer unparsed_bounds.append({"source": label, "level": level, "p": int(k), "bound": ">=3", "locator": "%s[%s] = [2, true]" % (locator, k)}) else: unparsed.append({"source": label, "key": str(k), "value": v, "why": "unknown encoding"}) return n def map_cells(level, m, label, locator, at): """Cells from a {prime: value} map whose values may be ints, [L, flag] pairs or {L: v} dicts.""" if not isinstance(m, dict): return 0 n = 0 for k, v in m.items(): if not INT_RE.match(str(k)): continue if isinstance(v, int): val = v elif isinstance(v, list) and v and isinstance(v[0], int): val = v[0] elif isinstance(v, dict) and isinstance(v.get("L"), int): val = v["L"] else: continue at({"level": level, "p": int(k), "value": val, "source": label, "locator": "%s[%s]" % (locator, k)}) n += 1 return n def ranged_map_cells(level, m, label, locator, at, note): """Cells from #645's range-compressed cited row: {"31": 4, "37": 3, "41..113": 2, ...}. A range key is expanded over the PRIMES it covers, and every cell made this way carries the range key verbatim in its locator, so the expansion can never be mistaken for a measurement of its own. """ if not isinstance(m, dict): return 0, [] n, unparsed = 0, [] for k, v in m.items(): if not isinstance(v, int): unparsed.append({"key": str(k), "why": "value is not an integer"}) continue if INT_RE.match(str(k)): at({"level": level, "p": int(k), "value": v, "source": label, "locator": "%s[%s]" % (locator, k), "expanded_from_range": False}) n += 1 continue mm = re.match(r"^(\d+)\.\.(\d+)$", str(k)) if not mm: unparsed.append({"key": str(k), "why": "not a prime key or a .. range"}) continue a, b = int(mm.group(1)), int(mm.group(2)) for p in range(a, b + 1): if is_prime(p): at({"level": level, "p": p, "value": v, "source": label, "locator": "%s['%s'] -> p=%d" % (locator, k, p), "expanded_from_range": True}) n += 1 return n, (unparsed or None) unparsed_bounds = [] def report_row_cells(text, label, at, unparsed): """#637's report prints the row as two monospace blocks: a `p` line, then `L(T_31,p)`. #627's report.md prints the same device. Primes are verified, arity must match exactly, or it is reported unparsed -- the loose version invented an impossible (T_29, p = 2).""" lines = text.splitlines() n = 0 for i, line in enumerate(lines): m = re.search(r"L\(T_?\{?(\d+)\}?\s*,\s*p\)", line) if not m: continue lvl = int(m.group(1)) vals = [int(t) for t in re.findall(r"[0-9]+", line.split(")", 1)[-1])] found = None for back in (1, 2): j = i - back if j < 0: break hdr = [int(t) for t in re.findall(r"[0-9]+", lines[j])] # the prime line carries no `L(T_`, its numeric tokens are all prime, and its arity matches if "L(T_" in lines[j] or not hdr or len(hdr) != len(vals): continue if all(is_prime(x) for x in hdr): found = hdr break if not found: unparsed.append({"source": label, "line": i + 1, "value_line": line[:80], "why": ("no prime line above with %d all-prime columns (a second row of the " "same block is the usual cause)" % len(vals))}) continue for p, v in zip(found, vals): at({"level": lvl, "p": p, "value": v, "source": label, "locator": "%s line %d row L(T_%d,p) at p=%d" % (label, i + 1, lvl, p)}) n += 1 return n # The diagonal is written in four shapes on this record, all of them stating cells: # A `L = 2, 1, 2, 2, 2, 3, 2, 4, 4 at folds 7 to 37` (corpus) # A' `L(T_{p-}, p) = 2, 1, 2, 2, 2, 3, 2, 4 at folds 7..31` (the route, #161's report) # B `L(T_{p-}, p) at folds 7..31: 2, 1, 2, 2, 2, 3, 2, 4` (#161's report) # C `L = 2, 1, 2, 2, 2, 3, 2 at folds 7, 11, 13, 17, 19, 23, 29` (a3-08's ladder, cited) # backticks and bold markers sit in the middle of these sentences, so every joiner below tolerates them _F = r"[`*\s]*" DIAG_A = re.compile(r"L(?:\([^)]*\))?" + _F + r"=" + _F + r"([\d,\s]+?)" + _F + r"at folds" + _F + r"(?:p" + _F + r"=" + _F + r")?(\d+)" + _F + r"(?:\.\.|to|through|-|–)" + _F + r"(\d+)") DIAG_B = re.compile(r"L(?:\([^)]*\))?" + _F + r"at folds" + _F + r"(\d+)" + _F + r"(?:\.\.|to|through|-|–)" + _F + r"(\d+)" + _F + r":" + _F + r"([\d,\s]+?)(?=[^\d,\s]|$)") DIAG_C = re.compile(r"L(?:\([^)]*\))?" + _F + r"=" + _F + r"([\d,\s]+?)" + _F + r"at folds" + _F + r"(?:p" + _F + r"=" + _F + r")?((?:\d+" + _F + r"," + _F + r")+\d+)") # Shape D: a bare restatement of the diagonal -- the value list, then `at folds a..b`, with no `L =`. # Guarded on the preceding 80 characters naming the object (`L(` or `diagonal`), because the corpus also # writes other 9-tuples at the same folds (the excess of a bound: `runs 6, 0, 0, 12, ..., 120 at folds # 7 to 37`), and those are NOT values of L. DIAG_D = re.compile(r"((?:\d{1,3}" + _F + r"," + _F + r"){5,11}\d{1,3})" + _F + r"at folds" + _F + r"(\d+)" + _F + r"(?:\.\.|to|through|-|–)" + _F + r"(\d+)") DIAG_D_GUARD = re.compile(r"(L\(|L\s*=|diagonal)", re.I) AT_FOLDS = re.compile(r"at folds") def diagonal_statements(text): """Every diagonal statement in `text`, in each of the four shapes above. A statement is only a cell statement when its arity matches the folds it names -- otherwise it is returned with `arity_ok: False` and reported, never dropped. """ out, taken = [], [] def add(quote, offset, vals, folds, span, form): # `length` keeps the TRUE extent: the quote is truncated for display, and an occurrence test that # used the truncated quote reported a statement as unparsed that had in fact been parsed. out.append({"quote": quote[:110], "length": len(quote), "offset": offset, "values": vals, "folds": folds, "arity_ok": len(vals) == len(folds) and bool(vals), "span": span, "form": form}) taken.append((offset, offset + len(quote))) for m in DIAG_A.finditer(text): a, b = int(m.group(2)), int(m.group(3)) add(m.group(0), m.start(), [int(x) for x in re.findall(r"\d+", m.group(1))], [f for f in sorted(FOLD_TO_LEVEL) if a <= f <= b], [a, b], "range") for m in DIAG_B.finditer(text): if any(s <= m.start() < e for s, e in taken): continue a, b = int(m.group(1)), int(m.group(2)) add(m.group(0), m.start(), [int(x) for x in re.findall(r"\d+", m.group(3))], [f for f in sorted(FOLD_TO_LEVEL) if a <= f <= b], [a, b], "range_then_values") for m in DIAG_C.finditer(text): if any(s <= m.start() < e for s, e in taken): continue add(m.group(0), m.start(), [int(x) for x in re.findall(r"\d+", m.group(1))], [int(x) for x in re.findall(r"\d+", m.group(2))], None, "fold_list") for m in DIAG_D.finditer(text): if any(s <= m.start() < e for s, e in taken): continue if not DIAG_D_GUARD.search(text[max(0, m.start() - 80):m.start()]): continue # not a statement about L: left to `unparsed` a, b = int(m.group(2)), int(m.group(3)) add(m.group(0), m.start(), [int(x) for x in re.findall(r"\d+", m.group(1))], [f for f in sorted(FOLD_TO_LEVEL) if a <= f <= b], [a, b], "bare_restatement") return out def diag_cells(text, label, at, unparsed, cited_from=None): n = 0 for st in diagonal_statements(text): if not st["arity_ok"]: unparsed.append({"source": label, "quote": st["quote"], "form": st["form"], "why": "%d values over %d folds" % (len(st["values"]), len(st["folds"]))}) continue for f, v in zip(st["folds"], st["values"]): if f not in FOLD_TO_LEVEL: unparsed.append({"source": label, "quote": st["quote"], "why": "fold %d names no level" % f}) continue at({"level": FOLD_TO_LEVEL[f], "p": f, "value": v, "source": label, "locator": "%s statement '%s' fold %d" % (label, st["quote"][:50], f), "kind": "cited" if cited_from else "own", "cited_from": cited_from}) n += 1 # every `at folds` occurrence that no statement shape covered is reported as unparsed, with its # quote, so the count of what the screen could NOT read is on the record rather than implied spans = [(st["offset"], st["offset"] + st["length"]) for st in diagonal_statements(text)] for m in AT_FOLDS.finditer(text): if any(s <= m.start() < e for s, e in spans): continue unparsed.append({"source": label, "offset": m.start(), "quote": text[max(0, m.start() - 120):m.end() + 90].replace("\n", " ")[:230], "why": "an 'at folds' statement in none of the four recognised shapes"}) return n PROSE_CELL = re.compile(r"L\(T_?\{?(\d+)\}?\s*,\s*\**(\d+)\**\)\s*=\s*\**(\d+)\**") REF_ID = re.compile(r"#(\d{1,4})\b") def prose_cell_cells(text, label, at, unparsed): """Single cells stated in prose: `L(T_31, 37) = 4`. These are the artifact's OWN statements -- what the sentence attributes them to is a separate question, and it is answered by the citation layer rather than guessed at here from a window. The window is still recorded, so a reader can see what the sentence around each cell says. """ n = 0 for m in PROSE_CELL.finditer(text): lvl, p, v = int(m.group(1)), int(m.group(2)), int(m.group(3)) if not is_prime(p) or p <= lvl: unparsed.append({"source": label, "quote": m.group(0), "why": "p=%d is not a prime above level %d" % (p, lvl)}) continue lo, hi = max(0, m.start() - 130), min(len(text), m.end() + 130) at({"level": lvl, "p": p, "value": v, "source": label, "locator": "%s prose '%s' at offset %d" % (label, m.group(0), m.start()), "kind": "own", "window": text[lo:hi].replace("\n", " ")[:220]}) n += 1 return n def load(p): with open(p, encoding="utf-8") as fh: return json.load(fh) def build_cells(): cells, sources, unparsed, tables_seen = [], [], [], [] def at(c): c.setdefault("kind", "own") c.setdefault("cited_from", None) cells.append(c) def add_source(label, note, count, artifact=None, sha=None): sources.append({"source": label, "what": note, "cells": count, "artifact": artifact, "sha256": sha}) def tbls_of(text): return md_tables(text) # ---------------- #622 -- the route-27 bank, served at its content address ---------------- d = load(path("622-L-grid.json")) n = 0 for r in d.get("rows") or []: if isinstance(r.get("level"), int) and isinstance(r.get("p"), int) and isinstance(r.get("L"), int): at({"level": r["level"], "p": r["p"], "value": r["L"], "source": "622:L-grid", "locator": "L-grid.json rows[level=%d,p=%d].L" % (r["level"], r["p"])}) n += 1 add_source("622:L-grid", "#622's bank rows, as served at its content address", n, "L-grid.json") n = 0 for g in d.get("gates") or []: mm = re.search(r"L\(T_(\d+),\s*(\d+)\)", g.get("gate") or "") if mm and isinstance(g.get("measured"), int): at({"level": int(mm.group(1)), "p": int(mm.group(2)), "value": g["measured"], "source": "622:gates", "locator": "L-grid.json gates: %s" % g["gate"], "kind": "cited", "cited_from": "the corpus's published diagonal", "cited_text": (g.get("gate") or "").split("=")[0].strip()}) n += 1 add_source("622:gates", "the bank's own diagonal gate list, each line naming the corpus value", n, "L-grid.json") t622 = open(path("622-L-TABLE.md"), encoding="utf-8").read() for t in tbls_of(t622): tables_seen.append({"artifact": "622-L-TABLE.md", "header_line": t["header_line"], "header": t["header"][:4], "rows": len(t["rows"]), "kind": "grid" if (len(t["header"]) >= 6 and all(INT_RE.match(c) for c in t["header"][1:])) else "other"}) for t in tbls_of(t622): n, sk = prime_grid_cells(t, "622:L-TABLE.grid", at) if n or sk: add_source("622:L-TABLE.grid", "#622's own transcription of the bank as a markdown grid", n, "L-TABLE.md") if sk: unparsed.append({"source": "622:L-TABLE.grid", "rows": sk}) break n = 0 for t in tbls_of(t622): hdr = [h.strip("*") for h in t["header"]] if not hdr or hdr[0].lower() != "fold": continue for row in t["rows"]: m = re.match(r"^T_?(\d+)\s*,\s*p\s*=\s*(\d+)$", row[0].replace(" ", " ")) if not m: unparsed.append({"source": "622:L-TABLE.diag", "row": row[0][:40], "why": "fold cell does not name (level, p)"}) continue lvl, p = int(m.group(1)), int(m.group(2)) for k, src, note in ((1, "622:L-TABLE.diag", "its own value"), (2, "622:L-TABLE.diag.corpus", "the corpus value it transcribes")): v = intval(row[k]) if len(row) > k else None if v is None: unparsed.append({"source": src, "row": row[0][:40], "why": "column %d not an int" % k}) continue at({"level": lvl, "p": p, "value": v, "source": src, "locator": "L-TABLE.md fold table '%s' col %s" % (row[0], k + 1), "kind": "own" if k == 1 else "cited", "cited_from": None if k == 1 else "the corpus's published diagonal"}) n += 1 add_source("622:L-TABLE.diag(+.corpus)", "#622's diagonal table: its value and the corpus's", n, "L-TABLE.md") # ---------------- #627 -- the T_29 row, the source #637 and #645 both cite ---------------- d = load(path("627-T29-grid.json")) n = 0 for lvlkey, lv in (d.get("levels") or {}).items(): n += map_cells(int(lvlkey), {str(r["p"]): r for r in (lv.get("rows") or []) if "p" in r}, "627:T29-grid.rows", "T29-grid.json levels[%s].rows" % lvlkey, at) add_source("627:T29-grid.rows", "#627's machine artifact for the T_29 row", n, "T29-grid.json", "22c08f836947") g = d.get("corpus") or {} n = 0 if isinstance(g.get("L(T29,31)"), int): at({"level": 29, "p": 31, "value": g["L(T29,31)"], "source": "627:T29-corpus-gate", "locator": "T29-grid.json corpus['L(T29,31)'] (source field: %s)" % g.get("source"), "kind": "cited", "cited_from": "the corpus's published diagonal"}) n = 1 add_source("627:T29-corpus-gate", "the corpus value #627 gates its T_29 row against", n, "T29-grid.json") t627 = open(path("627-L-TABLE-29.md"), encoding="utf-8").read() n, sk = 0, [] for t in tbls_of(t627): c, s = prime_col_cells(t, "627:L-TABLE-29.row", 29, at) n += c if s: sk.extend(s) add_source("627:L-TABLE-29.row", "#627's published T_29 row as a `p | L` table", n, "L-TABLE-29.md") if sk: unparsed.append({"source": "627:L-TABLE-29.row", "rows": sk}) # ---------------- #637 -- the T_31 row and its neighbouring T_29 row ---------------- d = load(path("637-T31-grid.json")) lvl = d.get("level", 31) n = map_cells(lvl, d.get("row"), "637:T31-grid.row", "T31-grid.json row", at) add_source("637:T31-grid.row", "#637's own grid row for level 31", n, "T31-grid.json", "44257ab731") n = map_cells(lvl, {k: (v or {}).get("L") for k, v in (d.get("rows") or {}).items()}, "637:T31-grid.rows", "T31-grid.json rows", at) add_source("637:T31-grid.rows", "the same grid's per-prime detail", n, "T31-grid.json") d2 = load(path("637-analyse31.json")) n = map_cells(lvl, {k: (v or {}).get("L") for k, v in (d2.get("per_prime") or {}).items()}, "637:analyse31", "analyse31.json per_prime", at) add_source("637:analyse31", "#637's per-prime analysis of level 31", n, "analyse31.json", "76609756ad") t637 = open(path("637-L-TABLE-31.md"), encoding="utf-8").read() n = 0 def t31_kind(label): # the table's SECOND row is not #637's measurement: it is the T_29 row it cites to #627 return ({"kind": "own"} if re.match(r"^\**L\(T_31", label) else {"kind": "cited", "cited_from": "return #627's T_29 row", "cited_text": label}) for t in tbls_of(t637): c, sk = prime_grid_cells(t, "637:L-TABLE-31", at, allowed_levels={29, 31}, kind_for=t31_kind) n += c if sk: unparsed.append({"source": "637:L-TABLE-31", "rows": sk}) add_source("637:L-TABLE-31", "#637's published table: the T_31 row and the T_29 row it cites", n, "L-TABLE-31.md", "b286e28d91") t637r = open(path("637-report.md"), encoding="utf-8").read() n = report_row_cells(t637r, "637:report", at, unparsed) add_source("637:report", "#637's report rows, printed as prime line + value line", n, "report.md", "ca8cb2e035") # ---------------- #644 -- the independent verification of the bank ---------------- d = load(path("644-job1415-bank-diff.json")) n = 0 for r in d.get("rows_out") or []: for k in ("bank_L", "corrected_L"): if isinstance(r.get(k), int): at({"level": r["level"], "p": r["p"], "value": r[k], "source": "644:" + k, "locator": "job1415-bank-diff.json rows_out[p=%d].%s" % (r["p"], k), # bank_L is #644's RE-READ of #622's bank, not its own instrument; corrected_L is # its own (the wrap-corrected one it re-measures with) "kind": "cited" if k == "bank_L" else "own", "cited_from": "#622's bank rows (re-read by #644)" if k == "bank_L" else None}) n += 1 add_source("644:bank_L / 644:corrected_L", "#644's re-read of the bank (bank_L) and its corrected instrument (corrected_L)", n, "job1415-bank-diff.json", "471a01d824") n = 0 for g in d.get("gates") or []: for k in ("literal_L", "gap_L", "bank_L"): if isinstance(g.get(k), int): at({"level": g["level"], "p": g["p"], "value": g[k], "source": "644:gates." + k, "locator": "job1415-bank-diff.json gates[level=%d,p=%d].%s" % (g["level"], g["p"], k)}) n += 1 add_source("644:gates.*", "#644's diagonal gates: literal scan / gap instrument / bank value", n, "job1415-bank-diff.json") # ---------------- #645 -- the citing return: its own rows AND the rows it cites ---------------- d = load(path("645-job1416-seam.json")) st = d.get("stages") or {} for stage, lvl in (("tuples", 29), ("t31", 31)): s = st.get(stage) or {} n = map_cells(lvl, s.get("row"), "645:%s.row" % stage, "%s.row" % stage, at) add_source("645:%s.row" % stage, "#645's own instrumented row, level %d" % lvl, n, "job1416-seam.json") n = map_cells(lvl, s.get("cited_row"), "645:%s.cited_row" % stage, "%s.cited_row" % stage, lambda c: cells.append({**c, "kind": "cited", "cited_from": "#627's T_29 row" if lvl == 29 else "#637's published T_31 row"})) add_source("645:%s.cited_row" % stage, "the row it COMPARED AGAINST -- a transcription, not a measurement of its own", n, "job1416-seam.json") lv = (st.get("level29") or {}).get("cells") n = 0 if isinstance(lv, list): for c in lv: if isinstance(c.get("p"), int) and isinstance(c.get("L_correct"), int): at({"level": 29, "p": c["p"], "value": c["L_correct"], "source": "645:level29.cells", "locator": "seam stages.level29.cells[p=%d].L_correct" % c["p"]}) n += 1 add_source("645:level29.cells", "its level-29 cell table (six gated cells)", n, "job1416-seam.json") n, un = ranged_map_cells(29, (st.get("level29") or {}).get("cited_row"), "645:level29.cited_row", "seam stages.level29.cited_row", lambda c: cells.append({**c, "kind": "cited", "cited_from": "#627's T_29 row"}), "range keys expanded over primes") add_source("645:level29.cited_row", "its level-29 cited row, written as range keys (e.g. '41..113'), expanded over primes", n, "job1416-seam.json") if un: unparsed.append({"source": "645:level29.cited_row", "keys": un}) g = load(path("645-job1416-gates.json")).get("stages", {}).get("gates", {}) n = 0 for c in g.get("literal_vs_fold") or []: if isinstance(c.get("literal"), int): at({"level": c["level"], "p": c["p"], "value": c["literal"], "source": "645:gates.literal_vs_fold", "locator": "job1416-gates.json literal_vs_fold[level=%d,p=%d].literal" % (c["level"], c["p"])}) n += 1 add_source("645:gates.literal_vs_fold", "its literal scan vs the fold criterion, nine cells", n, "job1416-gates.json", "06eea4a7f8") bank = g.get("bank") or {} n = 0 for c in bank.get("unshifted_wrong") or []: for k in ("bank", "mine"): if isinstance(c.get(k), int): at({"level": c["level"], "p": c["p"], "value": c[k], "source": "645:gates.bank.unshifted_wrong." + k, "locator": "job1416-gates.json bank.unshifted_wrong[level=%d,p=%d].%s" % (c["level"], c["p"], k), "kind": "cited" if k == "bank" else "alt_instrument", "cited_from": "#622's bank" if k == "bank" else None}) n += 1 add_source("645:gates.bank.*", ("the nine bank cells its unshifted reading disagrees on: `bank` is " "the value it reads off #622, `mine` its own"), n, "job1416-gates.json") # ---------------- #656 -- the level-23/29/31 re-measurements ---------------- for name, lvl in (("656-job1418-level29.json", None), ("656-job1418-level31.json", None)): d = load(path(name)) n = 0 for key, sub in d.items(): if not isinstance(sub, dict): continue m = re.match(r"^level(\d+)$", key) if m: n += map_cells(int(m.group(1)), sub.get("row"), "656:%s.%s.row" % (name, key), "%s.%s.row" % (name, key), at) n += bound_cells(int(m.group(1)), sub.get("row_ge2_ge3"), "656:%s.%s.row_ge2_ge3" % (name, key), "%s.%s.row_ge2_ge3" % (name, key), at, unparsed) elif key == "gates" and isinstance(sub.get("diagonal_folds"), dict): for fk, v in sub["diagonal_folds"].items(): mm = re.match(r"^fold_(\d+)$", fk) if mm and isinstance(v, int) and int(mm.group(1)) in FOLD_TO_LEVEL: f = int(mm.group(1)) at({"level": FOLD_TO_LEVEL[f], "p": f, "value": v, "source": "656:gates.diagonal_folds", "locator": "job1418-gates.json gates.diagonal_folds.%s" % fk, "kind": "cited", "cited_from": "the corpus's published diagonal"}) n += 1 add_source("656:%s" % name, "#656's measured rows and diagonal gates carried by this file", n, name, "bf08583a73" if name.endswith("level29.json") else "384ead8300") d = load(path("656-job1418-gates.json")).get("gates") or {} n = 0 for k, v in (d.get("diagonal_folds") or {}).items(): mm = re.match(r"^fold_(\d+)$", k) if mm and isinstance(v, int) and int(mm.group(1)) in FOLD_TO_LEVEL: f = int(mm.group(1)) at({"level": FOLD_TO_LEVEL[f], "p": f, "value": v, "source": "656:gates.diagonal_folds", "locator": "job1418-gates.json gates.diagonal_folds.%s" % k, "kind": "cited", "cited_from": "the corpus's published diagonal"}) n += 1 for k, v in (d.get("seam_cells") or {}).items(): mm = re.match(r"^T(\d+)/p(\d+)$", k) if mm and isinstance(v, int): at({"level": int(mm.group(1)), "p": int(mm.group(2)), "value": v, "source": "656:gates.seam_cells", "locator": "job1418-gates.json gates.seam_cells['%s']" % k}) n += 1 add_source("656:gates.*", "its diagonal folds and the nine seam-sensitive cells", n, "job1418-gates.json", "2521cd704e") # ---------------- the sources that are statements, not tables ---------------- uf = open(path("corpus-uframe.md"), encoding="utf-8").read() n = diag_cells(uf, "corpus:U-FRAME.diag", at, unparsed) add_source("corpus:U-FRAME.diag", "the corpus's diagonal statements: the range form and the ladder", n, "docs/research/U-FRAME.md") r161 = load(path("return161.served.json"))["body"] n = diag_cells(r161.get("report_md") or "", "return161:report.diag", at, unparsed) add_source("return161:report.diag", "#161's own report (fetched live): the corrected diagonal, in " "three phrasings", n, "return/161") n = diag_cells(r161.get("job_brief") or "", "return161:brief.diag", at, unparsed) add_source("return161:brief.diag", "#161's job brief, which the diagonal is quoted into", n, "return/161") r27 = load(os.path.join(RUN, "job2961", "raw", "route27.fetched.json"))["body"] n = diag_cells(r27.get("contribution_md") or "", "route27:contribution.diag", at, unparsed, cited_from="return #161's diagonal (named in the same sentence)") add_source("route27:contribution.diag", "route 27's statement of the diagonal it cites to #161", n, "research-routes/27") n = prose_cell_cells(r27.get("contribution_md") or "", "route27:contribution.prose", at, unparsed) add_source("route27:contribution.prose", "the route's own prose cells, e.g. L(T29,31) = 4", n, "research-routes/27") # ---- prose cells in the returns' own bodies: where most of the citations actually live ---- bodies = [("161", os.path.join(RAW, "return161.served.json")), ("627", os.path.join(RAW, "return627.served.json"))] for rid in (622, 637, 644, 645, 656): bodies.append((str(rid), os.path.join(RUN, "job2961", "raw", "return%d.json" % rid))) for rid, p in bodies: if not os.path.exists(p): unparsed.append({"source": "return%s" % rid, "why": "record not held"}) continue b = load(p).get("body", {}) n = 0 for field, text in (("report_md", b.get("report_md")), ("evidence_md", (b.get("research") or {}).get("evidence_md") or b.get("evidence_md")), ("finding", b.get("finding"))): if isinstance(text, str): n += prose_cell_cells(text, "return%s.%s.prose" % (rid, field), at, unparsed) add_source("return%s prose cells" % rid, "single cells stated in the body of return #%s" % rid, n, "return/%s" % rid) return cells, sources, unparsed, tables_seen def classify_disagreement(lst, vals): """Name the KIND of disagreement, mechanically, from the `kind` fields of the cells involved. A disagreement between an artifact's own value and a value it CITES from another return is a citation edge -- the question this screen exists to answer. One between an artifact's own value and an alternative reading that the SAME artifact reports as wrong is an instrument difference, and reporting it as data drift would be a false positive. Anything else is left as `unclassified` rather than forced into either bucket. """ # Classify by the DISSENTING value (the one fewest cells carry), not by the group's membership: a # group can contain both a citation and a self-declared alternative reading, and the first version # of this function called those nine instrument cells citation edges for that reason. counts = {} for c in lst: counts.setdefault(c["value"], []).append(c) majority = max(counts, key=lambda v: len(counts[v])) dissent = [c for v, cs in counts.items() if v != majority for c in cs] kinds = sorted({c["kind"] for c in dissent}) if dissent and all(c["kind"] == "alt_instrument" for c in dissent): return {"class": "alternative_instrument", "dissenting_kinds": kinds, "why": ("the dissenting value is an alternative reading of the SAME artifact, which the " "artifact itself reports as the wrong one (unshifted_matches 271 of 280)")} if any(c["kind"] == "cited" for c in dissent): return {"class": "citation_edge", "dissenting_kinds": kinds, "why": "a value an artifact CITES from another return disagrees with that source's own", "cited": sorted({(c["source"], c["cited_from"]) for c in dissent if c["kind"] == "cited"})} return {"class": "unclassified", "dissenting_kinds": kinds, "why": "neither a citation nor a self-declared alternative"} def main(): cells, sources, unparsed, tables_seen = build_cells() groups = {} for c in cells: groups.setdefault((c["level"], c["p"]), []).append(c) disagreements, corroborated, singleton = [], [], [] for cell, lst in sorted(groups.items()): vals = sorted({c["value"] for c in lst}) if len(vals) > 1: disagreements.append({"cell": {"level": cell[0], "p": cell[1]}, "class": classify_disagreement(lst, vals), "values": {str(v): sorted({c["source"] for c in lst if c["value"] == v}) for v in vals}, "locators": sorted({(c["source"], c["locator"]) for c in lst})}) elif len({c["source"] for c in lst}) > 1: corroborated.append({"cell": {"level": cell[0], "p": cell[1]}, "value": vals[0], "sources": sorted({c["source"] for c in lst})}) else: singleton.append({"cell": {"level": cell[0], "p": cell[1]}, "value": vals[0], "source": lst[0]["source"], "locator": lst[0]["locator"]}) out = { "sources": sources, "cells_total": len(cells), "cells_distinct": len(groups), "corroborated": len(corroborated), "singleton": len(singleton), "disagreements": disagreements, "corroborated_cells": corroborated, "singleton_cells": singleton, "unparsed": unparsed, "bounds": unparsed_bounds, "tables_seen": tables_seen, "by_kind": {k: sum(1 for c in cells if c["kind"] == k) for k in ("own", "cited", "alt_instrument")}, "cited_edges_named": sorted({(c["source"], c["cited_from"]) for c in cells if c["kind"] == "cited" and c["cited_from"]}), "artifact_index": json.load(open(os.path.join(HERE, "fetched-artifacts.json"), encoding="utf-8"))["fetched_artifacts"] + json.load(open(os.path.join(HERE, "fetched-627-161.json"), encoding="utf-8"))["fetched"], } with open(os.path.join(HERE, "cells.json"), "w", encoding="utf-8") as fh: json.dump(cells, fh, indent=1) with open(os.path.join(HERE, "screen.json"), "w", encoding="utf-8") as fh: json.dump(out, fh, indent=1) print("%-34s %s" % ("cells parsed", len(cells))) print("%-34s %s" % ("distinct cells", len(groups))) print("%-34s %s" % ("corroborated by >1 source", len(corroborated))) print("%-34s %s" % ("single-source cells", len(singleton))) print("%-34s %s" % ("DISAGREEMENTS", len(disagreements))) for d in disagreements: print(" (T_%d, p=%d) [%s]:" % (d["cell"]["level"], d["cell"]["p"], d["class"]["class"])) for v, srcs in sorted(d["values"].items()): print(" value %-4s from %s" % (v, ", ".join(srcs))) print("\n%-34s %s" % ("bounds recorded (not cells)", len(unparsed_bounds))) print("%-34s %s" % ("cells by kind", json.dumps(out["by_kind"]))) print("\nunparsed rows/statements: %d" % len(unparsed)) for u in unparsed: print(" %s: %s" % (u.get("source"), json.dumps(u)[:150])) print("\nsources and their cell counts:") for s in sources: print(" %-34s %4d cells %s" % (s["source"], s["cells"], (s["what"] or "")[:58])) zero = [s["source"] for s in sources if not s["cells"]] print("\nsources that parsed zero cells: %s" % (zero or "none")) return 0 if __name__ == "__main__": sys.exit(main())