#!/usr/bin/env python3 """Job #1446 (route 31 rev 5) -- the registered next_step, executed. THE QUESTION (route 31's next_step, quoted): "Is the large-L positive regime the class geometry re-emerging -- i.e. does the crossover L*(x) scale like the mean smooth-class size (or like the reciprocal of the residual's energy share), rather than being a fixed fraction of |J|?" WHAT THIS FILE DOES, in the order the route names it. (i) Locates L*(x) to within a factor 2 at x = 2^14, 2^16, 2^18 by bisecting the block length on a grid that is finer than the route's "roughly 12 values" where the bracket matters, at offsets 1 and 3 (L = 6, 10, 12, 48 do not divide |J|, so alignment is a real test), reporting R_L^cls and z per cell against the SAME class-preserving within-class permutation null (2000 draws) that return #654 used. L* is located by log-linear interpolation on the sign change of (R - 1), and the bracket is reported as well as the interpolated point. (ii) Computes, per scale, the mean and the quantiles of the smooth-class size |{n in J : s_U(n) = s}| -- both the plain mean over classes and the mean weighted by class membership, since a block of length L covers whole classes only in the second sense -- plus the residual energy share already on the record, and tests whether L* tracks either. (iii) The S-null control of #646: the support and |c| are kept, the support SIGNS are permuted uniformly, and the same class renormalisation and the same L grid are applied to the resulting field. #646's S-null is "uniform permutation of the support signs (destroys ALL sign order)". If a sign-shuffled field with the same class geometry and the same magnitudes shows the same crossover, then L* is block-and-class arithmetic; if it does not, L* is a property of the residual's sign arrangement. INSTRUMENT, UNCHANGED, AND WHERE IT COMES FROM. The field, the class key, the renormalisation c^cls(n) = c(n) - s_C * mean{|c| : class}, the R_L normalisation and the calibration baseline are imported from #654's file (job1438-cls-resid-offset.py, sha 3907b1518b8bc0133b09f1cd2f28a39f3fff62fc 5ded2d522c4016b67cbffce4) and the field comes from #636's accepted producer (pin read from that file's own PRODUCER_SHA constant, never typed here). The ~20 lines of setup are the instrument's own, copied so that this driver can substitute the control field; every definition used is the instrument's. Usage: python lstar.py --producer src/fibre-sign-lag.py --xs 16384,65536,262144 --draws 2000 --out out/lstar.json """ import argparse import hashlib import importlib.util import json import pathlib import sys import time import numpy as np HERE = pathlib.Path(__file__).parent SUPPORT_TOL = 1e-9 # the instrument's grid, plus the cells that tighten the bracket the route asks about BASE_GRID = [(4, 0), (8, 0), (16, 0), (32, 0), (64, 0), (128, 0), (256, 0), (6, 1), (6, 3), (10, 1), (10, 3), (12, 1), (12, 3), (48, 1), (48, 3), (8, 1), (8, 3), (16, 1), (16, 3), (64, 1), (64, 3), (128, 1), (128, 3), (96, 1), (96, 3), (192, 1), (192, 3), (256, 1), (256, 3), (384, 1), (384, 3), (512, 1), (512, 3), (56, 1), (56, 3), (160, 1), (160, 3), (224, 1), (224, 3)] SNULL_DRAWS = 200 SIGN_OFFSETS = (1, 3) def load_module(path, name): spec = importlib.util.spec_from_file_location(name, str(path)) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod def build(ins, producer_path, x, keymode="full"): """The instrument's own setup, verbatim in its definitions, so a control field can be swapped in.""" fssl = ins.load_producer(producer_path) b = fssl.build(x) mu = fssl.mu_array(b["hi"]).astype(float) c = fssl.c_field(b, fssl.coeff_from(b, "L", mu), fssl.coeff_from(b, "R", mu)) c = np.where(np.abs(c) <= SUPPORT_TOL, 0.0, c) ns = b["ns"] U, Y = b["U"], b["Y"] facts = b["facts"] keys, cls_sign, cls_abs, viol = {}, {}, {}, [] for i, n in enumerate(ns): n = int(n) if c[i] == 0: continue k = (ins.full_smooth_key(n, U, facts), ins.full_smooth_key(n - 2, Y, facts)) keys[i] = k if k not in cls_sign: cls_sign[k] = float(np.sign(c[i])) cls_abs[k] = [abs(float(c[i])), 1] else: cls_abs[k][0] += abs(float(c[i])); cls_abs[k][1] += 1 if float(np.sign(c[i])) != cls_sign[k]: viol.append(n) members = {} for i, k in keys.items(): members.setdefault(k, []).append(i) return {"fssl": fssl, "b": b, "c": c, "ns": ns, "U": U, "Y": Y, "facts": facts, "keys": keys, "cls_sign": cls_sign, "cls_abs": cls_abs, "members": members, "viol": viol} def renormalise(st, field): """The instrument's renormalisation, applied to ANY field on the same support/classes.""" resid = field.copy() for k, idxs in st["members"].items(): sc = st["cls_sign"][k] mn = st["cls_abs"][k][0] / st["cls_abs"][k][1] for i in idxs: resid[i] = field[i] - sc * mn return resid def r_curve(ins, resid, cells, resid_sq): out = {} for (L, off) in cells: r, nb = ins.rl(resid, L, off, resid_sq) out["%d:%d" % (L, off)] = {"R": r, "blocks": nb} return out def cross(ins, curve, off): """Locate the R = 1 crossing by log-linear interpolation, and report the bracket.""" cells = sorted((int(k.split(":")[0]), v["R"]) for k, v in curve.items() if int(k.split(":")[1]) == off and v["R"] is not None) pts = [(L, r) for L, r in cells] for (L1, r1), (L2, r2) in zip(pts, pts[1:]): if (r1 - 1.0) * (r2 - 1.0) <= 0 and r1 != r2: # log L against R t = (1.0 - r1) / (r2 - r1) Lx = L1 * (L2 / L1) ** t return {"bracket": [L1, L2], "R_bracket": [r1, r2], "L_star_loginterp": Lx} return {"bracket": None, "R_bracket": None, "L_star_loginterp": None} def class_stats(members, M): sizes = np.array([len(v) for v in members.values()], dtype=float) if sizes.size == 0: return {} wsum = float((sizes * sizes).sum()) # sum_C |C|^2 return {"n_classes": int(sizes.size), "members_in_classes": float(sizes.sum()), "mean_class_size": float(sizes.mean()), "element_weighted_mean_class_size": wsum / float(sizes.sum()), "median_class_size": float(np.median(sizes)), "q90_class_size": float(np.quantile(sizes, 0.90)), "q99_class_size": float(np.quantile(sizes, 0.99)), "max_class_size": float(sizes.max()), "singleton_classes": int((sizes == 1).sum()), "frac_elements_in_singleton_classes": float(sizes[sizes == 1].sum() / sizes.sum()), "frac_classes_singleton": float((sizes == 1).sum() / sizes.size)} 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("--out", required=True) a = ap.parse_args() ins = load_module(a.instrument, "ins") xs = [int(t) for t in a.xs.split(",")] out = {"tool": "lstar/1", "route_id": 31, "job": 1446, "instrument": { "path": a.instrument, "sha256": hashlib.sha256(pathlib.Path(a.instrument).read_bytes()).hexdigest()}, "producer": {"path": a.producer, "sha256": hashlib.sha256(pathlib.Path(a.producer).read_bytes()).hexdigest(), "pin_from_instrument": ins.PRODUCER_SHA}, "draws": a.draws, "s_null_draws": SNULL_DRAWS, "grid": BASE_GRID, "scales": {}} t0 = time.time() for x in xs: st = build(ins, a.producer, x) M = len(st["c"]) resid = renormalise(st, st["c"]) resid_sq = float((resid * resid).mean()) mean_sq = float((st["c"] * st["c"]).mean()) energy = {"mean_sq_c": mean_sq, "mean_sq_resid": resid_sq, "resid_share": None if mean_sq == 0 else resid_sq / mean_sq, "class_map_energy_share": None if mean_sq == 0 else 1.0 - resid_sq / mean_sq} cells = BASE_GRID obs = r_curve(ins, resid, cells, resid_sq) # ---- null: class-preserving within-class permutation, the instrument's own null ---- rng = np.random.default_rng(1421) cls_idx = [np.array(v) for v in st["members"].values()] acc = {k: [] for k in obs} for _ in range(a.draws): perm = resid.copy() for idxs in cls_idx: perm[idxs] = perm[idxs][rng.permutation(idxs.size)] for k in obs: L, off = (int(t) for t in k.split(":")) r, nb = ins.rl(perm, L, off, resid_sq) if r is not None: acc[k].append(r) for k in obs: v = np.asarray(acc[k], dtype=float) r = obs[k]["R"] obs[k]["null"] = ({"draws": int(v.size), "mean": float(v.mean()), "sd": float(v.std(ddof=1))} if v.size > 1 else {"draws": int(v.size)}) if v.size > 1 and v.std(ddof=1) > 0 and r is not None: obs[k]["z"] = (r - float(v.mean())) / float(v.std(ddof=1)) obs[k]["rank_p_one_sided"] = float((1 + int(np.sum(v <= r))) / (1 + v.size)) # ---- (iii) the S-null control: permute the support signs, keep support and |c| ---- sup = np.nonzero(st["c"])[0] abs_sup = np.abs(st["c"][sup]) s_acc = {k: [] for k in obs} s_star = [] for d in range(SNULL_DRAWS): sgn = rng.choice([-1.0, 1.0], size=sup.size) field = np.zeros_like(st["c"]) field[sup] = sgn * abs_sup rfield = renormalise(st, field) rq = float((rfield * rfield).mean()) if rq == 0: continue cur = {} for k in obs: L, off = (int(t) for t in k.split(":")) r, nb = ins.rl(rfield, L, off, rq) cur[k] = r if r is not None: s_acc[k].append(r) cr = cross(ins, {k: {"R": v, "blocks": None} for k, v in cur.items()}, 1) if cr["L_star_loginterp"] is not None: s_star.append(cr["L_star_loginterp"]) s_null = {} for k in obs: v = np.asarray(s_acc[k], dtype=float) s_null[k] = ({"draws": int(v.size), "mean": float(v.mean()), "sd": float(v.std(ddof=1))} if v.size > 1 else {"draws": int(v.size)}) if v.size > 1 and v.std(ddof=1) > 0 and obs[k]["R"] is not None: s_null[k]["z_obs_vs_snull"] = (obs[k]["R"] - float(v.mean())) / float(v.std(ddof=1)) out["scales"][str(x)] = { "x": x, "J": M, "U": st["U"], "Y": st["Y"], "support": int(np.count_nonzero(st["c"])), "classes": len(st["members"]), "one_signed": not st["viol"], "energy": energy, "class_stats": class_stats(st["members"], M), "cells": obs, "s_null": s_null, "s_null_L_star": ({"draws_with_crossing": len(s_star), "L_star_mean": float(np.mean(s_star)) if s_star else None, "L_star_min": float(np.min(s_star)) if s_star else None, "L_star_max": float(np.max(s_star)) if s_star else None}), "L_star": {str(off): cross(ins, obs, off) for off in (0,) + SIGN_OFFSETS}, "max_L_with_z_le_m3": {str(off): (lambda ls: max(ls) if ls else None)( [int(k.split(":")[0]) for k, v in obs.items() if int(k.split(":")[1]) == off and v.get("z") is not None and v["z"] <= -3.0]) for off in SIGN_OFFSETS}, } s = out["scales"][str(x)] print("x=%-8d J=%-7d U=%-3d classes=%-6d support=%-7d L*=%s maxL(z<=-3)=%s snull_L*=%s [%.1fs]" % (x, M, st["U"], s["classes"], s["support"], json.dumps(s["L_star"]["1"]["bracket"]), json.dumps(s["max_L_with_z_le_m3"]), None if not s["s_null_L_star"]["L_star_mean"] else round(s["s_null_L_star"]["L_star_mean"], 1), time.time() - t0)) out["runtime_s"] = round(time.time() - t0, 2) 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())