#!/usr/bin/env python3 """Experiment 1 - order dependence of the kill-graph component census. Controls and witnesses on the exact T23 gap word (D = 7 952 175): * rotation control: the same cyclic word read from a different start must give an identical census (the walk is on the cyclic word); * shuffle witness: a seeded random cyclic permutation of the SAME multiset (identical histogram) at p = 29 and p = 31. Edges (the adjacent-kill pair total, a histogram functional 2*N0 + N+-) must be exactly invariant; the component-size census n_L need not be. Usage: order_dependence.py """ import sys, json, subprocess, hashlib, os import numpy as np import census_indep as ci CENSUS = "./outputs/1925/killcensus" def run_c(path, D, primes): r = subprocess.run([CENSUS, path, str(D)] + [str(p) for p in primes], capture_output=True, text=True, check=True) return json.loads(r.stdout) def fold_view(f): return {"p": f["p"], "runs": {int(k): int(v) for k, v in f["runs"].items()}, "edges": int(f["edges"]), "ncomp": int(f["ncomp"]), "maxL": int(f["maxL"]), "nodes": int(f["nodes"])} def main(): path, nsh, out = sys.argv[1], int(sys.argv[2]), sys.argv[3] g = np.fromfile(path, dtype=np.uint16) D = int(g.size) primes = [29, 31] base = run_c(path, D, primes) hist = {int(k): int(v) for k, v in base["hist"].items()} ref = {f["p"]: fold_view(f) for f in base["folds"]} # independent censuses of the true word indep = {} for p in primes: runs_s, edges_s = ci.scipy_runs(g, p) runs_u, edges_u = ci.uf_runs(g, p) indep[p] = {"scipy": ci.runs_to_list(runs_s), "uf": ci.runs_to_list(runs_u), "scipy_edges": edges_s, "uf_edges": edges_u} print(f"p={p} scipy==stream:", indep[p]["scipy"] == ref[p]["runs"], " uf==stream:", indep[p]["uf"] == ref[p]["runs"]) result = {"D": D, "path": path, "hist_sha": hashlib.sha256( json.dumps(hist, sort_keys=True).encode()).hexdigest(), "reference": {str(p): ref[p] for p in primes}, "independent": {str(p): indep[p] for p in primes}, "rotations": [], "shuffles": []} # ---- rotation invariance control ------------------------------------- for rot in [0, 1, 137, D // 3, D - 1, 12345678 % D]: gr = np.roll(g, rot) rp = f"{path}.rot{rot}.bin" gr.tofile(rp) got = run_c(rp, D, primes) os.remove(rp) row = {"rot": int(rot), "match": all(fold_view(f)["runs"] == ref[f["p"]]["runs"] and fold_view(f)["edges"] == ref[f["p"]]["edges"] for f in got["folds"]), "folds": {str(f["p"]): fold_view(f) for f in got["folds"]}} result["rotations"].append(row) print("rotation", rot, "identical census:", row["match"]) # ---- shuffle witness -------------------------------------------------- for seed in range(1, nsh + 1): rng = np.random.default_rng(seed) perm = rng.permutation(D) gs = g[perm] assert gs.size == D h = {} for v in gs.tolist(): h[v] = h.get(v, 0) + 1 assert h == hist, "shuffle changed the histogram" sp = f"{path}.shuf{seed}.bin" gs.tofile(sp) got = run_c(sp, D, primes) os.remove(sp) row = {"seed": seed, "hist_same": True, "folds": {str(f["p"]): fold_view(f) for f in got["folds"]}} result["shuffles"].append(row) # ---- shuffle summary -------------------------------------------------- summary = {} for p in primes: stats = {} for key in ["edges", "ncomp", "maxL"]: vals = [r["folds"][str(p)][key] for r in result["shuffles"]] stats[key] = {"min": int(min(vals)), "max": int(max(vals)), "mean": float(np.mean(vals)), "std": float(np.std(vals)), "reference": ref[p][key]} for L in sorted(set(list(ref[p]["runs"].keys()) + [int(k) for r in result["shuffles"] for k in r["folds"][str(p)]["runs"]])): vals = [r["folds"][str(p)]["runs"].get(L, r["folds"][str(p)]["runs"].get(str(L), 0)) for r in result["shuffles"]] stats[f"n{L}"] = {"min": int(min(vals)), "max": int(max(vals)), "mean": float(np.mean(vals)), "std": float(np.std(vals)), "reference": ref[p]["runs"].get(L, 0)} summary[str(p)] = stats result["shuffle_summary"] = summary result["shuffle_stats"] = { str(p): {k: {kk: (round(vv, 6) if isinstance(vv, float) else vv) for kk, vv in v.items()} for k, v in summary[str(p)].items()} for p in primes} with open(out, "w") as f: json.dump(result, f, indent=2) for p in primes: print(f"\np={p}") for k, v in summary[str(p)].items(): print(f" {k:6s} ref={v['reference']:>12} shuffle min={v['min']:>12} " f"max={v['max']:>12} mean={v['mean']:>16.3f} sd={v['std']:>12.3f}") return 0 if __name__ == "__main__": sys.exit(main())