From d7be62201f103132127c61e8ee83b1ebb87a2a0e Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Tue, 24 Nov 2026 12:15:18 +0800 Subject: [PATCH] Establish sharp spectral occupancy gap for multiple noise directions --- README.md | 23 ++- learning/anchor.md | 37 ++++- learning/milestones.md | 24 +-- llms.txt | 6 +- references/related_work.md | 8 +- science/README.md | 3 + science/model.md | 4 + science/multiple_noise_directions.md | 198 +++++++++++++++++++++++++ verification/README.md | 17 +++ verification/verify_noise_rank.py | 214 +++++++++++++++++++++++++++ 10 files changed, 512 insertions(+), 22 deletions(-) create mode 100644 science/multiple_noise_directions.md create mode 100644 verification/verify_noise_rank.py diff --git a/README.md b/README.md index 76c090c..8406c21 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ **How much unknown quantum information can a finite register preserve during one interval of collective dephasing?** -The answer is controlled by how many noise eigenvalues fit inside one interval at the noise's finite-time resolution. For an arbitrary finite spectrum, this repository proves matching storage bounds up to constants at fixed error. For a register with explicitly known, unequal local couplings, it gives a finite-precision compiler whose code loses only a constant number of logical qubits relative to every allowed endpoint encoding and recovery. +With one Gaussian noise direction, the answer is controlled by how many noise eigenvalues fit inside one interval at the noise's finite-time resolution. With several commuting directions, a joint spectral cluster can miss a large amount of recoverable storage. The rank of the joint noise spectrum determines the sharp worst-case size of that gap. -## Main result +## One noise direction Let a known Hermitian operator $`A`$ generate Gaussian dephasing, @@ -29,6 +29,17 @@ For any fixed $`0\lt \epsilon\lt 1/4`$, the optimal stored dimension satisfies The explicit bounds, their constants, and a converse covering arbitrary mixed encoders are proved in [the spectral law](science/spectral_law.md). The result applies to finite, irregular, degenerate and nondegenerate spectra. +## Several commuting noise directions + +Let $`r`$ be the affine dimension of the covariance-weighted joint spectrum and $`M`$ the largest number of spectral points in a unit ball, counted with multiplicity. At fixed $`0\lt\epsilon\lt1/4`$, the [joint spectral theorem](science/multiple_noise_directions.md) gives the worst-case discrepancy + +```math +\sup_{\text{rank }r}\big(\log_2D_\epsilon-\log_2M\big) +=\frac r2\log_2r+O_\epsilon(r). +``` + +The supremum ranges over finite joint spectra. A family with $`M=1`$ attains the leading term. Its encoder uses superpositions across separated spectral points and recovery at the end of the same passive interval. In a separate explicit example, 151 independently dephasing qubits support one logical qubit by phase repetition at half-diamond error below $`1/16`$, even though every unit ball contains at most one spectral point. + ## From an existence theorem to an encoder For @@ -54,7 +65,8 @@ The upper curve is a conservative converse bound, not the exact optimum. The rig | Question | Account | |---|---| | What is the model, and what resources are permitted? | [Operational model](science/model.md) | -| Why does spectral occupancy characterize storage? | [Theorem and proofs](science/spectral_law.md) | +| 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) | | 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) | @@ -76,14 +88,15 @@ With Python 3.12, run from the repository root: python -m pip install -r verification/requirements.txt python verification/run_all.py python verification/generate_examples.py + python verification/verify_noise_rank.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. ## Scope -This is a result for one known common Gaussian noise direction. The true couplings are fixed during the storage interval and lie within the supplied calibration certificates. The core storage theorem treats boundary operations as ideal; a separate composable error budget explains what additional boundary accuracy suffices. Physical calibration cost, local noise, unmodeled time-dependent coupling drift, geometric circuit locality and fault-tolerant hardware overhead are not determined by this model. +The storage results use known, fixed commuting Gaussian noise generators and ideal boundary operations. The calibrated reversible compiler applies to the one-direction weighted-qubit model with supplied certificates. The general rank-dependent attaining family allows arbitrary commuting generators and unrestricted endpoint recovery. The local repetition example uses independent Gaussian dephasing on physical qubits. Physical calibration cost, coupling drift, and fault-tolerant hardware overhead remain outside these results. -Approximate protected subspaces, high rates under exact collective symmetry, channel comparison methods, and reversible combinatorial encoding are established ideas. The specific contribution is their finite-spectrum occupancy characterization together with a calibrated compiler certified against unrestricted endpoint codes. The [related-work account](references/related_work.md) makes the comparisons explicit, including the earlier fixed-Hamming-weight amplitude encoder coauthored by Ruge Lin. +The [related-work account](references/related_work.md) credits the inherited comparison, reversible encoding and error-correction methods and identifies the finite-time results established here. ## Purpose diff --git a/learning/anchor.md b/learning/anchor.md index 309993c..6a415e4 100644 --- a/learning/anchor.md +++ b/learning/anchor.md @@ -10,7 +10,7 @@ Use the [author's book page](https://jhwatrous.github.io/books-and-courses.html) The linked errata are dated July 23, 2025; they include corrected norm-conversion constants in Theorems 3.56 and 8.45. The project's interval-error estimate is proved directly, without using those conversions. -Watrous supplies the mathematical foundations. The project's spectral occupancy law and calibrated compiler require the additional arguments identified here. Primary papers in [Related work](../references/related_work.md) supply research attribution and theorem dependencies; they are separate from this one educational anchor. +Watrous supplies the mathematical foundations. The rank-one occupancy law, calibrated compiler and several-direction separation require the additional arguments identified here. Primary papers in [Related work](../references/related_work.md) give research attribution and theorem dependencies. ## Targeted reading map @@ -67,7 +67,7 @@ For $`t\gt0`$, the dimensionless quantity $`t(\lambda_i-\lambda_j)^2`$ determine **Finally, make the code executable.** For $`A=\sum_jg_jN_j`$, with $`N_j=|1\rangle\langle1|_j`$, [the compiler](../science/encoder.md) rounds certified coefficient estimates to an exact dyadic grid. It finds a populated integer-sum band by dynamic programming, then coherently ranks and unranks accepted strings. Reversing intermediate computations cleans all temporary workspace before storage. Explicit lookup gates and bit arithmetic establish polynomial resources under the stated parameter scaling. The precision certificate is an input assumption, not a claim about calibration sample cost. -This construction loses only a constant number of qubits relative to the all-code optimum at fixed error. Neither the occupancy theorem nor this calibration-to-circuit conclusion is attributed to the textbook. +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. ## Worked example: one logical qubit without an exact degeneracy @@ -101,4 +101,37 @@ Here $`Z=\mathrm{diag}(1,-1)`$ acts on the decoded logical qubit. Its half-diamo For every fixed coefficient vector consistent with the supplied certificates, the compiler's conservative storage bound is instead $`9\epsilon/16=9/256`$. The nominal exact value and robust bound answer different questions. This is finite-time approximate protection: the nondegenerate nominal operator has exact storage dimension one at every positive exposure, as [Proposition 2](../science/spectral_law.md#proposition-2-exact-storage-at-every-positive-time) establishes. The example demonstrates a functioning band code, without claiming its optimality from these small numbers alone. +## Several commuting noise directions + +Commuting couplings have a common eigenbasis. Put their joint eigenvalues in a vector $`\lambda_i`$, then use the Gaussian phase covariance $`C`$ for the entire interval, including the exposure, to form $`z_i=C^{1/2}\lambda_i`$. Watrous §4.1.3 again describes the channel as an entrywise multiplier. + +```math +G_{ij}=\exp\!\left(-\frac{\|z_i-z_j\|_2^2}{2}\right). +``` + +The effective rank $`r`$ is the dimension of the span of all differences $`z_i-z_j`$. This count removes directions that leave every coherence unchanged. For example, if both couplings assign proportional eigenvalues up to an additive scalar, the points lie on a line even with two independent Gaussian phases. Two independent phases with linearly independent coupling differences can instead produce a two-dimensional grid. + +Let $`M`$ be the maximum number of points, counted with multiplicity, inside any closed unit Euclidean ball. At rank one a unit ball is an interval of length two in the rescaled coordinate. Its occupancy is between one and two times the maximum occupancy of a unit-width interval. At growing rank, the [several-direction theorem](../science/multiple_noise_directions.md) gives a sharp worst-case gap for each fixed $`0<\epsilon<1/4`$. + +```math +\sup_{\text{effective rank }r}\bigl(\log_2D_\epsilon-\log_2M\bigr) +=\frac r2\log_2r+O_\epsilon(r). +``` + +The Choi comparison from the rank-one proof still bounds arbitrary codes by the largest Gaussian Gram eigenvalue. Counting neighbors in higher-dimensional balls gives the upper bound. For the matching family, the construction uses Tverberg’s theorem to match convex averages of truncated environmental features over disjoint supports. The discarded part of the environmental state controls the error. This gives a deterministic endpoint code for the family. The calibrated dynamic program above concerns one noise direction. + +### Worked example with one point per ball + +Take $`151`$ qubits, each with an independent phase flip of probability $`p=7/16`$. A single flip channel attenuates a differing-bit coherence by $`1-2p=1/8`$. The product channel has joint points $`z_x=\sqrt{2\ln 8}\,x`$ for binary strings $`x`$. Squared Euclidean distance is $`2\ln 8`$ times Hamming distance. The minimum separation exceeds two, so $`M=1`$. + +Encode logical basis states as $`|+\rangle^{\otimes151}`$ and $`|-\rangle^{\otimes151}`$. After storage, measure adjacent $`X_jX_{j+1}`$ parities. Each syndrome leaves a pair of complementary error patterns. Correcting the smaller pattern preserves coherence and succeeds when at most 75 flips occurred. A larger error pattern exchanges the two encoded basis states after correction. The resulting logical Pauli flip has probability + +```math +\sum_{k=76}^{151}\binom{151}{k} + \left(\frac7{16}\right)^k\left(\frac9{16}\right)^{151-k} +\approx 0.061217204448 \lt \frac1{16}. +``` + +This probability is the half-diamond error of the decoded channel. The triangle inequality gives the upper bound and a logical basis input attains it. The parity measurements and correction occur at the decoding endpoint. This example stores a logical qubit at the same tolerance as the two-qubit band example above. The asymptotic sharpness proof uses the separate feature construction. + [Milestone map](milestones.md) · [Scientific overview](../science/README.md) · [Repository overview](../README.md) diff --git a/learning/milestones.md b/learning/milestones.md index 537295c..f8a88af 100644 --- a/learning/milestones.md +++ b/learning/milestones.md @@ -2,9 +2,9 @@ The map follows one question: how much unknown quantum information can a finite memory preserve during a prescribed interval of Gaussian dephasing, and how can a nearly optimal code be compiled from calibrated couplings? -**Background/preliminaries contains M01–M11.** These eleven milestones connect individual coherences, reference systems, channel representations, admissible records and coherent encoding into the complete operational question. **Narrative/innovation contains M12–M30.** These nineteen milestones assemble the spectral converse and construction, then the finite-bit compiler, before integrating examples, limiting regimes and the separate communication corollary. The allocation reflects the project's two linked results: a characterization against arbitrary codes and an explicit implementation approaching that characterization. +**Background/preliminaries contains M01–M11.** These eleven milestones connect individual coherences, reference systems, channel representations, admissible records and coherent encoding into the complete operational question. **Narrative/innovation contains M12–M30.** These nineteen milestones assemble the rank-one spectral converse and construction, then the finite-bit compiler. The final milestones connect the proof to finite examples, the several-direction rank law and the separate communication corollary. -The sole educational anchor is John Watrous, *The Theory of Quantum Information* (2018), using the [author-hosted manuscript](https://jhwatrous.github.io/TQI.pdf). Section numbers below refer to that version. The [anchor bridge](anchor.md) translates its notation and provides a worked example. Watrous supplies the channel-theoretic foundations; the spectral estimates, calibration arithmetic and compiler arguments have their authoritative derivations in the linked scientific pages. This map identifies the main understanding targets without replacing those proofs. +The sole educational anchor is John Watrous, *The Theory of Quantum Information* (2018), using the [author-hosted manuscript](https://jhwatrous.github.io/TQI.pdf). Section numbers below refer to that version. The [anchor bridge](anchor.md) translates its notation and works through a rank-one band code and a many-direction endpoint code. Watrous supplies the channel-theoretic foundations. Follow the linked scientific pages for the proofs of the storage bounds and the compiler guarantees. The true coupling vector is fixed throughout each storage interval. For calibrated compilation it lies within the supplied uncertainty certificates. Uniformity over those fixed vectors does not include unmodeled time-dependent coupling drift. @@ -312,17 +312,17 @@ The true coupling vector is fixed throughout each storage interval. For calibrat **Sources.** [Watrous §§3.3.2–3.3.3][W3]; [encoder, §6 and (21)–(23)](../science/encoder.md#6-composable-implementation-error-budget). -### M26: What the examples and primitive circuits establish +### M26: What worked codes and primitive circuits establish -**Central question.** Which aspects of the result become visible in a small code, a larger spectrum and executable circuits? +**Central question.** How can a finite code reveal the protection mechanism and the strength of the error guarantee? -**Understanding target.** Connect the two-qubit worked example to the nondegenerate 16-qubit bands and the small primitive-gate checks. Distinguish exact arithmetic, tested state errors, analytic channel bounds and a conservative converse ceiling. Explain what enumeration verifies and why the general compiler avoids that enumeration. +**Understanding target.** Connect the two-qubit band code to the nondegenerate 16-qubit bands and the primitive-gate checks. Compare it with the many-direction repetition code, which corrects phase-flip patterns even though a unit ball contains only one joint point. Distinguish tested errors and certified channel bounds. Explain why the band compiler avoids full enumeration. **Dependencies and story role.** Brings M12–M25 together in concrete instances while keeping the evidence levels explicit. **Conceptual connection.** Examples expose the mechanism and implementation; uniform claims retain their analytical proofs. -**Sources.** [Watrous §§3.2–3.3][W3]; [worked example](anchor.md#worked-example-one-logical-qubit-without-an-exact-degeneracy); [examples](../science/examples.md); [verification limits](../verification/README.md#what-the-checks-do-not-establish). +**Sources.** [Watrous §§3.2–3.3][W3]; [rank-one worked example](anchor.md#worked-example-one-logical-qubit-without-an-exact-degeneracy); [many-direction worked example](anchor.md#worked-example-with-one-point-per-ball); [examples](../science/examples.md); [verification limits](../verification/README.md#what-the-checks-do-not-establish). ### M27: Variance, extensive storage and the order of limits @@ -360,17 +360,17 @@ The true coupling vector is fixed throughout each storage interval. For calibrat **Sources.** [Watrous §6.1.2][W6], [§8.2.1][W8]; [interpretation, (I11)–(I12)](../science/interpretation.md#upper-bound-for-adaptive-classical-assistance). -### M30: The combined contribution and its physical scope +### M30: Effective rank controls the gap to ball occupancy -**Central question.** What does the occupancy law together with the calibrated compiler establish about this memory model? +**Central question.** How much can a code gain beyond the most populated resolution ball when commuting noise acts in several directions? -**Understanding target.** Connect arbitrary-code optimality, finite-input construction and clean quantum implementation into one instance-wise guarantee. Separate the unrestricted spectral theorem from its efficient weighted-qubit realization, fixed-error conclusions from exact storage, and single-interval storage from independent-use communication. Identify inherited techniques and the assumptions needed for a physical application. +**Understanding target.** Derive the joint spectral points from the Gaussian covariance and explain why only the span of their differences counts. Connect Gaussian Gram row sums to the upper bound and the Tverberg construction with truncated environmental features to the matching family. Interpret the fixed-error worst-case gap $`\tfrac r2\log_2r+O_\epsilon(r)`$ and relate it to the rank-one characterization and calibrated compiler. -**Dependencies and story role.** Integrates M11–M29 into the project's complete scientific claim. +**Dependencies and story role.** Extends M12–M16 and applies the finite contrast in M26. The compiler in M18–M25 and the independent-use result in M28–M29 concern their stated rank-one settings. -**Conceptual connection.** Finite spectral resolution replaces exact degeneracy as the useful organizing quantity for approximate storage. +**Conceptual connection.** The rank-one law compares storage to a cluster of nearby eigenvalues. In higher rank, endpoint codes can distribute each logical state across many eigenvectors while concealing the logical label from the environment to the accuracy required for recovery. -**Sources.** [Watrous §3.3.3][W3], [§8.2.1][W8]; [scientific synthesis](../science/README.md); [specific contribution and limits](../references/related_work.md#what-remains-after-these-comparisons). +**Sources.** [Watrous §2.2.2][W2], [§4.1.3][W4]; [rank law and construction](../science/multiple_noise_directions.md); [scientific synthesis](../science/README.md); [specific contribution and limits](../references/related_work.md#what-remains-after-these-comparisons). [Scientific account](../science/README.md) · [Anchor and bridge](anchor.md) · [Repository overview](../README.md) diff --git a/llms.txt b/llms.txt index 8ff7dc7..ae41e5d 100644 --- a/llms.txt +++ b/llms.txt @@ -1,6 +1,6 @@ # Quantum Spectral Memory -> Finite-time Gaussian dephasing: an arbitrary-spectrum storage law and a calibrated reversible compiler for weighted qubit registers. +> Finite-time Gaussian dephasing: the one-direction occupancy law, the sharp gap for several commuting directions, and a calibrated reversible compiler for one-direction weighted qubit registers. ## Reading routes @@ -14,7 +14,8 @@ - [Overview](README.md): question, principal results, scope and reproduction commands. - [Science map](science/README.md): dependencies and reading order. - [Operational model](science/model.md): Gaussian normalization, deterministic endpoint codes, retained classical records and half-diamond error. -- [Spectral law](science/spectral_law.md): occupancy theorem, all-code converse and exact-error boundary. +- [Spectral law](science/spectral_law.md): scalar occupancy theorem, all-code converse and exact-error boundary. +- [Several noise directions](science/multiple_noise_directions.md): covariance-weighted joint spectrum, sharp rank dependence and the 151-qubit phase repetition example. - [Encoder](science/encoder.md): certified rounding, dynamic programming, coherent rank/unrank, explicit resources and clean workspace. - [Examples](science/examples.md): homogeneous limit, exactly specified nondegenerate register and small primitive circuits. - [Interpretation](science/interpretation.md): variance rates, order of limits and a separate independent-use capacity corollary. @@ -28,6 +29,7 @@ - [Unified checks](verification/run_all.py): matrix, exhaustive band and primitive-circuit checks. - [Reversible compiler](verification/verify_reversible_encoder.py): literal X, CNOT and Toffoli implementation. - [Examples generator](verification/generate_examples.py): rational data and plots. +- [Noise-rank checks](verification/verify_noise_rank.py): exact repetition tail and finite checks of the joint spectral proof ingredients. ## Reading cautions diff --git a/references/related_work.md b/references/related_work.md index 73ed6e5..ae1dc4a 100644 --- a/references/related_work.md +++ b/references/related_work.md @@ -71,6 +71,12 @@ That result solves the exact one-use memory optimum for one nondegenerate oscill The substantive remainder is the combination of a dimension- and spectrum-uniform finite-time characterization with a calibrated polynomial compiler that approaches the unrestricted optimum within a fixed number of logical qubits at fixed error. No novelty is attributed to the existence of approximate DFSs, high rates under exact collective symmetry, generalized-dephasing degradability, entanglement-based converse machinery, or reversible combinatorial encoding. -The general 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. Independent local noise, interleaved correction, and a polynomial-in-$`\log t`$ compiler are outside the result. +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. + +## 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. + +The [joint spectral theorem](../science/multiple_noise_directions.md) derives a uniform finite-environment approximation for Gaussian dephasing on a bounded spectral region. Its dimension, combined with Gaussian shell counting and a separated high-dimensional spectrum, determines the sharp leading rank dependence of the discrepancy between joint spectral occupancy and unrestricted storage. Singh and Datta's long-time peripheral-space analysis treats a different limit. The finite local-noise example uses the standard phase repetition code and an exact binomial calculation. [Scientific overview](../science/README.md) · [Bibliography](references.bib) diff --git a/science/README.md b/science/README.md index f29ddf9..0efe8f6 100644 --- a/science/README.md +++ b/science/README.md @@ -12,10 +12,13 @@ The [operational model](model.md) fixes the noise normalization, deterministic e | General-code converse | [Lemma 2](spectral_law.md#lemma-2-a-converse-for-arbitrary-encoding-and-classical-records) | The Gaussian Gram matrix bounds every allowed code through completely positive comparison with full dephasing. | | Occupancy estimate | [Lemma 3](spectral_law.md#lemma-3-gaussian-row-sums-from-local-occupancy) | Gaussian row sums are bounded by a constant times the maximum population of a resolution interval. | | 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. | 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 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 The [examples](examples.md) compare the homogeneous exact-noiseless limit with a nondegenerate finite register, then connect the construction to executable checks. The [interpretation](interpretation.md) derives a rate bound from spectral variance and explains the difference between finite-time approximate storage and the infinite-time algebra. diff --git a/science/model.md b/science/model.md index 3e3a23c..53d78e4 100644 --- a/science/model.md +++ b/science/model.md @@ -133,6 +133,10 @@ V:=2^{-n}\sum_x(\lambda(x)-\bar\lambda)^2 The general spectral theorem is information theoretic and does not assume an efficient description of an eigenbasis. Efficient compilation is asserted only for the explicitly supplied form (M10), with finite-precision coupling estimates and a stated error certificate. +## Several commuting generators + +For several known commuting generators, use the same endpoint operations, memory resources and half-diamond criterion with the covariance-weighted joint spectral channel defined in [several noise directions](multiple_noise_directions.md). The scalar normalization (M1)–(M3) and the compiler assumptions (M10)–(M12) specify the single-direction case. + ## Relation to the storage literature The use of arbitrary boundary encoders and recoveries to define quantum storage is part of the established Markovian-memory framework; see Singh and Datta, *Information storage and transmission under Markovian noise*, [arXiv:2504.10436v2](https://arxiv.org/html/2504.10436v2), Theorem 3.1. The present definitions specify the finite-time channel, classical record, and worst-case reference-sensitive error criterion used below. diff --git a/science/multiple_noise_directions.md b/science/multiple_noise_directions.md new file mode 100644 index 0000000..64d173c --- /dev/null +++ b/science/multiple_noise_directions.md @@ -0,0 +1,198 @@ +# Spectral memory with several commuting noise directions + +For one Gaussian noise direction, counting eigenvalues in a narrow interval estimates the optimal stored dimension within a constant number of qubits. With several directions, the analogous count uses a ball in the joint spectrum. The ball count still controls storage at fixed rank. As the rank grows, terminal quantum error correction can store many qubits even when every ball contains only one spectral point. + +## Model and result + +Use the [deterministic storage model](model.md) and the same reference-sensitive half-diamond error criterion. During a single storage interval the finite register experiences random phases from known commuting Hermitian operators $`A_1,\ldots,A_m`$. Let $`\lambda_i\in\mathbb R^m`$ be their joint eigenvalue vectors in a common eigenbasis, listed with multiplicity, and let $`\Sigma\succeq0`$ be the Gaussian phase covariance, including exposure. A known mean phase can be undone at the terminal boundary, so assume zero mean. The Gaussian characteristic function gives + +```math +\Phi(|i\rangle\langle j|) += G_{ij}|i\rangle\langle j|, +\qquad +G_{ij}=e^{-\|z_i-z_j\|^2/2}, +\qquad +z_i=\Sigma^{1/2}\lambda_i. +\qquad\text{(R1)} +``` + +Take $`r`$ to be the dimension of the affine span of the $`z_i`$, identifying that span isometrically with $`\mathbb R^r`$. This removes noise directions that act as scalars or carry redundant signatures. The case $`r=0`$ is the identity channel. For $`r\ge1`$ define + +```math +M=\max_{c\in\mathbb R^r}\#\{i:\|z_i-c\|\le1\}, +\qquad +C_r=\sum_{j=0}^\infty(2j+3)^r e^{-j^2/2}. +\qquad\text{(R2)} +``` + +The ball is closed, and $`M`$ counts multiplicity. Let $`D_\epsilon`$ be the optimal deterministic stored dimension for arbitrary endpoint encoding and recovery, including any retained classical record. All logarithms below that measure stored dimension are base two. + +For $`0\lt\epsilon\lt1/4`$ and every finite joint spectrum, + +```math +\left\lceil\frac{M}{(1+2/\epsilon)^r}\right\rceil +\le D_\epsilon\le\frac{\lambda_{\max}(G)}{1-\epsilon} +\le\frac{M C_r}{1-\epsilon}. +\qquad\text{(R3)} +``` + +For each fixed $`\epsilon`$, the supremum of $`\log_2D_\epsilon-\log_2M`$ over finite joint spectra of affine rank $`r`$ is + +```math +\frac r2\log_2 r+O_\epsilon(r). +\qquad\text{(R4)} +``` + +The lower bound in (R3) uses one small spectral subspace. The spectra witnessing (R4) have $`M=1`$. Their codes use superpositions of separated spectral points and a terminal recovery. The [one-direction theorem](spectral_law.md) still gives the sharper constants for the original width-one interval in normalized coordinates. The two conventions at rank one differ by at most a factor of two in occupancy because a unit ball there has width two. + +## The ball-code guarantee and the arbitrary-code converse + +We use the following Euclidean covering bound. A ball of radius $`R`$ in $`\mathbb R^r`$ is coverable by at most $`(1+2R/a)^r`$ balls of radius $`a`$. Indeed, choose a maximal $`a`$-separated set in the larger ball. Balls of radius $`a/2`$ around the chosen points have disjoint interiors and fit inside the ball of radius $`R+a/2`$. Their volumes bound the number of points, and maximality gives the cover. This works for arbitrary centers and finite spectra with repeated eigenvalues. + +For the lower bound, cover a unit ball achieving $`M`$ by balls of radius $`\epsilon`$. One of those contains at least $`\lceil M/(1+2/\epsilon)^r\rceil`$ eigenvectors. Center those signatures at the center of the small ball, obtaining $`\|z_i\|\le\epsilon`$ on that subset. The shift leaves its Gaussian channel unchanged. + +For real $`z\in\mathbb R^r`$ define a unit vector indexed by multi-indices $`\alpha\in\mathbb Z_{\ge0}^r`$, + +```math +|e(z)\rangle +=e^{-\|z\|^2/2} + \sum_{\alpha\in\mathbb Z_{\ge0}^r} + \frac{z^\alpha}{\sqrt{\alpha!}}|\alpha\rangle, +\qquad +\langle e(w)|e(z)\rangle=e^{-\|z-w\|^2/2}. +\qquad\text{(R5)} +``` + +Here $`z^\alpha=\prod_a z_a^{\alpha_a}`$, and $`\alpha!=\prod_a\alpha_a!`$. The overlap follows by summing the exponential series in each coordinate. These are coherent-state vectors, used only to express the channel's Stinespring isometry $`|i\rangle\mapsto |i\rangle|e(z_i)\rangle`$. The ideal isometry on the chosen spectral subspace uses the same system vectors with the environment fixed to $`|e(0)\rangle`$. The operator norm of the isometry difference is the largest norm of the difference in environment vectors over the chosen $`i`$, because the system vectors are orthogonal. Thus + +```math +\max_i\lVert |e(z_i)\rangle-|e(0)\rangle\rVert +=\max_i\sqrt{2-2e^{-\|z_i\|^2/2}} +\le\epsilon . +\qquad\text{(R6)} +``` + +For isometries $`V,W`$ into the same system and environment, the reduced channels differ in half diamond norm by at most $`\|V-W\|`$. To see this, expand the difference of $`VXV^\dagger`$ and $`WXW^\dagger`$ into two terms and bound the trace norm after adjoining any reference. Partial trace and the final recovery are contractions. Applying this observation to (R6) gives the first inequality in (R3), with the subspace decoder from [Lemma 1 of the scalar proof](spectral_law.md#lemma-1-reference-stable-protection-of-a-spectral-interval). + +For the converse, the [Schur-channel comparison in Lemma 2](spectral_law.md#lemma-2-a-converse-for-arbitrary-encoding-and-classical-records) applies to (R1). The Gaussian matrix in (R1) is a Gram matrix by (R5). With $`\mu=\lambda_{\max}(G)`$, one has $`\Phi\le_{\rm CP}\mu\Delta`$, where $`\Delta`$ deletes all off-diagonals. After arbitrary encoding and recovery, the comparison output for a maximally entangled input is separable across the reference and the recovered register, even with the retained classical record. Its overlap with the target is at most $`1/D`$. The true overlap is at most $`\mu/D`$ and must be at least $`1-\epsilon`$. This proves the middle bound in (R3). + +For the final inequality, fix a row $`i`$ and group the other indices, including $`i`$ itself, by $`j\le\|z_i-z_k\|\lt j+1`$. Each shell lies in the radius-$`(j+1)`$ ball around $`z_i`$. By the covering bound, it contains at most $`M(2j+3)^r`$ indices. An entry in that shell is at most $`e^{-j^2/2}`$, so the Gaussian row sum is at most $`M C_r`$. The matrix is nonnegative entrywise, and its largest eigenvalue is bounded by its maximum row sum. For an explicit estimate, use + +```math +\begin{aligned} +(2j+3)^r e^{-j^2/4} +&\le 3^r\,2^{r/2}(j^2+1)^{r/2}e^{-j^2/4}\\ +&\le e^{1/4}\bigl(6\sqrt{r/e}\bigr)^r . +\end{aligned} +``` + +The first step uses $`2j+3\le3(j+1)`$ and $`(j+1)^2\le2(j^2+1)`$. For the second, maximize $`x^{r/2}e^{-x/4}`$ at $`x=2r`$. Since $`\sum_{j\ge0}e^{-j^2/4}\le1+\sqrt\pi`$, + +```math +C_r\le e^{1/4}(1+\sqrt\pi)\bigl(6\sqrt{r/e}\bigr)^r . +\qquad\text{(R7)} +``` + +Equations (R3) and (R7) prove the upper side of (R4). + +## A joint spectrum that needs error correction + +### Separated signatures + +For integer $`r\ge9`$, take a maximal set of points with pairwise distance at least three in the closed ball about the origin of radius $`\sqrt r`$. Start with the points $`0,\sqrt r\,e_1,\ldots,\sqrt r\,e_r`$, where $`e_a`$ are coordinate unit vectors, to ensure affine rank $`r`$. The volume of the disjoint radius-$`3/2`$ interiors around the points bounds the size of any such set, so a greedy extension can stop with a finite maximal set. The radius-three balls around the points cover the original ball. Volume comparison gives + +```math +d\ge(\sqrt r/3)^r,\qquad M=1. +\qquad\text{(R8)} +``` + +Use these points as the normalized signatures of a $`d`$-dimensional register. They define a commuting Gaussian channel by taking the $`r`$ observables diagonal in the chosen eigenbasis and choosing identity phase covariance. + +For these signatures, any code whose range is spanned by a subset of at least two joint eigenvectors fails at the target error, even with a general terminal recovery. Equal superpositions of two selected eigenvectors with opposite relative signs are orthogonal inputs, but after (R1) their trace distance is at most $`e^{-9/2}`$. Recovery cannot increase it. To recover both with half-diamond error at most $`\epsilon`$, their output trace distance would have to be at least $`1-2\epsilon`$, by the triangle inequality. This is impossible for $`\epsilon\lt1/4`$. + +### Truncating the environment vectors + +Let $`P_L`$ be the projection onto $`|\alpha|=\sum_a\alpha_a\le L`$ in (R5), and let $`|\widetilde e_i\rangle`$ be the normalized projection of $`|e(z_i)\rangle`$ onto its range. The zero index ensures nonzero norm. The squared norm removed by the projection is + +```math +q_i=\Pr[X_i>L], +\qquad +X_i\sim\mathrm{Poisson}(\|z_i\|^2). +``` + +This follows by summing the squared coefficients of fixed total degree with the multinomial theorem. For $`\|z_i\|^2\le r`$, Markov's inequality for $`2^{X_i}`$ gives $`q_i\le e^r2^{-L-1}`$. In particular, + +```math +L=\left\lceil 2r+\log_2(2/\epsilon^2)\right\rceil +\quad\Longrightarrow\quad +\max_i q_i\le\epsilon^2/2. +\qquad\text{(R9)} +``` + +The truncated channel $`\widetilde\Phi`$ is defined by the isometry $`|i\rangle\mapsto |i\rangle|\widetilde e_i\rangle`$. Both dilations can be represented in the same environment. Their distance and the induced channel error satisfy + +```math +\frac12\|\Phi-\widetilde\Phi\|_\diamond +\le\max_i\lVert |e(z_i)\rangle-|\widetilde e_i\rangle\rVert +=\max_i\sqrt{2-2\sqrt{1-q_i}} +\le\epsilon . +\qquad\text{(R10)} +``` + +The truncated environment dimension is $`k=\binom{r+L}{r}\le2^{r+L}`$. This dimension bounds the proof representation. The code will access only the noisy system register. + +### A deterministic code for the truncated channel + +Apply Tverberg's theorem to the $`d`$ matrices $`|\widetilde e_i\rangle\langle\widetilde e_i|`$, regarded as points in the affine real space of unit-trace Hermitian $`k\times k`$ matrices, of dimension $`k^2-1`$. Since $`d\ge (K-1)k^2+1`$ for $`K=\lceil d/k^2\rceil`$, there are $`K`$ disjoint index sets $`S_\ell`$ and probability weights $`p_{\ell i}`$ such that the weighted mixtures in all sets equal the same state $`\omega`$. Equivalently, this is the [diagonal error-space construction in Weaver's Lemma 2.9](https://arxiv.org/abs/1802.07394), following earlier work by [Knill, Laflamme and Viola](https://arxiv.org/abs/quant-ph/9908066). + +Encode in orthonormal vectors $`|c_\ell\rangle=\sum_{i\in S_\ell}\sqrt{p_{\ell i}}|i\rangle`$. The complementary channel of $`\widetilde\Phi`$ keeps only diagonal entries in this physical basis. On encoded matrix units it therefore satisfies + +```math +\widetilde\Phi^{\,c}(|c_\ell\rangle\langle c_{\ell'}|) +=\delta_{\ell\ell'}\omega. +\qquad\text{(R11)} +``` + +The condition gives exact recovery on this subspace. Concretely, write $`\omega=\sum_{s:\nu_s>0}\nu_s|u_s\rangle\langle u_s|`$ and form the Kraus operators $`A_s`$ of the encoded system channel by taking the $`\langle u_s|`$ components of the encoded isometry. Equation (R11) implies $`A_s^\dagger A_{s'}=\nu_s\delta_{ss'}I_K`$. Components in the zero-eigenvalue space vanish. Thus $`W_s=A_s/\sqrt{\nu_s}`$ are isometries with orthogonal ranges. Recovery applies $`W_s^\dagger`$ on each such range and sends the complement to any fixed logical state, which defines a trace-preserving decoder. The encoder and decoder are chosen once, with no postselection and no operation during storage. By (R10) the same fixed code for the actual channel satisfies the target half-diamond error. + +Finally, (R8)–(R11) give + +```math +\begin{aligned} +\log_2D_\epsilon +&\ge \log_2d-2\log_2k\\ +&\ge \frac r2\log_2r-r\log_2 3-2(r+L)\\ +&=\frac r2\log_2r-O_\epsilon(r). +\end{aligned} +\qquad\text{(R12)} +``` + +This establishes the other side of (R4) with $`M=1`$. Tverberg's theorem and the finite-channel recovery are inherited coding steps. The Gaussian cutoff estimate, together with the high-dimensional packing and the converse, gives the sharp coefficient of $`r\log r`$. + +## A finite example with local noise + +For $`r=151`$ physical qubits, take $`z_x=sx`$ for $`x\in\{0,1\}^r`$ and $`s=\sqrt{2\ln8}>2`$. Independent Gaussian fields couple to the local projectors $`s|1\rangle\langle1|_a`$. The joint spectrum again has $`M=1`$. The channel multiplies a computational-basis off-diagonal by $`(1/8)^{d_{\rm H}(x,y)}`$, where $`d_{\rm H}`$ is Hamming distance. It is exactly the product of single-qubit Pauli $`Z`$ errors of probability $`p=7/16`$, because $`1-2p=1/8`$. + +Encode one qubit in the two basis vectors $`|+\rangle^{\otimes r}`$ and $`|-\rangle^{\otimes r}`$. Standard binary repetition-code syndrome recovery in the $`X`$ basis changes the logical symbol precisely when more than half the physical qubits have flipped. The syndrome can distinguish an error pattern only up to its complement. Correcting the lower-weight one preserves the encoded coherence and leaves a logical Pauli $`X`$ error for the higher-weight one. The half-diamond error equals the probability of this logical error, since the identity and logical $`X`$ are perfectly distinguishable channels. The resulting error at $`r=151`$ is + +```math +\sum_{j=76}^{151}\binom{151}{j} + \left(\frac{7}{16}\right)^j + \left(\frac9{16}\right)^{151-j} +=0.06121720444\ldots\lt\frac1{16}. +\qquad\text{(R13)} +``` + +The comparison can be evaluated by integer arithmetic with common denominator $`16^{151}`$. For a code spanned by joint eigenvectors, the two-sign superposition test above gives a recovered trace distance at most $`1/8`$, well below the required $`1-2/16`$. This establishes a separation for a simple local realization. Equations (R7) and (R12) give the coefficient in (R4) over arbitrary finite commuting spectra. + +## Interpretation and scope + +The ball count is a reliable storage estimate when the effective noise rank is fixed. It supplies a constructive subspace guarantee at every rank. For the separated spectra, each resolution ball holds just one eigenvector. At large rank there are far more eigenvectors than the dimension required to approximate the environment outputs. An endpoint code can give several orthogonal logical states the same compressed environment output by assigning different superpositions with matching environment mixtures. + +The fixed positive error matters. For zero error, joint eigenvectors with identical signatures form exact noiseless subspaces. Distinct joint signatures have a strictly positive definite Gaussian Gram matrix. Its quadratic form is the Gaussian average of a squared finite exponential sum. The Gaussian measure has full support, and restricting that sum to a line whose direction separates the finitely many signatures gives linearly independent exponentials. Applying [the scalar exact-error argument](spectral_law.md#proposition-2-exact-storage-at-every-positive-time) to the distinct joint signature blocks then gives exact stored dimension equal to the largest joint multiplicity. + +All physical system carriers count. The endpoint operations in the theorem are ideal, and the signatures and phase covariance are supplied. The environment vectors in (R5) are a mathematical representation. The scheme requires neither added bosonic carriers nor access to the actual environment. Finding the Tverberg partition and its weights, and implementing the exact endpoint maps, can be costly. The result for arbitrary commuting observables establishes a storage-dimension law with no efficiency, calibration, or local gate guarantee. The [existing calibrated compiler](encoder.md) treats one known noise direction with additive qubit couplings. + +The channel comparison with complete dephasing follows the scalar account's use of established completely positive ordering techniques. Singh and Datta's [storage theorem](https://arxiv.org/html/2504.10436v2) treats finite-time convergence toward an asymptotic peripheral-space characterization. Aydin, Albert and Barg use [Tverberg geometry for spin, bosonic and permutation-invariant codes](https://doi.org/10.1103/kx3b-4nrp). Here the finite-time objective is the largest possible failure of joint ball occupancy to estimate unrestricted storage, with matching rank dependence and a code for one Gaussian storage interval. The [related-work account](../references/related_work.md) gives further comparisons. + +[Scientific overview](README.md) · [Repository overview](../README.md) · [Related work](../references/related_work.md) diff --git a/verification/README.md b/verification/README.md index 4272685..40a1ab5 100644 --- a/verification/README.md +++ b/verification/README.md @@ -40,6 +40,22 @@ The independently constructed tables and classical maps are compared against `ba Two separate boundary checks exercise the zero-logical-qubit case and a one-physical-qubit negative-weight code. For weights `[-9, 18]`, the encoder has logical dimension one and prepares the nonzero physical word `10`; the decoder must clean both physical qubits. For weight `[-3]`, it encodes one logical qubit into the physical words `1, 0`. Both cases propagate the actual primitive gates, check cleanup and the decoded channel, and compare the classical maps with `band_code.py`. The dimension-one logical test cannot be entangled with its reference; the one-qubit case includes entangled inputs. These checks have their own summary and do not change the five-case performance table. +### Noise rank, Gaussian features, and the 151-qubit example + +The noise-rank theorem and examples have a standalone check that uses only the Python standard library: + +```bash +python verification/verify_noise_rank.py +``` + +The script verifies the following finite instances. + +- **Independent phase flips.** It derives the flip probability `7/16` from the Gaussian one-bit coherence `1/8`. It computes the majority-failure tail for 151 qubits by an exact integer sum and independently by a rational recurrence. The probability is **0.061217204448** to twelve decimal places and is strictly below `1/16`. Exhausting all error patterns for odd physical register sizes from one through nine checks that a syndrome identifies each pattern up to its complement. Choosing the lighter pattern leaves a logical flip exactly for the majority-failure events. The resulting Pauli error probability equals the half-diamond error by the analytic argument. +- **Gaussian feature truncation.** At effective ranks one, two, and three, the script enumerates the feature coordinates of the specified total-degree projection and verifies their count, normalization, and Gram entries against the scalar exponential series. It independently computes the omitted Poisson mass for each signature and verifies the uniform dilation bound at those points. These floating-point comparisons cover 12 signatures and 48 ordered pairs. +- **Exact recovery condition.** At a separate degree-one cutoff, two disjoint weighted groups of five signatures give the same normalized feature mixture, exactly `I/2`. Rational arithmetic checks all four entries of each mixture. The disjoint supports also make the off-diagonal complementary output zero. This is a finite instance of the condition used for exact recovery of the projected channel. + +The script prints its results and does not change the existing generated evidence. + ### 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: @@ -51,6 +67,7 @@ Grid selection, integer counts, rounding, codewords, gate permutations, bandwidt | Decoded density-matrix trace | Absolute deviation from one strictly less than `1e-12` | | Decoded density-matrix positivity | Minimum eigenvalue strictly greater than `-1e-12` | | Tested state trace distance versus the analytic storage bound | At most the bound plus `1e-12` | +| Gaussian feature normalization, Poisson mass and Gram entries | Absolute difference at most `2e-14` | ## Generated evidence diff --git a/verification/verify_noise_rank.py b/verification/verify_noise_rank.py new file mode 100644 index 0000000..3b91915 --- /dev/null +++ b/verification/verify_noise_rank.py @@ -0,0 +1,214 @@ +"""Check finite examples for the Gaussian noise-rank theorem.""" + +from decimal import Decimal, localcontext +from fractions import Fraction +from itertools import product +from math import ceil, comb, e, exp, factorial, fsum, isclose, log, sqrt + + +def majority_failure_numerator(qubits, flip_weight, no_flip_weight): + """Count majority events with integer probability weights.""" + return sum( + comb(qubits, weight) + * flip_weight**weight + * no_flip_weight**(qubits - weight) + for weight in range(qubits // 2 + 1, qubits + 1) + ) + + +def majority_failure_recurrence(qubits, flip_probability): + """Obtain the same probability by propagating rational masses.""" + masses = [Fraction(1)] + for _ in range(qubits): + updated = [Fraction(0)] * (len(masses) + 1) + for weight, mass in enumerate(masses): + updated[weight] += mass * (1 - flip_probability) + updated[weight + 1] += mass * flip_probability + masses = updated + assert sum(masses) == 1 + return sum(masses[qubits // 2 + 1 :]) + + +def check_phase_repetition(): + # The squared separation of distinct hypercube signatures is at least + # 2 ln(8) = 6 ln(2) > 4, as certified by two positive terms of + # ln(2) = 2 atanh(1/3). + series_argument = Fraction(1, 3) + separation_squared_lower_bound = 12 * ( + series_argument + series_argument**3 / 3 + ) + assert separation_squared_lower_bound > 4 + # Gaussian coherence exp(-ln(8)) equals 1/8. A Z flip attenuates + # coherence by 1 - 2p, because it negates every one-bit off-diagonal. + coherence = Fraction(1, 8) + flip_probability = (1 - coherence) / 2 + assert flip_probability == Fraction(7, 16) + flip_weight, denominator = flip_probability.as_integer_ratio() + no_flip_weight = denominator - flip_weight + + pattern_count = 0 + for qubits in range(1, 10, 2): + all_qubits = (1 << qubits) - 1 + syndrome_representatives = {} + failure_numerator = 0 + for error in range(1 << qubits): + # Adjacent X-parity measurements identify a phase-error mask up + # to flipping every bit. The two masks have distinct weights. + syndrome = (error ^ (error >> 1)) & (all_qubits >> 1) + complement = all_qubits ^ error + weight = error.bit_count() + correction = error if weight <= qubits // 2 else complement + representative = syndrome_representatives.setdefault(syndrome, correction) + assert representative == correction + residual = correction ^ error + assert residual == (all_qubits if weight > qubits // 2 else 0) + if residual: + failure_numerator += flip_weight**weight * no_flip_weight**( + qubits - weight + ) + pattern_count += 1 + assert len(syndrome_representatives) == 1 << (qubits - 1) + assert failure_numerator == majority_failure_numerator( + qubits, flip_weight, no_flip_weight + ) + + qubits = 151 + risk = Fraction( + majority_failure_numerator(qubits, flip_weight, no_flip_weight), + denominator**qubits, + ) + assert risk == majority_failure_recurrence(qubits, flip_probability) + assert risk < Fraction(1, 16) + # A much smaller point supplies an independent check against using an + # off-by-one majority threshold. + assert majority_failure_recurrence(3, flip_probability) == Fraction(833, 2048) + with localcontext() as context: + context.prec = 40 + rounded_risk = f"{Decimal(risk.numerator) / Decimal(risk.denominator):.12f}" + assert rounded_risk == "0.061217204448" + print(f"Phase repetition: {pattern_count} small error patterns checked.") + print(f"151-qubit half-diamond error: {rounded_risk} < 1/16 (exact comparison).") + + +def dot(left, right): + return fsum(x * y for x, y in zip(left, right, strict=True)) + + +def polynomial_exponential(argument, cutoff): + return fsum(argument**degree / factorial(degree) for degree in range(cutoff + 1)) + + +def poisson_tail(mean, cutoff): + # Evaluate the omitted positive series directly instead of subtracting + # a cumulative probability close to one. + degree = cutoff + 1 + term = exp(-mean) * mean**degree / factorial(degree) + tail = term + while term: + degree += 1 + term *= mean / degree + updated = tail + term + if updated == tail: + break + tail = updated + return tail + + +def normalized_features(signature, indices): + features = [] + for index in indices: + feature = 1.0 + for coordinate, power in zip(signature, index, strict=True): + feature *= coordinate**power / sqrt(factorial(power)) + features.append(feature) + norm = sqrt(dot(features, features)) + return [value / norm for value in features], norm + + +def check_gaussian_features(): + fixtures = ( + ((0.0,), (1.0,), (-0.75,), (0.3,)), + ((0.0, 0.0), (1.0, 1.0), (-0.8, 0.4), (0.2, -1.2)), + ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (-1.0, 0.2, 0.7), (0.4, -0.8, 1.2)), + ) + epsilon = 1 / 16 + max_gram_residual = 0.0 + max_dilation_displacement = 0.0 + for rank, signatures in enumerate(fixtures, start=1): + cutoff = ceil(2 * rank + log(2 / epsilon**2)) + indices = [ + index + for index in product(range(cutoff + 1), repeat=rank) + if sum(index) <= cutoff + ] + assert len(indices) == comb(rank + cutoff, cutoff) + projected = [] + for signature in signatures: + mean = dot(signature, signature) + assert mean <= rank + features, norm = normalized_features(signature, indices) + assert isclose(dot(features, features), 1, abs_tol=2e-14, rel_tol=0) + tail = poisson_tail(mean, cutoff) + mass = exp(-mean) * norm**2 + assert isclose(mass, 1 - tail, abs_tol=2e-14, rel_tol=0) + assert tail <= exp((e - 1) * mean - cutoff) <= epsilon**2 / 2 + # Stable form of sqrt(2 - 2 sqrt(1 - tail)). + displacement = sqrt(2 * tail / (1 + sqrt(1 - tail))) + assert displacement <= epsilon + max_dilation_displacement = max(displacement, max_dilation_displacement) + projected.append((signature, features, norm, displacement)) + + for left, left_features, left_norm, left_shift in projected: + for right, right_features, right_norm, right_shift in projected: + actual_gram = dot(left_features, right_features) + expected_norm = sqrt( + polynomial_exponential(dot(left, left), cutoff) + * polynomial_exponential(dot(right, right), cutoff) + ) + assert isclose(left_norm * right_norm, expected_norm, rel_tol=2e-14) + expected_gram = polynomial_exponential(dot(left, right), cutoff) / ( + expected_norm + ) + residual = abs(actual_gram - expected_gram) + assert residual < 2e-14 + max_gram_residual = max(residual, max_gram_residual) + squared_distance = fsum( + (x - y) ** 2 for x, y in zip(left, right, strict=True) + ) + true_gram = exp(-squared_distance / 2) + assert abs(actual_gram - true_gram) <= left_shift + right_shift + 2e-14 + print( + f"Gaussian features: 48 Gram entries checked " + f"(max residual {max_gram_residual:.3g})." + ) + print( + f"Largest dilation displacement among 12 signatures: " + f"{max_dilation_displacement:.6g}." + ) + + +def check_disjoint_feature_mixtures(): + # With degree one, the normalized feature projector for signature z is + # the matrix [[1, z], [z, z^2]] / (1 + z^2). + groups = ( + {-1: Fraction(1, 2), 1: Fraction(1, 2)}, + {-2: Fraction(5, 16), 0: Fraction(3, 8), 2: Fraction(5, 16)}, + ) + first, second = groups + assert first.keys().isdisjoint(second) + expected = (Fraction(1, 2), Fraction(0), Fraction(0), Fraction(1, 2)) + for weights in groups: + assert all(weight > 0 for weight in weights.values()) + assert sum(weights.values()) == 1 + mixture = tuple( + sum(weight * Fraction(z**power, 1 + z**2) for z, weight in weights.items()) + for power in (0, 1, 1, 2) + ) + assert mixture == expected + print("Truncated code: two disjoint groups give identical feature mixtures I/2.") + + +if __name__ == "__main__": + check_phase_repetition() + check_gaussian_features() + check_disjoint_feature_mixtures()