Jump to content

The Principia Machina/TPC-PY/diff hunk.py: Difference between revisions

From The Invariance Itself
TPC-PY source diff_hunk.py (0.1.0), SHA-256 0e2ae21ea4ddfd57; conformed TPS 0.3.0; PROPOSED, not declared (CO-8)
 
m 1 revision imported
 
(No difference)

Latest revision as of 04:32, 28 September 2026

"""diff_hunk 0.1.0: the cross-residence differential for tpc_hunk 0.1.0.
Random bases over a small alphabet with multi-byte characters, random
hunks drawn from substrings of the base (so that ABSENT, MULTIPLE, OVERLAP
and EMPTY all occur), both residences on the same inputs, 0 differences
the pass. Usage: python3 diff_hunk.py [seed] [cases]."""
import json, os, random, subprocess, sys, tempfile
here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, here)
from tpc_hunk import run_case
seed = int(sys.argv[1]) if len(sys.argv) > 1 else 1
count = int(sys.argv[2]) if len(sys.argv) > 2 else 20000
random.seed(seed)
ALPHA = "ab \n|\\é́模\U0001F600xyz\t"
cases = []
for t in range(count):
    n = random.randint(0, 40)
    base = "".join(random.choice(ALPHA) for _ in range(n))
    hunks = []
    for _ in range(random.randint(0, 4)):
        r = random.random()
        if r < 0.08 or not base:
            old = "" if r < 0.04 else "".join(random.choice(ALPHA) for _ in range(random.randint(1, 3)))
        else:
            i = random.randrange(len(base))
            j = min(len(base), i + random.randint(1, 6))
            old = base[i:j]
        new = "".join(random.choice(ALPHA) for _ in range(random.randint(0, 5)))
        h = {"old": old, "new": new}
        if random.random() < 0.1:
            h["n"] = len(hunks) + 1
        hunks.append(h)
    cases.append({"fn": "hunk", "args": {"base": base, "hunks": hunks}})
CASES_PATH = os.environ.get("TPC_DIFF_CASES")  # named: kept, for crosspy.py
if not CASES_PATH:
    fd, CASES_PATH = tempfile.mkstemp(prefix="tpc_diff_", suffix=".json")  # outside the tree
    os.close(fd)
with open(CASES_PATH, "w", encoding="utf-8") as f:
    json.dump(cases, f, ensure_ascii=False)
py = [run_case(c["fn"], c["args"]) for c in cases]
php = json.loads(subprocess.run(["php", os.path.join(here, "diff_hunk.php"), CASES_PATH], capture_output=True, text=True, check=True).stdout)
if not os.environ.get("TPC_DIFF_CASES"):
    os.remove(CASES_PATH)
diffs = sum(1 for a, b in zip(py, php) if a != b)
kinds = {}
for x in py:
    k = x.split("|")[0] if not x.startswith("REFUSED") else x.split("|")[1]
    kinds[k] = kinds.get(k, 0) + 1
print("seed", seed, "cases", len(cases), "differences", diffs, "outcomes", json.dumps(kinds, sort_keys=True))
for a, b in zip(py, php):
    if a != b:
        print(a); print("---"); print(b); break