#!/usr/bin/env python3 """Reproduce the finite audit reported in the paper. Usage: python3 anc/reproduce.py # recompute, compare, write anc/audit.json python3 anc/reproduce.py --quiet # only print the verdict line Inputs (all inside this directory, no absolute paths): frozen_state.json path-free frozen parameters of the audit artefacts/*.json the engine outputs shipped with the paper artefact_digests.json SHA-256 of every shipped artefact The script recomputes every audit quantity from frozen_state.json with the same formulas as the mission engine, compares the result with the shipped artefacts within a relative tolerance of 1e-9, verifies the shipped digests, and writes the headline numbers to audit.json. It exits non-zero if any comparison fails. Only the Python standard library and NumPy are required. """ import argparse import hashlib import json import math import os import sys import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) ARTEFACTS = os.path.join(HERE, 'artefacts') LOSS_CATEGORIES = ['L_STRENGTH', 'L_CONSTANT', 'L_EXPONENT', 'L_DIMENSION', 'L_NORM', 'L_ERROR', 'L_INTEGRALITY', 'L_REGULARITY', 'L_UNIFORMITY', 'L_BOUNDARY', 'L_EXCEPTION', 'L_HYPOTHESIS', 'L_DEPENDENCY', 'L_PROVENANCE', 'L_RESOURCE'] # -------------------------------------------------------------------------- # arithmetic helpers (identical to the mission engine) # -------------------------------------------------------------------------- def is_prime(n): if n < 2: return False for d in range(2, int(math.isqrt(n)) + 1): if n % d == 0: return False return True def primitive_root(q): if q < 3: raise ValueError('degenerate modulus q=%d' % q) if not is_prime(q): raise ValueError('modulus not prime q=%d' % q) for g in range(2, q): seen = set() value = 1 for _ in range(q - 1): value = (value * g) % q seen.add(value) if len(seen) == q - 1: return g raise ValueError('no primitive root for q=%d' % q) def units_of(q): return [a for a in range(1, q) if math.gcd(a, q) == 1] def characters(q): g = primitive_root(q) table = {} value = 1 for k in range(q - 1): table[value] = k value = (value * g) % q units = units_of(q) order = q - 1 chi = np.zeros((order, len(units)), dtype=complex) for j in range(order): for idx, a in enumerate(units): chi[j, idx] = np.exp(2j * np.pi * j * table[a] / order) return units, chi, g def kernel_values(units, q, kind, support_n): if kind == 'bump': denom = max(q - 2, 1) return np.array([(1.0 - ((a - 1) / denom) ** 2) ** 2 for a in units], dtype=float) if kind == 'indicator': return np.array([1.0 if a <= support_n else 0.0 for a in units], dtype=float) if kind == 'half': return np.array([1.0 if a <= q // 2 else 0.0 for a in units], dtype=float) if kind == 'delta': return np.array([1.0 if a == units[0] else 0.0 for a in units], dtype=float) if kind == 'zero': return np.zeros(len(units), dtype=float) raise ValueError('unknown kernel ' + kind) def amplifier_weights(q, length, weights='ones', reject_non_unit=False): lam = [] for ell in range(1, length + 1): residue = ell % q if residue == 0 or math.gcd(residue, q) != 1: if reject_non_unit: raise ValueError('non-unit weight ell=%d for q=%d' % (ell, q)) continue if weights == 'ones': lam.append((residue, 1.0)) elif weights == 'inverse': lam.append((residue, 1.0 / ell)) elif weights == 'negative': lam.append((residue, -1.0)) elif weights == 'zero': lam.append((residue, 0.0)) else: raise ValueError('unknown weights ' + weights) return lam def amplifier_values(units, chi, lam): index = {a: i for i, a in enumerate(units)} values = np.zeros(chi.shape[0], dtype=complex) for ell, weight in lam: values += weight * chi[:, index[ell]] return values def second_moment_direct(amp, khat): return float(np.sum(np.abs(amp) ** 2 * np.abs(khat) ** 2)) def second_moment_orth(units, kernel, lam, q): phi = len(units) total = 0.0 for ell, w1 in lam: for m, w2 in lam: for i, a in enumerate(units): for j, b in enumerate(units): if (ell * a - m * b) % q == 0: total += w1 * w2 * kernel[i] * kernel[j] return float(phi * total) def diagonal_term(units, kernel, lam): phi = len(units) weight_sq = sum(w * w for _, w in lam) return float(phi * weight_sq * float(np.sum(kernel ** 2))) def grid_points(mech): independent = set(mech.get('support_independent_kernels', ['bump', 'half'])) points = [] for q in mech['moduli']: for kind in mech['kernels']: supports = [mech['support_N'][0]] if kind in independent else mech['support_N'] for support_n in supports: for length in mech['amplifier_lengths']: points.append({'q': q, 'kernel': kind, 'support_N': support_n, 'L': length}) return points def unique_spectra_points(mech): seen = [] for point in grid_points(mech): key = (point['q'], point['kernel'], point['support_N']) if key not in [(p['q'], p['kernel'], p['support_N']) for p in seen]: seen.append({'q': point['q'], 'kernel': point['kernel'], 'support_N': point['support_N']}) return seen def decay_alpha(rows, key='sup_abs_khat_nonprincipal'): qs = np.array([row['q'] for row in rows], dtype=float) sups = np.array([row[key] for row in rows], dtype=float) mask = sups > 0 if int(mask.sum()) < 2: return None alpha, beta = np.polyfit(np.log(qs[mask]), np.log(sups[mask]), 1) return {'alpha': float(alpha), 'beta': float(beta), 'n': int(mask.sum())} def evaluate_term(term, midpoint): if term.get('constant') is None: return None, 'constant not declared' shape = term.get('shape') c = term['constant'] q = midpoint['q'] x = midpoint['x'] T = midpoint['T'] if shape == 'c*x*log(q*x)^2/T': return c * x * (math.log(q * x) ** 2) / T, None if shape == 'c*(q*T)^A*(1-sigma)^B': A = term.get('A') B = term.get('B') sigma = term.get('sigma') if A is None or B is None or sigma is None: return None, 'shape parameters A, B or sigma missing' return c * ((q * T) ** A) * ((1.0 - sigma) ** B), None if shape == 'c': return c, None return None, 'shape not evaluable: ' + str(shape) # -------------------------------------------------------------------------- # recomputation of every audit artefact # -------------------------------------------------------------------------- def compute_spectra(state): mech = state['mechanism'] rows = [] for point in unique_spectra_points(mech): q = point['q'] units, chi, g = characters(q) kernel = kernel_values(units, q, point['kernel'], point['support_N']) khat = chi @ kernel lhs = float(np.sum(np.abs(khat) ** 2)) rhs = float(len(units) * np.sum(kernel ** 2)) nonprincipal = khat[1:] if len(khat) > 1 else khat rows.append({ 'q': q, 'primitive_root': g, 'kernel': point['kernel'], 'support_N': point['support_N'], 'phi': len(units), 'sup_abs_khat': float(np.max(np.abs(khat))), 'principal_abs_khat': float(abs(khat[0])), 'sup_abs_khat_nonprincipal': float(np.max(np.abs(nonprincipal))), 'min_abs_khat_nonprincipal': float(np.min(np.abs(nonprincipal))), 'kernel_constant': bool(np.allclose(kernel, kernel[0])), 'nonprincipal_spectrum_zero': bool(float(np.max(np.abs(nonprincipal))) < 1e-9), 'mean_abs_khat_nonprincipal': float(np.mean(np.abs(nonprincipal))), 'parseval_lhs': lhs, 'parseval_rhs': rhs, 'parseval_gap': abs(lhs - rhs), }) return { 'rows': rows, 'parseval_max_gap': max(row['parseval_gap'] for row in rows), 'parseval_ok': all(row['parseval_gap'] <= 1e-8 * max(1.0, row['parseval_rhs']) for row in rows), } def compute_decay(state, cost, spectra): groups = {} excluded = [] for row in spectra['rows']: if row.get('kernel_constant'): excluded.append({'q': row['q'], 'kernel': row['kernel'], 'support_N': row['support_N'], 'reason': 'kernel is constant on the unit group'}) continue if row.get('nonprincipal_spectrum_zero'): excluded.append({'q': row['q'], 'kernel': row['kernel'], 'support_N': row['support_N'], 'reason': 'non-principal spectrum is numerically zero'}) continue groups.setdefault((row['kernel'], row['support_N']), []).append(row) fits = [] for (kind, support_n), rows in sorted(groups.items()): fit = decay_alpha(rows) if len(rows) >= 2 else None entry = {'kernel': kind, 'support_N': support_n, 'fit': fit, 'n_rows': len(rows)} if fit is None: entry['reason'] = 'fewer than two admissible moduli' fits.append(entry) control_rows = [] for q in state['mechanism']['moduli'][:5]: units, chi, g = characters(q) kernel = kernel_values(units, q, 'delta', 1) khat = chi @ kernel control_rows.append({'q': q, 'sup_abs_khat_nonprincipal': float(np.max(np.abs(khat[1:]))) if len(khat) > 1 else 0.0}) control_fit = decay_alpha(control_rows) delta_values = [row['sup_abs_khat_nonprincipal'] for row in control_rows] delta_flat = bool(delta_values) and all(abs(value - 1.0) < 1e-9 for value in delta_values) bump_rows = [row for row in spectra['rows'] if row['kernel'] == 'bump'] bump_spread = None if bump_rows: widest = max(bump_rows, key=lambda row: row['q']) if widest['min_abs_khat_nonprincipal'] > 0: bump_spread = widest['sup_abs_khat_nonprincipal'] / widest['min_abs_khat_nonprincipal'] bound = cost['donor_bounds']['char_sum'] violations = [] blocker = None if bound.get('constant') is None: blocker = 'character-sum constant not declared; decay bound not evaluated' else: for row in spectra['rows']: limit = bound['constant'] * math.sqrt(row['q']) * math.log(math.log(row['q'])) if row['sup_abs_khat_nonprincipal'] > limit * (1.0 + 1e-9): violations.append({'q': row['q'], 'kernel': row['kernel'], 'sup': row['sup_abs_khat_nonprincipal'], 'limit': limit}) return { 'fits': fits, 'excluded_rows': excluded, 'control_delta': {'rows': control_rows, 'fit': control_fit}, 'discrimination': {'delta_flat_spectrum': delta_flat, 'delta_values': delta_values, 'bump_spectral_spread': bump_spread, 'passed': bool(delta_flat and bump_spread is not None and bump_spread > 1.0)}, 'bound': {'shape': bound['shape'], 'constant': bound.get('constant'), 'status': bound.get('status'), 'violations': violations, 'blocker': blocker}, } def compute_amplifier(state): mech = state['mechanism'] rows = [] orth_checked = [] for point in grid_points(mech): q = point['q'] units, chi, g = characters(q) kernel = kernel_values(units, q, point['kernel'], point['support_N']) khat = chi @ kernel lam = amplifier_weights(q, point['L'], mech['weights']) amp = amplifier_values(units, chi, lam) direct = second_moment_direct(amp, khat) diag = diagonal_term(units, kernel, lam) s0 = float(np.sum(np.abs(khat) ** 2)) amp_np = amp[1:] if len(amp) > 1 else amp khat_np = khat[1:] if len(khat) > 1 else khat direct_np = second_moment_direct(amp_np, khat_np) s0_np = float(np.sum(np.abs(khat_np) ** 2)) principal_term = float(abs(amp[0]) ** 2 * abs(khat[0]) ** 2) identity_gap = abs(direct - direct_np - principal_term) diag_np = float((len(units) - 1) * sum(w * w for _, w in lam) * float(np.sum(kernel ** 2))) row = { 'q': q, 'kernel': point['kernel'], 'support_N': point['support_N'], 'L': point['L'], 'phi': len(units), 'weights': [[ell, w] for ell, w in lam], 'measured_norm': float(np.max(np.abs(amp))), 'declared_bound': float(sum(abs(w) for _, w in lam)), 'second_moment_direct': direct, 'diagonal': diag, 'second_moment_nonprincipal': direct_np, 'unamplified_nonprincipal': s0_np, 'principal_term': principal_term, 'identity_gap': identity_gap, 'diagonal_nonprincipal': diag_np, 'off_diagonal': direct - diag, 'off_diagonal_nonprincipal': direct_np - diag_np, 'signal_present': bool(s0_np > 1e-9), 'unamplified': s0, 'gain_ratio': (direct_np / s0_np) if s0_np > 0 else None, 'localization': (diag_np / direct_np) if direct_np > 0 else None, } if q * point['L'] <= mech['orth_rule_max']: orth = second_moment_orth(units, kernel, lam, q) orth_np = orth - float(abs(sum(w for _, w in lam)) ** 2 * float(np.sum(kernel)) ** 2) row['second_moment_orth'] = orth row['orth_gap'] = abs(direct - orth) row['orth_gap_nonprincipal'] = abs(direct_np - orth_np) orth_checked.append({'q': q, 'kernel': point['kernel'], 'support_N': point['support_N'], 'L': point['L'], 'gap': row['orth_gap'], 'gap_nonprincipal': row['orth_gap_nonprincipal']}) rows.append(row) expected = [p for p in grid_points(mech) if p['q'] * p['L'] <= mech['orth_rule_max']] max_gap = max((item['gap'] for item in orth_checked), default=None) return { 'rows': rows, 'orth_rule': mech['orth_rule'], 'orth_checked': orth_checked, 'orth_expected_count': len(expected), 'orth_checked_count': len(orth_checked), 'orth_max_gap': max_gap, 'orth_ok': bool(max_gap is not None and max_gap <= 1e-6 * max(1.0, max(r['second_moment_direct'] for r in rows))), 'orth_ok_nonprincipal': bool(orth_checked and max(item['gap_nonprincipal'] for item in orth_checked) <= 1e-6 * max(1.0, max(r['second_moment_nonprincipal'] for r in rows))), 'identity_max_gap': max(r['identity_gap'] for r in rows), 'grid_count': len(rows), } def compute_norm(state, operator): mech = state['mechanism'] rows = [] eps = 1e-3 for row in operator['rows']: q = row['q'] units, chi, g = characters(q) lam = amplifier_weights(q, row['L'], mech['weights']) base = amplifier_values(units, chi, lam) perturbed = [] for index, (ell, weight) in enumerate(lam): shifted = list(lam) shifted[index] = (ell, weight + eps) perturbed.append(amplifier_values(units, chi, shifted)) lipschitz = 0.0 for values in perturbed: delta = float(np.max(np.abs(values - base))) lipschitz = max(lipschitz, delta / eps) rows.append({ 'q': q, 'kernel': row['kernel'], 'support_N': row['support_N'], 'L': row['L'], 'measured_norm': row['measured_norm'], 'declared_bound': row['declared_bound'], 'bounded': row['measured_norm'] <= row['declared_bound'] + 1e-9, 'lipschitz': lipschitz, 'lipschitz_ok': lipschitz <= 1.0 + 1e-6, }) return {'rows': rows, 'all_bounded': all(r['bounded'] for r in rows), 'all_lipschitz_ok': all(r['lipschitz_ok'] for r in rows)} def compute_regime(state): mech = state['mechanism'] points = grid_points(mech) bad_moduli = [q for q in mech['moduli'] if not is_prime(q) or q < 3] bad_lengths = [L for L in mech['amplifier_lengths'] if L < 1] bad_support = [N for N in mech['support_N'] if N < 1] return { 'grid_count': len(points), 'moduli': mech['moduli'], 'kernels': mech['kernels'], 'support_N': mech['support_N'], 'amplifier_lengths': mech['amplifier_lengths'], 'iterations': mech['iterations'], 'bad_moduli': bad_moduli, 'bad_lengths': bad_lengths, 'bad_support': bad_support, 'regime_ok': not (bad_moduli or bad_lengths or bad_support), 'points': points, } def compute_iterate(state): mech = state['mechanism'] rows = [] for point in grid_points(mech): q = point['q'] units, chi, g = characters(q) kernel = kernel_values(units, q, point['kernel'], point['support_N']) khat = chi @ kernel lam = amplifier_weights(q, point['L'], mech['weights']) amp = amplifier_values(units, chi, lam) for m in mech['iterations']: amp_m = amp ** m moment = second_moment_direct(amp_m, khat) norm_m = float(np.max(np.abs(amp)) ** m) rows.append({ 'q': q, 'kernel': point['kernel'], 'support_N': point['support_N'], 'L': point['L'], 'm': m, 'second_moment': moment, 'norm_m': norm_m, 'polynomial_length': m * point['L'], 'length_growth': (m - 1) * point['L'], 'well_defined': bool(np.isfinite(moment) and np.isfinite(norm_m)), }) return {'rows': rows, 'all_well_defined': all(r['well_defined'] for r in rows), 'accumulates': 'second_moment and norm_m grow with m', 'degrades': 'Dirichlet polynomial length grows as m*L', 'max_length_growth': max(r['length_growth'] for r in rows)} def compute_adequacy(state, operator): mech = state['mechanism'] thresholds = mech['adequacy'] min_length = mech.get('admissible_min_L', 1) rows = [] for row in operator['rows']: gain = row['gain_ratio'] loc = row['localization'] bounded = row['measured_norm'] <= row['declared_bound'] + 1e-9 adequate = bool(gain is not None and loc is not None and gain >= thresholds['min_gain_ratio'] and loc >= thresholds['min_localization'] and bounded and row['unamplified'] > 0) rows.append({'q': row['q'], 'kernel': row['kernel'], 'support_N': row['support_N'], 'L': row['L'], 'gain_ratio': gain, 'localization': loc, 'bounded': bounded, 'adequate': adequate, 'admissible': bool(row['L'] >= min_length and row.get('signal_present', True)), 'signal_present': row.get('signal_present', True)}) admissible_rows = [r for r in rows if r['admissible']] for row in rows: if row['gain_ratio'] is not None and abs(row['gain_ratio']) < 1e-12: row['gain_ratio'] = 0.0 adequate_rows = [r for r in admissible_rows if r['adequate']] return { 'thresholds': thresholds, 'rows': rows, 'adequate_count': len(adequate_rows), 'grid_count': len(rows), 'admissible_count': len(admissible_rows), 'admissible_min_L': min_length, 'excluded_for_no_signal': len([r for r in rows if not r['signal_present']]), 'status': 'ADEQUATE' if admissible_rows and len(adequate_rows) == len(admissible_rows) else 'INADEQUATE', 'worst_gain': min((r['gain_ratio'] for r in admissible_rows if r['gain_ratio'] is not None), default=None), 'worst_gain_row': min((r for r in admissible_rows if r['gain_ratio'] is not None), key=lambda r: r['gain_ratio'], default=None), 'worst_localization': min((r['localization'] for r in admissible_rows if r['localization'] is not None), default=None), 'all_grid_adequate_count': len([r for r in rows if r['adequate']]), 'adequacy_statement': 'The amplifier M_T performs the amplification role when the gain ratio is at least the declared threshold and the diagonal share of the amplified second moment is at least the declared localization threshold.', } def run_falsify_tests(state): mech = state['mechanism'] thresholds = mech['adequacy'] results = [] q = 13 units, chi, g = characters(q) kernel = kernel_values(units, q, 'zero', 1) khat = chi @ kernel lam = amplifier_weights(q, 4, mech['weights']) amp = amplifier_values(units, chi, lam) s0 = float(np.sum(np.abs(khat) ** 2)) direct = second_moment_direct(amp, khat) results.append({'test': 'zero_kernel', 'expected': 'unamplified spectrum is zero and adequacy is false', 'observed': {'unamplified': s0, 'second_moment': direct, 'adequate': False}, 'passed': bool(s0 == 0.0 and direct == 0.0)}) delta_rows = [] for modulus in mech['moduli'][:5]: u, c, _ = characters(modulus) delta_khat = c @ kernel_values(u, modulus, 'delta', 1) values = np.abs(delta_khat[1:]) if len(delta_khat) > 1 else np.abs(delta_khat) delta_rows.append({'q': modulus, 'min': float(np.min(values)), 'max': float(np.max(values))}) flat = all(abs(row['min'] - 1.0) < 1e-9 and abs(row['max'] - 1.0) < 1e-9 for row in delta_rows) results.append({'test': 'delta_kernel', 'expected': 'a delta kernel produces a flat unit spectrum on every non-principal character, so no cancellation is available', 'observed': {'rows': delta_rows, 'flat': flat}, 'passed': flat}) kernel = kernel_values(units, q, 'bump', mech['support_N'][0]) khat = chi @ kernel lam1 = amplifier_weights(q, 1, mech['weights']) amp1 = amplifier_values(units, chi, lam1) direct1 = second_moment_direct(amp1, khat) s0b = float(np.sum(np.abs(khat) ** 2)) gain1 = direct1 / s0b if s0b > 0 else None results.append({'test': 'unit_amplifier', 'expected': 'length-one amplifier gives gain exactly one and fails the gain threshold', 'observed': {'gain_ratio': gain1, 'threshold': thresholds['min_gain_ratio']}, 'passed': bool(gain1 is not None and abs(gain1 - 1.0) < 1e-9 and gain1 < thresholds['min_gain_ratio'])}) raised = False try: amplifier_weights(5, 6, mech['weights'], reject_non_unit=True) except ValueError: raised = True results.append({'test': 'non_unit_weight', 'expected': 'a non-unit weight is rejected by the constructor', 'observed': {'raised': raised}, 'passed': raised}) raised = False try: characters(2) except ValueError: raised = True results.append({'test': 'degenerate_modulus', 'expected': 'modulus two is rejected as degenerate', 'observed': {'raised': raised}, 'passed': raised}) lamz = amplifier_weights(q, 4, 'zero') ampz = amplifier_values(units, chi, lamz) directz = second_moment_direct(ampz, khat) results.append({'test': 'zero_weights', 'expected': 'zero weights give a zero amplified moment and fail adequacy', 'observed': {'second_moment': directz}, 'passed': bool(directz == 0.0)}) lamn = amplifier_weights(q, 4, 'negative') ampn = amplifier_values(units, chi, lamn) norm_neg = float(np.max(np.abs(ampn))) norm_pos = float(np.max(np.abs(amplifier_values(units, chi, amplifier_weights(q, 4, 'ones'))))) bound_neg = float(sum(abs(w) for _, w in lamn)) bound_pos = float(sum(abs(w) for _, w in amplifier_weights(q, 4, 'ones'))) collapse = None independent = set(mech.get('support_independent_kernels', ['bump', 'half'])) for modulus in mech['moduli']: u, c, _ = characters(modulus) for kind in mech['kernels']: supports = [mech['support_N'][0]] if kind in independent else mech['support_N'] for support_n in supports: kh = c @ kernel_values(u, modulus, kind, support_n) kh_np = kh[1:] if len(kh) > 1 else kh base = float(np.sum(np.abs(kh_np) ** 2)) if base <= 1e-9: continue for length in mech['amplifier_lengths']: amp_local = amplifier_values(u, c, amplifier_weights(modulus, length, mech['weights'])) amp_np = amp_local[1:] if len(amp_local) > 1 else amp_local moment = second_moment_direct(amp_np, kh_np) if moment <= 1e-12 * max(1.0, base): collapse = {'q': modulus, 'kernel': kind, 'support_N': support_n, 'L': length, 'moment': moment, 'unamplified': base} break if collapse: break if collapse: break if collapse: break results.append({'test': 'rank_collapse', 'expected': 'the grid contains a configuration where the amplifier annihilates the non-principal spectrum, so the mechanism can fail its functional role', 'observed': collapse, 'passed': collapse is not None}) results.append({'test': 'negative_weights', 'expected': 'sign flip leaves the norm and the l1 bound unchanged', 'observed': {'norm_neg': norm_neg, 'norm_pos': norm_pos, 'bound_neg': bound_neg, 'bound_pos': bound_pos}, 'passed': bool(abs(norm_neg - norm_pos) < 1e-9 and abs(bound_neg - bound_pos) < 1e-9)}) return results def compute_falsify(state): declared = state['mechanism']['falsify_tests'] results = run_falsify_tests(state) executed = [item['test'] for item in results] return {'tests_declared': declared, 'tests_executed': executed, 'results': results, 'enumeration_complete': sorted(declared) == sorted(executed), 'all_passed': all(item['passed'] for item in results)} def compute_transfer(state, cost): midpoint = cost['regime_midpoint'] terms = {} blockers = [] for name in ('E_trunc', 'E_unif', 'E_exception'): term = cost['terms'][name] value, reason = evaluate_term(term, midpoint) terms[name] = {'shape': term['shape'], 'constant': term.get('constant'), 'status': term.get('status'), 'source_id': term.get('source_id'), 'value_at_midpoint': value, 'reason': reason} if term.get('status') != 'DECLARED' or term.get('constant') is None: blockers.append({'term': name, 'status': term.get('status'), 'reason': 'constant not declared from a verified donor'}) elif reason: blockers.append({'term': name, 'status': term.get('status'), 'reason': reason}) return {'transfer_identity': state['target']['transfer_identity'], 'terms': terms, 'blockers': blockers, 'status': 'DECLARED' if not blockers else 'BLOCKED'} def compute_density(state, cost): midpoint = cost['regime_midpoint'] term = cost['terms']['E_density'] value, reason = evaluate_term(term, midpoint) blockers = [] if term.get('status') != 'DECLARED' or term.get('constant') is None: blockers.append({'term': 'E_density', 'status': term.get('status'), 'reason': 'zero-density constant not declared from a verified donor'}) elif reason: blockers.append({'term': 'E_density', 'status': term.get('status'), 'reason': reason}) return {'term': {'shape': term['shape'], 'constant': term.get('constant'), 'status': term.get('status'), 'source_id': term.get('source_id'), 'value_at_midpoint': value, 'reason': reason}, 'blockers': blockers, 'status': 'DECLARED' if not blockers else 'BLOCKED', 'donor_candidates': ['hexagon:2610.00661v2', 'hexagon:2610.00375v1', 'hexagon:2611.01456v1', 'hexagon:2612.00363v1']} def compute_budget(state, cost, operator, iteration, transfer, density): measured = { 'E_char': {'value': max(row['off_diagonal_nonprincipal'] for row in operator['rows'] if row['L'] >= state['mechanism'].get('admissible_min_L', 1) and row.get('signal_present', True)), 'status': 'MEASURED', 'source': 'out/operator.json'}, 'E_iter': {'value': max(row['length_growth'] for row in iteration['rows']), 'status': 'MEASURED', 'source': 'out/iteration.json'}, } declared = {} blockers = [] for name, artifact in (('E_trunc', transfer), ('E_unif', transfer), ('E_exception', transfer), ('E_density', density)): entry = artifact['terms'][name] if name in artifact.get('terms', {}) else artifact.get('term') declared[name] = {'value': entry.get('value_at_midpoint'), 'status': entry.get('status'), 'source': 'out/transfer.json' if name != 'E_density' else 'out/density.json'} if entry.get('status') != 'DECLARED' or entry.get('value_at_midpoint') is None: blockers.append({'term': name, 'status': entry.get('status'), 'reason': 'declared constant missing or not evaluable'}) normalization = cost.get('normalization', {}) if normalization.get('status') != 'DECLARED' or normalization.get('constant') is None: blockers.append({'term': 'normalization', 'status': normalization.get('status'), 'reason': 'no declared normalization between spectral units and remainder units'}) total = None if not blockers: total = sum(item['value'] for item in measured.values()) + sum(item['value'] for item in declared.values()) return {'measured': measured, 'declared': declared, 'normalization': normalization, 'blockers': blockers, 'cost_total': total, 'status': 'PRICED' if not blockers else 'BLOCKED'} def compute_loss_vector(state, cost, budget, operator, donors): unverified = [d['homm_id'] for d in donors if d.get('evidence_status') == 'UNVERIFIED'] open_children = [c['id'] for c in state['target']['children']] entries = { 'L_STRENGTH': {'value': budget['status'], 'status': 'PRICED' if budget['status'] == 'PRICED' else 'UNPRICED', 'source': 'out/net_verdict.json'}, 'L_CONSTANT': {'value': sum(1 for t in cost['terms'].values() if t.get('constant') is not None), 'status': 'PRICED' if budget['status'] == 'PRICED' else 'UNPRICED', 'source': 'params/cost_model.json'}, 'L_EXPONENT': {'value': None, 'status': 'UNPRICED', 'source': 'required decay exponent not declared'}, 'L_DIMENSION': {'value': state['mechanism']['moduli'], 'status': 'PRICED', 'source': 'engine/state.json'}, 'L_NORM': {'value': max(row['declared_bound'] for row in operator['rows']), 'status': 'PRICED', 'source': 'out/operator.json'}, 'L_ERROR': {'value': budget['cost_total'], 'status': 'PRICED' if budget['cost_total'] is not None else 'UNPRICED', 'source': 'out/budget.json'}, 'L_INTEGRALITY': {'value': 'not applicable', 'status': 'NOT_APPLICABLE', 'source': 'no denominators or divisibility conditions in the mechanism'}, 'L_REGULARITY': {'value': state['mechanism']['kernels'], 'status': 'PRICED', 'source': 'engine/state.json'}, 'L_UNIFORMITY': {'value': cost['terms']['E_unif'].get('status'), 'status': 'PRICED' if cost['terms']['E_unif'].get('status') == 'DECLARED' else 'UNPRICED', 'source': 'params/cost_model.json'}, 'L_BOUNDARY': {'value': {'moduli': state['mechanism']['moduli'], 'support_N': state['mechanism']['support_N'], 'L': state['mechanism']['amplifier_lengths']}, 'status': 'PRICED', 'source': 'engine/state.json'}, 'L_EXCEPTION': {'value': cost['terms']['E_exception'].get('status'), 'status': 'PRICED' if cost['terms']['E_exception'].get('status') == 'DECLARED' else 'UNPRICED', 'source': 'params/cost_model.json'}, 'L_HYPOTHESIS': {'value': 'unconditional route required', 'status': 'UNPRICED', 'source': 'no GRH-conditional step may be used without an explicit hypothesis entry'}, 'L_DEPENDENCY': {'value': open_children, 'status': 'UNPRICED', 'source': 'children are open until their evidence artefacts exist'}, 'L_PROVENANCE': {'value': unverified, 'status': 'UNPRICED' if unverified else 'PRICED', 'source': 'params/donor_fields.json'}, 'L_RESOURCE': {'value': {'grid': len(operator['rows'])}, 'status': 'PRICED', 'source': 'out/operator.json'}, } missing = [name for name in LOSS_CATEGORIES if name not in entries] blockers = [{'category': name, 'status': entries[name]['status'], 'source': entries[name]['source']} for name in LOSS_CATEGORIES if entries.get(name, {}).get('status') == 'UNPRICED'] return {'categories': entries, 'missing_categories': missing, 'blockers': blockers, 'status': 'PRICED' if not blockers and not missing else 'UNPRICED'} def compute_net(state, cost, budget, operator): min_length = state['mechanism'].get('admissible_min_L', 1) gains = [row['gain_ratio'] for row in operator['rows'] if row['gain_ratio'] is not None and row['L'] >= min_length and row.get('signal_present', True)] gain_min = min(gains) if gains else None c_gain = cost['c_gain'] blockers = list(budget['blockers']) if c_gain.get('status') != 'DECLARED' or c_gain.get('value') is None: blockers.append({'term': 'c_gain', 'status': c_gain.get('status'), 'reason': 'gain coefficient not declared'}) net_value = None if not blockers and gain_min is not None and budget['cost_total'] is not None: net_value = c_gain['value'] * gain_min - budget['cost_total'] return {'gain_min': gain_min, 'gain_points': len(gains), 'c_gain': c_gain, 'cost_total': budget['cost_total'], 'normalization': budget.get('normalization'), 'blockers': blockers, 'net': net_value, 'status': 'BLOCKED' if blockers or net_value is None else ('POSITIVE' if net_value > 0 else 'NONPOSITIVE')} def compute_verdict(state, net): classification = None next_action = None threshold = state['mechanism']['adequacy']['min_gain_ratio'] if net['status'] == 'BLOCKED': classification = 'F4' next_action = 'price the blocking terms from named donors or declare the normalization; do not evaluate a net gain without them' elif net['status'] == 'NONPOSITIVE': classification = 'F1' if (net['gain_min'] is not None and net['gain_min'] < threshold) else 'F3' next_action = 'losses consume the gains; re-open donor selection under TADTE and re-cut the mechanism' else: classification = None next_action = 'net strength positive; proceed to formal verification and the status sweep' return {'net_status': net['status'], 'classification': classification, 'blockers': net['blockers'], 'next_action': next_action, 'target_status': state['target']['status']} def compute_ablate(state, cost): rows = [] for assumption in state['assumptions']: aid = assumption['id'] observed = None failed = None status = 'TESTED' if aid == 'A_PRIME_MODULUS': raised = False try: characters(9) except ValueError: raised = True observed = {'composite_modulus_rejected': raised} failed = 'P1_TRANSFER' elif aid == 'A_SMOOTH_KERNEL': units, chi, g = characters(13) bump = float(np.max(np.abs(chi @ kernel_values(units, 13, 'bump', state['mechanism']['support_N'][0])))) sharp = float(np.max(np.abs(chi @ kernel_values(units, 13, 'indicator', state['mechanism']['support_N'][0])))) observed = {'bump_sup': bump, 'indicator_sup': sharp, 'ratio': (sharp / bump) if bump > 0 else None} failed = 'L_EXPONENT' status = 'CHANGED' elif aid == 'A_COPRIME_WEIGHTS': raised = False try: amplifier_weights(5, 6, state['mechanism']['weights'], reject_non_unit=True) except ValueError: raised = True observed = {'non_unit_rejected': raised} failed = 'P5_ADEQUACY' elif aid == 'A_AMPLIFIER_LENGTH': units, chi, g = characters(13) kernel = kernel_values(units, 13, 'bump', state['mechanism']['support_N'][0]) khat = chi @ kernel amp = amplifier_values(units, chi, amplifier_weights(13, 1, state['mechanism']['weights'])) gain = second_moment_direct(amp, khat) / float(np.sum(np.abs(khat) ** 2)) observed = {'gain_ratio': gain} failed = 'P5_ADEQUACY' elif aid == 'A_ZERO_DENSITY': observed = {'E_density_status': cost['terms']['E_density'].get('status')} failed = 'P2_DENSITY' elif aid == 'A_UNIFORMITY': observed = {'E_unif_status': cost['terms']['E_unif'].get('status')} failed = 'P4_NET' rows.append({'assumption': aid, 'description': assumption['description'], 'removed': True, 'observed': observed, 'failed_obligation': failed, 'status': status}) return {'rows': rows, 'assumptions_declared': [a['id'] for a in state['assumptions']], 'assumptions_tested': [r['assumption'] for r in rows], 'enumeration_complete': sorted(a['id'] for a in state['assumptions']) == sorted(r['assumption'] for r in rows)} # -------------------------------------------------------------------------- # comparison # -------------------------------------------------------------------------- SKIP_KEYS = {'generated_at', 'state', 'invocation', 'tex', 'lean', 'register', 'census', 'scores', 'weights', 'kernel_log', 'platform_submission', 'note', 'failures', 'donor_candidates'} PATH_PREFIXES = ('out/', 'params/', 'donor/', 'engine/', 'formal/', 'refs/', 'mirror/') def looks_like_path(value): return value.startswith('/') or value.startswith(PATH_PREFIXES) def normalize(value): if isinstance(value, dict): return {k: normalize(v) for k, v in value.items() if k not in SKIP_KEYS} if isinstance(value, list): return [normalize(v) for v in value] if isinstance(value, str) and looks_like_path(value): return os.path.basename(value) return value def compare(a, b, path, problems, tol_rel=1e-9, tol_abs=1e-12): if isinstance(a, dict) and isinstance(b, dict): for key in sorted(set(a) | set(b)): if key in a and key in b: compare(a[key], b[key], path + '/' + key, problems, tol_rel, tol_abs) else: problems.append('%s: key present only in %s' % (path + '/' + key, 'recomputation' if key in a else 'artefact')) elif isinstance(a, list) and isinstance(b, list): if len(a) != len(b): problems.append('%s: length %d (recomputed) vs %d (artefact)' % (path, len(a), len(b))) else: for index, (x, y) in enumerate(zip(a, b)): compare(x, y, '%s[%d]' % (path, index), problems, tol_rel, tol_abs) elif isinstance(a, bool) or isinstance(b, bool): if a != b: problems.append('%s: %r (recomputed) vs %r (artefact)' % (path, a, b)) elif isinstance(a, (int, float)) and isinstance(b, (int, float)): diff = abs(float(a) - float(b)) scale = max(abs(float(a)), abs(float(b)), 1.0) if diff > tol_abs and diff > tol_rel * scale: problems.append('%s: %r (recomputed) vs %r (artefact)' % (path, a, b)) elif a != b: problems.append('%s: %r (recomputed) vs %r (artefact)' % (path, a, b)) return problems def load(path): with open(path, encoding='utf-8') as handle: return json.load(handle) def main(): parser = argparse.ArgumentParser() parser.add_argument('--audit-out', default=os.path.join(HERE, 'audit.json')) parser.add_argument('--quiet', action='store_true') args = parser.parse_args() frozen = load(os.path.join(HERE, 'frozen_state.json')) state = frozen cost = frozen['cost_model'] donors = frozen['donors_summary'] spectra = compute_spectra(state) decay = compute_decay(state, cost, spectra) operator = compute_amplifier(state) norm = compute_norm(state, operator) regime = compute_regime(state) iteration = compute_iterate(state) adequacy = compute_adequacy(state, operator) falsify = compute_falsify(state) transfer = compute_transfer(state, cost) density = compute_density(state, cost) budget = compute_budget(state, cost, operator, iteration, transfer, density) loss_vector = compute_loss_vector(state, cost, budget, operator, donors) net = compute_net(state, cost, budget, operator) verdict = compute_verdict(state, net) ablation = compute_ablate(state, cost) recomputed = { 'spectra': spectra, 'spectra_decay': decay, 'operator': operator, 'operator_norm': norm, 'regime': regime, 'iteration': iteration, 'adequacy': adequacy, 'falsify_mechanism': falsify, 'transfer': transfer, 'density': density, 'budget': budget, 'loss_vector': loss_vector, 'net': net, 'net_verdict': verdict, 'ablation': ablation, } results = {} failures = 0 for name, payload in recomputed.items(): path = os.path.join(ARTEFACTS, name + '.json') if not os.path.exists(path): results[name] = 'MISSING' failures += 1 continue problems = compare(normalize(payload), normalize(load(path)), name, []) results[name] = 'PASS' if not problems else 'FAIL (%d)' % len(problems) failures += 1 if problems else 0 if problems and not args.quiet: for line in problems[:12]: print(' %s' % line) digests = load(os.path.join(HERE, 'artefact_digests.json')) digest_problems = [] for name, entry in sorted(digests.items()): path = os.path.join(ARTEFACTS, name + '.json') if not os.path.exists(path): digest_problems.append('%s: file missing' % name) continue with open(path, 'rb') as handle: digest = hashlib.sha256(handle.read()).hexdigest() if digest != entry['sha256']: digest_problems.append('%s: sha256 mismatch' % name) if digest_problems: failures += 1 if not args.quiet: for line in digest_problems: print(' digest: %s' % line) audit = { 'mission_id': frozen['mission_id'], 'grid': {'K': frozen['grid']['K'], 'M': frozen['grid']['M'], 'cells': frozen['grid']['cells']}, 'spectra': {'rows': len(spectra['rows']), 'parseval_ok': spectra['parseval_ok'], 'parseval_max_gap': spectra['parseval_max_gap']}, 'decay': {'fits': [{'kernel': f['kernel'], 'support_N': f['support_N'], 'alpha': (f['fit'] or {}).get('alpha'), 'beta': (f['fit'] or {}).get('beta'), 'n': (f['fit'] or {}).get('n'), 'n_rows': f['n_rows']} for f in decay['fits']], 'excluded_rows': len(decay['excluded_rows']), 'discrimination_passed': decay['discrimination']['passed'], 'bump_spectral_spread': decay['discrimination']['bump_spectral_spread'], 'bound_blocker': decay['bound']['blocker']}, 'operator': {'grid_count': operator['grid_count'], 'orth_checked': operator['orth_checked_count'], 'orth_expected': operator['orth_expected_count'], 'orth_max_gap': operator['orth_max_gap'], 'orth_ok': operator['orth_ok'], 'orth_ok_nonprincipal': operator['orth_ok_nonprincipal'], 'identity_max_gap': operator['identity_max_gap']}, 'norm': {'rows': len(norm['rows']), 'all_bounded': norm['all_bounded'], 'all_lipschitz_ok': norm['all_lipschitz_ok'], 'max_lipschitz': max(row['lipschitz'] for row in norm['rows']), 'max_declared_bound': max(row['declared_bound'] for row in norm['rows'])}, 'regime': {'grid_count': regime['grid_count'], 'regime_ok': regime['regime_ok'], 'moduli': regime['moduli'], 'kernels': regime['kernels'], 'support_N': regime['support_N'], 'amplifier_lengths': regime['amplifier_lengths'], 'iterations': regime['iterations']}, 'iteration': {'rows': len(iteration['rows']), 'all_well_defined': iteration['all_well_defined'], 'max_length_growth': iteration['max_length_growth']}, 'adequacy': {'grid_count': adequacy['grid_count'], 'admissible_count': adequacy['admissible_count'], 'adequate_count': adequacy['adequate_count'], 'all_grid_adequate_count': adequacy['all_grid_adequate_count'], 'excluded_for_no_signal': adequacy['excluded_for_no_signal'], 'status': adequacy['status'], 'thresholds': adequacy['thresholds'], 'worst_gain': adequacy['worst_gain'], 'worst_gain_row': adequacy['worst_gain_row'], 'worst_localization': adequacy['worst_localization']}, 'falsify': {'declared': len(falsify['tests_declared']), 'executed': len(falsify['tests_executed']), 'enumeration_complete': falsify['enumeration_complete'], 'all_passed': falsify['all_passed'], 'rank_collapse': [r['observed'] for r in falsify['results'] if r['test'] == 'rank_collapse'][0]}, 'transfer': {'status': transfer['status'], 'blockers': transfer['blockers']}, 'density': {'status': density['status'], 'blockers': density['blockers']}, 'budget': {'status': budget['status'], 'blockers': budget['blockers'], 'measured': budget['measured'], 'declared': budget['declared'], 'cost_total': budget['cost_total']}, 'loss_vector': {'status': loss_vector['status'], 'categories': len(loss_vector['categories']), 'unpriced': len(loss_vector['blockers']), 'unpriced_categories': [b['category'] for b in loss_vector['blockers']]}, 'net': {'status': net['status'], 'gain_min': net['gain_min'], 'gain_points': net['gain_points'], 'cost_total': net['cost_total'], 'net': net['net'], 'c_gain': net['c_gain'], 'blockers': net['blockers']}, 'verdict': {'net_status': verdict['net_status'], 'classification': verdict['classification'], 'target_status': verdict['target_status'], 'next_action': verdict['next_action']}, 'ablation': {'rows': len(ablation['rows']), 'enumeration_complete': ablation['enumeration_complete'], 'failed_obligations': {r['assumption']: r['failed_obligation'] for r in ablation['rows']}}, 'comparison': results, 'digest_check': 'PASS' if not digest_problems else 'FAIL (%d)' % len(digest_problems), 'reproduced': failures == 0, } with open(args.audit_out, 'w', encoding='utf-8') as handle: json.dump(audit, handle, ensure_ascii=False, indent=1) handle.write(chr(10)) if not args.quiet: for name in sorted(results): print('%-18s %s' % (name, results[name])) print('%-18s %s' % ('digests', audit['digest_check'])) print('reproduce %s: %d artefacts compared, %d failures' % ('PASS' if failures == 0 else 'FAIL', len(results), failures)) return 0 if failures == 0 else 1 if __name__ == '__main__': sys.exit(main())