#!/usr/bin/env python3 r"""Job #1446 (route 31 rev 5) -- WHAT the large-L positive regime is made of. The route's registered question is whether L*(x) is the class geometry re-emerging (L* tracking the mean smooth-class size, or 1/residual energy share) rather than a fixed fraction of |J|. lstar.py measures L* and the class-size statistics that question names. THIS file asks the prior question that lstar.py cannot: the statistic it applies to is R_L^cls = R_L(c - s_C mean{|c| : class}), and on the one-signed classes that #1438 verified, the residual is exactly resid_i = s_{C(i)} * d_i , d_i = |c_i| - mean{|c| : class of i} (an identity, checked below as a gate). Substituting into the block sum S_b = sum_{i in b} resid_i and squaring gives an EXACT two-term split with no approximation and no fitted quantity: S_b^2 = sum_C PS_{C,b}^2 + 2 sum_{C 0 else None, "chunks": nchunks, "elements_used": sum((im.size // m) * m for im in members)} return out def analyse(ins, lst, producer, x, grid, draws, rng): st = lst.build(ins, producer, x) c = st["c"] M = len(c) resid = lst.renormalise(st, c) keys = list(st["members"].keys()) ncls = len(keys) cid = np.full(M, -1, dtype=np.int64) d = np.zeros(M) members = [] for ci, k in enumerate(keys): idx = np.asarray(st["members"][k], dtype=np.int64) # ascending n members.append(idx) cid[idx] = ci d[idx] = resid[idx] * st["cls_sign"][k] sign_vec = np.array([st["cls_sign"][k] for k in keys], dtype=float) mean_sq = float((resid * resid).mean()) # ---- gates on the identity resid_i = s_{C(i)} * d_i , d_i = |c_i| - mean{|c| : class} ---- gate = {} err_ident = 0.0 for k, idx in zip(keys, members): mn = st["cls_abs"][k][0] / st["cls_abs"][k][1] err_ident = max(err_ident, float(np.max(np.abs(d[idx] - (np.abs(c[idx]) - mn))))) err_ident = max(err_ident, float(np.max(np.abs(resid[idx] - st["cls_sign"][k] * d[idx])))) gate["identity_d_max_abs_err"] = err_ident gate["identity_holds_exactly"] = err_ident < 1e-12 sums = np.array([float(d[idx].sum()) for idx in members]) gate["max_abs_class_sum_d"] = float(np.max(np.abs(sums))) gate["class_sums_zero"] = gate["max_abs_class_sum_d"] < 1e-9 cells = {} for (L, off) in grid: nb = (M - off) // L if nb < 2: continue r_ref, nb_ref = ins.rl(resid, L, off, mean_sq) valid = np.arange(off, off + nb * L) bi = (valid - off) // L S = resid[valid].reshape(nb, L).sum(axis=1) Dsum = 0.0 recon = np.zeros(nb) cls_seen = 0 for ci, idx in enumerate(members): m = idx[(idx >= off) & (idx < off + nb * L)] if m.size == 0: continue cls_seen += 1 ps = np.bincount(bi[m - off], weights=d[m], minlength=nb) Dsum += float((ps * ps).sum()) recon += sign_vec[ci] * ps sumS2 = float((S * S).sum()) R = sumS2 / (nb * L * mean_sq) D_L = Dsum / nb X_L = (sumS2 - Dsum) / nb order = np.sort(S * S)[::-1] tot_sq = float(order.sum()) cells["%d:%d" % (L, off)] = { "L": L, "off": off, "blocks": nb, "R": R, "R_from_instrument": r_ref, "blocks_from_instrument": nb_ref, "R_match_instrument": (r_ref is not None and abs(R - r_ref) < 1e-12), "D_L": D_L, "X_L": X_L, "D_share": D_L / (D_L + X_L) if (D_L + X_L) else None, "identity_split_max_abs_err": float(np.max(np.abs(recon - S))), "classes_touching_blocks": int(cls_seen), "mean_classes_per_block": cls_seen / nb, "top1pct_share_of_sumS2": float(order[:max(1, nb // 100)].sum() / tot_sq) if tot_sq else None, "top10pct_share_of_sumS2": float(order[:max(1, nb // 10)].sum() / tot_sq) if tot_sq else None, "z_vs_class_sign_null": None, "class_sign_null": None, } # ---- class-sign permutation null: |field| = |resid| elementwise, class sums still zero ---- ck = list(cells.keys()) acc = {k: [] for k in ck} for _ in range(draws): mult = rng.choice([-1.0, 1.0], size=ncls) * sign_vec field = resid * mult[cid] for k in ck: L, off = (int(t) for t in k.split(":")) r, _ = ins.rl(field, L, off, mean_sq) if r is not None: acc[k].append(r) for k in ck: v = np.asarray(acc[k], dtype=float) if v.size > 1: mu, sd = float(v.mean()), float(v.std(ddof=1)) cells[k]["class_sign_null"] = {"draws": int(v.size), "mean": mu, "sd": sd} cells[k]["z_vs_class_sign_null"] = (cells[k]["R"] - mu) / sd if sd > 0 else None # ---- thirds of J, at offset 1, and the within-class ordering statistic ---- thirds = {} for L in (64, 128, 256, 512): rs = [] for t in range(3): s = (M // 3) * t e = M if t == 2 else (M // 3) * (t + 1) rs.append(r_seg(resid, mean_sq, s, e, L, 1)) if all(r is not None for r in rs): thirds[str(L)] = [round(r, 6) for r in rs] return {"x": x, "J": M, "U": st["U"], "Y": st["Y"], "classes": ncls, "support": int(np.count_nonzero(c)), "one_signed": not st["viol"], "mean_sq_resid": mean_sq, "mean_sq_d": float((d * d).mean()), "gates": gate, "cells": cells, "within_class_ordering": within_class_ordering(d, members, (4, 16, 64, 256)), "thirds_R_offset1": thirds} def selftest(ins, lst, producer): """Small synthetic checks of every piece of this file, on data with known answers.""" rng = np.random.default_rng(7) ok = [] # (a) the split identity on a random field with a synthetic class map M, ncls = 20000, 37 cid = rng.integers(0, ncls, size=M) while len(np.unique(cid)) < ncls: cid = rng.integers(0, ncls, size=M) d = rng.normal(size=M) for ci in range(ncls): d[cid == ci] -= d[cid == ci].mean() # exact per-class zero sum sign_vec = rng.choice([-1.0, 1.0], size=ncls) resid = sign_vec[cid] * d mean_sq = float((resid * resid).mean()) errs = [] for (L, off) in [(4, 0), (8, 1), (16, 3), (64, 1)]: nb = (M - off) // L valid = np.arange(off, off + nb * L) bi = (valid - off) // L S = resid[valid].reshape(nb, L).sum(axis=1) recon = np.zeros(nb) for ci in range(ncls): m = np.nonzero(cid == ci)[0] m = m[(m >= off) & (m < off + nb * L)] if m.size == 0: continue recon += sign_vec[ci] * np.bincount(bi[m - off], weights=d[m], minlength=nb) errs.append(float(np.max(np.abs(recon - S)))) r = float((S * S).mean() / (L * mean_sq)) r_ref, _ = ins.rl(resid, L, off, mean_sq) ok.append(abs(r - r_ref) < 1e-12) ok.append(max(errs) < 1e-9) # (b) the class-sign permutation null must leave every class sum identically zero mult = rng.choice([-1.0, 1.0], size=ncls) field = resid * mult[cid] worst = 0.0 for ci in range(ncls): worst = max(worst, abs(float(field[cid == ci].sum()))) ok.append(worst < 1e-9) # (c) W(m) = 1 for iid-within-class d, and > 1 for a monotone trend within class members = [np.nonzero(cid == ci)[0] for ci in range(ncls)] w_iid = within_class_ordering(d, members, (4, 16))["16"]["W"] trend = np.zeros(M) for ci in range(ncls): m = members[ci] v = np.linspace(-1.0, 1.0, m.size) v -= v.mean() trend[m] = v w_tr = within_class_ordering(trend, members, (4, 16))["16"]["W"] ok.append(0.7 < w_iid < 1.4) ok.append(w_tr > 3.0) return {"ok": all(ok), "checks": {"split_identity_and_R": all(ok[:5]), "null_preserves_class_sums": ok[5], "W_iid_approx_1": w_iid, "W_trend_gt_3": w_tr}, "detail": ok} def main(): ap = argparse.ArgumentParser() ap.add_argument("--producer", required=True) ap.add_argument("--xs", default="16384,65536,262144") ap.add_argument("--draws", type=int, default=2000) ap.add_argument("--instrument", default=str(HERE / "src" / "job1438-cls-resid-offset.py")) ap.add_argument("--driver", default=str(HERE / "lstar.py")) ap.add_argument("--out") ap.add_argument("--selftest", action="store_true") a = ap.parse_args() ins = load_module(a.instrument, "ins") lst = load_module(a.driver, "lst") if a.selftest: res = selftest(ins, lst, a.producer) print(json.dumps(res, indent=1, sort_keys=True)) return 0 if res["ok"] else 1 xs = [int(t) for t in a.xs.split(",")] out = {"tool": "exch/1", "route_id": 31, "job": 1446, "instrument": {"path": a.instrument, "sha256": hashlib.sha256(pathlib.Path(a.instrument).read_bytes()).hexdigest()}, "driver": {"path": a.driver, "sha256": hashlib.sha256(pathlib.Path(a.driver).read_bytes()).hexdigest()}, "within_class_ordering_note": "W(m) has expectation exactly 1 for iid-within-class d; " "it exceeds 1 iff d is positively correlated within class", "producer": {"path": a.producer, "sha256": hashlib.sha256(pathlib.Path(a.producer).read_bytes()).hexdigest(), "pin_from_instrument": ins.PRODUCER_SHA}, "draws": a.draws, "grid": lst.BASE_GRID, "selftest": None, "scales": {}} out["selftest"] = selftest(ins, lst, a.producer) t0 = time.time() rng = np.random.default_rng(SEED) for x in xs: s = analyse(ins, lst, a.producer, x, lst.BASE_GRID, a.draws, rng) out["scales"][str(x)] = s big = max((v for v in s["cells"].values() if v["R"] > 1), key=lambda v: v["R"], default=None) print("x=%-8d J=%-7d classes=%-5d W16=%s max-R cell=%s D_share=%s z_csn=%s [%.1fs]" % (x, s["J"], s["classes"], s["within_class_ordering"]["16"]["W"], None if big is None else "%d:%d R=%.2f" % (big["L"], big["off"], big["R"]), None if big is None else round(big["D_share"], 4), None if big is None else round(big["z_vs_class_sign_null"], 2), time.time() - t0)) out["runtime_s"] = round(time.time() - t0, 2) if a.out: pathlib.Path(a.out).parent.mkdir(parents=True, exist_ok=True) pathlib.Path(a.out).write_text(json.dumps(out, indent=1, sort_keys=True), encoding="utf-8", newline="\n") print("wrote", a.out, out["runtime_s"], "s") return 0 if __name__ == "__main__": sys.exit(main())