File size: 14,810 Bytes
e740887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""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