# -*- coding: utf-8 -*- """Job #1420 — RESCUE on route 31: does a CONTROL-FREE block-variance ratio measure local cancellation of the singleton-fibre coefficient c, or does it hit the same wall as #638's mismatched control? WHY THIS EXPERIMENT EXISTS. Route 31 asks WHERE the proved aggregate cancellation of alpha(n) = C_{U,V}(n) C_{Y,Z}(n-2) lives: inside short blocks (local) or only over J_x (aggregate). Return #636 measured it with a lag-h disagreement rate against a control that re-randomizes mu; #638 proved (identity (I)) that with EQUAL cutoffs each factor's SIGN is a deterministic function of the B-smooth part, while the randomized control does not collapse -- so that instrument's signal is a property of the control's construction at EVERY scale. #638's own `revisit_when` names two possible rescues, and this file tests the first one that needs no new scale: r_L(x) = mean over blocks of length L of (sum_{n in block} c(n))^2 / sum_{n in J_x} c(n)^2 = the "control-free statistic of the true field". It needs only c, so a mismatched control cannot inject a signal by construction. That is the sense in which it AVOIDS #638's obstruction. BUT A RESCUE MUST BE TESTED, NOT JUST PROPOSED. Three ways this alternative can still fail, each given its own gate below: (a) BASELINE. As written in the revisit note the ratio is NOT calibrated: for an uncorrelated field E[(sum_block c)^2] = L * Var, and sum_J c^2 = M * Var, so the ratio is ~ L/M = 1/N_b, not 1. An uncalibrated r_L confuses "no cancellation" with "few blocks". This file uses the calibrated form R_L = [ (1/N_b) sum_blocks (sum_block c)^2 ] / [ (1/M) sum_J c^2 ], baseline 1, and MEASURES the baseline on the nulls rather than asserting it (gate CAL). (b) DEAD INSTRUMENT. A statistic that cannot see local anti-correlation in a field that HAS it would return "no local structure" for any input. Positive control gate PC: an alternating-sign field on the true support must give R_L << 1. (c) THE REAL HAZARD, and the one this job is about. c is 68% zero and its support and magnitudes are themselves highly structured (near-deterministic in n mod small primes), and by (I) its SIGN is a deterministic function of the U-smooth part s_U(n) for composite non-prime-power n. So R_L on the true field can deviate from 1 with NO local anti-correlation, driven only by (i) support/magnitude clustering or (ii) the collapse itself. Discriminated by the DECOMPOSITION (field c, sign field sigma, magnitude field |c|) against the COLLAPSE-RESPECTING NULL. PRE-REGISTERED DESIGN (frozen before any run). Scales x in {2^14, 2^16, 2^18} (portable; 2^20 is ~1 core-h and out of this assignment's 0.5 h, so it is NOT run and NOT claimed) Block lengths L in {4, 8, 16, 32, 64, 128, 256} (finite-size, all << |J_x|) Fields c(n); sigma(n) = sign c(n); w(n) = |c(n)| Nulls (both keep the true support and the true |c| at each support position; neither samples mu, so neither is #638's mismatched control): S-null uniform permutation of the support signs (destroys ALL sign order) C-null reassign each U-smooth class a sign derived from a RANDOMIZED TRUNCATED Mobius sum: M~_U(s) = sum_{d|s, d<=U} eps_d mu(d), eps_d iid +-1, class sign = -sign M~_U (holds the class geometry AND the magnitudes exactly; randomizes only M_U, which identity (I) names as the one place Mobius enters) <-- the null that decides this job, and the faithful form of #638's "randomizing only the truncated sums M_U". NOTE, measured below: the LITERAL reading of that hint (permute the signs WITHIN each class) is DEGENERATE -- the sign is constant on every class, so permuting within a class is the identity and reproduces the true field exactly. Draws 200 per null per scale Alignment both left- and right-aligned block partitions (the field is sparse; an alignment artefact must be visible) Statistic per null z_L = (R_L^true - mean_null) / sd_null, and the p-value for R_L^true < null. DECISION RULE (frozen): RESCUE WORKS iff there is an L with z_L(C-null) <= -3.0 AND R_L^true < 1 at that L, at EVERY scale tested -> local cancellation beyond the collapse; report the scale-free pattern and a next_step. RESCUE FAILS iff |z_L(C-null)| <= 3.0 at every L at every scale -> a block-local statistic of the true field is statistically indistinguishable from a field whose only structure is the smooth-part collapse. Then the obstruction is NOT "aggregate only": it is that this instrument measures the collapse too, and the correct next ingredient is named explicitly (see the report). MIXED otherwise -> report which L and scales separate, with the sign of z. No outcome is claimed beyond the scales actually run; no exponent, asymptotic or power saving is inferred from a finite census. Reuses #636's producer (fibre-sign-lag.py, sha256 a74825d84e54...) for the field, its factorization and its mu table, so the coefficient is built by the same code whose identity and audit gates are already accepted. Nothing published is recomputed: the lag-h statistic of #636 is NOT run here. Usage: python blockvariance-rescue.py --x 65536 [--draws 200] [--out out.json] """ import argparse import hashlib import importlib.util import io import json import os import sys import time import numpy as np sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace") HERE = os.path.dirname(os.path.abspath(__file__)) PRODUCER = os.path.join(HERE, "fibre-sign-lag.py") # copy of #636's accepted producer SEED = 1420 LS = [4, 8, 16, 32, 64, 128, 256] def load_producer(path): spec = importlib.util.spec_from_file_location("fibre_producer", path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod def smooth_part(fact, B): """The B-smooth part of m, from its factorization [(p, e)].""" s = 1 for p, e in fact: if p <= B: s *= p ** e return s def block_sums(v, L, right_aligned=False): """Block sums of `v` over disjoint consecutive blocks of length L.""" M = len(v) if right_aligned: off = M % L w = v[off:] else: w = v[: M - (M % L)] nb = len(w) // L if nb < 2: return None return w.reshape(nb, L).sum(axis=1) def R_L(v, L, right_aligned=False): """Calibrated block-variance ratio: baseline 1 for an uncorrelated field.""" bs = block_sums(v, L, right_aligned) if bs is None: return None M = len(v) den = float(np.mean(v * v)) if den <= 0: return None return float(np.mean(bs * bs)) / (den * L) def zscore(obs, draws): a = np.array([d for d in draws if d is not None], dtype=float) if a.size < 2: return None, None, None mu, sd = float(a.mean()), float(a.std(ddof=1)) if sd <= 0: return None, mu, sd z = (obs - mu) / sd p_less = float((np.sum(a <= obs) + 1) / (a.size + 1)) return z, mu, sd, p_less def permuted_signs(rng, sgn_sup): """A uniform permutation of the support signs: destroys ALL sign order.""" out = sgn_sup.copy() rng.shuffle(out) return out def divisors_upto(s, cap): """Squarefree divisors d of s with d <= cap (s is U-smooth, so this is a tiny list).""" ds = [1] for d in range(2, cap + 1): if s % d == 0: ok = True for q in range(2, int(d ** 0.5) + 1): if d % (q * q) == 0: ok = False break if ok: ds.append(d) return ds def class_sign_from_truncated_mu(rng, s_vals, U, mu_table): """The COLLAPSE-RESPECTING null, in the form #638's revisit_when actually prescribes: randomize ONLY the truncated Mobius sums M_U(s) = sum_{d|s, d<=U} mu(d), which is the single place identity (I) lets Mobius enter -- NOT mu on the range d > U, which (I) annihilates inside the smooth part and which is what made #636's control mismatched. For each distinct U-smooth value s, M~_U(s) = sum_{d|s, d<=U, squarefree} eps_d mu(d) with eps_d iid uniform +-1; the class sign is -sign M~_U(s) (the dominant term of (I) for composite non-prime-power m). eps_d = 0 falls back to the observed class sign, which only weakens the null (it makes it conservatively closer to the true field). """ cache = {} def eps(d): if d not in cache: cache[d] = 1.0 if rng.random() < 0.5 else -1.0 return cache[d] out = {} for s in s_vals: tot = 0.0 for d in divisors_upto(s, U): tot += eps(d) * float(mu_table[d]) if tot != 0: out[s] = -1.0 if tot > 0 else 1.0 return out def run(x, draws): t0 = time.time() m = load_producer(PRODUCER) b = m.build(x) mu = m.mu_array(b["hi"]).astype(float) CL = m.coeff_from(b, "L", mu) CR = m.coeff_from(b, "R", mu) c = m.c_field(b, CL, CR) ns = b["ns"] M = len(ns) sup = np.flatnonzero(c != 0) sgn_sup = np.sign(c[sup]) abs_sup = np.abs(c[sup]) U, Y = b["U"], b["Y"] # ---- support / structure facts (context, not the decision) ---- n_sup = len(sup) # U-smooth classes of the support elements, and on the full range cls = np.array([smooth_part(b["facts"][int(n)], U) for n in ns]) uniq = np.unique(cls[sup]) groups = [np.flatnonzero(cls[sup] == v) for v in uniq] class_vals = [int(v) for v in uniq] # Evidence for why the LITERAL within-class permutation from #638's revisit_when is # DEGENERATE and cannot serve as a null: the sign is constant on every class. literal_identity = bool(all(len(np.unique(sgn_sup[g])) == 1 for g in groups)) # class purity of the sign field: does each class carry one sign only? one_signed = int(sum(1 for g in groups if len(np.unique(sgn_sup[g])) == 1)) # and the same for the raw value sign of the LEFT factor (the collapse probe) left_sgn_sup = np.sign(CL[b["li"]])[sup] fields = {} # full coefficient v_full = np.zeros(M) v_full[sup] = c[sup] fields["c"] = v_full # sign field on the support (0 off support) v_sgn = np.zeros(M) v_sgn[sup] = sgn_sup fields["sigma"] = v_sgn # magnitude field (nonnegative, same support) v_abs = np.zeros(M) v_abs[sup] = abs_sup fields["abs_c"] = v_abs res = {"x": x, "U": U, "V": b["V"], "Y": Y, "Z": b["Z"], "J": M, "support": int(n_sup), "support_fraction": n_sup / M, "L": LS, "draws": draws, "smooth_classes_on_support": int(uniq.size), "one_signed_classes": one_signed, "literal_within_class_permutation_is_identity": literal_identity, "left_factor_sign_one_signed_classes": int( sum(1 for g in groups if len(np.unique(left_sgn_sup[g])) == 1)), "nulls": {}} rng = np.random.default_rng(SEED) def field_from(perm): """The field with support signs replaced by `perm` (magnitude untouched).""" if fname == "abs_c": return v_abs w = np.zeros(M) w[sup] = perm if fname == "sigma" else perm * abs_sup return w for fname, v in fields.items(): entry = {"observed": {}, "S_null": {}, "C_null": {}, "PC_alternating": {}} for L in LS: obs = R_L(v, L) entry["observed"][L] = obs entry["PC_alternating"][L] = None # positive control: alternating signs on the support, magnitude 1 alt = np.zeros(M) alt[sup] = np.where(np.arange(n_sup) % 2 == 0, 1.0, -1.0) for L in LS: entry["PC_alternating"][L] = R_L(alt, L) # Monte-Carlo nulls S = {L: [] for L in LS} C = {L: [] for L in LS} for _ in range(draws): # S-null: uniform permutation of the support signs (destroys all sign order) w = field_from(permuted_signs(rng, sgn_sup)) # C-null: reassign each U-smooth class a sign derived from RANDOMIZED TRUNCATED mu. if fname == "abs_c": w2 = v_abs else: cs = class_sign_from_truncated_mu(rng, class_vals, U, mu) q2 = np.zeros(n_sup) for g, v in zip(groups, class_vals): q2[g] = cs.get(v, float(sgn_sup[g][0])) w2 = np.zeros(M) w2[sup] = q2 * abs_sup if fname == "c" else q2 for L in LS: S[L].append(R_L(w, L)) C[L].append(R_L(w2, L)) for L in LS: for tag, acc in (("S_null", S), ("C_null", C)): o = entry["observed"][L] got = zscore(o, acc[L]) if o is not None else (None, None, None, None) z, mn, sdv = got[0], got[1], got[2] p = got[3] if len(got) > 3 else None entry[tag][L] = {"mean": mn, "sd": sdv, "z": z, "p_less": p} res["nulls"][fname] = entry # ---- frozen decision rule, applied to the C-null on the full coefficient ---- entry = res["nulls"]["c"] sep = [] for L in LS: obs, cn = entry["observed"][L], entry["C_null"][L] if obs is None or cn.get("z") is None: continue seps = {"L": L, "R_obs": obs, "z_C": cn["z"], "z_S": entry["S_null"][L]["z"], "p_less_C": cn["p_less"]} sep.append(seps) res["separation_c_vs_C_null"] = sep works = [s for s in sep if s["z_C"] is not None and s["z_C"] <= -3.0 and s["R_obs"] < 1.0] res["min_z_C"] = min((s["z_C"] for s in sep), default=None) res["verdict_rule"] = ("local cancellation beyond the collapse at L=%s (z_C<=-3 and R<1)" % [s["L"] for s in works]) if works else "no L separates: rescue fails" res["elapsed_s"] = round(time.time() - t0, 3) res["producer_sha256"] = hashlib.sha256(open(PRODUCER, "rb").read()).hexdigest() return res def main(): ap = argparse.ArgumentParser() ap.add_argument("--x", type=int, required=True) ap.add_argument("--draws", type=int, default=200) ap.add_argument("--out", default=None) a = ap.parse_args() r = run(a.x, a.draws) txt = json.dumps(r, indent=1, sort_keys=True) if a.out: with open(a.out, "w", encoding="utf-8", newline="\n") as fh: fh.write(txt + "\n") print(txt) return 0 if __name__ == "__main__": sys.exit(main())