"""Exact periodic-T / negacyclic-Paley product with implicit large endpoints. The mathematical construction works over every finite field q=3 mod4. This bounded replay implements prime fields only. It stores four T rows and sixteen small Paley blocks; the default T631 endpoint is never expanded. """ from __future__ import annotations import argparse import hashlib import json from pathlib import Path import numpy as np from sympy import factorint, isprime ROOT = Path(__file__).resolve().parents[2] T631_PATH = ROOT / 'artifacts/hadamard-7572/t631.json' T631_SHA256 = 'c5497ef485a23f1c99385035eaf02472b4dad4dee9d906d0d6b2aeb2f3680871' MAXIMUM_PRIME = 211 MAXIMUM_T_LENGTH = 4096 MAXIMUM_DENSE_ORDER = 512 PRIMARY = 'https://documents.uow.edu.au/~jennie/WEBPDF/139_1990.pdf' NEGACYCLIC_PRIMARY = 'https://arxiv.org/abs/1508.00640v1' def require(condition, message): if not condition: raise ValueError(message) def sha(raw): return hashlib.sha256(raw).hexdigest() def checked_prime(prime): require(type(prime) is int and prime >= 3, 'prime must be an integer at least3') require(prime <= MAXIMUM_PRIME, 'prime-field replay budget exceeded') require(prime % 4 == 3 and isprime(prime), 'this finite replay requires a prime congruent3mod4, not a composite prime power') return prime def checked_t_rows(values): raw = np.asarray(values) require(raw.ndim == 2 and raw.shape[0] == 4 and raw.shape[1] > 0, 'four nonempty periodic T rows required') require(raw.shape[1] <= MAXIMUM_T_LENGTH, 'periodic T replay budget exceeded') require(np.issubdtype(raw.dtype, np.integer) and not np.issubdtype(raw.dtype, np.bool_), 'T rows must have exact integer entries') require(np.all((raw == -1) | (raw == 0) | (raw == 1)), 'invalid periodic T alphabet') rows = raw.astype(np.int64) require(np.all(np.sum(abs(rows), axis=0) == 1), 'T support must partition every position') t = rows.shape[1] correlations = [int(np.sum(rows * np.roll(rows, -shift, axis=1))) for shift in range(t)] require(correlations == [t] + [0] * (t-1), 'periodic T correlation identity failed') rows.setflags(write=False) return rows, {'length': t, 'actual_alphabet': sorted(map(int, np.unique(rows))), 'disjoint_full_support_checked': True, 'integer_periodic_shifts_checked': t, 'summed_periodic_correlations': correlations, 'literal_rows_int8_sha256': sha(rows.astype(np.int8).tobytes())} def literal_t_rows(t): require(type(t) is int and t in (3, 7), 'literal controls are T3 and T7 only') rows = np.zeros((4, t), dtype=np.int64) if t == 3: rows[0, 0] = rows[1, 1] = rows[2, 2] = 1 else: rows[0, 0] = 1 rows[0, [1, 2, 4]] = -1 rows[1, 3] = rows[2, 6] = rows[3, 5] = 1 return rows def load_t631(path=None): path = T631_PATH if path is None else Path(path) raw = path.read_bytes() require(sha(raw) == T631_SHA256, 'retained T631 source-record hash mismatch') data = json.loads(raw) require(data['p'] == 631 and data['schema'] == 'twisted-t631-recipe-v1', 'unexpected retained T631 record') rows, proof = checked_t_rows(data['b_sequences']) require(rows.shape == (4, 631), 'retained source is not four length631 rows') relative = (path.relative_to(ROOT).as_posix() if (ROOT/'artifacts').is_dir() and path.is_relative_to(ROOT) else str(path)) return rows, {'path': relative, 'source_record_sha256': sha(raw), 'row_field': 'b_sequences', 'T_row_verification': proof} def character(x, prime): return 0 if x % prime == 0 else (1 if pow(x % prime, (prime-1)//2, prime) == 1 else -1) def _multiply(x, y, nonsquare, prime): a, b = x c, d = y return ((a*c+nonsquare*b*d) % prime, (a*d+b*c) % prime) def _power(x, exponent, nonsquare, prime): result = (1, 0) while exponent: if exponent & 1: result = _multiply(result, x, nonsquare, prime) x = _multiply(x, x, nonsquare, prime) exponent //= 2 return result def checked_negacyclic_blocks(values, prime): prime = checked_prime(prime) s = (prime+1)//4 raw = np.asarray(values) require(raw.shape == (4, 4, s, s), 'wrong four-by-four Paley block dimensions') require(np.issubdtype(raw.dtype, np.integer) and not np.issubdtype(raw.dtype, np.bool_), 'Paley blocks must have exact integer entries') require(np.all((raw == 1) | (raw == -1)), 'Paley blocks must have sign entries') blocks = raw.astype(np.int64) offsets = (np.arange(s)[None, :] - np.arange(s)[:, None]) % s wraps = np.where(np.arange(s)[None, :] < np.arange(s)[:, None], -1, 1) for block_row in blocks: for block in block_row: require(np.array_equal(block, block[0][offsets] * wraps), 'Paley block is not negacyclic') require(np.array_equal(block[::-1, ::-1], block.T), 'negacyclic reflection identity failed') matrix = blocks.transpose(0, 2, 1, 3).reshape(prime+1, prime+1) require(np.array_equal(matrix @ matrix.T, (prime+1)*np.eye(prime+1, dtype=np.int64)), 'complete Paley block Hadamard Gram failed') blocks.setflags(write=False) return blocks, {'prime': prime, 'field': f'GF({prime})', 'block_order': s, 'input_Hadamard_order': prime+1, 'all_sixteen_negacyclic_blocks_checked': True, 'all_sixteen_reflection_identities_checked': True, 'full_input_Hadamard_integer_Gram_checked': True, 'input_Hadamard_Gram_entries_checked': (prime+1)**2, 'blocks_int8_sha256': sha(blocks.astype(np.int8).tobytes()), 'literal_negacyclic_first_rows_pm': [[ ''.join('+' if x == 1 else '-' for x in block[0]) for block in row] for row in blocks]} def paley_negacyclic_blocks(prime): prime = checked_prime(prime) s = (prime+1)//4 nonsquare = next(d for d in range(2, prime) if character(d, prime) == -1) divisors = tuple(map(int, factorint(2*s))) generator = next((a, b) for a in range(prime) for b in range(prime) if (a*a-nonsquare*b*b) % prime == 1 and _power((a, b), 2*s, nonsquare, prime) == (1, 0) and all(_power((a, b), 2*s//d, nonsquare, prime) != (1, 0) for d in divisors)) a, b = generator permutation, signs = [], [] for x in range(prime+1): u, v = ((a, b) if x == prime else ((a*x+nonsquare*b) % prime, (b*x+a) % prime)) permutation.append(prime if v == 0 else u*pow(v, -1, prime) % prime) signs.append(character(u if v == 0 else v, prime)) require(sorted(permutation) == list(range(prime+1)) and all(abs(x) == 1 for x in signs), 'invalid signed projective action') orbits, seen = [], set() switches = np.zeros(prime+1, dtype=np.int64) for x in range(prime+1): if x in seen: continue orbit, y, sign = [], x, 1 while y not in seen: seen.add(y) orbit.append(y) switches[y] = sign sign *= signs[y] y = permutation[y] require(y == x and len(orbit) == s and sign == -1, 'projective orbit or negative wrap sign failed') orbits.append(orbit) require(len(orbits) == 4, 'projective action must have four orbits') chi = np.array([character(i, prime) for i in range(prime)], dtype=np.int64) core = chi[(np.arange(prime)[:, None]-np.arange(prime)[None, :]) % prime] matrix = np.eye(prime+1, dtype=np.int64) matrix[:prime, :prime] += core matrix[prime, :prime] = 1 matrix[:prime, prime] = -1 require(np.array_equal(matrix @ matrix.T, (prime+1)*np.eye(prime+1, dtype=np.int64)), 'quadratic-character Paley Gram failed') order = sum(orbits, []) matrix = (switches[:, None]*matrix*switches[None, :])[np.ix_(order, order)] blocks, proof = checked_negacyclic_blocks(matrix.reshape(4, s, 4, s).transpose(0, 2, 1, 3), prime) proof.update({'nonsquare': nonsquare, 'norm_one_generator': list(generator), 'generator_order': 2*s, 'projective_orbits': orbits, 'diagonal_switches': list(map(int, switches)), 'signed_orbit_products': [-1]*4, 'code_scope': 'Prime fields only; the all-prime-power existence theorem is mathematical.'}) return blocks, proof class ImplicitPaleyTEndpoint: """Literal entry access; only the bounded source data are stored.""" _channels = ((0, 1, 2, 3), (1, 0, 3, 2), (2, 3, 0, 1), (3, 2, 1, 0)) _signs = ((1, 1, 1, 1), (-1, 1, 1, -1), (-1, -1, 1, 1), (-1, 1, -1, 1)) def __init__(self, t_rows, prime, source_record=None): self.prime = checked_prime(prime) self.t_rows, self.t_proof = checked_t_rows(t_rows) self.blocks, self.block_proof = paley_negacyclic_blocks(prime) self.t, self.s = self.t_rows.shape[1], (prime+1)//4 self.component_order = self.t*self.s self.order = 4*self.component_order self.axes = np.argmax(abs(self.t_rows), axis=0) self.axis_signs = self.t_rows[self.axes, np.arange(self.t)] self.axes.setflags(write=False) self.axis_signs.setflags(write=False) self.source_record = source_record self._dense_checked = False def _reflection(self, index): a, i = divmod(index, self.s) return ((-a) % self.t)*self.s + self.s-1-i def _component_entry(self, channel, row, column): a, i = divmod(row, self.s) b, j = divmod(column, self.s) shift = (b-a) % self.t return int(self.axis_signs[shift] * self.blocks[self.axes[shift], channel, i, j]) def entry(self, row, column): for index in (row, column): require(isinstance(index, (int, np.integer)) and not isinstance(index, (bool, np.bool_)) and 0 <= index < self.order, 'endpoint index is outside the integer range') block_row, i = divmod(int(row), self.component_order) block_column, j = divmod(int(column), self.component_order) channel = self._channels[block_row][block_column] if block_row == block_column: value = self._component_entry(channel, i, j) elif block_row == 0 or block_column == 0: value = self._component_entry(channel, i, self._reflection(j)) else: value = self._component_entry(channel, self._reflection(j), i) return self._signs[block_row][block_column] * value def dense(self, maximum_order=MAXIMUM_DENSE_ORDER): require(type(maximum_order) is int and 1 <= maximum_order <= MAXIMUM_DENSE_ORDER, 'dense replay budget must be an integer from1through512') require(self.order <= maximum_order, 'dense endpoint replay budget exceeded') # The output budget is checked before any endpoint/component allocation. differences = (np.arange(self.t)[None, :]-np.arange(self.t)[:, None]) % self.t Ts = self.t_rows[:, differences] components = [sum(np.kron(Ts[k], self.blocks[k, j]) for k in range(4)) for j in range(4)] m = self.component_order reflected = [self._reflection(i) for i in range(m)] R = np.eye(m, dtype=np.int64)[:, reflected] A, B, C, D = components output = np.block([[A, B@R, C@R, D@R], [-B@R, A, D.T@R, -C.T@R], [-C@R, -D.T@R, A, B.T@R], [-D@R, C.T@R, -B.T@R, A]]) require(np.all(abs(output) == 1), 'dense output sign test failed') require(np.array_equal(output @ output.T, self.order*np.eye(self.order, dtype=np.int64)), 'full dense endpoint integer Gram failed') self._dense_checked = True return output def proof(self): m = self.component_order samples = [(a*m+i, b*m+j) for a in range(4) for b in range(4) for i, j in ((0, m-1), (m//2, (m//3+1) % m))] report = {'schema': 'periodic-T-negacyclic-Paley-endpoint-v1', 'implementation_sha256': sha(Path(__file__).read_bytes()), 'T_verification': self.t_proof, 'Paley_block_verification': self.block_proof, 'prime': self.prime, 'T_length': self.t, 'component_order': m, 'endpoint_order': self.order, 'endpoint_Gram_scale': self.order, 'all_endpoint_sign_entries_proved_by_disjoint_support': True, 'full_endpoint_Gram_verified_algebraically': True, 'full_dense_endpoint_Gram_checked': self._dense_checked, 'dense_endpoint_allocated': self._dense_checked, 'entry_recipe': 'T-axis selection in A_j=sum_k T_k tensor N_kj, then the signed/transposed Goethals-Seidel array; R(a,i)=(-a modt,s-1-i)', 'literal_entry_samples': [{'row': i, 'column': j, 'value': self.entry(i, j)} for i, j in samples], 'source_urls': [PRIMARY, NEGACYCLIC_PRIMARY], 'scope': 'Exact bounded prime-field inputs and complete algebraic endpoint proof. No individual-order priority, equivalence class, source classification or new Lean proof is claimed.'} if self.source_record is not None: report['retained_source_record'] = self.source_record return report def finite_order_union(limit, t=631): """Count distinct integers in the two proved families, with a sieve budget. These arithmetic counts use the mathematical prime-power theorem; the entry builder above implements only bounded prime-field examples. """ require(type(limit) is int and limit >= 0, 'order limit must be a nonnegative integer') require(type(t) is int and t > 0, 'design length must be a positive integer') q_limit = limit // t - 1 require(q_limit <= 2_000_000, 'prime-power counting sieve budget exceeded') from theory.code.density_checks import primes_through, source_orders first = set(source_orders(limit, t)[0]) second = set() for prime in primes_through(q_limit): if prime % 4 != 3: continue q = prime while q <= q_limit: if q % 4 == 3: second.add(t * (q + 1)) q *= prime return { 'maximum_order': limit, 'T_length': t, 'Spence_family_distinct_orders': len(first), 'Paley_T_family_distinct_orders': len(second), 'intersection_distinct_orders': len(first & second), 'union_distinct_orders': len(first | second), 'additional_relative_to_Spence_family': len(second - first), 'Paley_T_orders_through_100000': sorted(n for n in second if n <= 100000), 'scope': 'Distinct arithmetic orders of the two mathematical families, conditional on a verified periodic T source. No individual-order novelty or finite proof of an asymptotic is inferred.', } def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--prime', type=int, default=43) parser.add_argument('--source', type=Path, default=T631_PATH) parser.add_argument('--toy-t', type=int, choices=(3, 7)) parser.add_argument('--dense', action='store_true', help='Full integer Gram replay, restricted to output order<=512') parser.add_argument('--output', type=Path) parser.add_argument('--order-count-limit', type=int, help='Also replay the distinct-family count, with a bounded prime sieve') args = parser.parse_args(argv) checked_prime(args.prime) if args.toy_t is None: rows, source = load_t631(args.source) else: rows, source = literal_t_rows(args.toy_t), None endpoint = ImplicitPaleyTEndpoint(rows, args.prime, source) if args.dense: endpoint.dense() result = endpoint.proof() if args.order_count_limit is not None: result['finite_family_order_counts'] = finite_order_union(args.order_count_limit, endpoint.t) rendered = json.dumps(result, indent=2) + '\n' if args.output: args.output.write_text(rendered) else: print(rendered, end='') if __name__ == '__main__': main()