"""ORYNTHRA-H6: reference computations for branch-covariant compression. This is a small research implementation, not a general-purpose file compressor, a quantum hardware controller, or a certified formal proof system. Finite-field routines support prime fields only; the manuscript permits F_q. """ from __future__ import annotations from dataclasses import dataclass from functools import lru_cache from itertools import permutations, product from math import comb, ceil, log2, sqrt, log1p, log, isfinite from typing import Iterable, Sequence, Hashable import numpy as np def _positive_int(value: int, name: str) -> int: if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < 1: raise ValueError(f"{name} must be a positive integer") return int(value) def _prime(p: int) -> int: p = _positive_int(p, "p") if p < 2 or any(p % d == 0 for d in range(2, int(sqrt(p)) + 1)): raise ValueError("Only prime fields are implemented") return p def rref_mod(rows: np.ndarray, p: int = 2) -> tuple[np.ndarray, tuple[int, ...]]: """Reduced row basis over F_p, with pivot-column indices.""" p = _prime(p) a = np.asarray(rows, dtype=np.int64).copy() % p if a.ndim != 2: raise ValueError("rows must be a two-dimensional array") pivot_columns: list[int] = [] r = 0 for c in range(a.shape[1]): nz = np.flatnonzero(a[r:, c]) if not len(nz): continue j = r + int(nz[0]) a[[r, j]] = a[[j, r]] a[r] = (a[r] * pow(int(a[r, c]), -1, p)) % p for j in range(a.shape[0]): if j != r and a[j, c]: a[j] = (a[j] - a[j, c] * a[r]) % p pivot_columns.append(c) r += 1 if r == a.shape[0]: break return a[:r], tuple(pivot_columns) def inverse_mod(matrix: np.ndarray, p: int = 2) -> np.ndarray: a = np.asarray(matrix, dtype=np.int64) if a.ndim != 2 or a.shape[0] != a.shape[1]: raise ValueError("matrix must be square") n = a.shape[0] reduced, pivots = rref_mod(np.hstack((a, np.eye(n, dtype=int))), p) if pivots[:n] != tuple(range(n)): raise ValueError("matrix is singular over the supplied field") return reduced[:, n:] @dataclass(frozen=True) class LinearEdge: source: int target: int matrix: np.ndarray name: str = "" def observable_closure(observations: Sequence[np.ndarray], edges: Sequence[LinearEdge], p: int = 2, horizon: int | None = None) -> tuple[list[np.ndarray], list[list[int]]]: """Simultaneous pullback closure, or paths of length <= horizon. A row at the target of T pulls back to row @ T at its source. The trace contains ranks at initialization and after strict changes. Matrices need not be invertible for this routine. """ p = _prime(p) if not observations: raise ValueError("At least one domain is required") bases = [rref_mod(np.asarray(a), p)[0] for a in observations] dimensions = [a.shape[1] for a in bases] if horizon is not None and (not isinstance(horizon, int) or horizon < 0): raise ValueError("horizon must be a nonnegative integer or None") for e in edges: if not (0 <= e.source < len(bases) and 0 <= e.target < len(bases)): raise ValueError("edge domain index out of range") if np.shape(e.matrix) != (dimensions[e.target], dimensions[e.source]): raise ValueError("edge matrix shape is incompatible with domains") trace = [[len(a) for a in bases]] for _ in range(sum(dimensions) + 1 if horizon is None else horizon): candidates = [[a] for a in bases] for e in edges: candidates[e.source].append((bases[e.target] @ e.matrix) % p) newer = [rref_mod(np.vstack(parts), p)[0] for parts in candidates] if all(np.array_equal(a, b) for a, b in zip(bases, newer)): break bases = newer trace.append([len(a) for a in bases]) return bases, trace def induced_linear_map(c_source: np.ndarray, c_target: np.ndarray, transition: np.ndarray, p: int = 2) -> np.ndarray: """Return B with C_target T = B C_source; C_source must be in RREF.""" c, pivots = rref_mod(c_source, p) if not np.array_equal(c, np.asarray(c_source) % p): raise ValueError("c_source must be an independent RREF basis") pulled = (np.asarray(c_target) @ transition) % p b = pulled[:, list(pivots)] if not np.array_equal((b @ c) % p, pulled): raise ValueError("The proposed source quotient is not transition-closed") return b def canonical_labels(values: Sequence[Hashable]) -> tuple[int, ...]: labels: dict[Hashable, int] = {} return tuple(labels.setdefault(v, len(labels)) for v in values) def finite_partition(observation: Sequence[Hashable], transitions: Sequence[Sequence[int]]) -> tuple[int, ...]: """Minimal deterministic future-observation partition of one finite domain.""" n = len(observation) if not n: raise ValueError("At least one state is required") for t in transitions: if len(t) != n or any(not 0 <= int(j) < n for j in t): raise ValueError("Invalid transition map") labels = canonical_labels(observation) for _ in range(n): newer = canonical_labels([(labels[x], tuple(labels[t[x]] for t in transitions)) for x in range(n)]) if newer == labels: return labels labels = newer raise RuntimeError("Partition refinement exceeded its finite bound") def permutation_matrix(perm: Sequence[int]) -> np.ndarray: """Column convention: P|j> = |perm[j]>.""" p = tuple(int(x) for x in perm) if sorted(p) != list(range(len(p))): raise ValueError("perm is not a permutation of 0,...,n-1") result = np.zeros((len(p), len(p))) result[np.array(p), np.arange(len(p))] = 1.0 return result def six_wing_actions(n: int, wings: int = 6) -> list[np.ndarray]: """Involutions swapping equally colored edges of a path of n coordinates.""" n = _positive_int(n, "n") wings = _positive_int(wings, "wings") if wings < 2: raise ValueError("At least two colors are needed for disjoint matchings") maps = [np.arange(n) for _ in range(wings)] for i in range(n - 1): color = i % wings maps[color][i], maps[color][i + 1] = maps[color][i + 1], maps[color][i] return [permutation_matrix(a).astype(int) for a in maps] def six_wing_rank_formula(n: int, active: Iterable[int], wings: int = 6) -> int: active = set(active) if not active.issubset(set(range(wings))): raise ValueError("Invalid wing index") for i in range(n - 1): if i % wings not in active: return i + 1 return n def photon_sector(modes: int, photons: int) -> int: modes = _positive_int(modes, "modes") if not isinstance(photons, (int, np.integer)) or photons < 0: raise ValueError("photons must be a nonnegative integer") return comb(modes + int(photons) - 1, int(photons)) def photon_capacity(modes: int, cutoff: int) -> int: modes = _positive_int(modes, "modes") if not isinstance(cutoff, (int, np.integer)) or cutoff < 0: raise ValueError("cutoff must be a nonnegative integer") return comb(modes + int(cutoff), int(cutoff)) def _first_true(predicate) -> int: if predicate(0): return 0 high = 1 while not predicate(high): high *= 2 low = 0 while low + 1 < high: mid = (low + high) // 2 if predicate(mid): high = mid else: low = mid return high def storage_cutoff(messages: int, modes: int) -> int: messages = _positive_int(messages, "messages") modes = _positive_int(modes, "modes") return _first_true(lambda k: photon_capacity(modes, k) >= messages) def symmetric_cutoff(messages: int, modes: int) -> int | None: """Exact phase-registered S_M action, arbitrary number-preserving gates. None means impossible for a single nondegenerate oscillator and M >= 3. """ messages = _positive_int(messages, "messages") modes = _positive_int(modes, "modes") if messages == 1: return 0 if messages == 2: return 1 if modes == 1: return None return max(1, _first_true(lambda k: photon_sector(modes, k) >= messages - 1)) def minimum_storage_mean(messages: int, modes: int) -> float: """Mean photons for uniform orthogonal messages, without gate constraints.""" k = storage_cutoff(messages, modes) if k == 0: return 0.0 lower_count = photon_capacity(modes, k - 1) lower_sum = 0 if k == 1 else modes * comb(modes + k - 1, k - 2) return (lower_sum + k * (messages - lower_count)) / messages def pack_items(items: Sequence[int], capacities: Sequence[int]) -> tuple[int, ...] | None: """Exact indivisible packing. Return the bin index for each original item. This exponential reference solver is intended only for small instances. Equal residual capacities are symmetry-pruned. Bin identity is retained. """ original = tuple(_positive_int(v, "item size") for v in items) cap = tuple(int(v) for v in capacities) if any(v < 0 for v in cap): raise ValueError("capacities must be nonnegative") order = sorted(range(len(original)), key=lambda i: original[i], reverse=True) ordered = tuple(original[i] for i in order) if sum(ordered) > sum(cap): return None @lru_cache(None) def recurse(i: int, residual: tuple[int, ...]): if i == len(ordered): return () if sum(ordered[i:]) > sum(residual): return None tried = set() for b, room in enumerate(residual): if room in tried or room < ordered[i]: continue tried.add(room) nxt = list(residual) nxt[b] -= ordered[i] tail = recurse(i + 1, tuple(nxt)) if tail is not None: return (b,) + tail return None assignment = recurse(0, cap) if assignment is None: return None result = [0] * len(order) for i, b in zip(order, assignment): result[i] = b return tuple(result) def maximum_packed_dimension(items: Sequence[int], capacities: Sequence[int]) -> int: """Largest total dimension of a subset of irrep copies that fits.""" values = tuple(sorted((_positive_int(v, "item size") for v in items), reverse=True)) capacities = tuple(sorted((int(x) for x in capacities), reverse=True)) if any(x < 0 for x in capacities): raise ValueError("capacities must be nonnegative") @lru_cache(None) def recurse(i: int, residual: tuple[int, ...]) -> int: if i == len(values): return 0 best = recurse(i + 1, residual) tried = set() for b, room in enumerate(residual): if room < values[i] or room in tried: continue tried.add(room) nxt = list(residual) nxt[b] -= values[i] candidate = values[i] + recurse(i + 1, tuple(sorted(nxt, reverse=True))) best = max(best, candidate) return best return recurse(0, capacities) def representation_cutoff(irrep_dimensions: Sequence[int], modes: int, max_cutoff: int = 100) -> int | None: """Find exact cutoff for a supplied list of complex irrep-copy dimensions. The group decomposition is supplied, not inferred. None can mean the requested finite search range was insufficient (except single-mode no-go). """ dims = tuple(_positive_int(d, "irrep dimension") for d in irrep_dimensions) modes = _positive_int(modes, "modes") if not dims: raise ValueError("At least one irrep copy is required") if modes == 1 and max(dims) > 1: return None for k in range(storage_cutoff(sum(dims), modes), max_cutoff + 1): if pack_items(dims, [photon_sector(modes, n) for n in range(k + 1)]) is not None: return k return None def helmert_matrix(messages: int) -> np.ndarray: """Orthogonal matrix with constant first row; remaining rows span a simplex.""" m = _positive_int(messages, "messages") h = np.zeros((m, m)) h[0] = 1 / sqrt(m) for j in range(1, m): h[j, :j] = 1 / sqrt(j * (j + 1)) h[j, j] = -j / sqrt(j * (j + 1)) return h def simplex_code(messages: int, modes: int = 2): """Return code matrix in its occupied subspace, photon number, and cutoff. First physical basis vector is vacuum. Remaining M-1 vectors are chosen within the same K-photon sector. Full unused Fock levels are omitted. """ k = symmetric_cutoff(messages, modes) if k is None: raise ValueError("The requested coherent branch representation is impossible") v = helmert_matrix(messages) number = np.diag([0] + [k] * (messages - 1)) return v, number, k def bosonic_entropy(mean_per_mode: float) -> float: """Thermal entropy in bits, evaluated without large-n cancellation.""" n = float(mean_per_mode) if not isfinite(n) or n < 0: raise ValueError("mean_per_mode must be finite and nonnegative") if n == 0: return 0.0 if n >= 1: # g(n) = log(1+n) + n*log(1+1/n), converted from nats to bits. return (log1p(n) + n * log1p(1 / n)) / log(2) # This form also handles subnormal n without evaluating 1/n. return (1 + n) * log1p(n) / log(2) - n * log2(n) def binary_entropy(error: float) -> float: if not 0 <= error <= 1: raise ValueError("error must lie in [0,1]") if error in (0, 1): return 0.0 return -error * log2(error) - (1 - error) * log2(1 - error) def mean_photon_lower_bound(bits: float, modes: int, error: float = 0.0) -> float: """Numerical value of a necessary mean-energy bound; not certified rounding. This does not claim that a code attains the entropy-based lower bound. """ modes = _positive_int(modes, "modes") if not isfinite(bits) or bits < 0 or not 0 <= error <= 0.5: raise ValueError("bits must be finite and nonnegative and error in [0,0.5]") target = bits * (1 - binary_entropy(error)) if target == 0: return 0.0 hi = 1.0 while modes * bosonic_entropy(hi / modes) < target: hi *= 2 if hi > 1e12: raise ValueError("Target is too large for this floating-point demo") lo = 0.0 for _ in range(90): mid = (lo + hi) / 2 if modes * bosonic_entropy(mid / modes) >= target: hi = mid else: lo = mid return hi