#!/usr/bin/env python3 """Replay finite arithmetic checks accompanying PROOFS.md; no matrix search. The construction theorem and PNT in arithmetic progressions are mathematical inputs, not claims verified by this finite calculation. Distinct source orders are counted as a set: the (q,r) parametrization is not injective. """ from __future__ import annotations import argparse from collections import defaultdict import hashlib import json import math from pathlib import Path def require(condition: bool, message: str) -> None: """Keep every finite replay gate active under Python optimization.""" if not condition: raise ValueError(message) def primes_through(limit: int) -> list[int]: if limit < 2: return [] sieve = bytearray(b"\x01") * (limit + 1) sieve[:2] = b"\x00\x00" for p in range(2, math.isqrt(limit) + 1): if sieve[p]: sieve[p * p : limit + 1 : p] = b"\x00" * ( (limit - p * p) // p + 1 ) return [n for n in range(2, limit + 1) if sieve[n]] def source_orders(limit: int, t: int) -> tuple[dict[int, list[tuple[int, int]]], set[int]]: if type(limit) is not int or limit < 0: raise ValueError("limit must be a nonnegative integer") if type(t) is not int or t < 1: raise ValueError("t must be a positive integer") source_factor = 2 * t q_limit = limit // source_factor - 1 primes = primes_through(q_limit) prime_set = set(primes) prime_powers: set[int] = set() for p in primes: if p == 2: continue q = p while q <= q_limit: if q % 4 == 1: prime_powers.add(q) q *= p parameters: dict[int, list[tuple[int, int]]] = defaultdict(list) main: set[int] = set() for q in sorted(prime_powers): n, r = source_factor * (q + 1), 0 while n <= limit: parameters[n].append((q, r)) if r == 0 and q in prime_set: main.add(n) n *= q r += 1 return dict(parameters), main def v2(n: int) -> int: return (n & -n).bit_length() - 1 def grammar_checks(max_budget: int = 128) -> dict: if type(max_budget) is not int or max_budget < 0: raise ValueError("max_budget must be a nonnegative integer") # Best leaf reduction at cost AT MOST budget, independently computed. reductions = [0] * (max_budget + 1) for budget in range(1, max_budget + 1): reductions[budget] = max( [reductions[budget - 1]] + [ reductions[budget - cost] + reduction for cost, reduction in ((1, 1), (2, 3), (7, 11)) if cost <= budget ] ) require(reductions[budget] == 11 * budget // 7, "Dynamic leaf budget differs from the sharp formula") t, remainder = divmod(budget, 7) four_nodes, two_nodes = divmod(remainder, 2) require(7 * t + 2 * four_nodes + two_nodes == budget, "Leaf-budget witness has a different cost") require(11 * t + 3 * four_nodes + two_nodes == reductions[budget], "Leaf-budget witness has a different reduction") # Independently minimize cost for an EXACT leaf reduction. Every root # operation splits it into arity-1 new leaves plus an existing subtree. costs = [0] for reduction in range(1, 256): costs.append( min( cost + costs[reduction - gained] for cost, gained in ((1, 1), (2, 3), (7, 11)) if gained <= reduction ) ) require(costs[-1] == (7 * reduction + 10) // 11, "Dynamic product cost differs from the ceiling formula") t, remainder = divmod(reduction, 11) four_nodes, two_nodes = divmod(remainder, 3) require(7 * t + 2 * four_nodes + two_nodes == costs[-1], "Product-cost witness does not attain the dynamic minimum") return { "budget_range_checked": [0, max_budget], "sharp_maximum_leaf_count": "1+floor(11*budget/7)", "exact_minimum_cost_for_k_leaves": "ceil(7*(k-1)/11)", "exact_leaf_reductions_checked": [0, 255], "cost_for_k_source_leaves": {str(k): costs[k - 1] for k in (1, 2, 4, 12, 64)}, "all_dynamic_programming_checks_passed": True, } def ledger_check(path: Path) -> dict: payload = path.read_bytes() ledger = json.loads(payload) new_orders = ledger["completed_new_real_orders"] known_orders = ledger["completed_known_real_orders"] all_orders = sorted(set(new_orders) | set(known_orders)) require(len(set(new_orders)) == len(new_orders), "Duplicate new-order ledger entry") require(len(set(known_orders)) == len(known_orders), "Duplicate known-order ledger entry") require(not set(new_orders) & set(known_orders), "Known and new ledger labels overlap") require(all(n % 4 == 0 for n in all_orders), "Ledger order is not divisible by four") return { "ledger_path": str(path), "ledger_sha256": hashlib.sha256(payload).hexdigest(), "new_label_scope": "new to the best of the author's knowledge in the supplied ledger", "new_count": len(new_orders), "known_count": len(known_orders), "all_count": len(all_orders), "new_not_divisible_by_631": [n for n in new_orders if n % 631], "all_not_divisible_by_631": [n for n in all_orders if n % 631], "gcd_of_all_orders": math.gcd(*all_orders), } def report(limit: int, t: int, ledger: Path | None) -> dict: parameters, main = source_orders(limit, t) if limit < 60 * t: raise ValueError("limit must be at least 60*t to include the collision control") orders = set(parameters) require(all(v2(n) == 2 + v2(t) for n in orders), "Source order has an unexpected exact power of two") require((5, 1) in parameters[60 * t] and (29, 0) in parameters[60 * t], "The declared parameter-collision control is missing") intervals = [] for n in (100_000, 1_000_000, 10_000_000, 100_000_000): if 2 * n > limit: continue count = sum(n <= order <= 2 * n for order in orders) main_count = sum(n <= order <= 2 * n for order in main) leading = n / (4 * t * math.log(n)) intervals.append({ "N": n, "c": 2, "distinct_order_count": count, "prime_r0_count": main_count, "other_distinct_orders": count - main_count, "leading_asymptotic_term": leading, "count_divided_by_leading_term": count / leading, }) result = { "schema": "hadamard-source-counts-v1", "scope": "Finite arithmetic replay for a proved source family; no matrix search and no finite verification of an asymptotic theorem.", "source_order_formula": "2*t*(q+1)*q^r, q an odd prime power congruent to 1 mod 4, r>=0", "t": t, "design_hypothesis": "An independently verified OD(4t;t,t,t,t) source, with coefficient supports partitioning the entries", "maximum_order": limit, "distinct_orders_through_maximum": len(orders), "parameter_pairs_through_maximum": sum(map(len, parameters.values())), "prime_r0_orders_through_maximum": len(main), "orders_not_in_prime_r0_subfamily": len(orders - main), "exact_v2_of_every_source_order": 2 + v2(t), "collision_count": sum(len(pairs) > 1 for pairs in parameters.values()), "first_parameter_collisions": [ {"order": n, "parameters_q_r": parameters[n]} for n in sorted(parameters) if len(parameters[n]) > 1 ][:20], "fixed_ratio_interval_counts": intervals, "grammar": grammar_checks(), "proof_dependencies_not_proved_by_script": [ "An independently verified T_t design and the Turyn/Spence existence theorem; t=631 is the retained source", "Classical two-, four-, twelve-input Hadamard product theorems", "Prime number theorem in the progression 1 mod 4", ], } if ledger: result["finite_seed_ledger"] = ledger_check(ledger) return result def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--limit", type=int, default=1_000_000_000) parser.add_argument("--t", type=int, default=631, help="Positive design parameter, conditional on an independently verified T_t source") parser.add_argument("--ledger", type=Path) parser.add_argument("--output", type=Path) args = parser.parse_args() if args.t <= 0: parser.error("--t must be positive") if args.limit < 60 * args.t: parser.error("--limit must be at least 60*t to include the collision control") try: data = report(args.limit, args.t, args.ledger) except (OSError, ValueError, KeyError, TypeError) as exc: parser.exit(1, f"Arithmetic replay failed: {exc}\n") rendered = json.dumps(data, indent=2, sort_keys=True) + "\n" if args.output: args.output.write_text(rendered) else: print(rendered, end="") if __name__ == "__main__": main()