"""Job #2815 (pursue route 31 rev 14): #664's within-class drift share against a matched Mobius-randomized control. QUESTION (route 31 rev 14 next_step, frozen): with the drift statistic frozen as #664's served contract -- support |c| > 1e-9 (lstar.SUPPORT_TOL), class key (s_U(n), s_Y(n-2)) with FULL smooth parts (lstar.build keymode 'full'), response d = s_g*c - mean{|c| : g} with s_g the sign of the class's first member (lstar.renormalise), share = sum_g sum fit^2 / sum_g sum d^2 with every class of >= 2 members and sxx > 0 fitted by OLS on n (detrend.detrend) -- does the observed share 0.6776 / 0.8019 / 0.8331 at x = 2^14, 2^16, 2^18 exceed a matched Mobius-randomized control? CONTROL (pre-registered, primary 'full'): 200 draws per scale; a draw is eps(d) = +-1 uniform for every squarefree d <= x, eps(1) = 1, eps = 0 off the squarefree d -- exactly the producer's measure() draw. The control field is c~ = C~_L(n) C~_R(n-2) from the producer's coeff_from with mu replaced by eps. The support S and the class partition are the OBSERVED ones (held fixed, as measure() holds its support fixed); on each draw the share is recomputed as a functional of the draw's own values on S: its own first-member signs and its own class means of |c~|. CRITERION (registered before any run): 'field-specific' if the observed share exceeds the control's 95th percentile at all three scales; 'partition artefact' if it lies inside the control's [2.5%, 97.5%] band at all three scales; otherwise 'scale-dependent, no verdict'. Rank = number of draws with share >= observed; z = (obs - mean) / sd. SECONDARY (NOT in the registered design; added because the route's central uncertainty says Y = Z = 1 at all three scales, so the true right factor is Lambda(m) - log m <= 0, a structure any mu re-randomization destroys): 'L_only' eps replaces mu in the left coefficient only, the right factor stays the true C_R; 'R_only' eps replaces mu in the right coefficient only, the left factor stays the true C_L. These locate which factor's randomization moves the share. They are reported beside, never in place of, 'full'. GATES: producer sha; support 2208/2191 at 2^14 (published); observed share = #664's detrend.json 0.6776387465508169 at 2^14 (1e-12) and its published 0.8019 / 0.8331 at 2^16 / 2^18 (5e-5); the vectorised share equals the served contract1894.share_g664 loop on the observed field (1e-12); G4 identity: eps = mu reproduces c exactly. stdout = the JSON artifact (deterministic, seeded); timing goes to stderr. RUN: python control2815.py --x 16384 --x 65536 --x 262144 --draws 200 > control2815.json """ import argparse, hashlib, importlib.util, json, math, sys, time import numpy as np ap = argparse.ArgumentParser() ap.add_argument('--x', type=int, action='append'); ap.add_argument('--draws', type=int, default=200) a = ap.parse_args(); XS = a.x or [16384] PROD = 'src/fibre-sign-lag.py'; PSHA = 'a74825d84e5421eb330d6b54f93029a0aebdc2fd5120fce02ab5d6d857545b56' PUBLISHED = {16384: (0.6776387465508169, 1e-12), 65536: (0.8019, 5e-5), 262144: (0.8331, 5e-5)} SEEDS = {'full': 2815, 'L_only': 28151, 'R_only': 28152} TOL = 1e-9 led = [] def check(tag, ok, detail): led.append({'check': tag, 'pass': bool(ok), 'detail': detail}); print(('PASS ' if ok else 'FAIL ') + tag + ' :: ' + str(detail), file=sys.stderr, flush=True) check('producer_sha', hashlib.sha256(open(PROD, 'rb').read()).hexdigest() == PSHA, PSHA[:16]) spec = importlib.util.spec_from_file_location('fssl', PROD); fssl = importlib.util.module_from_spec(spec); spec.loader.exec_module(fssl) def smooth_part(m, B, facts): # = contract1894.smooth_part = lstar full_smooth_key's value s = 1 for p, e in facts[m]: if p <= B: s *= p ** e return s def share_loop(groups, c, ns): """contract1894.share_g664 on f = c - s_g mean|c| (s_g = first member's sign): the served loop, for the gate.""" num = den = 0.0 for idx in groups: s = float(np.sign(c[idx[0]])); y = c[idx] - s * np.abs(c[idx]).mean() xc = ns[idx].astype(float) - ns[idx].astype(float).mean(); sxx = float((xc * xc).sum()) if len(idx) >= 2 and sxx > 0: b = float((xc * y).sum() / sxx); fit = y.mean() + b * xc; num += float((fit * fit).sum()) den += float((y * y).sum()) return num / den if den else None class Share: """Vectorised #664 share over a fixed partition: sum fit^2 = n*ybar^2 + Sxy^2/Sxx per fitted class.""" def __init__(self, groups, ns, nfield): self.sup = np.concatenate(groups); self.gid = np.concatenate([np.full(len(g), k) for k, g in enumerate(groups)]) self.first = np.array([g[0] for g in groups]); self.G = len(groups) self.cnt = np.bincount(self.gid, minlength=self.G).astype(float) xv = ns[self.sup].astype(float); xbar = np.bincount(self.gid, xv, self.G) / self.cnt self.xc = xv - xbar[self.gid]; self.sxx = np.bincount(self.gid, self.xc * self.xc, self.G) self.fit_ok = (self.cnt >= 2) & (self.sxx > 0) def __call__(self, c): v = c[self.sup]; s = np.sign(c[self.first])[self.gid] mabs = (np.bincount(self.gid, np.abs(v), self.G) / self.cnt)[self.gid] y = v - s * mabs sy = np.bincount(self.gid, y, self.G); sxy = np.bincount(self.gid, self.xc * y, self.G) num = np.where(self.fit_ok, sy * sy / self.cnt + np.divide(sxy * sxy, self.sxx, out=np.zeros(self.G), where=self.fit_ok), 0.0) den = float((y * y).sum()) return float(num.sum()) / den if den else None def summ(v, obs): v = np.asarray(v, float); q = np.quantile(v, [0.025, 0.05, 0.5, 0.95, 0.975]) sd = float(v.std(ddof=1)) return {'draws': int(v.size), 'mean': float(v.mean()), 'sd': sd, 'min': float(v.min()), 'max': float(v.max()), 'q025': float(q[0]), 'q05': float(q[1]), 'median': float(q[2]), 'q95': float(q[3]), 'q975': float(q[4]), 'rank_ge_obs': int(np.sum(v >= obs)), 'p_upper': (1 + int(np.sum(v >= obs))) / (1 + v.size), 'z': (obs - float(v.mean())) / sd if sd > 0 else None, 'above_q95': bool(obs > q[3]), 'inside_band': bool(q[0] <= obs <= q[4])} out = {'instrument': 'control2815.py', 'job': 2815, 'producer_sha': PSHA, 'draws': a.draws, 'seeds': SEEDS, 'scales': {}} for x in XS: t0 = time.time(); b = fssl.build(x); mu = fssl.mu_array(b['hi']).astype(float); ns = b['ns'] CL, CR = fssl.coeff_from(b, 'L', mu), fssl.coeff_from(b, 'R', mu) raw = fssl.c_field(b, CL, CR); c = np.where(np.abs(raw) <= TOL, 0.0, raw) U, Y, facts = b['U'], b['Y'], b['facts'] members = {} for i in np.flatnonzero(c): members.setdefault((smooth_part(int(ns[i]), U, facts), smooth_part(int(ns[i]) - 2, Y, facts)), []).append(int(i)) groups = [np.array(g) for g in members.values()] two = sum(1 for g in groups if np.any(np.sign(c[g]) != np.sign(c[g[0]]))) S = Share(groups, ns, len(c)); obs = S(c); loop = share_loop(groups, c, ns) if x == 16384: check('support_published_2^14', int(np.count_nonzero(raw)) == 2208 and int(np.count_nonzero(c)) == 2191, f'exact {int(np.count_nonzero(raw))} tol {int(np.count_nonzero(c))}') pub, tol = PUBLISHED.get(x, (None, None)) check(f'x={x}_observed_equals_published', pub is None or abs(obs - pub) < tol, f'{obs!r} vs {pub}') check(f'x={x}_vectorised_equals_served_loop', abs(obs - loop) < 1e-12, f'{obs!r} vs {loop!r}') check(f'x={x}_G4_identity_draw', bool(np.allclose(fssl.c_field(b, fssl.coeff_from(b, 'L', mu), fssl.coeff_from(b, 'R', mu)), raw)), 'eps = mu reproduces c') sqf = np.abs(mu) == 1; mask = np.zeros(len(c), bool); mask[S.sup] = True rec = {'x': x, 'U': U, 'Y': Y, 'J': int(len(ns)), 'support': int(mask.sum()), 'classes': len(groups), 'classes_ge2_fitted': int(S.fit_ok.sum()), 'two_signed_observed': two, 'right_factor_le0_on_support': bool(np.all(CR[b['ri']][mask] <= TOL)), 'observed_share': obs, 'controls': {}} for kind, seed in SEEDS.items(): rng = np.random.default_rng(seed); vals = []; zeros = 0; twos = 0 for _ in range(a.draws): eps = (rng.integers(0, 2, size=b['hi'] + 1) * 2 - 1).astype(float); eps[~sqf] = 0.0; eps[1] = 1.0 cl = fssl.coeff_from(b, 'L', eps) if kind in ('full', 'L_only') else CL cr = fssl.coeff_from(b, 'R', eps) if kind in ('full', 'R_only') else CR cd = np.where(mask, fssl.c_field(b, cl, cr), 0.0) zeros += int(np.sum(np.abs(cd[mask]) <= TOL)) twos += sum(1 for g in groups if np.any(np.sign(cd[g]) * np.sign(cd[g[0]]) < 0)) vals.append(S(cd)) r = summ(vals, obs); r['mean_zero_valued_support_per_draw'] = zeros / a.draws; r['mean_two_signed_classes_per_draw'] = twos / a.draws rec['controls'][kind] = r print(f"x={x} {kind}: obs {obs:.6f} mean {r['mean']:.6f} sd {r['sd']:.6f} q95 {r['q95']:.6f} rank {r['rank_ge_obs']} z {r['z']}", file=sys.stderr, flush=True) out['scales'][str(x)] = rec; print(f'x={x} done {time.time() - t0:.1f}s', file=sys.stderr, flush=True) full = [out['scales'][s]['controls']['full'] for s in out['scales']] out['verdict_registered'] = ('field-specific' if all(f['above_q95'] for f in full) else 'partition artefact' if all(f['inside_band'] for f in full) else 'scale-dependent, no verdict') out['ledger'] = led; out['all_gates_pass'] = all(l['pass'] for l in led) print(json.dumps(out, indent=1, sort_keys=True))