From bdc61587b979afd069064269e57521db337bfc26 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Tue, 24 Nov 2026 21:02:38 +0800 Subject: [PATCH] Compile calibrated spectral bands at fixed Hamming weight --- README.md | 4 + learning/anchor.md | 2 + learning/milestones.md | 14 +-- references/related_work.md | 6 ++ science/README.md | 3 + science/encoder.md | 2 + science/fixed_weight_encoder.md | 84 +++++++++++++++++ verification/README.md | 10 ++ verification/verify_fixed_weight.py | 141 ++++++++++++++++++++++++++++ 9 files changed, 259 insertions(+), 7 deletions(-) create mode 100644 science/fixed_weight_encoder.md create mode 100644 verification/verify_fixed_weight.py diff --git a/README.md b/README.md index 8406c21..86b5701 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,8 @@ the [calibrated compiler](science/encoder.md) rounds certified coupling estimate At fixed error, its logical dimension is within a spectrum-independent constant number of qubits of the unrestricted optimum. The compiler is polynomial for bounded couplings, polynomial storage time, and fixed or inverse-polynomial error tolerance. The explicit qubit gap grows with the demanded accuracy; polynomial time in the binary length of the storage time is not claimed. +The [fixed-weight compiler](science/fixed_weight_encoder.md) uses signed integer counts within a prescribed Hamming-weight sector, where a common coupling offset contributes only a scalar phase. [Quantum Memory Calibration](https://github.com/GoGoKo699/Quantum-Memory-Calibration/blob/main/science/compiled_calibration.md) uses these clean blocks and endpoint phase correction to attain the sharp leading calibration budget with polynomial endpoint costs at polynomial hold times. + ## A finite example ![Compiled storage and single-qubit coherence for a nondegenerate 16-qubit register](figures/finite_time_memory.png) @@ -68,6 +70,7 @@ The upper curve is a conservative converse bound, not the exact optimum. The rig | Why does spectral occupancy characterize storage with one noise direction? | [Scalar law](science/spectral_law.md) | | How far can joint spectral occupancy fall short? | [Several noise directions](science/multiple_noise_directions.md) | | How is the code compiled with finite precision and clean workspace? | [Encoder construction](science/encoder.md) | +| How can a conserved weight remove a common coupling offset? | [Fixed-weight compiler](science/fixed_weight_encoder.md) | | What do concrete spectra and circuits demonstrate? | [Examples](science/examples.md) | | How do finite time, exact noiseless sectors and communication capacity differ? | [Consequences and interpretation](science/interpretation.md) | | Which ingredients are inherited, and what is the specific contribution? | [Related work](references/related_work.md) and [bibliography](references/references.bib) | @@ -89,6 +92,7 @@ With Python 3.12, run from the repository root: python verification/run_all.py python verification/generate_examples.py python verification/verify_noise_rank.py + python verification/verify_fixed_weight.py The checks include exact rational band enumeration, Gaussian-matrix inequalities, and actual reversible-gate propagation of basis and reference-entangled inputs. The 16-qubit illustration uses the classical dynamic program; the full primitive circuits are verified on smaller instances. Finite tests support the implementations and examples. The mathematical proofs establish the general storage and complexity claims. diff --git a/learning/anchor.md b/learning/anchor.md index 6a415e4..0fc8d06 100644 --- a/learning/anchor.md +++ b/learning/anchor.md @@ -69,6 +69,8 @@ For $`t\gt0`$, the dimensionless quantity $`t(\lambda_i-\lambda_j)^2`$ determine For one noise direction, this construction loses only a constant number of qubits relative to the all-code optimum at fixed error. Several commuting directions share the Schur-channel description and the same all-code comparison. Their geometry and attainable codes require the separate argument below. +**When a common offset is unknown, fix the physical weight.** In the [fixed-weight compiler](../science/fixed_weight_encoder.md), the weight label determines the eigenvalue of the collective operator $`\sum_i Z_i`$. Every codeword then acquires the same phase from the common offset. Watrous §§2.2.2 and 3.3.2 give the framework for the clean isometry and reference-complete error of its restricted channel. [Quantum Memory Calibration](https://github.com/GoGoKo699/Quantum-Memory-Calibration/blob/main/science/compiled_calibration.md) uses Watrous §§4.1.2–4.1.3 to turn the encoded Schur channels into correlated phase errors by averaging Pauli shifts and then corrects those errors at the far boundary. + ## Worked example: one logical qubit without an exact degeneracy Take two physical qubits with nominal operator diff --git a/learning/milestones.md b/learning/milestones.md index f8a88af..184528a 100644 --- a/learning/milestones.md +++ b/learning/milestones.md @@ -232,13 +232,13 @@ The true coupling vector is fixed throughout each storage interval. For calibrat **Central question.** How does the rounded spectrum become an exact counting problem without losing negative weights or degeneracies? -**Understanding target.** Explain the known bit flips that replace signed weights by nonnegative ones. Preserve zero-weight multiplicities and distinguish an integer band's diameter from its number of integer values. Identify the deterministic maximizing band and the power-of-two subset used for logical qubits. +**Understanding target.** Explain the known bit flips that replace signed weights by nonnegative ones in the full register. In a fixed-weight sector, retain signed weights because those flips generally change the required physical weight. Preserve zero-weight multiplicities and distinguish an integer band's diameter from its number of integer values. Identify the deterministic maximizing band and the power-of-two subset used for logical qubits. **Dependencies and story role.** Converts M18's calibration statement into the discrete object the compiler will count. -**Conceptual connection.** A unitary relabeling preserves the physical problem while simplifying classical arithmetic. +**Conceptual connection.** A relabeling can simplify the arithmetic when it preserves the set of allowed strings. -**Sources.** [Watrous §2.2.2][W2]; [encoder, §2 and (8)–(10)](../science/encoder.md#2-signed-weights-and-the-optimal-closed-band). +**Sources.** [Watrous §2.2.2][W2]; [encoder, §2 and (8)–(10)](../science/encoder.md#2-signed-weights-and-the-optimal-closed-band); [fixed-weight counting](../science/fixed_weight_encoder.md#exact-counting-and-rank-access). ### M20: Physical protection and constant-qubit optimality @@ -256,13 +256,13 @@ The true coupling vector is fixed throughout each storage interval. For calibrat **Central question.** How can the compiler count an exponentially large set without listing its members? -**Understanding target.** Interpret suffix subset-sum counts and their recurrence, then explain how prefix sums count accepted completions of a partial string. Track the bit width of counts, including zero weights and the all-strings case, and the cost of finding the maximizing closed band. +**Understanding target.** Interpret suffix subset-sum counts and their recurrence, then explain how prefix sums count accepted completions of a partial string. For a fixed sector, track the residual weight and signed partial sum together. Track the bit width of counts, including zero weights and the all-strings case, and the cost of finding the maximizing closed band. **Dependencies and story role.** Implements the discrete search defined in M19 while preserving the certificate in M20. **Conceptual connection.** Exact counting supplies a compact description from which coherent codeword selection can be constructed. -**Sources.** [Watrous §2.1.2][W2] for basis labels; [encoder, §3 and (14)–(16)](../science/encoder.md#3-exact-classical-preprocessing). +**Sources.** [Watrous §2.1.2][W2] for basis labels; [encoder, §3 and (14)–(16)](../science/encoder.md#3-exact-classical-preprocessing); [signed suffix recurrence](../science/fixed_weight_encoder.md#exact-counting-and-rank-access). ### M22: Ranking and unranking without listing codewords @@ -296,9 +296,9 @@ The true coupling vector is fixed throughout each storage interval. For calibrat **Dependencies and story role.** Integrates M06, M10 and M21–M23 into the actual quantum implementation. -**Conceptual connection.** Workspace cleanup enforces the physical-memory constraint, rather than merely improving memory usage. +**Conceptual connection.** Workspace cleanup ensures that the physical memory carries the full unknown state. The fixed-weight inverse makes each protected block available to endpoint phase correction. -**Sources.** [Watrous §§2.1.3, 2.2.2][W2]; [encoder, §5 and (19)–(20)](../science/encoder.md#5-clean-coherent-isometry-and-decoding-channel). +**Sources.** [Watrous §§2.1.3, 2.2.2][W2]; [encoder, §5 and (19)–(20)](../science/encoder.md#5-clean-coherent-isometry-and-decoding-channel); [compiled calibration across blocks](https://github.com/GoGoKo699/Quantum-Memory-Calibration/blob/main/science/compiled_calibration.md). ### M25: Composing storage and boundary-operation errors diff --git a/references/related_work.md b/references/related_work.md index ae1dc4a..229c336 100644 --- a/references/related_work.md +++ b/references/related_work.md @@ -73,6 +73,12 @@ The substantive remainder is the combination of a dimension- and spectrum-unifor The scalar occupation theorem is information theoretic. Efficient implementation requires the explicit linear-coupling form; it does not promise efficient diagonalization of an arbitrary many-body operator. The construction assumes supplied coupling estimates with certified error, and counts their representation and processing costs without identifying those costs with the physical resources needed to perform calibration. It covers one known common Gaussian noise direction, boundary operations, and the specified storage-error metric. The scalar compiler has no polynomial-in-$`\log t`$ guarantee. +## Fixed occupation and calibration + +The [fixed-weight compiler](../science/fixed_weight_encoder.md) adapts reversible rank and unrank to count signed energies on a conserved Hamming-weight sector. Exact collective decoherence-free subspaces and approximate protection under inhomogeneous coupling have the precedents above. The sector compiler supplies an explicit narrow-band isometry with a finite certificate for signed coupling differences and a constant-qubit comparison with the best code within that sector at fixed error. + +[Lidar, Bacon and Whaley (1999)](https://doi.org/10.1103/PhysRevLett.82.4556) concatenate decoherence-free subspaces with an outer code for collective noise perturbed by independent noise. The endpoint construction in [Inhomogeneous Collective Memory](https://github.com/GoGoKo699/Inhomogeneous-Collective-Memory/blob/b6bbf3cae33b300d0c793628e168616dc4919bdc/science/resources.md#6-an-explicit-growing-rate-alternative) uses numerical inner codes, Pauli averaging and growing-field outer coding when the coupling profile is supplied. [Quantum Memory Calibration](https://github.com/GoGoKo699/Quantum-Memory-Calibration/blob/main/science/compiled_calibration.md) uses the fixed-weight compiler inside a costed calibration protocol for a single shared Gaussian phase. It attributes the existing hard-budget converse and establishes that its leading coefficient can be attained with explicitly compiled endpoints. + ## Several commuting noise directions [Knill, Laflamme and Viola](https://doi.org/10.1103/PhysRevLett.84.2525), Theorems 3–4, and [Weaver](https://arxiv.org/abs/1802.07394), Lemma 2.9, give exact error-detecting codes for diagonal operator systems via convex geometry. Their disjoint-support construction supplies the code for the finite environment obtained by truncation. [Aydin, Albert and Barg](https://doi.org/10.1103/kx3b-4nrp) also use Tverberg's theorem for specified finite error families in permutation-invariant, bosonic and spin state spaces. diff --git a/science/README.md b/science/README.md index 0efe8f6..be3f03b 100644 --- a/science/README.md +++ b/science/README.md @@ -14,9 +14,12 @@ The [operational model](model.md) fixes the noise normalization, deterministic e | Finite-time law | [Theorem 1](spectral_law.md#theorem-1-one-register-storage) | The optimal number of logical qubits is $`\log_2M_t+O_\epsilon(1)`$. | | Several noise directions | [Joint spectral theorem](multiple_noise_directions.md) | Gives the sharp leading growth of the worst-case occupancy gap with effective rank and an explicit local-noise example. | | Calibrated compilation | [Encoder construction](encoder.md) | Certified finite-precision couplings suffice to compile a clean coherent code within a fixed-error constant number of qubits of the unrestricted optimum. | +| Fixed-weight compilation | [Sector compiler](fixed_weight_encoder.md) | Counts signed energy bands while retaining the physical Hamming-weight constraint, so the common coupling offset is irrelevant. | The general theorem assumes no efficient eigenbasis. The compiler makes a stronger implementation statement for the explicitly supplied weighted-qubit operator $`A=\sum_jg_jN_j`$. Its integer counting tables, arithmetic, lookups, reversible gates, workspace and input precision are all charged. It uses no unpriced quantum RAM. +The fixed-weight compiler returns the band isometry and its inverse from the signed midpoint integers and a weight constraint. [Quantum Memory Calibration](https://github.com/GoGoKo699/Quantum-Memory-Calibration/blob/main/science/compiled_calibration.md) composes these clean blocks with terminal phase correction to account for both calibration bits and endpoint resources. + The joint spectral theorem keeps the same endpoint contract. Its converse uses the general Schur-channel comparison. Its attaining family encodes across separated spectral points after controlling a finite approximation of the noise environment, while its finite example uses phase repetition. ## Interpretation and boundaries diff --git a/science/encoder.md b/science/encoder.md index e53a141..158a321 100644 --- a/science/encoder.md +++ b/science/encoder.md @@ -38,6 +38,8 @@ b_\epsilon=\left\lceil\frac4{\sqrt\epsilon}\right\rceil. Thus its loss is a constant number of logical qubits for fixed $`\epsilon`$, uniformly in the number, spacing, signs and degeneracies of the actual spectrum. The constant in (1) is not optimized. For inverse-polynomial $`\epsilon`$, the loss is $`O(\log(1/\epsilon))`$, not a constant independent of $`\epsilon`$. +The [fixed-weight specialization](fixed_weight_encoder.md) preserves the physical Hamming weight by carrying signed sums and residual weights together. This makes it possible to use certified centered couplings even when a common offset is unknown. + ## 1. Exact dyadic grid selection Set diff --git a/science/fixed_weight_encoder.md b/science/fixed_weight_encoder.md new file mode 100644 index 0000000..eeb542a --- /dev/null +++ b/science/fixed_weight_encoder.md @@ -0,0 +1,84 @@ +# Clean reversible compilation in a fixed-weight sector + +A common coupling offset contributes the same phase to every string of the same physical Hamming weight. Fixing that weight makes it possible to compile a memory block using only certified estimates of the coupling differences from the common offset. + +## Compiler interface + +Let $`m\ge1`$ be the physical block size and $`h\in\{0,\ldots,m\}`$ its required Hamming weight. In the Pauli-$`Z`$ convention, the noise generator and supplied certificate are + +```math +A_{\boldsymbol g}=\sum_{i=1}^m g_i Z_i, +\qquad +|g_i-c-\gamma q_i|\le u_i, +\qquad +q_i\in\mathbb Z,\quad \gamma\gt0. +``` + +A common real offset $`c`$ may be unknown. The endpoint compiler uses the integers $`q_i`$, the weight $`h`$ and an integer band. The scale $`\gamma`$, bounds $`u_i`$ and exposure $`t`$ enter the storage certificate. The [original compiler](encoder.md) uses occupation projectors $`N_i`$, with $`Z_i=I-2N_i`$. + +For a computational string $`x`$ of weight $`h`$ define the signed integer energy $`S(x)=\sum_i q_i(1-2x_i)`$. Choose a closed integer band $`[a,b]`$ with population $`C\ge1`$ among those strings. A half-open integer band $`[a,b+1)`$ specifies the same set. For any integer $`0\le r\le\lfloor\log_2C\rfloor`$, the compiler produces clean reversible encoding and inverse decoding for the first $`2^r`$ accepted strings in lexicographic order. + +The true energy differs from $`c(m-2h)+\gamma S(x)`$ by at most $`\sum_i u_i`$. The chosen span is invariant under the actual diagonal storage channel. Its half-diamond storage error, including a reference, satisfies + +```math +\frac12\|\mathcal R\Phi_{\boldsymbol g,t}\mathcal E-\mathrm{id}\|_\diamond +\le +\min\left\{1,\frac{t}{4} + \left(\gamma(b-a)+2\sum_i u_i\right)^2\right\}. +``` + +This follows by applying the [spectral interval bound](spectral_law.md#lemma-1-reference-stable-protection-of-a-spectral-interval) to the true diameter. The offset contributes a scalar throughout the allowed sector, independent of its value. + +## Exact counting and rank access + +Put $`Q=\sum_i|q_i|`$. Let $`F_i(k,s)`$ count suffix strings on sites $`i,\ldots,m`$ of weight $`k`$ and signed energy $`s`$. The first bit contributes $`q_i`$ for zero and $`-q_i`$ for one. Thus + +```math +F_{m+1}(k,s)=\mathbf1_{\{k=0,\ s=0\}},\qquad +F_i(k,s)=F_{i+1}(k,s-q_i)+F_{i+1}(k-1,s+q_i). +``` + +Use zero outside the valid range, with $`0\le k\le h`$ and $`-Q\le s\le Q`$. Negative weights remain signed. Complementing individual bits to make their weights positive would change the Hamming-weight constraint. The two branches at a zero weight continue to count different physical strings. + +For each suffix and each $`k`$, precompute the prefix sum $`P_i(k,z)=\sum_{s\le z}F_i(k,s)`$, saturated at the ends of the table. The band population is $`P_1(h,b)-P_1(h,a-1)`$. These same prefix sums give the population of every supplied band or find a maximum-population closed band of a prescribed integer diameter by scanning its possible start points. One can scan $`a\in[-Q,Q]`$ because the minimum energy of any nonempty accepted set is also a valid start point with at least that population. + +Before processing site $`i`$, let $`p`$ be the signed energy already accumulated and let $`k`$ be the remaining weight. The number of accepted completions whose next bit is zero is + +```math +C_i(k,p)=P_{i+1}(k,b-p-q_i)-P_{i+1}(k,a-1-p-q_i). +``` + +Unranking chooses zero when the residual rank is below $`C_i(k,p)`$ and otherwise chooses one and subtracts $`C_i(k,p)`$. Ranking adds the same count on every one branch. After choosing $`x_i`$, both procedures update $`k\gets k-x_i`$ and $`p\gets p+q_i(1-2x_i)`$. The accepted strings with next bit zero precede the one branch, proving the rank and unrank rules by induction. This holds for one-state sectors, truncated logical ranks, and bands with gaps or repeated energies. + +For example, $`q=(-3,0,2)`$ at weight one gives energies $`-5,-1,5`$ on the lexicographically ordered strings $`001,010,100`$. The band $`[-5,-1]`$ keeps the first two strings. An arbitrary common shift leaves their energy difference unchanged. + +## Clean workspace and finite costs + +Precompute $`C_i(k,p)`$ from the prefix sums. Suffix counts, prefix sums and this lookup table have $`O(m(h+1)(2Q+1))`$ words. Each count uses at most $`m+1`$ bits. A lookup uses the joint integer address $`(k,p)`$. Equality checks against classical addresses and controlled XOR of the specified count bits implement it using $`X`$, CNOT and Toffoli gates. Comparisons, additions and subtractions have ordinary Boolean circuits in their bit widths. This gives classical bit preprocessing, emitted reversible gates and temporary wires polynomial in $`m`$, $`Q+1`$ and the input description length. It uses a literal table scan and charges the emitted gate description. The range dependence is on $`Q`$ itself. + +Total Boolean extensions on the finite registers are sufficient. Implement signed partial sums with a fixed offset, give unused addresses zero counts and use total fixed-width arithmetic. Apply compute-copy-uncompute separately to rank and unrank, as in the [clean encoder construction](encoder.md#5-clean-coherent-isometry-and-decoding-channel). Unrank into a clean physical block, then XOR the lower $`r`$ bits of the physical word's rank into the original input. For the selected $`2^r`$ words this erases the input, as well as every temporary computation wire. Both operations extend linearly to arbitrary superpositions and external reference entanglement. Inverse decoding on the chosen code span returns the physical block and work wires to zero. For an arbitrary physical input the decoder applies the inverse circuit with fresh zero wires and discards all non-output registers, giving a trace-preserving map. + +### Comparison with the optimum within the sector + +The [scalar spectral law](spectral_law.md#theorem-1-one-register-storage) applies directly to the noise generator restricted to the weight-$`h`$ sector. Let $`D_\epsilon^{(h)}`$ be the best stored dimension in that sector under the same endpoint model. For $`0\lt\epsilon\lt1/4`$, take the [dyadic step from the original compiler](encoder.md#1-exact-dyadic-grid-selection) with $`n=m`$, so + +```math +\gamma^2\le\frac{\epsilon}{16m^2t}\lt4\gamma^2. +``` + +Suppose the supplied grid certificates satisfy $`u_i\le\gamma`$. Choose a most occupied band of integer diameter $`4m`$ and take $`r=\lfloor\log_2C\rfloor`$. The true diameter is at most $`6m\gamma`$, giving error at most $`9\epsilon/16`$. Any interval of true energies of diameter $`2m\gamma`$ fits in an estimated interval of diameter $`4m\gamma`$ after a common shift. Divide a true resolution interval of width $`t^{-1/2}`$ into at most $`b_\epsilon=\lceil4/\sqrt\epsilon\rceil`$ pieces of that diameter, assigning shared boundaries once. The selected population is at least the maximum true resolution occupancy divided by $`b_\epsilon`$. The [occupancy converse](spectral_law.md#theorem-1-one-register-storage) and power-of-two rounding then give + +```math +0\le\log_2 D_\epsilon^{(h)}-r +\le 1+\log_2\frac{(2+\sqrt{2\pi})b_\epsilon}{1-\epsilon}. +``` + +The comparison includes all encoders confined to the physical sector. The sector restriction can itself reduce the occupancy relative to the full register. + +## Use in passive memory with a charged calibration transcript + +[Quantum Memory Calibration](https://github.com/GoGoKo699/Quantum-Memory-Calibration/blob/main/science/compiled_calibration.md) uses this compiler on chosen active blocks, at weight $`h=\lfloor m/2\rfloor`$. A transcript supplies the signed midpoint integers and the endpoint circuits use the same public bin partition for each block. Its outer correction handles errors correlated by the one shared Gaussian phase. Together these steps achieve the sharp leading continuous calibration budget with polynomial endpoint costs at polynomial dimensionless hold times. + +[Independent finite checks](../verification/README.md#fixed-weight-signed-bands) compare table counts, rank access and exact energy certificates with direct enumeration. + +[Scientific overview](README.md) · [Original compiler](encoder.md) · [Learning route](../learning/anchor.md) diff --git a/verification/README.md b/verification/README.md index 40a1ab5..7848b98 100644 --- a/verification/README.md +++ b/verification/README.md @@ -56,6 +56,16 @@ The script verifies the following finite instances. The script prints its results and does not change the existing generated evidence. +### Fixed-weight signed bands + +Run the independent standard-library check from the repository root. + +```bash +python verification/verify_fixed_weight.py +``` + +Across 200 sectors, direct enumeration checks 13,216 closed-band populations and 624 lexicographic rank/unrank pairs for the most populated bands. Exact rational arithmetic verifies that a common offset changes the energy by the same scalar throughout the sector and that coefficient uncertainty respects the bandwidth bound. The cases include signed and zero weights, exact degeneracies, and the two single-state sectors. These checks exercise the counting and certificate. The [fixed-weight proof](../science/fixed_weight_encoder.md) gives the clean reversible gate construction and channel guarantee. + ### Numerical tolerances Grid selection, integer counts, rounding, codewords, gate permutations, bandwidth certificates and exact workspace-zero checks use no floating tolerance. The floating-point checks use the following explicit thresholds: diff --git a/verification/verify_fixed_weight.py b/verification/verify_fixed_weight.py new file mode 100644 index 0000000..642505f --- /dev/null +++ b/verification/verify_fixed_weight.py @@ -0,0 +1,141 @@ +"""Check the signed fixed-weight counting and certificate with exact arithmetic.""" + +from collections import Counter +from fractions import Fraction +from itertools import product +from random import Random + + +def signed_energy(bits, weights): + return sum(weight * (1 - 2 * bit) for bit, weight in zip(bits, weights)) + + +def suffix_counts(weights, target_weight): + """Return signed energy counts indexed by suffix start and residual weight.""" + size = len(weights) + counts = [ + [Counter() for _ in range(target_weight + 1)] for _ in range(size + 1) + ] + counts[size][0][0] = 1 + for site in range(size - 1, -1, -1): + weight = weights[site] + for left in range(target_weight + 1): + for energy, multiplicity in counts[site + 1][left].items(): + counts[site][left][energy + weight] += multiplicity + if left: + for energy, multiplicity in counts[site + 1][left - 1].items(): + counts[site][left][energy - weight] += multiplicity + return counts + + +def population(counts, lower, upper): + return sum(value for energy, value in counts.items() if lower <= energy <= upper) + + +def zero_branch(weights, counts, site, left, partial, lower, upper): + after_zero = partial + weights[site] + return population(counts[site + 1][left], lower - after_zero, upper - after_zero) + + +def unrank(weights, counts, target_weight, lower, upper, index): + bits = [] + left = target_weight + partial = 0 + for site, weight in enumerate(weights): + count = zero_branch(weights, counts, site, left, partial, lower, upper) + bit = int(index >= count) + if bit: + index -= count + bits.append(bit) + left -= bit + partial += weight * (1 - 2 * bit) + assert index == left == 0 + assert lower <= partial <= upper + return tuple(bits) + + +def rank(bits, weights, counts, target_weight, lower, upper): + index = 0 + left = target_weight + partial = 0 + for site, (bit, weight) in enumerate(zip(bits, weights)): + if bit: + index += zero_branch(weights, counts, site, left, partial, lower, upper) + left -= bit + partial += weight * (1 - 2 * bit) + return index + + +def verify_case(weights, target_weight, diameter): + size = len(weights) + counts = suffix_counts(weights, target_weight) + exhaustive = { + bits: signed_energy(bits, weights) + for bits in product((0, 1), repeat=size) + if sum(bits) == target_weight + } + assert counts[0][target_weight] == Counter(exhaustive.values()) + + total_range = sum(map(abs, weights)) + closed_bands = {} + for lower in range(-total_range, total_range + 1): + upper = lower + diameter + accepted = [ + bits for bits, energy in exhaustive.items() if lower <= energy <= upper + ] + assert population(counts[0][target_weight], lower, upper) == len(accepted) + closed_bands[lower] = accepted + lower = max(closed_bands, key=lambda start: len(closed_bands[start])) + upper = lower + diameter + accepted = closed_bands[lower] + for index, bits in enumerate(accepted): + assert unrank(weights, counts, target_weight, lower, upper, index) == bits + assert rank(bits, weights, counts, target_weight, lower, upper) == index + + scale = Fraction(1, 8) + errors = [Fraction((-1) ** site, 16) for site in range(size)] + centered = [scale * weight + error for weight, error in zip(weights, errors)] + shift = Fraction(59, 7) + shifted = [coefficient + shift for coefficient in centered] + actual = [] + for bits in accepted: + energy = signed_energy(bits, shifted) + assert energy - signed_energy(bits, centered) == shift * ( + size - 2 * target_weight + ) + predicted = shift * (size - 2 * target_weight) + scale * exhaustive[bits] + assert abs(energy - predicted) <= sum(map(abs, errors)) + actual.append(energy) + actual_diameter = max(actual) - min(actual) + assert actual_diameter <= scale * diameter + 2 * sum(map(abs, errors)) + return len(closed_bands), len(accepted) + + +def main(): + cases = [ + ((-3, 0, 2), 1, 4), + ((0, 0, 0, 0), 2, 0), + ((-5, -2, -2, 0), 2, 0), + ((-5, 0, 8), 0, 0), + ((-5, 0, 8), 3, 0), + ] + random = Random(20261124) + for trial in range(195): + size = 1 + trial % 9 + weights = tuple(random.randint(-13, 13) for _ in range(size)) + cases.append((weights, random.randint(0, size), random.randint(0, 11))) + + band_count = rank_count = 0 + for weights, target_weight, width in cases: + bands, ranks = verify_case(weights, target_weight, width) + band_count += bands + rank_count += ranks + print( + f"Fixed-weight checks passed: {len(cases)} sectors, " + f"{band_count} band populations, {rank_count} rank/unrank pairs, " + f"and {rank_count} exact common-offset and coefficient certificates." + ) + + +if __name__ == "__main__": + main()