#!/usr/bin/env python3 r"""Job #1446 (route 31 rev 5) -- is the large-L positive regime a within-class DRIFT of |c| in n? WHY THIS TEST. exch.py splits R_L^cls exactly (see its header) and gives three independent fingerprints of what the rise is: * D_L carries the rise: the sign-free within-class energy is 12.2x its iid value at (2^18, L=512) while the observed R_L is 6.8x, and the class-sign permutation null has mean D_L -- so the rise is not the class-sign arrangement. (See report; exch.json cells, D_share and z_vs_class_sign_null.) * W(m), the confound-free within-class block-sum ratio, is 10-12 at m = 16 and 122-163 at m = 256, at EVERY scale, growing like m^0.9 -- almost linearly in m. * R_L computed inside each contiguous THIRD of J is U-shaped in J and strongly scale-ordered: at (2^18, L = 512) the thirds are 10.81 / 0.95 / 8.76, and the middle third is *below* 1 at every L (0.28 at L = 64). A statistic that is large at the two ends of a range and cancels in the middle is the signature of a systematic drift whose partial sums change sign, not of any stationary arrangement. THE CANDIDATE, stated exactly. d_i = |c_i| - mean{|c| : class of i}; the class is the pair (s_U(n), s_U(n-2)). Within one class the cofactor m = n / s_U(n) is proportional to n, so "d drifts linearly in n inside its class" IS "|c| depends systematically on the cofactor m", and the class-mean subtraction cannot remove it -- it only centres it over the whole class, which is what makes the partial sums positive in the first part of the class's range and negative in the last, i.e. exactly the observed U. Prediction: remove the per-class linear drift and the whole large-L regime goes away while every short-L cell is untouched. WHAT IS COMPUTED (all exactly, no fitted global parameter -- the fit is per class, 2 coefficients, and every class keeps its own identity): T1 per-class OLS slope of d against n, its t-like significance, the sign split, and the exact share of sum_J d^2 explained by the within-class linear trend (orthogonality of OLS residuals is a gate, not an assumption). T2 R'_L on the detrended field d' = d - OLS fit, same grid, same normalisation convention (denominator = mean_J d'^2) -- with the OLS residual sums as a gate (sum_C d'_i = 0 exactly, and sum_C (n_i - nbar_C) d'_i = 0 exactly, per class). T3 L* before and after, on the same grid and from the same interpolation. T4 thirds of J before and after -- the U must flatten. T5 W(m) before and after -- the m^0.9 growth must flatten toward 1. T6 the class-sign permutation null on the detrended field. NC negative controls: (a) the same detrending applied to an iid-within-class synthetic field must leave R at ~1 -- the operation must not manufacture a result; (b) a synthetic field carrying a planted per-class linear drift must show R > 1 before and ~1 after; (c) the instrument's own within-class permutation null is detrended as well (it cannot gain a rise from the operation); (d) the dead-instrument probe (alternating signs) must stay << 1. Usage: python detrend.py --producer src/fibre-sign-lag.py --xs 16384,65536,262144 --draws 2000 \ --out out/detrend.json [--selftest] """ import argparse import hashlib import importlib.util import json import pathlib import sys import time import numpy as np HERE = pathlib.Path(__file__).parent SEED = 20250916 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 r_cells(ins, f, mean_sq, grid): out = {} for (L, off) in grid: r, nb = ins.rl(f, L, off, mean_sq) if nb >= 2: out["%d:%d" % (L, off)] = {"R": r, "blocks": nb} return out def cross(grid_cells, off): cells = sorted((int(k.split(":")[0]), v["R"]) for k, v in grid_cells.items() if int(k.split(":")[1]) == off and v["R"] is not None) for (L1, r1), (L2, r2) in zip(cells, cells[1:]): if (r1 - 1.0) * (r2 - 1.0) <= 0 and r1 != r2: t = (1.0 - r1) / (r2 - r1) return {"bracket": [L1, L2], "R_bracket": [r1, r2], "L_star_loginterp": L1 * (L2 / L1) ** t} return {"bracket": None, "R_bracket": None, "L_star_loginterp": None} def r_seg(f, mean_sq, s, e, L, off): n = e - s if n < off + 2 * L: return None sub = f[s + off:e] nb = len(sub) // L if nb < 2 or mean_sq == 0: return None seg = sub[:nb * L].reshape(nb, L).sum(axis=1) return float((seg * seg).mean() / (L * mean_sq)) def wof(d, members, ms): out = {} for m in ms: num = den = 0.0 nch = 0 for idx in members: v = d[idx] k = v.size // m if k < 1: continue used = v[:k * m] ch = used.reshape(k, m).sum(axis=1) num += float((ch * ch).sum()) den += float((used * used).sum()) nch += k out[str(m)] = {"W": (num / den) if den > 0 else None, "chunks": nch} return out def detrend(d, nsv, members): """Per-class OLS of d on n. Every array returned is aligned with `members` (length nclasses), so a class that cannot be fitted contributes a zero slope and zero trend energy rather than shortening the array.""" dp = d.copy() n_c = len(members) slopes = np.zeros(n_c) tvals = np.zeros(n_c) wts = np.zeros(n_c) num = den = 0.0 err_sum = err_cov = 0.0 fitted = 0 for ci, idx in enumerate(members): x = nsv[idx].astype(float) y = d[idx] xc = x - x.mean() sxx = float((xc * xc).sum()) # size 2 is fitted exactly (2 points, 2 coefficients) -- mean-centring it instead would leave # half the |c| difference behind and under-remove the drift; size 1 has d == 0 identically # (mean{|c| : class} = |c| for a singleton), so it needs no subtraction at all. if idx.size >= 2 and sxx > 0: b = float((xc * y).sum() / sxx) fit = float(y.mean()) + b * xc slopes[ci] = b wts[ci] = float((fit * fit).sum()) resid_sd = float(np.sqrt(((y - fit) ** 2).sum() / max(1, idx.size - 2))) if resid_sd > 0 and idx.size >= 3: tvals[ci] = b / (resid_sd / np.sqrt(sxx)) fitted += 1 else: fit = np.full(idx.size, 0.0) if idx.size else y dp[idx] = y - fit num += float((fit * fit).sum()) den += float((y * y).sum()) if idx.size: err_sum = max(err_sum, abs(float(dp[idx].sum()))) err_cov = max(err_cov, abs(float((xc * dp[idx]).sum()))) return dp, slopes, tvals, wts, num, den, {"classes_fitted": fitted, "max_abs_class_sum_detrended": err_sum, "max_abs_class_n_covariance": err_cov} def analyse(ins, lst, producer, x, grid, draws, rng): st = lst.build(ins, producer, x) c = st["c"] M = len(c) nsv = np.asarray(st["ns"]) resid = lst.renormalise(st, c) keys = list(st["members"].keys()) ncls = len(keys) members = [np.asarray(st["members"][k], dtype=np.int64) for k in keys] cid = np.full(M, -1, dtype=np.int64) d = np.zeros(M) for ci, (k, idx) in enumerate(zip(keys, members)): cid[idx] = ci d[idx] = resid[idx] * st["cls_sign"][k] mean_sq = float((resid * resid).mean()) sign_vec = np.array([st["cls_sign"][k] for k in keys], dtype=float) dp, slopes, tvals, wts, fit_ss, d_ss, gates = detrend(d, nsv, members) gates["trend_energy_share_of_d"] = fit_ss / d_ss if d_ss else None # every class with >= 2 members is now fitted, so BOTH orthogonality conditions are forced for # every class and the gate is a real test of the arithmetic rather than of the criterion gates["ols_residual_orthogonal"] = (gates["max_abs_class_sum_detrended"] < 1e-9 and gates["max_abs_class_n_covariance"] < 1e-3) gates["classes_unfitted"] = ncls - gates["classes_fitted"] gates["classes_with_ge3"] = int(sum(1 for idx in members if idx.size >= 3)) gates["classes_with_ge2"] = int(sum(1 for idx in members if idx.size >= 2)) gates["energy_share_in_unfitted_classes"] = float( sum(float((d[idx] ** 2).sum()) for ci, idx in enumerate(members) if not (idx.size >= 2 and float(((nsv[idx].astype(float) - nsv[idx].mean()) ** 2).sum()) > 0)) / d_ss) if d_ss else None resid_p = np.zeros(M) for ci, (k, idx) in enumerate(zip(keys, members)): resid_p[idx] = st["cls_sign"][k] * dp[idx] mean_sq_p = float((resid_p * resid_p).mean()) # sign split of the trend, weighted by each class's own trend energy pos = float(wts[slopes > 0].sum()) neg = float(wts[slopes < 0].sum()) cells_p = r_cells(ins, resid_p, mean_sq_p, grid) cells_b = r_cells(ins, resid, mean_sq, grid) thirds = {} for L in (64, 128, 256, 512): a, b = [], [] for t in range(3): s = (M // 3) * t e = M if t == 2 else (M // 3) * (t + 1) a.append(r_seg(resid, mean_sq, s, e, L, 1)) b.append(r_seg(resid_p, mean_sq_p, s, e, L, 1)) thirds[str(L)] = {"before": a, "after": b} # class-sign permutation null on the DETRENDED field (|field| = |resid_p| elementwise) acc = {k: [] for k in cells_p} for _ in range(draws): mult = rng.choice([-1.0, 1.0], size=ncls) * sign_vec f = resid_p * mult[cid] for k in cells_p: L, off = (int(t) for t in k.split(":")) r, _ = ins.rl(f, L, off, mean_sq_p) if r is not None: acc[k].append(r) for k in cells_p: v = np.asarray(acc[k], dtype=float) if v.size > 1: mu, sd = float(v.mean()), float(v.std(ddof=1)) cells_p[k]["class_sign_null"] = {"draws": int(v.size), "mean": mu, "sd": sd} cells_p[k]["z_vs_class_sign_null"] = (cells_p[k]["R"] - mu) / sd if sd > 0 else None 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_detrended": mean_sq_p, "gates": gates, "trend": {"classes_fitted": gates.pop("classes_fitted"), "slope_mean": float(slopes.mean()) if slopes.size else None, "frac_classes_positive_slope": float((slopes > 0).mean()) if slopes.size else None, "trend_energy_pos_slope": pos, "trend_energy_neg_slope": neg, "t_gt2": int(np.sum(np.abs(tvals) > 2)), "t_gt3": int(np.sum(np.abs(tvals) > 3)), "t_n": int(tvals.size), "median_abs_t": float(np.median(np.abs(tvals))) if tvals.size else None}, "cells_before": cells_b, "cells_after": cells_p, "L_star_before": {str(o): cross(cells_b, o) for o in (0, 1, 3)}, "L_star_after": {str(o): cross(cells_p, o) for o in (0, 1, 3)}, "thirds_offset1": thirds, "W_before": wof(d, members, (4, 16, 64, 256)), "W_after": wof(dp, members, (4, 16, 64, 256))} def _trend_energy(d, nsv, idx): x = nsv[idx].astype(float) y = d[idx] xc = x - x.mean() sxx = float((xc * xc).sum()) if idx.size < 3 or sxx == 0: return 0.0 b = float((xc * y).sum() / sxx) a = float(y.mean()) fit = a + b * xc return float((fit * fit).sum()) def _cells_before(ins, resid, mean_sq, grid): return r_cells(ins, resid, mean_sq, grid) def selftest(ins, lst, producer): """NC(a): detrending an iid-within-class field must not create a rise. NC(b): a planted per-class linear drift must show R > 1 before and ~1 after.""" rng = np.random.default_rng(11) ok = {} M, ncls = 131072, 60 nsv = np.arange(1, M + 1, dtype=np.int64) cid = rng.integers(0, ncls, size=M) members = [np.nonzero(cid == ci)[0] for ci in range(ncls)] grid = [(4, 0), (16, 1), (64, 1), (256, 1), (512, 3)] # (a) iid within class di = rng.normal(size=M) for idx in members: di[idx] -= di[idx].mean() mq = float((di * di).mean()) ri = r_cells(ins, di, mq, grid) dp = detrend(di, nsv, members)[0] mqp = float((dp * dp).mean()) rp = r_cells(ins, dp, mqp, grid) ok["NC_a_iid_before_max_dev"] = max(abs(v["R"] - 1.0) for v in ri.values()) ok["NC_a_iid_after_max_dev"] = max(abs(v["R"] - 1.0) for v in rp.values()) # (b) planted drift dt = di.copy() for idx in members: x = nsv[idx].astype(float) xc = (x - x.mean()) / max(1.0, float(np.abs(x).max())) dt[idx] = dt[idx] + 3.0 * xc * float(np.std(di[idx])) # 3 sd of drift across the class for idx in members: dt[idx] -= dt[idx].mean() mqt = float((dt * dt).mean()) rt = r_cells(ins, dt, mqt, grid) dp2, _, _, _, fit_ss, d_ss, _ = detrend(dt, nsv, members) mqp2 = float((dp2 * dp2).mean()) rp2 = r_cells(ins, dp2, mqp2, grid) ok["NC_b_planted_R_512_before"] = rt["512:3"]["R"] ok["NC_b_planted_R_512_after"] = rp2["512:3"]["R"] ok["NC_b_drift_energy_share"] = fit_ss / d_ss # the comparison threshold is the sampling sd of R itself, sqrt(2/blocks): 0.088 for the L=512 # cell of this synthetic M, so 0.15 is ~1.7 sd and is the right scale for "did not move" good = (ok["NC_a_iid_before_max_dev"] < 0.15 and ok["NC_a_iid_after_max_dev"] < 0.15 and rt["512:3"]["R"] > 1.5 and abs(rp2["512:3"]["R"] - 1.0) < 0.15) return {"ok": bool(good), "checks": {k: (round(v, 6) if isinstance(v, float) else v) for k, v in ok.items()}} 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": "detrend/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()}, "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": selftest(ins, lst, a.producer), "scales": {}} 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 print("x=%-8d J=%-7d trend share=%.4f L*before=%s L*after=%s R512:1 %.3f -> %.3f [%.1fs]" % (x, s["J"], s["gates"]["trend_energy_share_of_d"], json.dumps(s["L_star_before"]["1"]["bracket"]), json.dumps(s["L_star_after"]["1"]["bracket"]), s["cells_before"]["512:1"]["R"], s["cells_after"]["512:1"]["R"], 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())