"""Implicit Sylvester block mixing of separately verified Hadamard seeds. The block formula also appears in Cinna Davis's research notes: https://github.com/1337isnot1337/solved-conjectures/blob/959a0e7b4e9a1699b2a41fa994d16a7a615faac3/research/minc/sign-matrices/hadamard_arbitrary_order_codes.md This implements a classical construction; that link is a research lead, not a claim that the construction originated there. Order and equivalence claims remain separate. Large seeds are mathematical inputs certified by the retained rank comparison, not reverified by allocating a large matrix. """ from __future__ import annotations import argparse from dataclasses import dataclass from functools import cached_property import hashlib import json import operator from pathlib import Path from typing import Callable import numpy as np RANK_CERTIFICATE_SHA256 = '5c16d568d7f30d5bb06cad187f920fd482a67721614a3170a832a67e7a5352a0' WILLIAMSON_INPUT_SHA256 = '242f554cf113c68ab882e147c3b2702b7bb62e68b66ad36b16c92b6c194f8560' CINNA_SOURCE = 'https://github.com/1337isnot1337/solved-conjectures/blob/959a0e7b4e9a1699b2a41fa994d16a7a615faac3/research/minc/sign-matrices/hadamard_arbitrary_order_codes.md' MAX_EXPONENT = 4096 def require(condition, message): if not condition: raise ValueError(message) def integer(value, name, minimum=0): require(not isinstance(value, (bool, np.bool_)), name + ' must be an exact integer') try: result = operator.index(value) except TypeError as error: raise ValueError(name + ' must be an exact integer') from error require(result >= minimum, name + ' is below its minimum') return result def bounded_index(value, bound, name): result = integer(value, name) require(result < bound, name + ' is outside its range') return result def block_count(exponent): exponent = integer(exponent, 'exponent') require(exponent <= MAX_EXPONENT, 'exponent exceeds the supported bit budget') return 1 << exponent def digest(raw): return hashlib.sha256(raw).hexdigest() def rank_mod3(matrix): """Exact elimination for small controls, independent of rank predictions.""" values = np.asarray(matrix) require(values.ndim == 2 and np.issubdtype(values.dtype, np.integer), 'rank input must be an integer matrix') require(max(values.shape, default=0) <= 512, 'direct rank control exceeds its order budget') rows = (values % 3).astype(np.int64).tolist() if not rows: return 0 pivot = 0 for column in range(len(rows[0])): found = next((i for i in range(pivot, len(rows)) if rows[i][column]), None) if found is None: continue rows[pivot], rows[found] = rows[found], rows[pivot] inverse = rows[pivot][column] # Both nonzero residues are self-inverse. rows[pivot] = [(inverse * x) % 3 for x in rows[pivot]] for i in range(pivot + 1, len(rows)): factor = rows[i][column] if factor: rows[i] = [(x-factor*y) % 3 for x, y in zip(rows[i], rows[pivot])] pivot += 1 if pivot == len(rows): break return pivot @dataclass(frozen=True, init=False, eq=False) class ArrayHadamard: """A small immutable literal seed with every integer row Gram checked.""" def __init__(self, matrix, maximum_order=256): values = np.asarray(matrix) maximum_order = integer(maximum_order, 'maximum seed order', 1) require(values.ndim == 2 and values.shape[0] == values.shape[1] and values.shape[0] > 0, 'seed must be a nonempty square matrix') require(len(values) <= maximum_order, 'seed exceeds the dense verification budget') require(np.issubdtype(values.dtype, np.integer) and np.all(np.isin(values, [-1, 1])), 'seed entries must be integer signs') checked = values.astype(np.int64, copy=True) require(np.array_equal(checked @ checked.T, len(checked)*np.eye(len(checked), dtype=np.int64)), 'seed fails its complete integer Gram') literal = checked.astype(np.int8) literal.setflags(write=False) object.__setattr__(self, '_matrix', literal) object.__setattr__(self, 'order', len(checked)) object.__setattr__(self, 'sha256', digest(literal.tobytes())) def entry(self, row, column): row = bounded_index(row, self.order, 'seed row') column = bounded_index(column, self.order, 'seed column') return int(self._matrix[row, column]) def array(self): return self._matrix.copy() @dataclass(frozen=True) class ThresholdSelector: first_b: int def __call__(self, block): return int(block < self.first_b) class SylvesterBlocks: """Entry recipe conditional on separately verified equal-order seeds. The selector is evaluated at a column-block index. For arbitrary callable selectors the caller supplies a total function into the seed indices; every requested selection and sign is checked. The two-seed factory below gives a total selector with known block counts without storing 2^t choices. """ def __init__(self, seeds, exponent, selector: Callable[[int], int]): self.seeds = tuple(seeds) require(self.seeds and callable(selector), 'seeds and a callable block selector are required') orders = [integer(getattr(seed, 'order', None), 'seed order', 1) for seed in self.seeds] require(len(set(orders)) == 1 and all(callable(getattr(seed, 'entry', None)) for seed in self.seeds), 'all seeds must have the same order and an entry recipe') self.seed_order = orders[0] self.blocks = block_count(exponent) self.order = self.seed_order*self.blocks self.selector = selector def selected_seed(self, block): block = bounded_index(block, self.blocks, 'column block') return bounded_index(self.selector(block), len(self.seeds), 'selected seed') def entry(self, row, column): row = bounded_index(row, self.order, 'row') column = bounded_index(column, self.order, 'column') u, i = divmod(row, self.seed_order) v, j = divmod(column, self.seed_order) sign = integer(self.seeds[self.selected_seed(v)].entry(i, j), 'seed sign', -1) require(sign in (-1, 1), 'seed recipe returned a non-sign') return (-sign if (u & v).bit_count() % 2 else sign) def row(self, row, maximum_entries=262144): row = bounded_index(row, self.order, 'row') maximum_entries = integer(maximum_entries, 'row entry budget', 1) require(self.order <= maximum_entries, 'row exceeds the requested allocation budget') return np.fromiter((self.entry(row, j) for j in range(self.order)), dtype=np.int8, count=self.order) def dense(self, maximum_order=256): maximum_order = integer(maximum_order, 'dense order budget', 1) require(self.order <= maximum_order, 'matrix exceeds the dense allocation budget') return np.stack([self.row(i, maximum_entries=maximum_order) for i in range(self.order)]) def conditional_rank_mod3(self, seed_ranks, maximum_blocks=4096): """Apply rank additivity assuming the supplied seed ranks are proved.""" ranks = tuple(integer(r, 'seed rank') for r in seed_ranks) require(len(ranks) == len(self.seeds) and all(r <= self.seed_order for r in ranks), 'seed rank metadata disagree with the sources') if type(self.selector) is ThresholdSelector and len(ranks) == 2: k = integer(self.selector.first_b, 'number of B blocks') require(k <= self.blocks, 'number of B blocks exceeds all blocks') return (self.blocks-k)*ranks[0]+k*ranks[1] maximum_blocks = integer(maximum_blocks, 'block census budget', 1) require(self.blocks <= maximum_blocks, 'selector census exceeds the requested budget') return sum(ranks[self.selected_seed(v)] for v in range(self.blocks)) def two_seed_recipe(seed_a, seed_b, exponent, b_blocks): m = block_count(exponent) k = integer(b_blocks, 'number of B blocks') require(k <= m, 'number of B blocks exceeds all blocks') return SylvesterBlocks((seed_a, seed_b), exponent, ThresholdSelector(k)) def small_seed_pair(williamson_inputs): """Literal H36 controls: retained WT9 (rank16), Paley-II17 (rank18).""" raw = Path(williamson_inputs).read_bytes() require(digest(raw) == WILLIAMSON_INPUT_SHA256, 'Williamson input hash mismatch') record = next(x for x in json.loads(raw)['entries'] if x['order'] == 9) words = record['first_rows_pm'] require(len(words) == 4 and all(len(s) == 9 and set(s) <= {'+', '-'} for s in words), 'invalid WT9 literal input') indices = (np.arange(9)[None, :]-np.arange(9)[:, None]) % 9 a, b, c, d = [np.array([1 if x == '+' else -1 for x in word], dtype=np.int64)[indices] for word in words] williamson = np.block([[a,b,c,d],[-b,a,-d,c],[-c,d,a,-b],[-d,-c,b,a]]) q = 17 character = np.array([0]+[1 if pow(x, 8, q) == 1 else -1 for x in range(1,q)], dtype=np.int64) conference = np.ones((18,18), dtype=np.int64) conference[0,0] = 0 conference[1:,1:] = character[(np.arange(q)[None,:]-np.arange(q)[:,None]) % q] a, b = conference+np.eye(18,dtype=np.int64), conference-np.eye(18,dtype=np.int64) paley = np.block([[a,b],[b,-a]]) return ArrayHadamard(williamson), ArrayHadamard(paley) def small_control_report(williamson_inputs): a, b = small_seed_pair(williamson_inputs) seed_ranks = rank_mod3(a.array()), rank_mod3(b.array()) require(seed_ranks == (16,18), 'H36 control ranks disagree') outputs = [] for exponent in (1,2): m = block_count(exponent) for k in range(m+1): recipe = two_seed_recipe(a,b,exponent,k) matrix = recipe.dense().astype(np.int64) require(np.array_equal(matrix @ matrix.T, recipe.order*np.eye(recipe.order,dtype=np.int64)), 'bootstrap control fails its full integer Gram') actual = rank_mod3(matrix) require(actual == recipe.conditional_rank_mod3(seed_ranks) == 16*m+2*k, 'direct bootstrap rank disagrees with the block formula') outputs.append({'order':recipe.order,'B_blocks':k,'rank_mod3':actual, 'full_integer_Gram_checked':True,'literal_int8_sha256':digest(matrix.astype(np.int8).tobytes())}) return {'source_order':36,'seed_ranks_mod3':list(seed_ranks), 'seed_int8_sha256':[a.sha256,b.sha256], 'Williamson_input_sha256':WILLIAMSON_INPUT_SHA256,'outputs':outputs} def _checked_retained_rank_certificate(certificate_path): path = Path(certificate_path) raw = path.read_bytes() require(digest(raw) == RANK_CERTIFICATE_SHA256, 'retained rank certificate hash mismatch') record = json.loads(raw) require(record['order'] == 885924 and record['field'] == 'F3' and record['endpoint_rank'] == 246090 and record['Paley_I']['rank_mod3'] == 442962, 'retained rank certificate fields disagree') return record class RetainedScalarSeed: """The existing scalar endpoint, initialized only at its first entry. Existing source initialization checks the351-source and builds/replays its2524-dimensional frames once for this seed object. It never creates the885924-by-885924 output. Constructing this adapter alone is cheap. """ order = 885924 rank_mod3 = 246090 @cached_property def _endpoint(self): from search.code.tripled_unreal_scalar_endpoints import endpoint source = endpoint(351) require(source.order == self.order, 'retained scalar endpoint order disagrees') return source def entry(self, row, column): row = bounded_index(row, self.order, 'seed row') column = bounded_index(column, self.order, 'seed column') return self._endpoint.entry(row, column) class RetainedPaleySeed: """Implicit Paley-I matrix at the certificate's fixed prime885923.""" order = 885924 rank_mod3 = 442962 def entry(self, row, column): row = bounded_index(row, self.order, 'seed row') column = bounded_index(column, self.order, 'seed column') if row == 0: return 1 if column == 0: return -1 if row == column: return 1 prime = self.order-1 return 1 if pow((column-row) % prime, (prime-1)//2, prime) == 1 else -1 def retained_seed_recipes(certificate_path): """Digest-bind both proved seeds without replaying or allocating them. The scalar adapter lazily invokes its existing bounded frame/source initialization at the first explicit scalar entry request. Paley entries use modular exponentiation. Neither adapter allocates the large matrix. """ _checked_retained_rank_certificate(certificate_path) return RetainedScalarSeed(), RetainedPaleySeed() def known_rank_family_report(certificate_path, exponents=(0,1,2,4,8)): path = Path(certificate_path) _checked_retained_rank_certificate(path) families=[] for exponent in exponents: exponent = integer(exponent, 'exponent') m=block_count(exponent) families.append({'exponent':exponent,'order':885924*m, 'pairwise_inequivalent_representatives':m+1, 'rank_formula':f'{m}*246090 + k*196872, 0<=k<={m}', 'extreme_ranks_mod3':[m*246090,m*442962]}) return {'source_certificate':str(path),'source_certificate_sha256':RANK_CERTIFICATE_SHA256, 'source_order':885924,'source_ranks_mod3':[246090,442962], 'production_factory':'retained_seed_recipes(certificate_path)', 'entry_recipe':'Use two_seed_recipe(*retained_seed_recipes(path), exponent=t, b_blocks=k).entry(i,j)', 'lazy_initialization_scope':'Only an explicit scalar entry invokes the existing351-source/2524-frame replay; default reporting does not.', 'families':families,'large_dense_matrix_allocated':False, 'rank_input_scope':'Existing exact certificate reused by digest; its 702-dimensional audit is not rerun here.', 'global_new_equivalence_class_claimed':False,'new_Hadamard_order_claimed':False, 'new_Lean_proof_claimed':False} def main(argv=None): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--williamson-inputs',type=Path,default=Path('search/code/williamson_inputs.json')) parser.add_argument('--rank-certificate',type=Path,default=Path('certificates/scalar-lift/known-order-paley-comparison.json')) parser.add_argument('--output',type=Path) args=parser.parse_args(argv) report={'schema':'Hadamard-Sylvester-block-bootstrap-v1','source_lead':CINNA_SOURCE, 'construction_attribution':'Classical block construction; Cinna Davis notes supplied the present lead.', 'identity':'H=(W_m tensor I_h)*diag(K_0,...,K_(m-1)); m=2^t', 'equivalence':'Independent signed row/column permutations, also allowing transpose', 'small_controls':small_control_report(args.williamson_inputs), 'retained_large_seed_family':known_rank_family_report(args.rank_certificate)} rendered=json.dumps(report,indent=2)+'\n' if args.output:args.output.write_text(rendered) else:print(rendered,end='') return report if __name__=='__main__': main()