diff --git a/.github/workflows/hosted-review.yml b/.github/workflows/hosted-review.yml new file mode 100644 index 0000000..f1c9892 --- /dev/null +++ b/.github/workflows/hosted-review.yml @@ -0,0 +1,75 @@ +name: Hosted mathematics review + +on: + pull_request: + branches: [main] + types: [opened, synchronize] + +concurrency: + group: hosted-math-${{ github.event.pull_request.head.sha }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + hosted-review: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + env: + CAPTURE_REVISION: ${{ github.event.pull_request.head.sha }} + steps: + - name: Check out the exact public source revision + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ env.CAPTURE_REVISION }} + fetch-depth: 0 + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: '24' + package-manager-cache: false + + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: '3.12' + + - name: Install temporary browser dependencies + timeout-minutes: 8 + shell: bash + env: + HOSTED_DEPS: ${{ runner.temp }}/hosted-math-deps + PLAYWRIGHT_BROWSERS_PATH: ${{ runner.temp }}/hosted-math-browsers + run: | + mkdir -p "$HOSTED_DEPS" + npm install --prefix "$HOSTED_DEPS" --ignore-scripts --no-audit --no-fund --save-exact \ + playwright@1.56.1 mathjax-full@3.2.1 + "$HOSTED_DEPS/node_modules/.bin/playwright" install --with-deps chromium + + - name: Capture every tracked Markdown page on GitHub + timeout-minutes: 15 + shell: bash + env: + NODE_PATH: ${{ runner.temp }}/hosted-math-deps/node_modules + PLAYWRIGHT_BROWSERS_PATH: ${{ runner.temp }}/hosted-math-browsers + HOSTED_OUTPUT: ${{ runner.temp }}/hosted-math-evidence + run: | + test "$(git rev-parse HEAD)" = "$CAPTURE_REVISION" + node verification/hosted/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --contract verification/hosted/math-contract.json \ + --output "$HOSTED_OUTPUT" + + - name: Preserve the actual report and captures + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: hosted-math-${{ env.CAPTURE_REVISION }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/hosted-math-evidence/ + if-no-files-found: error + retention-days: 30 diff --git a/README.md b/README.md index 713f9a4..71d2f30 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,17 @@ The [related-work account](references/RELATED_WORK.md) credits Choi-state compos ## Reading and reproduction -Start with the [scientific account](science/README.md). For an exact statement, go directly to [Model and composition law](science/model.md). The [verification guide](verification/README.md) explains the finite checks and their limits. +Choose a route according to the question you want to answer: + +| Reader's question | Starting point | +|---|---| +| What is the task, and what is proved? | [Scientific account](science/README.md) and [exact model](science/model.md) | +| How does a stored operation become a composed program? | [Worked tutorial](learning/TUTORIAL.md) | +| Which foundations connect to the proofs? | [Watrous bridge](learning/WATROUS_BRIDGE.md) | +| How do the ideas fit into one learning route? | [Learning guide](learning/README.md) and [30 milestones](learning/MILESTONES.md) | +| How can I reproduce the finite checks? | [Verification guide](verification/README.md) | + +The single educational anchor is John Watrous's *The Theory of Quantum Information* (2018). The bridge identifies relevant sections and translates the Choi normalization and fidelity conventions. The specialist proofs remain in the scientific account. From the repository root, with Python 3.11 or later: diff --git a/learning/MILESTONES.md b/learning/MILESTONES.md new file mode 100644 index 0000000..2a3b84a --- /dev/null +++ b/learning/MILESTONES.md @@ -0,0 +1,286 @@ +# Thirty milestones for understanding program composition + +[Scientific account](../science/README.md) · [Exact model and statements](../science/model.md) · [Proof dependencies](../references/RELATED_WORK.md) + +This map describes the understanding needed to connect the supplied programs, collective measurement, converse and circuit into one scientific account. Its targets follow the project, independently of a reader's starting knowledge. It covers the load-bearing ideas and their connections; specialist details remain in the canonical scientific pages. + +## Structure and educational anchor + +The single educational anchor is John Watrous, *The Theory of Quantum Information* (Cambridge University Press, 2018): [author's page](https://cs.uwaterloo.ca/~watrous/TQI/) and [author's online text][watrous]. The section numbers below refer to that text. PDF links open the beginning of the cited section; the section number is authoritative if a viewer ignores the page fragment. + +| Phase | Milestones | Allocation and direction | +|---|---|---| +| Background / preliminaries | M01–M13: 13 targets | Assemble individual operators and states into referenced programs, physical processing, error measures, spectral probability and symmetry; finish with the complete supplied-program task. | +| Narrative / innovation | M14–M30: 17 targets | Follow the local contraction through the collective construction, then the distinguishing converse and charged implementation; finish with the allocation law, precision regimes and complete operational interpretation. | + +Thirteen background targets are needed because this project joins matrix multiplication to the physics of referenced states, probabilistic instruments, spectral bounds and group averages. Seventeen narrative targets connect three substantial arguments: how the processor works, why arbitrary processors need enough copies, and how known gates implement it. The allocation reflects those connections, rather than a fixed division inherited from another project. + +Three source conventions matter throughout: + +- Watrous writes vectors and adjoints as $u$ and $A^*$. The science pages also use $\lvert u\rangle$ and $A^\dagger$. The normalized program is $\mathrm{vec}(U)/\sqrt d$; the normalized Choi density is the channel's Choi operator divided by $d$. +- Watrous's fidelity in §3.2 is the root convention. Here $F(\rho,w)=\langle w\rvert\rho\lvert w\rangle$ is its square for a normalized pure target. A success probability and a conditional fidelity are separate quantities. +- Anchor pointers provide foundations. The mixed-tensor ingredients, two-pool derivations, QSVT and compilation results are supplied or cited in the scientific pages. Those primary research sources remain proof dependencies, not additional educational anchors. Projector symbols are local to each proof: whole-copy symmetry in the construction and the harmonic projector in the converse are different objects. + +## Phase I — Background / preliminaries + +### M01 — Finite registers and linear operators + +- **Central question:** What mathematical objects describe a program register and an operation acting on it? +- **Understanding target:** Relate a finite register to a complex vector space, its dimension to a basis, and a linear operator to its matrix entries. Distinguish the local operation dimension $d$ from the $d^2$ dimensions of a two-register program and from the number of physical qubits used to encode it. +- **Dependencies and story role:** No earlier milestone. Establishes the objects whose tensor products, transformations and resource counts appear throughout the project. +- **Conceptual connection:** The dimension in the copy law is a physical Hilbert-space dimension, so a scaling statement in $d$ must be interpreted before comparing it with a qubit count. +- **Sources:** [Watrous §§1.1.1][w111]–[1.1.2][w112]; [programs, inputs and outputs](../science/model.md#programs-inputs-and-outputs), [charged circuit resources](../science/implementation.md#5-charged-circuit-resources). + +### M02 — Pure states, mixtures, and irrelevant phase + +- **Central question:** What information belongs to a quantum state, and which changes leave that state unchanged? +- **Understanding target:** Connect normalized vectors with pure density operators, distinguish a coherent vector from a probabilistic mixture, and explain why multiplying a program vector by a global phase changes no state-level prediction. Understand that an unknown fixed state and an averaged ensemble are different descriptions used for different purposes. +- **Dependencies and story role:** M01. Gives the physical meaning of the vectors and density operators used later in both construction and converse. +- **Conceptual connection:** The target program remains well defined even though unitary Choi states do not encode an observable global phase of their matrices. +- **Sources:** [Watrous §2.1.2][w212]; [program convention and phase](../science/model.md#programs-inputs-and-outputs), [averaged program ensembles](../science/converse.md#1-correlated-programs-and-independent-programs). + +### M03 — Composite registers and accessible correlations + +- **Central question:** Why do both halves of a Choi specimen matter when either half alone is maximally mixed? +- **Understanding target:** Explain tensor products, joint states and reduced states, and distinguish independence across supplied specimens from entanglement within each specimen. Identify which registers the processor can access and which correlations disappear when a register is discarded. +- **Dependencies and story role:** M01–M02. Moves from an isolated state to the multi-register setting in which the physical task lives. +- **Conceptual connection:** Full access to both halves is a material input promise. The construction uses the maximally mixed inner marginal while preserving useful information in the joint state. +- **Sources:** [Watrous §§2.1.2][w212]–[2.1.3][w213]; [input access and joint target](../science/model.md#programs-inputs-and-outputs), [inner-register marginal](../science/construction.md#3-exact-first-and-second-moments). + +### M04 — Unitary products, adjoints, and order + +- **Central question:** How do matrix multiplication and adjoints determine the meaning of the desired composed operation? +- **Understanding target:** Explain unitarity, the distinction between transpose, complex conjugate and adjoint, and why $UV$ and $VU$ generally differ. Separate the mathematical identity $U^\dagger U=I$ from operational permission to query or implement an unknown inverse. +- **Dependencies and story role:** M01–M03. Supplies the algebra that fixes the composition target and the inverse-correlated prior used by the converse. +- **Conceptual connection:** A register-order mistake can change the task. A mathematical conjugate in an ensemble definition does not supply a physical conjugation procedure. +- **Sources:** [Watrous §1.1.2][w112]; [row-first program convention](../science/model.md#programs-inputs-and-outputs), [correlated programs](../science/converse.md#1-correlated-programs-and-independent-programs). + +### M05 — Vectorization and normalized Choi programs + +- **Central question:** How can a matrix be represented by a bipartite quantum state without supplying its classical entries? +- **Understanding target:** Identify the row and column registers in $\lvert U\rangle=\mathrm{vec}(U)/\sqrt d$, account for normalization, and relate this vector to the Choi representation of a unitary channel. Distinguish possessing the state from possessing an executable gate or a matrix description. +- **Dependencies and story role:** M02–M04. Turns the abstract matrix product into a state-conversion problem with explicit physical input specimens. +- **Conceptual connection:** The same matrix indices that describe composition become quantum registers; the processor must eliminate the shared index while retaining coherence. +- **Sources:** [Watrous §§1.1.2][w112] and [2.2.2][w222]; [program definition](../science/model.md#programs-inputs-and-outputs), [composition and execution](../science/interpretation.md#program-composition-and-program-execution). + +### M06 — Bell pairs and teleportation contractions + +- **Central question:** How does projection onto a maximally entangled pair connect two register indices? +- **Understanding target:** Explain a Bell ket, its corresponding bra and projector, and the coherent sum produced by contracting two registers. Track the difference between an unnormalized branch vector, its squared norm as an outcome probability, and its normalized conditional state. Understand the role of outcome-dependent corrections in ordinary teleportation. +- **Dependencies and story role:** M03–M05. Introduces the generic physical contraction before its program-specific action is derived in the narrative. +- **Conceptual connection:** The normalization of an entangled projection determines its probability; obtaining a useful contraction is not itself a deterministic operation. +- **Sources:** [Watrous §§1.1.2][w112] and [6.3.1][w631]; [Bell projectors and routing maps](../science/construction.md#1-a-physical-instrument-on-two-pools). + +### M07 — Channels, instruments, and success flags + +- **Central question:** What makes a collection of probabilistic branches a legal quantum processor? +- **Understanding target:** Distinguish a channel, a completely positive branch and a quantum instrument. Explain how Kraus effects determine probabilities, why their sum must satisfy a normalization condition, and how retaining or discarding a classical success flag changes the output description. +- **Dependencies and story role:** M02–M03, M06. Extends one Bell outcome into the framework for a complete physical procedure. +- **Conceptual connection:** The composer must act legally on the entire input space, even though its accuracy promise concerns a special family of identical-copy states. Preparing a fixed output on failure completes a channel. +- **Sources:** [Watrous §§2.2.1][w221]–[2.2.2][w222] and [2.3.2][w232], including instruments; [physical instrument](../science/construction.md#1-a-physical-instrument-on-two-pools). + +### M08 — Squared fidelity and joint targets + +- **Central question:** What does it mean for the composed program and returned specimens to be accurate together? +- **Understanding target:** Translate Watrous's root fidelity into the project's squared convention. Distinguish unconditional overlap, successful conditional overlap and success probability. Explain why fidelity with one full product target controls the joint returned state more strongly than a statement about the composed output alone. +- **Dependencies and story role:** M02–M03, M07. Fixes the correctness criterion before any resource bound is interpreted. +- **Conceptual connection:** The promise includes residual correlations and approximation error, so returned registers cannot automatically be counted as exact fresh copies. +- **Sources:** [Watrous §3.2.1][w321], especially Proposition 3.13, and [§3.2.2][w322]; [global target](../science/construction.md#the-global-output-guarantee), [joint return interpretation](../science/interpretation.md#a-joint-return-guarantee). + +### M09 — Trace distance and operational distinguishability + +- **Central question:** How does closeness of two input ensembles limit every possible measurement strategy? +- **Understanding target:** Interpret $\mathrm{TD}(\rho,\sigma)=\tfrac12\lVert\rho-\sigma\rVert_1$ as the maximum difference between the probabilities of a measurement event. Explain why physical processing followed by a test cannot create a larger distinguishing advantage than was available in the input states. +- **Dependencies and story role:** M02, M07. Introduces the operational measure used to constrain arbitrary composers, complementing the fidelity measure used to certify an output. +- **Conceptual connection:** A lower bound can follow from a task reduction: an accurate composer would enable a discrimination experiment forbidden by the supplied information. +- **Sources:** [Watrous §3.1.1][w311]; [moment comparison](../science/converse.md#1-correlated-programs-and-independent-programs), [composer-to-test reduction](../science/converse.md#2-turning-a-composer-into-a-correlation-test). + +### M10 — Positive operators, support, and polar maps + +- **Central question:** How can a known contraction be normalized when it has a nontrivial kernel? +- **Understanding target:** Relate positive operators to their spectral square roots and support projectors, and interpret inverse powers that vanish on the kernel. Explain how singular values separate the magnitude of a rectangular map from its polar partial isometry, without mistaking that partial isometry for a unitary on the full input space. +- **Dependencies and story role:** M01, M04, M07. Supplies the algebra behind the PGM effects and the exact collective channel. +- **Conceptual connection:** Support-aware normalization produces legal success effects and leaves a complementary failure effect; it does not require inverting an unknown preparation. +- **Sources:** [Watrous §1.1.3][w113], including singular values, polar decompositions and the pseudoinverse; [instrument normalization](../science/construction.md#1-a-physical-instrument-on-two-pools), [polar map](../science/construction.md#2-symmetry-identifies-the-common-successful-state). + +### M11 — Spectral probability and moment bounds + +- **Central question:** How can a few operator moments control fidelity without solving a complete large spectrum? +- **Understanding target:** Interpret the eigenvalues of a positive operator, weighted by a state, as a nonnegative random variable. Relate its first two moments to mean and variance, and explain how scalar inequalities bound its square-root average or a low-value tail. Distinguish this spectral distribution from a claim that overlapping measurements are independent. +- **Dependencies and story role:** M08, M10. Connects operator normalization to quantitative probability bounds. +- **Conceptual connection:** The construction and finite circuit use different consequences of the same exact moments: a global overlap bound and control of the small-singular-value region. +- **Sources:** [Watrous §§1.1.3][w113] and [1.2.2][w122]; [exact moments](../science/construction.md#3-exact-first-and-second-moments), [fidelity inequality](../science/construction.md#4-fidelity-and-success-probability), [spectral tail](../science/implementation.md#controlling-the-small-singular-value-tail). + +### M12 — Permutation symmetry and Haar averaging + +- **Central question:** What do symmetries of repeated copies and averages over unknown unitaries each accomplish? +- **Understanding target:** Explain the symmetric subspace, a known permutation average and an invariant operator. Separately explain Haar averaging and its invariance under known unitary changes of basis. Distinguish a projector onto symmetry of whole copies from a state averaged over an ensemble of unknown matrices. +- **Dependencies and story role:** M03–M05, M07, M11. Connects the physical and probabilistic ingredients into the symmetry framework shared by all three proof strands. +- **Conceptual connection:** Whole-copy symmetry identifies output branches; Haar symmetry simplifies the converse. Neither operation provides a reflection about an unknown program state. +- **Sources:** [Watrous §§7.1.1][w711]–[7.1.2][w712] and [7.2.1][w721]; [common successful state](../science/construction.md#2-symmetry-identifies-the-common-successful-state), [averaged priors](../science/converse.md#1-correlated-programs-and-independent-programs). + +### M13 — The complete supplied-program task + +- **Central question:** Which inputs, operations, outputs and accuracy promises define the theorem being studied? +- **Understanding target:** Assemble the full model: $m$ copies of the first unknown unitary program, $n$ of the second, access to both halves, a fixed known processor, the ordered product target and optional joint return. Interpret universal quantifiers, worst-case copy budgets, deterministic versus heralded performance, and separate accounting of copies, gates and memory. +- **Dependencies and story role:** M01–M12. Integrates the background into one operational specification, completing this phase. +- **Conceptual connection:** A copy law has meaning only with this resource boundary. State conversion, gate execution and classical reconstruction are distinct requested outputs. +- **Sources:** [Watrous §§2.2.1][w221], [2.3.2][w232] and [3.2.1][w321] for the processing and accuracy language; [complete model](../science/model.md), [composition and execution](../science/interpretation.md#program-composition-and-program-execution). + +## Phase II — Narrative / innovation + +### M14 — One pair contracts to the ordered product + +- **Central question:** What exactly happens when the inner halves of one $U$ program and one $V$ program meet a Bell bra? +- **Understanding target:** Follow the row and column indices to obtain $L(\lvert U\rangle\otimes\lvert V\rangle)=\lvert UV\rangle/d$. Account for every normalization factor and infer success probability $d^{-2}$. Explain why the accepted target is exact for this single trial and why its probability establishes only a baseline, not an arbitrary-processor lower bound. +- **Dependencies and story role:** M04–M06, M08, M13. Begins the narrative with its smallest complete physical mechanism. +- **Conceptual connection:** The matrix product is already present in one coherent contraction; the collective construction changes the copy cost of obtaining a useful output. +- **Sources:** [Watrous §§1.1.2][w112] and [6.3.1][w631]; [ordered contraction, equation (9)](../science/construction.md#2-symmetry-identifies-the-common-successful-state), [paired-trial baseline](../science/construction.md#5-copy-budgets-and-the-precision-boundary). + +### M15 — All cross-pool pairs form one Bell-sum operator + +- **Central question:** How are all $mn$ potential contractions combined without treating them as independent trials? +- **Understanding target:** Identify the pair-labelled Bell effects $E_{rs}$ and the known positive operator $G=d\sum_{r,s}E_{rs}$. Explain why shared registers make some effects noncommuting and why counting port pairs alone does not yield a classical success formula. +- **Dependencies and story role:** M10–M11, M14. Moves from one contraction to the collective operator whose fluctuations determine performance. +- **Conceptual connection:** The useful product of copy budgets enters through a jointly normalized family of overlapping alternatives, rather than through $mn$ disjoint pairs of specimens. +- **Sources:** [Watrous §§1.1.2][w112]–[1.1.3][w113] and [2.3.2][w232]; [Bell-sum definition](../science/construction.md#1-a-physical-instrument-on-two-pools), [why two pools help](../science/interpretation.md#why-two-pools-help). + +### M16 — A universal PGM instrument and deterministic completion + +- **Central question:** How does square-root normalization turn the overlapping alternatives into a valid universal processor? +- **Understanding target:** Explain $J_{rs}=\sqrt dL_{rs}G^{-1/2}$ and the support identity for the sum of its effects. Relate these effects to the pretty-good measurement for a known Bell-signal ensemble, and account for the kernel by a separate failure output. Distinguish the effects from the routed quantum outputs that make this an instrument. +- **Dependencies and story role:** M07, M10, M15. Establishes physical legality before claiming fidelity on the promised inputs. +- **Conceptual connection:** The measured signals and their normalization are known from $d,m,n$; no program-dependent correction is supplied. The generic PGM prescription is inherited machinery. +- **Sources:** [Watrous §§2.3.2][w232] and [3.1.2][w312], including its PGM discussion; [instrument and completion](../science/construction.md#1-a-physical-instrument-on-two-pools), [PGM relation](../science/construction.md#relation-to-the-pretty-good-measurement). + +### M17 — Whole-copy symmetry identifies every routed branch + +- **Central question:** Why can the port label be discarded without mixing different useful output states? +- **Understanding target:** Explain why permutation symmetry acts on complete two-register programs, why $G$ preserves that subspace, and why the routing maps agree there. Connect $M^\dagger M=G$ on the restricted domain to the common branch vector $Kv/\sqrt{mn}$, where $K$ is the polar map. +- **Dependencies and story role:** M10, M12, M14–M16. Converts a many-outcome instrument into one analyzable successful state. +- **Conceptual connection:** Physical ordered-register symmetry supplies the simplification. No coherent port-label output, occupation encoding or bosonic access is assumed, and the leftover registers remain part of the state being analyzed. +- **Sources:** [Watrous §§1.1.3][w113] and [7.1.1][w711]; [common successful state, equations (7)–(12)](../science/construction.md#2-symmetry-identifies-the-common-successful-state). + +### M18 — Exact Gram moments expose the copy product + +- **Central question:** Why is the normalized spectral variance exactly $(d^2-1)/(mn)$ for every pair of unitaries? +- **Understanding target:** Use the maximally mixed joint inner marginal to turn expectations into normalized traces. Distinguish diagonal, disjoint-pair and shared-register terms in $G^2$, and explain why the last two have the same trace despite noncommutation. Connect the resulting mean $mn/d$ and variance $mn(1-d^{-2})$ to the dimensionless ratio $r$. +- **Dependencies and story role:** M03, M11, M15, M17. Supplies the quantitative input for both the exact channel and its finite implementation. +- **Conceptual connection:** Uniformity over unknown $U,V$ follows from the marginal structure, not from averaging the accuracy guarantee over those unitaries. +- **Sources:** [Watrous §§2.1.3][w213] and [1.2.2][w122]; [exact moment derivation](../science/construction.md#3-exact-first-and-second-moments). + +### M19 — Polar normalization preserves the full joint target + +- **Central question:** How do the moments certify the composed program and every returned specimen together? +- **Understanding target:** Connect the polar overlap to $(\mathbb E\sqrt X)^2$, with $X=G/\mathbb EG$, and follow the Hölder step yielding $F_{\rm global}\geq1/(1+r)=mn/(mn+d^2-1)$. Keep this unconditional contribution distinct from the support probability $p$ and the conditional fidelity $f_{\rm pol}/p$. +- **Dependencies and story role:** M08, M11, M16–M18. Completes the constructive argument by joining physical branches to a global error guarantee. +- **Conceptual connection:** The bound remains informative when $1-r$ is negative. It certifies approximate joint return without asserting that every successful output is exact or that the bound is optimal. +- **Sources:** [Watrous §§1.1.3][w113], [1.2.2][w122] and [3.2.1][w321] for the spectral and fidelity language; [local Hölder derivation and success probability](../science/construction.md#4-fidelity-and-success-probability), [global theorem](../science/model.md#theorem-1-a-universal-collective-construction). + +### M20 — Correlated and independent program priors + +- **Central question:** Which two collections of programs would an accurate universal composer help distinguish? +- **Understanding target:** Explain the inverse-correlated and independent Haar hypotheses, their averaged input density operators, and the known SWAP that converts an inverse program into the conjugate notation used in the moment proof. Distinguish correlations between unknown source matrices from the identical-copy structure inside each pool. +- **Dependencies and story role:** M04–M05, M09, M12–M13. Begins the converse with an information-theoretic experiment rather than a restriction to the proposed measurement. +- **Conceptual connection:** The product is the identity in one hypothesis and Haar distributed in the other. Conjugation in the mathematical ensemble is not an extra access operation granted to the processor. +- **Sources:** [Watrous §§3.1.1][w311] and [7.2.1][w721]; [two averaged priors](../science/converse.md#1-correlated-programs-and-independent-programs), [physical reduction](../science/converse.md#2-turning-a-composer-into-a-correlation-test). + +### M21 — Harmonic subspaces beyond the faithful range + +- **Central question:** What large common part of the mixed tensor space prevents the two priors from being easily distinguished? +- **Understanding target:** Interpret the harmonic subspace as the intersection of all cross-pool contraction kernels and obtain its discarded dimension fraction $q\leq mn/d^2$. Explain the role of a central projector and why the argument concerns the represented matrix algebra even when $m+n>d$. +- **Dependencies and story role:** M10, M12, M20. Identifies the geometric structure carrying the lower bound before comparing its moment blocks. +- **Conceptual connection:** Vanishing small-dimension sectors can be omitted without assuming faithful abstract algebra action. The mixed-centralizer and centrality ingredients are research dependencies, not consequences asserted from the anchor alone. +- **Sources:** [Watrous §§1.1.2][w112] and [7.1.2][w712], including the double-commutant framework; [harmonic dimension bound](../science/converse.md#11-a-large-common-harmonic-subspace), [all-dimensional representation argument](../science/converse.md#12-why-the-harmonic-decomposition-works-in-every-dimension) and its primary references. + +### M22 — Ordered compressed moments limit distinguishability + +- **Central question:** How does the common harmonic structure yield a quantitative trace-distance bound? +- **Understanding target:** Explain the common positive blocks of the compressed moments, their ordering $A\succeq B$, and the control of their missing masses. Connect these facts to $\mathrm{TD}(\Omega_{\rm c},\Omega_{\rm i})\leq\min\lbrace1,2mn/d^2\rbrace$. Distinguish commutation of an averaged moment with the compression from invariance of the harmonic subspace under every independent group element. +- **Dependencies and story role:** M09–M10, M20–M21. Converts representation structure and dimension counting into an operational information bound. +- **Conceptual connection:** The independent moment's block structure is essential; pretending its underlying representation preserves the harmonic subspace would omit a load-bearing step. +- **Sources:** [Watrous §§1.1.3][w113], [3.1.1][w311] and [7.2.2][w722] for norms, discrimination and invariant averages; [ordered compressed moments](../science/converse.md#13-the-two-harmonic-moment-blocks-are-ordered). + +### M23 — A composer becomes a correlation test + +- **Central question:** How does the moment bound constrain every successful processor, including adaptive ones? +- **Understanding target:** Follow symmetrization and the final maximally entangled output test to obtain $mn\geq p_0(d^2F_0-1)/2$. Explain why worst-case bounded sequential access can be precollected. For Haar averages, identify $\bar s-\bar p/d^2\leq2mn/d^2$ and distinguish success-weighted conditional fidelity $\bar s/\bar p$ from an unweighted conditional average. +- **Dependencies and story role:** M07–M09, M12–M13, M20–M22. Completes the unrestricted converse and its precise averaging extension. +- **Conceptual connection:** The test uses only the composed output, so requesting leftovers cannot evade the bound. The statement does not cover merely expected copy budgets or arbitrary non-Haar promise distributions. +- **Sources:** [Watrous §§2.3.2][w232], [3.1.1][w311] and [7.2.1][w721]; [composer-to-test proof](../science/converse.md#2-turning-a-composer-into-a-correlation-test), [Haar-average statement](../science/converse.md#haar-average-performance). + +### M24 — The physical projected block for QSVT + +- **Central question:** Which known operator must a circuit encode to reproduce the polar mechanism? +- **Understanding target:** Identify the right whole-copy symmetry projector $P$, the left Bell projector $Q$, and the routed contraction $A=JQP$. Explain $A v=w/d$ and $A^\dagger A=G/(dmn)$ on the symmetric domain. Distinguish the nontrivial singular spectrum of the compressed block from the binary spectrum of an unrestricted Bell projector. +- **Dependencies and story role:** M10, M12, M17–M19. Begins the implementation argument by locating the exact physical operator, before invoking a transformation theorem. +- **Conceptual connection:** QSVT is applied to a block defined by known subspaces. Its applicability does not supply a free reflection about an unknown input state. +- **Sources:** [Watrous §§1.1.3][w113] and [2.2.2][w222] for singular values and operator representations; [projected encoding](../science/implementation.md#1-a-projected-encoding-on-physical-registers), [compressed Gram operator](../science/implementation.md#the-compressed-gram-operator). The QSVT theorem is a primary dependency cited in that page. + +### M25 — Spectral tails and finite circuit accuracy + +- **Central question:** Why can a finite circuit work without a lower bound on every nonzero singular value? +- **Understanding target:** Explain the polynomial cutoff at singular value $1/(2d)$, the corresponding event $X<1/4$, and the small weighted contribution bounded by the exact moments. Track the separate errors from polar distortion, polynomial approximation and gate synthesis, including deterministic completion on failure. +- **Dependencies and story role:** M07–M08, M11, M18–M19, M24. Connects the exact mathematical channel to a finite implementation with an explicit fidelity budget. +- **Conceptual connection:** The approximation is justified on the promised states. A uniform inverse approximation near zero is unnecessary; the finite circuit uses larger sufficient copy constants than the exact polar channel. +- **Sources:** [Watrous §§1.1.3][w113] and [1.2.2][w122] for spectra and probability bounds; [polar approximation](../science/implementation.md#2-approximating-the-polar-map-on-the-supplied-states), [tail estimate](../science/implementation.md#controlling-the-small-singular-value-tail), [finite-precision guarantee](../science/implementation.md#3-deterministic-completion-and-finite-precision). + +### M26 — Known symmetry phases and charged addressing + +- **Central question:** What resources implement the known symmetry operations when coherent routing is charged? +- **Understanding target:** Relate a uniform permutation encoding to its symmetry-projector block and explain why the resulting reflection returns clean ancillas. Account for the explicit loop over possible swap addresses, its quadratic pool-size cost and multiplication by the QSVT degree. Interpret the resulting balanced fixed-error gate bound $\widetilde O(d^3)$ separately from the copy count. +- **Dependencies and story role:** M01, M07, M12, M24–M25. Completes the circuit argument by making its access assumptions and known-gate costs concrete. +- **Conceptual connection:** Mathematical symmetry does not make controlled routing free. Gate synthesis concerns known operations and contributes precision overhead; it does not compile unknown $U$ or $V$. +- **Sources:** [Watrous §§2.2.2][w222] and [7.1.1][w711] for isometries and permutation projectors; [clean symmetry phases](../science/implementation.md#4-known-phases-about-the-symmetric-input-subspace), [charged resources and synthesis references](../science/implementation.md#5-charged-circuit-resources). + +### M27 — The balanced and unbalanced allocation law + +- **Central question:** What becomes optimal when the construction and unrestricted converse are put together? +- **Understanding target:** Explain the fixed-error threshold $mn=\Theta(d^2)$, the balanced total scale $\Theta(d)$, and the $\Theta(d^2)$ requirement on one pool when the other has one copy. Interpret the finite upper and lower bounds on achievable output fidelity without equating them or reading a threshold as an exact constant. +- **Dependencies and story role:** M13, M19, M23, M26. Joins the three proof strands into a resource statement that applies across allocations. +- **Conceptual connection:** A construction with a joint-return promise meets, in dimension scaling, a lower bound that asks only for one composed output. Its proven optimality concerns supplied copies at fixed error, not gates or vanishing-error dependence. +- **Sources:** [Watrous §§2.2.1][w221], [3.1.1][w311] and [3.2.1][w321] for the operational framework; [finite fidelity interval and allocation table](../science/model.md#what-is-optimal), [resources and boundaries](../science/model.md#resources-and-boundaries). + +### M28 — Precision regimes and exact Bell repetition + +- **Central question:** How does the preferred sufficient strategy change when the requested error becomes very small? +- **Understanding target:** Compare the collective sufficient product $mn=O(d^2/\epsilon)$ and balanced supplies $O(d/\sqrt\epsilon)$ with independent paired Bell trials using $O(d^2\log(1/\epsilon))$ pairs. Explain the latter's exact accepted target, its failure completion and the different treatment of leftover specimens. +- **Dependencies and story role:** M08, M14, M19, M25, M27. Refines the global resource law by retaining the error parameter and the promised output. +- **Conceptual connection:** A strategy that wins at constant error need not win at extreme precision. The available converse does not settle the optimal approach to unit fidelity. +- **Sources:** [Watrous §§1.2.2][w122], [2.3.2][w232] and [6.3.1][w631]; [copy budgets and precision boundary](../science/construction.md#5-copy-budgets-and-the-precision-boundary), [precision comparison](../science/interpretation.md#precision-and-alternative-strategies). + +### M29 — Returned programs and operational limits + +- **Central question:** Which further capabilities do the established promises leave unresolved? +- **Understanding target:** Explain why approximate joint return is a one-shot statement, why successive reuse needs accumulated-error accounting, and why a Choi output does not itself execute the product on arbitrary fresh data. Retain the pure-unitary-program and full-access assumptions when considering noise, mixed programs, many outputs or expected budgets. Translate the gate count into its dependence on a qubit operation's dimension. +- **Dependencies and story role:** M03, M08, M13, M19, M23, M26–M28. Interprets the integrated result under its material assumptions and resource costs. +- **Conceptual connection:** The theorem establishes a capability for manipulating supplied quantum information. It does not establish an indefinite catalyst, a noisy-program theorem or a practical runtime advantage. +- **Sources:** [Watrous §§2.1.3][w213], [2.2.1][w221] and [3.2.1][w321] for joint states, channels and fidelity; [interpretation and limits](../science/interpretation.md), [converse boundaries](../science/converse.md#3-verification-and-boundaries), [charged resources](../science/implementation.md#5-charged-circuit-resources). + +### M30 — The integrated result, evidence, and inherited tools + +- **Central question:** How do the mechanism, obstruction, implementation and attribution support one coherent scientific claim? +- **Understanding target:** Trace the complete chain from Bell contraction and collective normalization through moments and joint fidelity, then from correlated priors and harmonic blocks to the universal converse, and finally to charged gates. Identify which finite checks test consequential identities, which arguments establish the all-dimensional theorem, and which tools are inherited from prior research. +- **Dependencies and story role:** M14–M29, drawing on the complete background phase. Integrates the narrative into the project's final scientific interpretation. +- **Conceptual connection:** The result is an optimal fixed-error copy-allocation law for the stated program task, with a stronger constructive return guarantee and an explicit implementation. PGM, representation theory and QSVT retain their prior attribution; finite numerical agreement does not replace proof or determine priority. +- **Sources:** [Watrous §§2.2.2][w222], [3.1.1][w311], [3.1.2][w312] and [7.1.2][w712] as foundations; [canonical model](../science/model.md), [scientific account](../science/README.md), [verification scope](../verification/README.md), [operational comparisons and inherited ingredients](../references/RELATED_WORK.md). + +[watrous]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf +[w111]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=9 +[w112]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=16 +[w113]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=32 +[w122]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=55 +[w212]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=69 +[w213]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=75 +[w221]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=80 +[w222]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=85 +[w232]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=113 +[w311]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=133 +[w312]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=140 +[w321]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=148 +[w322]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=152 +[w631]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=367 +[w711]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=399 +[w712]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=408 +[w721]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=416 +[w722]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.pdf#page=428 diff --git a/learning/README.md b/learning/README.md new file mode 100644 index 0000000..5ef1a80 --- /dev/null +++ b/learning/README.md @@ -0,0 +1,45 @@ +# Learning quantum program composition + +Two sources supply quantum states that encode unknown operations. A processor +must combine those states into a program for the product operation. This +learning route explains the physical task, the collective construction and +the reason every processor faces the same copy-product scale. + +The single educational anchor is **John Watrous, *The Theory of Quantum +Information* (2018)**. The [Watrous bridge](WATROUS_BRIDGE.md) identifies +targeted sections of the author's manuscript, translates its notation and +normalization conventions, and supplies the connections needed here. The +book is a foundation for the project; the project's theorem and its +research-level dependencies have their own cited scientific sources. + +## Choose a starting point + +| Aim | Route | +|---|---| +| See what a program represents and what composition does | [Worked tutorial](TUTORIAL.md) | +| Build the complete conceptual picture | [Thirty-milestone map](MILESTONES.md) | +| Connect familiar quantum-information foundations to this task | [Watrous bridge](WATROUS_BRIDGE.md) | +| Inspect exact quantifiers and proofs | [Scientific account](../science/README.md) | +| Reproduce the small-system checks | [Verification guide](../verification/README.md) | + +The milestone map is defined by the scientific project and is shared by all +readers. Its background phase builds the operational and mathematical +framework; its narrative phase connects the construction, converse, +implementation and final resource interpretation. Each milestone has an +understanding target, dependencies and source pointers. The worked tutorial +provides a connected entry into that map, while specialist derivations stay +in their authoritative scientific pages. + +## Keep the physical resources visible + +The supplied inputs are complete, ideal, pure Choi copies. Both halves are +accessible, but no classical matrix or query access to the unknown +operations is supplied. The output is one composed program state. The +construction also controls the joint state of all returned specimens. + +Fidelity in this project is the **squared** pure-target overlap. A finite +copy guarantee and an implementation's gate cost answer different +questions. A good single-use return guarantee does not establish a +repeated-reuse rate. These conventions and boundaries are carried through +the learning route and stated precisely in the [model](../science/model.md) +and [interpretation](../science/interpretation.md). diff --git a/learning/TUTORIAL.md b/learning/TUTORIAL.md new file mode 100644 index 0000000..9c7989e --- /dev/null +++ b/learning/TUTORIAL.md @@ -0,0 +1,303 @@ +# Composing quantum programs: a worked route through the result + +A processor is handed quantum states encoding two unknown operations. It +must produce a state encoding their product. It receives no classical +descriptions, calls to the operations, or inverses of their preparation +circuits. The available resource is a counted supply of program states. + +This tutorial follows the [30-milestone map](MILESTONES.md). The single +educational anchor is Watrous's *The Theory of Quantum Information*; +[the source bridge](WATROUS_BRIDGE.md) identifies the relevant sections and +convention changes. The exact assumptions and bounds are in +[Model and composition law](../science/model.md). + +## 1. What a program state contains + +**Milestones M01–M05 and M13.** A d-dimensional unitary $U$ is encoded in +the normalized bipartite state + +$$ +|U\rangle +=\frac1{\sqrt d}\sum_{i,j=0}^{d-1}U_{ij}|i\rangle|j\rangle. +$$ + +The first register labels the matrix row and the second labels its column. +This ordering fixes the multiplication performed below. A global phase of +$U$ changes only the global phase of the ket, so the physical program +$|U\rangle\langle U|$ is unaffected. + +For a unitary, either half alone has state $I/d$. The information about the +operation is in the correlations. The model supplies both halves of every +copy, so collective processing can use those correlations. The supply is +$m$ identical copies of the first program and $n$ identical copies of the +second, each in its own physical registers. + +These are pure programs because the encoded operations are unitary. A +general channel's normalized Choi state can be mixed; the +[source bridge](WATROUS_BRIDGE.md#two-convention-conversions) gives an +explicit example. Producing a program for $UV$ is also different from +applying $UV$ to an additional data register: no such data register is the +output target here. + +## 2. A complete qubit example + +**Milestones M06–M08 and M14.** Take $d=2$ and, for a worked example, choose + +$$ +H|0\rangle=\frac{|0\rangle+|1\rangle}{\sqrt2},\qquad H|1\rangle=\frac{|0\rangle-|1\rangle}{\sqrt2}. +$$ + +$$ +S|0\rangle=|0\rangle,\qquad S|1\rangle=i|1\rangle. +$$ + +Their programs are + +$$ +|H\rangle_{AB} +=\frac{|00\rangle+|01\rangle+|10\rangle-|11\rangle}{2}, +\qquad +|S\rangle_{CD} +=\frac{|00\rangle+i|11\rangle}{\sqrt2}. +$$ + +The four input qubits are ordered $A,B,C,D$. Project the two middle qubits +$B,C$ onto +$|\Phi_2\rangle=(|00\rangle+|11\rangle)/\sqrt2$, and retain the outer +qubits $A,D$. The unnormalized state on those outer qubits is + +$$ +\begin{aligned} +(I_A\otimes\langle\Phi_2|_{BC}\otimes I_D) + |H\rangle_{AB}|S\rangle_{CD} +&=\frac{|00\rangle+i|01\rangle+|10\rangle-i|11\rangle}{4}\\ +&=\frac12|HS\rangle_{AD}. +\end{aligned} +$$ + +Its squared norm is $1/4$. Thus the two-outcome measurement +$\lbrace|\Phi_2\rangle\langle\Phi_2|,I-|\Phi_2\rangle\langle\Phi_2|\rbrace$ +has a designated successful outcome with probability $1/4$. Conditioned on +that outcome, the output is exactly the normalized program + +$$ +|HS\rangle +=\frac{|00\rangle+i|01\rangle+|10\rangle-i|11\rangle}{2}. +$$ + +The order matters: the program for $SH$ instead has coefficients +$(1,1,i,-i)/2$ in the same basis. These two vectors are not related by a +global phase. The contraction consequently distinguishes the order of the +operations, rather than merely changing an unobservable phase. + +The matrices above let us verify the calculation. The processor does not +need to know them: it performs the same middle-register Bell projection for +every supplied pair. It uses four program qubits and returns a two-qubit +program on the designated outcome. The other outcome occurs with probability +$3/4$; it is not declared an exact composition. + +The calculation extends directly to every dimension: + +$$ +(I_A\otimes\langle\Phi_d|_{BC}\otimes I_D) + |U\rangle_{AB}|V\rangle_{CD} +=\frac{|UV\rangle_{AD}}{d}. +$$ + +The normalization factors therefore give amplitude $1/d$ and probability +$1/d^2$. Conditional fidelity is one, while this branch's contribution to +unconditional fidelity is only $1/d^2$. Assigning a fixed output on failure +makes a trace-preserving processor, whose fidelity includes both outcomes. + +## 3. Pooling the programs without pretending the pairs are independent + +**Milestones M10–M12 and M15–M19.** With $m$ first-program copies and $n$ +second-program copies, there are $mn$ candidate cross-pool pairs. They +overlap: a copy can participate in several candidates, and their Bell +projectors generally do not commute. Measuring every candidate as an +independent classical trial would not be a legal use of the same copies. + +The collective construction instead forms the known positive operator + +$$ +G=d\sum_{r=1}^m\sum_{s=1}^n E_{rs}, +$$ + +where $E_{rs}$ is the Bell projector on the two chosen inner halves and the +identity on the others. If $L_{rs}$ contracts that pair and routes its outer +halves to the output, the useful instrument operators are + +$$ +J_{rs}=\sqrt dL_{rs}G^{-1/2}. +$$ + +The inverse vanishes on the kernel. These operators satisfy +$\sum_{r,s}J_{rs}^\dagger J_{rs}=\Pi_{\mathrm{supp}G}\leq I$. +Adding a failure outcome gives a complete physical instrument. Its +square-root normalization is the pretty-good measurement construction; +[the source bridge](WATROUS_BRIDGE.md) relates it to Watrous §3.1.2. + +All copies in either pool are identical. Permuting **whole programs** +within a pool therefore fixes the input. After the selected outer halves +are routed consistently, every useful outcome produces the same +unnormalized global vector, up to the common branch factor. This is why +the analysis can compare the entire output with + +$$ +|w\rangle=|UV\rangle + |U\rangle^{\otimes(m-1)}|V\rangle^{\otimes(n-1)}. +$$ + +The joint inner marginal is exactly maximally mixed. Consequently the +spectral distribution of $G$ on the supplied state has moments + +$$ +\mathbb E G=\frac{mn}{d}, +\qquad +\mathrm{Var}(G)=mn(1-d^{-2}). +$$ + +The relative variance $r=(d^2-1)/(mn)$ controls the distortion from the +square-root normalization. The moment argument in +[Construction](../science/construction.md) proves + +$$ +F_{\mathrm{global}}\geq\frac1{1+r} +=\frac{mn}{mn+d^2-1}. +$$ + +This fidelity includes the composed program and all returned programs in a +single target. It is an unconditional guarantee for the completed channel. +The useful branches are generally approximate, unlike the designated +single-pair Bell outcome. + +For example, with qubit programs and $m=n=6$, the exact collective channel +guarantees global fidelity at least $36/39=12/13$, approximately $0.923$. +The input comprises twelve two-qubit programs. The joint target comprises +eleven: one composed program and five from each original pool. Six +independent paired Bell trials have success probability +$1-(3/4)^6\approx0.822$, and do not provide that joint-return promise. +These are guaranteed bounds and a baseline success probability, not claims +about the exact optimal fidelity or the constants of the finite QSVT +circuit. + +## 4. The lower bound applies to every processor + +**Milestones M09, M12 and M20–M23.** Consider two ways to supply the +unknown operations. In the first, $U$ is Haar random and $V=U^\dagger$, +so the product is always the identity. In the second, $U,V$ are independent +Haar unitaries, so their product is Haar random. + +A composer could help distinguish these situations: run it and test the +output against the known identity program $|I\rangle=|\Phi_d\rangle$. +After averaging known changes of basis, a successful universal composer has +constant success probability $p$ and conditional target fidelity $F$. The +event “success and identity test accepts” then has probabilities $pF$ and +$p/d^2$ in the two situations. + +The hard part is bounding how distinguishable the supplied inputs were +before this processing. Swapping the physical halves of each second-program +copy turns the correlated input into programs for $U$ and $\overline U$. +The relevant symmetry is $U^{\otimes m}\otimes\overline U^{\otimes n}$. + +After regrouping the Choi halves, the proof works with a harmonic subspace +on a space of dimension $D=d^{m+n}$. Its vectors vanish under every +cross-pool contraction, and its lost dimension fraction is at most +$mn/d^2$. This is a different subspace from the whole-program symmetric +subspace used in the construction. The mixed-tensor centralizer theorem +makes its projector central, which permits an ordered comparison of the +two averaged Choi states. The result is + +$$ +\mathrm{TD}(\Omega_{\mathrm c},\Omega_{\mathrm i}) +\leq\frac{2mn}{d^2}. +$$ + +No later measurement can create a larger probability gap than this trace +distance. Therefore + +$$ +p\left(F-\frac1{d^2}\right)\leq\frac{2mn}{d^2}, +\qquad +mn\geq\frac p2(d^2F-1). +$$ + +This argument permits arbitrary collective gates, ancillary memory and +adaptive measurements with bounded source budgets. Its all-dimensional +representation step is given in [Converse](../science/converse.md), with +the research-level dependencies distinguished from the textbook foundation +in [the source bridge](WATROUS_BRIDGE.md#research-bridges-supplied-by-the-project). + +## 5. A known mathematical operation still needs a charged circuit + +**Milestones M24–M26.** The polar normalization defines a valid processor, +but that alone does not count its gates. The explicit circuit uses two known +projectors: one onto whole-copy symmetry and one onto a selected Bell +subspace. Its projected block has the normalization needed for the polar +map; the Bell projector alone has the wrong singular spectrum. + +Projected QSVT approximates the required singular-value transformation. +The actual input's spectral moments bound the weight of the troublesome +small singular values, so the proof does not assume a lower bound on every +nonzero singular value. Known permutation averaging implements the symmetry +phases. A quantum address is processed by visiting its possible register +locations explicitly, and those gates are counted. + +The resulting conservative count is + +$$ +\widetilde O\left(d(m^2+n^2)(\log d+\log(m+n))\right) +$$ + +known gates, with logarithmic accuracy factors suppressed. At balanced, +fixed-error budgets, this gives a $\widetilde O(d^3)$ upper bound. The +physical program storage alone is $2(m+n)\lceil\log_2d\rceil$ qubits. +The circuit also uses $O(m\log(m+1)+n\log(n+1)+\log d)$ permutation and +work qubits and one QSVT control qubit. Computing the known QSVT phases +classically is separate from the quantum gate count. These costs, their +finite-error allocation and their imported QSVT ingredients are in +[Implementation](../science/implementation.md). + +## 6. Read the resource law with its scope + +**Milestones M27–M29.** At fixed accuracy and success requirements, a +sufficiently large constant times $d^2$ in copy product suffices for the +construction. The converse requires at least another constant times $d^2$. +Thus the threshold is $mn=\Theta(d^2)$, with constants depending on those +requirements. It does not claim an exact finite-copy optimum. + +Balancing the supplies gives $m=n=\Theta(d)$ and minimizes the total +number supplied. If one pool has only one copy, the other needs order d² +copies. A scarcity in one pool can therefore be compensated by more of the +other, subject to the product law. + +For small infidelity $\epsilon$, the collective construction has the +sufficient balanced allocation $O(d/\sqrt\epsilon)$. Independent paired +Bell trials give a different output-only allocation, +$O(d^2\log(1/\epsilon))$, because their designated successful outputs are +exact. The latter can use fewer copies at extremely small error. The fixed +error theorem does not determine the optimal precision dependence. + +Returned programs are covered by one joint fidelity bound, but they need +not be exact, independent specimens. Reusing them in a long sequence would +require accumulated-error accounting. Finally, $d$ is a Hilbert-space +dimension: for a q-qubit operation, $d=2^q$. A linear copy count in d and a +cubic gate count in d do not mean polynomial complexity in q. + +## 7. Connect the evidence to the result + +**Milestone M30.** The central conclusion combines a legal collective +instrument, its dimension-dependent fidelity guarantee, a converse for +all processors, and an explicit charged implementation. Each part has a +separate role. The [verification guide](../verification/README.md) explains +the finite checks of register ordering, Gram moments, mixed Choi ensembles +and projected encodings, and distinguishes them from the all-dimensional +proofs. + +Watrous provides the shared language. The +[related-work account](../references/RELATED_WORK.md) supplies attribution +for the PGM, teleportation, mixed-tensor representation theory and QSVT. +The project's conclusion is the composition resource law under the stated +copy access model. Return to the [milestone map](MILESTONES.md) to locate +the individual conceptual dependencies, or to the +[scientific account](../science/README.md) for the complete proofs. diff --git a/learning/WATROUS_BRIDGE.md b/learning/WATROUS_BRIDGE.md new file mode 100644 index 0000000..0910e68 --- /dev/null +++ b/learning/WATROUS_BRIDGE.md @@ -0,0 +1,164 @@ +# From Watrous to quantum program composition + +The educational anchor is **John Watrous, *The Theory of Quantum +Information*** (Cambridge University Press, 2018). The +[author's official page](https://cs.uwaterloo.ca/~watrous/TQI/) provides +individual chapters, a pre-publication manuscript and errata. The source +locations below refer to that author-hosted manuscript. It is available for +personal use; this repository links to it and supplies its own explanations. + +The project asks how many copies of two unknown unitary programs are needed +to construct a program for their product. Watrous supplies the language of +states, channels, measurements, distinguishability and symmetry. The +[milestone map](MILESTONES.md) organizes those foundations around this +particular task; the [tutorial](TUTORIAL.md) connects them through a worked +example. The specialist statements remain in the +[scientific account](../science/README.md). + +## Targeted source map + +There is no need to read the whole book before approaching the project. + +| Source location | Foundation to extract | Where it enters the project | +|---|---|---| +| [§§1.1.2–1.1.3](https://cs.uwaterloo.ca/~watrous/TQI/TQI.1.pdf): operator-vector correspondence, decompositions and norms | Matrix entries can be stored in a bipartite vector; an SVD separates directions from singular values. | The Choi convention in [Model](../science/model.md) and the polar contraction in [Construction](../science/construction.md). | +| [§1.2.2](https://cs.uwaterloo.ca/~watrous/TQI/TQI.1.pdf), especially Theorem 1.13: random variables and Markov's inequality | Moments of a nonnegative random variable bound its tail probabilities. | Applying those bounds to the Gram operator's spectral weights in [Construction](../science/construction.md) and [Implementation](../science/implementation.md), as used in M11 and M25. | +| [§§2.1.2–2.1.3 and §2.2.2](https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf): states, reductions, channel representations | Distinguish a channel from a physical state representing it, and track partial traces. | Normalized unitary Choi programs and their maximally mixed inner halves. | +| [§2.3.2](https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf): measurements and instruments | A measurement can return both a classical outcome and an unnormalized quantum output. | Port selection, register routing, success probability and failure completion. | +| [§3.1.1 and §3.1.2](https://cs.uwaterloo.ca/~watrous/TQI/TQI.3.pdf): binary discrimination and the pretty-good measurement | Trace distance bounds observable probability differences; square-root normalization defines a legal measurement. | The correlation test in [Converse](../science/converse.md) and the two-pool measurement in [Construction](../science/construction.md). | +| [§3.2](https://cs.uwaterloo.ca/~watrous/TQI/TQI.3.pdf): fidelity | Read approximation guarantees with the convention conversion below. | Joint output fidelity, successful-branch overlap and returned programs. | +| [§6.3.1](https://cs.uwaterloo.ca/~watrous/TQI/TQI.6.pdf): teleportation and dense coding | Bell measurements connect entanglement to operational transformations. | The single-pair Bell contraction and its dimension-dependent probability. | +| [§§7.1.1–7.1.2 and §7.2.1](https://cs.uwaterloo.ca/~watrous/TQI/TQI.7.pdf), including Theorem 7.14: permutation symmetry, double commutants and Haar measure | Permutation invariance, commutants and unitary averaging have separate roles. | Whole-copy symmetry, Haar-correlated ensembles, and the representation framework for M21–M22; the required mixed-tensor theorem is supplied below. | + +## Two convention conversions + +### A Choi operator becomes a physical state only after normalization + +Watrous defines the Choi representation in §2.2.2, equations (2.64)–(2.65), +using the unnormalized vector $\mathrm{vec}(I)$. For a channel +$\mathcal E$ with d-dimensional input, + +$$ +J(\mathcal E) +=(\mathcal E\otimes\mathrm{id}) + \bigl(\mathrm{vec}(I)\mathrm{vec}(I)^\dagger\bigr), +\qquad +\mathrm{Tr}J(\mathcal E)=d. +$$ + +The normalized Choi state is therefore $\omega_{\mathcal E}=J(\mathcal E)/d$. +For the unitary channel $\mathcal U(X)=UXU^\dagger$, + +$$ +J(\mathcal U)=\mathrm{vec}(U)\mathrm{vec}(U)^\dagger, +\qquad +\omega_{\mathcal U}=|U\rangle\langle U|, +\qquad +|U\rangle=\frac{\mathrm{vec}(U)}{\sqrt d}. +$$ + +The tensor order is output followed by input, matching this project's +row-first convention. Both halves have reduced state $I/d$ for a unitary. + +**Normalization does not imply purity.** For example, the qubit dephasing +channel $\mathcal D(X)=\sum_{j=0}^1|j\rangle\langle j|X|j\rangle\langle j|$ +has normalized Choi state + +$$ +\omega_{\mathcal D} +=\frac12\bigl(|00\rangle\langle00|+|11\rangle\langle11|\bigr), +$$ + +which has rank two. The supplied programs in this project are pure because +the channels are unitary, not because Choi states are always pure. + +### Watrous's fidelity is the square root of the project's fidelity + +Watrous's Definition 3.11 uses + +$$ +F_{\mathrm W}(\rho,\sigma) +=\Vert\sqrt\rho\sqrt\sigma\Vert_1. +$$ + +For a normalized pure target $|w\rangle$, this project uses + +$$ +F_{\mathrm{project}}(\rho,w) +=\langle w|\rho|w\rangle +=F_{\mathrm W}(\rho,|w\rangle\langle w|)^2. +$$ + +Thus the project's infidelity $\epsilon$ means +$F_{\mathrm W}\geq\sqrt{1-\epsilon}$. For an unnormalized successful output +$\tau=p\rho_{\mathrm s}$, its unconditional target contribution is +$\langle w|\tau|w\rangle=pF_{\mathrm{project}}(\rho_{\mathrm s},w)$. +Dividing by the success probability changes the quantity being reported. + +## Translating the measurement and symmetry language + +The pretty-good measurement appears in Watrous §3.1.2, equations +(3.49)–(3.52). For a singular average state, the inverse is a pseudoinverse +on its support and the kernel needs a completion. Here that completion is a +separate failure outcome with a fixed output state; the useful outcomes +select a pair $(r,s)$ of ports. The derivation of their action and fidelity +is in [Construction](../science/construction.md), rather than being supplied +by a general PGM theorem. + +In §7.1.1, take one textbook tensor factor to be an **entire two-register +program**, of dimension $d^2$. The relevant input subspace is + +$$ +\mathrm{Sym}^m(\mathbb C^{d^2}) +\otimes\mathrm{Sym}^n(\mathbb C^{d^2}). +$$ + +Permuting only one half changes which registers are paired and need not +preserve the promised input state. The permutation projector is known from +the register dimensions and copy counts, whereas a +reflection about an unknown supplied program is not an available primitive. + +In the converse, Haar averaging concerns unitaries in $U(d)$ and their Choi +states. It does not mean drawing a uniformly random pure vector in +$\mathbb C^{d^2}$. Those are different ensembles. The local +[converse](../science/converse.md) explains the correlated and independent +priors before applying the discrimination bound. + +## Research bridges supplied by the project + +The following are research dependencies, not additional educational anchors. +They are introduced where the project needs them. + +**From symmetry to the universal converse.** The lower bound uses the +represented commutant of $U^{\otimes m}\otimes\overline U^{\otimes n}$. +Its cross-contractions define a harmonic subspace; centrality of that +subspace's projector allows the two Choi moments to be compared without a +square-root loss. These mixed-tensor facts go beyond the foundation mapped +above. The exact inputs are Goncharov's Theorem 2.3 and Proposition 2.4 in +[arXiv:2511.00303v1](https://arxiv.org/html/2511.00303v1), together with the +mixed Schur–Weyl formulation in Grinko–Ozols, +[arXiv:2207.05713v2](https://arxiv.org/abs/2207.05713v2). The +[converse proof](../science/converse.md) supplies their application, including +the all-dimensional argument and the final identity-program test. + +**From a polar operator to a circuit.** The textbook's SVD and polar +decomposition explain the desired transformation. They do not by themselves +give an economical circuit for it. Projected QSVT is imported from Gilyén, +Su, Low and Wiebe, +[arXiv:1806.01838v1](https://arxiv.org/abs/1806.01838v1). The +[implementation proof](../science/implementation.md) supplies the specific +block $QP$, a known singular-value cutoff justified by the supplied input's +spectral-tail bound, known symmetry phases, and the charged gate count. It +invokes no inverse of an unknown program preparation. + +**From teleportation to two-pool composition.** The Bell contraction and +square-root normalization have established antecedents. The project derives +the port-pair instrument, its exact Gram moments, the joint-return fidelity +and the matching constant-error copy-product law. The +[related-work account](../references/RELATED_WORK.md) identifies what comes +from teleportation and quantum-programming literature and what the present +task adds. + +Return to the [learning overview](README.md) for the map and tutorial, or go +directly to the [model](../science/model.md) for the exact assumptions and +bounds. diff --git a/llms.txt b/llms.txt index 6ab0fc1..0b248c8 100644 --- a/llms.txt +++ b/llms.txt @@ -12,5 +12,16 @@ Meaning, precision alternatives and limitations: science/interpretation.md Closest work and inherited ingredients: references/RELATED_WORK.md Structured source metadata: references/bibliography.json Reproduction commands and tested limits: verification/README.md +Learning entry and route selection: learning/README.md +Project-defined understanding map, M01-M30: learning/MILESTONES.md +Selected educational anchor, verified sections and notation translation: learning/WATROUS_BRIDGE.md +Worked composition example and connected explanation: learning/TUTORIAL.md + +Story route: README.md -> learning/TUTORIAL.md -> science/interpretation.md. +Study route: learning/README.md -> learning/MILESTONES.md, using learning/WATROUS_BRIDGE.md for targeted Watrous readings and notation conversions. +Theorem route: science/model.md -> science/construction.md -> science/converse.md -> science/implementation.md. +Reproduction route: verification/README.md -> the three documented Python scripts. + +Educational anchor: John Watrous, The Theory of Quantum Information (2018), official author-hosted prepublication manuscript. Its Choi operator is unnormalized and its fidelity is unsquared. The project divides a unitary channel's Choi operator by d and uses squared pure-target overlap. The learning map is a common route through the scientific understanding targets. Essential distinctions: Fidelity is pure-target overlap (squared convention). Inputs are complete pure unitary Choi copies; no unknown-unitary query or preparation oracle is supplied. The main theorem is a bounded-copy, constant-error resource law. The output is a program state, not application to fresh data. Global approximate program return does not establish indefinite reuse. Copy complexity and known-gate complexity are distinct. diff --git a/references/bibliography.json b/references/bibliography.json index c33493c..c5e42f1 100644 --- a/references/bibliography.json +++ b/references/bibliography.json @@ -307,6 +307,34 @@ "https://github.com/GoGoKo699/Quantum-Coherent-Collisions/blob/219f590010247124f48feffaf244a60f306335f4/science/model.md", "https://github.com/GoGoKo699/Quantum-Coherent-Collisions/blob/219f590010247124f48feffaf244a60f306335f4/science/coherent_extraction.md" ] + }, + { + "id": "watrous2018", + "type": "book", + "authors": [ + "John Watrous" + ], + "title": "The Theory of Quantum Information", + "year": 2018, + "publisher": "Cambridge University Press", + "url": "https://cs.uwaterloo.ca/~watrous/TQI/", + "source_version": "Author-hosted 2018 prepublication manuscript; front matter dated January 2018, published book April 2018.", + "inspected_locations": [ + "Section 1.1.3", + "Section 2.2.2", + "Section 3.1.1", + "Section 3.2.1", + "Section 6.3.1", + "Sections 7.1-7.2" + ], + "role": "Single educational anchor for channel representations, state comparison, teleportation and symmetry. The project bridge converts unnormalized Choi operators and unsquared fidelity and identifies additional research-level dependencies.", + "primary_sources": [ + "https://cs.uwaterloo.ca/~watrous/TQI/", + "https://cs.uwaterloo.ca/~watrous/TQI/TQI.frontmatter.pdf", + "https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf", + "https://cs.uwaterloo.ca/~watrous/TQI/TQI.3.pdf", + "https://cs.uwaterloo.ca/~watrous/TQI/TQI.7.pdf" + ] } ] } diff --git a/science/README.md b/science/README.md index 3685a99..a1f1673 100644 --- a/science/README.md +++ b/science/README.md @@ -11,3 +11,5 @@ Read the account in this order: 5. [Interpretation and limits](interpretation.md): what program composition enables, how the copy advantage arises, and the boundaries of the result. The [related-work comparison](../references/RELATED_WORK.md) identifies inherited techniques and the distinct input models of earlier teleportation and program-processing tasks. The [verification guide](../verification/README.md) provides the commands and the tested scope of the finite checks. Those checks complement the analytical proofs; they do not replace them. + +For the foundations and a worked example before the full proofs, use the [learning route](../learning/README.md). Its [Watrous bridge](../learning/WATROUS_BRIDGE.md) translates textbook conventions into the normalized programs used here. diff --git a/science/construction.md b/science/construction.md index a2bd9b3..c5d76b9 100644 --- a/science/construction.md +++ b/science/construction.md @@ -8,6 +8,8 @@ This page proves the construction on ordinary ordered registers. The finite circ Fix $d\geq2$ and integers $m,n\geq1$. Use the row-first convention +**Equation (1).** + $$ |U\rangle=\frac1{\sqrt d}\sum_{i,j=0}^{d-1}U_{ij}|i\rangle|j\rangle, \qquad @@ -31,14 +33,15 @@ $$ F_{\mathrm{global}} \geq \frac{mn}{mn+d^2-1} \geq 1-\frac{d^2-1}{mn}. -\tag{1} $$ The processor receives only the stated copies. Both halves of every copy are accessible. It receives no unitary description, query access, preparation inverse, or reflection about an unknown program state. The copies returned in $w$ are part of the same global fidelity guarantee; they are not asserted to be exact or indefinitely reusable. ## 1. A physical instrument on two pools -Write the $r$th copy of $U$ on registers $(A_r,B_r)$ and the $s$th copy of $V$ on $(C_s,D_s)$. The inner registers are $B_1,\ldots,B_m,C_1,\ldots,C_n$. Let +Write the copy indexed by $r$ of $U$ on registers $(A_r,B_r)$ and the copy indexed by $s$ of $V$ on $(C_s,D_s)$. The inner registers are $B_1,\ldots,B_m,C_1,\ldots,C_n$. Let + +**Equation (2).** $$ |\Phi_d\rangle=\frac1{\sqrt d}\sum_{j=0}^{d-1}|j,j\rangle, @@ -46,40 +49,43 @@ $$ E_{rs}=|\Phi_d\rangle\langle\Phi_d|_{B_rC_s}\otimes I_{\mathrm{rest}}, \qquad G=d\sum_{r=1}^m\sum_{s=1}^n E_{rs}. -\tag{2} $$ The identity in each $E_{rs}$ acts on the other inner registers. The same operators act as the identity on every outer register when used on the full input. Different $E_{rs}$ need not commute. Let $L_{rs}$ contract $B_rC_s$ with $\langle\Phi_d|$, then route $A_r,D_s$ into the two output registers. It places the remaining whole $U$ copies first and the remaining whole $V$ copies second, in increasing original index order. Thus all $L_{rs}$ have the same output Hilbert space, and +**Equation (3).** + $$ L_{rs}^{\dagger}L_{rs}=E_{rs}. -\tag{3} $$ Define inverse square roots to vanish on the kernel, and set +**Equation (4).** + $$ -J_{rs}=\sqrt d\,L_{rs}G^{-1/2}. -\tag{4} +J_{rs}=\sqrt dL_{rs}G^{-1/2}. $$ These maps form a valid incomplete instrument on the entire ordered input space, since +**Equation (5).** + $$ \sum_{r,s}J_{rs}^{\dagger}J_{rs} =G^{-1/2}\left(d\sum_{r,s}E_{rs}\right)G^{-1/2} -=\Pi_{\operatorname{supp}G}\leq I. -\tag{5} +=\Pi_{\mathrm{supp}G}\leq I. $$ On the complementary effect, discard the input and prepare any fixed normalized state $\sigma_0$ on the output space. This defines the channel +**Equation (6).** + $$ \mathcal E(\rho)=\sum_{r,s}J_{rs}\rho J_{rs}^{\dagger} - +\operatorname{Tr}\!\left[(I-\Pi_{\operatorname{supp}G})\rho\right]\sigma_0. -\tag{6} + +\mathrm{Tr}\left[(I-\Pi_{\mathrm{supp}G})\rho\right]\sigma_0. $$ The first term can be implemented with a classical outcome $(r,s)$ followed by the prescribed register routing. Equation (6) discards that outcome. The second term supplies a deterministic completion; it does not assert an exact target state upon a success flag. @@ -88,14 +94,16 @@ The first term can be implemented with a classical outcome $(r,s)$ followed by t On the $m+n$ inner registers, the known density operators +**Equation (7).** + $$ \sigma_{rs}=\frac{E_{rs}}{d^{m+n-2}} $$ -with equal priors $1/(mn)$ have average $G/(mn\,d^{m+n-1})$. Their pretty-good measurement has effects +with equal priors $1/(mn)$ have average $G/(mnd^{m+n-1})$. Their pretty-good measurement has effects $$ -d\,G^{-1/2}E_{rs}G^{-1/2}=J_{rs}^{\dagger}J_{rs}. +dG^{-1/2}E_{rs}G^{-1/2}=J_{rs}^{\dagger}J_{rs}. $$ The square-root measurement is established machinery [1]. Its use in port-based teleportation, second-moment fidelity bounds, and approximate preservation of unused resource ports are developed in [2]. Here the index set selects one port from each of two unknown-program pools. The normalization itself is not a new general measurement method. @@ -105,8 +113,8 @@ The square-root measurement is established machinery [1]. Its use in port-based The input belongs to the known subspace $$ -\mathcal S=\operatorname{Sym}^{m}(\mathbb C^{d^2}) - \otimes\operatorname{Sym}^{n}(\mathbb C^{d^2}), +\mathcal S=\mathrm{Sym}^{m}(\mathbb C^{d^2}) + \otimes\mathrm{Sym}^{n}(\mathbb C^{d^2}), $$ where the symmetrization permutes **whole two-register copies** within each pool. Let $P$ be its orthogonal projector. The sum $G$ commutes with these permutations and therefore preserves $\mathcal S$. After the common routing convention, symmetry also gives @@ -114,59 +122,63 @@ where the symmetrization permutes **whole two-register copies** within each pool $$ L_{rs}P=L_{11}P \qquad\text{for every }r,s. -\tag{7} $$ Indeed, a permutation can send the selected copy in either pool to the first position. It fixes every vector in $\mathcal S$; any resulting permutation of the surviving whole copies fixes their separately symmetric output. This proves (7) on the full subspace, including states other than identical-copy products. -Restrict $L=L_{11}|_{\mathcal S}$ and $G_{\mathcal S}=G|_{\mathcal S}$, and introduce the scaled contraction +Let $L$ be the restriction of $L_{11}$ to $\mathcal S$, and let $G_{\mathcal S}$ be the restriction of $G$ to $\mathcal S$. Introduce the scaled contraction + +**Equation (8).** $$ -M=\sqrt{dmn}\,L. +M=\sqrt{dmn}L. $$ For vectors in $\mathcal S$, equations (3) and (7) imply $$ M^{\dagger}M=G_{\mathcal S}. -\tag{8} $$ -Here the adjoint of $M$ is taken with domain $\mathcal S$. Equivalently, on the full input space $(\sqrt{dmn}\,L_{11}P)^{\dagger}(\sqrt{dmn}\,L_{11}P)=PGP$. Individual Bell projectors need not preserve $\mathcal S$; their complete sum does. +Here the adjoint of $M$ is taken with domain $\mathcal S$. Equivalently, on the full input space $(\sqrt{dmn}L_{11}P)^{\dagger}(\sqrt{dmn}L_{11}P)=PGP$. Individual Bell projectors need not preserve $\mathcal S$; their complete sum does. The row-first convention fixes the product order. Direct contraction gives +**Equation (9).** + $$ (\langle\Phi_d|_{B_1C_1}\otimes I) (|U\rangle_{A_1B_1}|V\rangle_{C_1D_1}) =\frac1d|UV\rangle_{A_1D_1}. -\tag{9} $$ Consequently, +**Equation (10).** + $$ Lv=\frac1d w, \qquad -Mv=\sqrt\mu\,w, +Mv=\sqrt\muw, \qquad \mu=\frac{mn}{d}. -\tag{10} $$ -Let $K=MG_{\mathcal S}^{-1/2}$ be the polar partial isometry, zero on the kernel. It is a contraction, with $K^{\dagger}K=\Pi_{\operatorname{supp}G_{\mathcal S}}$. Since $G^{-1/2}$ preserves $\mathcal S$, every routed physical branch satisfies +Let $K=MG_{\mathcal S}^{-1/2}$ be the polar partial isometry, zero on the kernel. It is a contraction, with $K^{\dagger}K=\Pi_{\mathrm{supp}G_{\mathcal S}}$. Since $G^{-1/2}$ preserves $\mathcal S$, every routed physical branch satisfies + +**Equation (11).** $$ J_{rs}v=\frac1{\sqrt{mn}}Kv. -\tag{11} $$ Summing the $mn$ branches therefore produces the unnormalized pure state $Kv\langle v|K^{\dagger}$. In particular, the useful contribution to global fidelity is exactly +**Equation (12).** + $$ f_{\mathrm{pol}}=|\langle w|Kv\rangle|^2 =\frac{\langle v|\sqrt G|v\rangle^2}{\mu}. -\tag{12} $$ Equation (12) uses $w=Mv/\sqrt\mu$ and (8). It is an identity for the actual instrument, not an assumption that coherent port labels or physical bosonic modes are available. @@ -175,14 +187,17 @@ Equation (12) uses $w=Mv/\sqrt\mu$ and (8). It is an identity for the actual ins Every inner half of a unitary Choi state is maximally mixed. Since the supplied specimens are independent copies, the joint inner marginal of $v$ is $I/d^{m+n}$. Thus, for any spectral function $h$ of the inner operator $G$, +**Equation (13).** + $$ \langle v|h(G)|v\rangle -=\frac{\operatorname{Tr}_{\mathrm{inner}}h(G)}{d^{m+n}}. -\tag{13} +=\frac{\mathrm{Tr}_{\mathrm{inner}}h(G)}{d^{m+n}}. $$ The distribution is independent of $U,V$. Put $Q_{rs}=dE_{rs}$ and write $\mathbb E$ for this normalized trace. Then +**Equation (14).** + $$ \mathbb E Q_{rs}=\frac1d, \qquad @@ -190,40 +205,43 @@ $$ \qquad \mathbb E(Q_{rs}Q_{tu})=\frac1{d^2} \quad\text{if }(r,s)\ne(t,u). -\tag{14} $$ For disjoint pairs the last identity factors. For pairs sharing one register, take the partial trace over the two unshared registers: each Bell projector has reduced operator $I/d$, giving the same normalized trace. This calculation does not replace the noncommuting projectors by independent classical variables. There are $mn$ diagonal terms and $(mn)^2-mn$ ordered off-diagonal terms in $G^2$. Therefore +**Equation (15).** + $$ \begin{aligned} \mathbb E G&=\frac{mn}{d}=\mu,\\ \mathbb E G^2&=mn+\frac{m^2n^2-mn}{d^2},\\ -\operatorname{Var}G&=mn(1-d^{-2}). +\mathrm{Var}G&=mn(1-d^{-2}). \end{aligned} -\tag{15} $$ For $X=G/\mu$, these identities become +**Equation (16).** + $$ \mathbb E X=1, \qquad \mathbb E X^2=1+r, \qquad r=\frac{d^2-1}{mn}. -\tag{16} $$ ## 4. Fidelity and success probability By Hölder's inequality with exponents $3/2$ and $3$, +**Equation (17).** + $$ 1=\mathbb E X -=\mathbb E\!\left[(\sqrt X)^{2/3}(X^2)^{1/3}\right] +=\mathbb E\left[(\sqrt X)^{2/3}(X^2)^{1/3}\right] \leq (\mathbb E\sqrt X)^{2/3}(\mathbb E X^2)^{1/3}. $$ @@ -232,30 +250,31 @@ It follows that $$ f_{\mathrm{pol}}=(\mathbb E\sqrt X)^2 \geq\frac1{1+r}=\frac{mn}{mn+d^2-1}. -\tag{17} $$ The failure term in (6) adds a nonnegative target overlap, so $F_{\mathrm{global}}\geq f_{\mathrm{pol}}$. The second inequality in (1) is the elementary relation $1/(1+r)\geq1-r$. This proves the theorem, including budgets for which the simpler $1-r$ bound is negative. The success probability of the incomplete instrument is +**Equation (18).** + $$ -p=\langle v|\Pi_{\operatorname{supp}G}|v\rangle -=\frac{\operatorname{rank}G}{d^{m+n}} +p=\langle v|\Pi_{\mathrm{supp}G}|v\rangle +=\frac{\mathrm{rank}G}{d^{m+n}} \geq\frac{(\mathbb E G)^2}{\mathbb E G^2} =\frac1{1+r}. -\tag{18} $$ -The inequality follows from Cauchy–Schwarz applied to $G\,1_{G>0}$. Conditional on success, the normalized output is $Kv/\sqrt p$ and has global fidelity $f_{\mathrm{pol}}/p$. In general it is only approximately $w$. Equations (17) and (18) must not be interpreted as exact composition on every successful branch. +The inequality follows from Cauchy–Schwarz applied to $G1_{G>0}$. Conditional on success, the normalized output is $Kv/\sqrt p$ and has global fidelity $f_{\mathrm{pol}}/p$. In general it is only approximately $w$. Equations (17) and (18) must not be interpreted as exact composition on every successful branch. ## 5. Copy budgets and the precision boundary For $0<\epsilon<1$, the exact channel achieves global infidelity at most $\epsilon$ whenever +**Equation (19).** + $$ mn\geq\frac{(1-\epsilon)(d^2-1)}{\epsilon}. -\tag{19} $$ The convenient sufficient condition $mn\geq(d^2-1)/\epsilon$ follows from the simpler form of (1). Balanced supplies therefore use $O(d/\sqrt\epsilon)$ copies of each source. At any fixed error, $O(d)$ copies per source suffice. With $m=1$, the sufficient budget for the other source is $n=O(d^2/\epsilon)$. diff --git a/science/converse.md b/science/converse.md index 8021c52..3da05d3 100644 --- a/science/converse.md +++ b/science/converse.md @@ -14,6 +14,8 @@ product is the identity. For a unitary $U\in\mathrm U(d)$, use the normalized Choi convention +**Equation (1).** + $$ |U\rangle=\frac{1}{\sqrt d}\sum_{i,j=1}^d U_{ij}|i\rangle|j\rangle, \qquad \psi_U=|U\rangle\langle U|. @@ -32,7 +34,6 @@ For $d\geq2$ and $F_0\geq d^{-2}$, $$ \boxed{mn\geq\frac{p_0}{2}\bigl(d^2F_0-1\bigr).} -\tag{1} $$ The copy budgets are worst-case bounds, including all branches of an adaptive @@ -51,16 +52,17 @@ increase the fidelity with the corresponding pure target. Define two density operators, using normalized Haar measure: +**Equation (2).** + $$ \begin{aligned} \Omega_{\mathrm c} - &=\mathbb E_U\, + &=\mathbb E_U \psi_U^{\otimes m}\otimes\psi_{\overline U}^{\otimes n},\\ \Omega_{\mathrm i} - &=\mathbb E_{U,W}\, + &=\mathbb E_{U,W} \psi_U^{\otimes m}\otimes\psi_{\overline W}^{\otimes n}. \end{aligned} -\tag{2} $$ Here $U,W$ are independent in the second line. Complex conjugation in this @@ -71,11 +73,12 @@ $|\overline U\rangle$. **Moment comparison.** For every $d\geq2$ and $m,n\geq1$, +**Equation (3).** + $$ -\operatorname{TD}(\Omega_{\mathrm c},\Omega_{\mathrm i}) -:=\frac12\|\Omega_{\mathrm c}-\Omega_{\mathrm i}\|_1 -\leq\min\left\{1,\frac{2mn}{d^2}\right\}. -\tag{3} +\mathrm{TD}(\Omega_{\mathrm c},\Omega_{\mathrm i}) +:=\frac12\Vert\Omega_{\mathrm c}-\Omega_{\mathrm i}\Vert_1 +\leq\min\lbrace1,\frac{2mn}{d^2}\rbrace. $$ The proof of (3) uses the mixed-tensor commutant and its traceless subspace. @@ -90,6 +93,8 @@ below is an application of those established representation facts. Regroup the first halves of all Choi copies into $K_A$ and their second halves into $K_B$, where +**Equation (4).** + $$ K=(\mathbb C^d)^{\otimes m}\otimes (\overline{\mathbb C^d})^{\otimes n}, @@ -104,26 +109,27 @@ $$ R(U)=U^{\otimes m}\otimes\overline U^{\otimes n}, \qquad S(U,W)=U^{\otimes m}\otimes\overline W^{\otimes n}. -\tag{4} $$ For each pair consisting of one first-pool factor and one second-pool factor, let $C_{ij}$ contract those factors by the canonical pairing $\langle\Phi_d|\sqrt d$. Define +**Equation (5).** + $$ H=\bigcap_{i=1}^m\bigcap_{j=1}^n\ker C_{ij}, \qquad P=\Pi_H, \qquad q=1-\frac{\dim H}{D}. -\tag{5} $$ Every contraction has rank $d^{m+n-2}$. The codimension of an intersection is at most the sum of the codimensions, so +**Equation (6).** + $$ q\leq\frac{mn}{d^2}. -\tag{6} $$ The projection $P$ is real in the standard basis. It commutes with $R(U)$ @@ -149,12 +155,13 @@ when the correlated Choi moment is projected onto $H$ on both halves. To identify the multiplicities on $H$, first apply ordinary Schur–Weyl duality separately to the two pools: +**Equation (7).** + $$ K=\bigoplus_a V_a\otimes M_a, \qquad V_a=V_\lambda\otimes\overline{V_\nu}, \qquad M_a=M_\lambda\otimes M_\nu. -\tag{7} $$ The index $a=(\lambda,\nu)$ ranges over partitions of $m,n$ with at most d @@ -166,11 +173,12 @@ $v_a=\dim V_a$ and $f_a=\dim M_a$. Because $P$ commutes with the within-pool permutation algebra, its range has the form +**Equation (8).** + $$ H=\bigoplus_a W_a\otimes M_a, \qquad W_a\subseteq V_a, \qquad 0\leq w_a:=\dim W_a\leq v_a. -\tag{8} $$ The compressed commutant $P\mathcal B P$ is exactly the represented @@ -195,6 +203,8 @@ unitary representation has decomposition $\bigoplus_a V_a\otimes M_a$ with inequivalent irreducible $V_a$, its maximally entangled vector decomposes as +**Equation (9).** + $$ |\Phi_D\rangle =\bigoplus_a\sqrt{\frac{v_af_a}{D}} @@ -209,7 +219,6 @@ $$ \bigoplus_a\frac{f_a}{D v_a} I_{V_a,A}\otimes I_{\overline{V_a},B} \otimes|\Phi_{M_a}\rangle\langle\Phi_{M_a}|. -\tag{9} $$ Paired conjugate bases are used on the two Choi halves. Applying (9) to the @@ -224,12 +233,13 @@ factors restricted to $W_a$, while retaining the denominator $v_a$. For the correlated moment, centrality and the irreducibility established above give +**Equation (10).** + $$ A:=\Pi\Omega_{\mathrm c}\Pi =\bigoplus_{a:w_a>0}\frac{f_a}{D w_a} I_{W_a,A}\otimes I_{\overline{W_a},B} \otimes|\Phi_{M_a}\rangle\langle\Phi_{M_a}|. -\tag{10} $$ The correlated moment also commutes with $\Pi$, because $H$ and $H^\perp$ @@ -237,34 +247,37 @@ contain disjoint correlated-group irreducible representations. The two compressed moments have the same positive blocks and $w_a\leq v_a$. Consequently, +**Equation (11).** + $$ A\succeq B, \qquad -\operatorname{tr}A=\frac1D\sum_a f_aw_a=1-q. -\tag{11} +\mathrm{tr}A=\frac1D\sum_a f_aw_a=1-q. $$ Moreover, using $w^2/v\geq2w-v$, +**Equation (12).** + $$ -\operatorname{tr}B +\mathrm{tr}B =\frac1D\sum_a\frac{f_aw_a^2}{v_a} \geq1-2q. -\tag{12} $$ -Let $\delta=\operatorname{tr}(A-B)$. Equations (11)–(12) give +Let $\delta=\mathrm{tr}(A-B)$. Equations (11)–(12) give $0\leq\delta\leq q$. Block diagonality implies that $\Omega_{\mathrm c}-A$ and $\Omega_{\mathrm i}-B$ are positive, with traces $q$ and $q+\delta$. The triangle inequality therefore gives +**Equation (13).** + $$ \begin{aligned} -\frac12\|\Omega_{\mathrm c}-\Omega_{\mathrm i}\|_1 +\frac12\Vert\Omega_{\mathrm c}-\Omega_{\mathrm i}\Vert_1 &\leq\frac12\bigl(\delta+q+(q+\delta)\bigr)\\ &=q+\delta\leq2q\leq\frac{2mn}{d^2}. \end{aligned} -\tag{13} $$ Together with the universal trace-distance bound of one, this proves (3). @@ -276,9 +289,10 @@ purported composer, after any unwanted output registers have been traced out. Introduce independent known Haar unitaries $A,B,C$ and transform every input copy according to +**Equation (14).** + $$ (U,V)\longmapsto(AUB^\dagger,\ BVC^\dagger). -\tag{14} $$ These transformations are the known gates $A\otimes\overline B$ on the @@ -301,10 +315,11 @@ are the span of $|\Phi_d\rangle$ and its orthogonal complement, corresponding to scalar and traceless matrices. Covariance consequently gives the successful normalized output +**Equation (15).** + $$ \rho_{U,V} =F\psi_{UV}+\frac{1-F}{d^2-1}(I-\psi_{UV}). -\tag{15} $$ Now compare two priors on the original input programs: @@ -324,11 +339,12 @@ $\mathbb E_{U,V}\psi_{UV}=I/d^2$, so its probability is $p/d^2$. Contractivity of trace distance under the entire instrument and final test gives +**Equation (16).** + $$ p\left(F-\frac1{d^2}\right) -\leq\operatorname{TD}(\Omega_{\mathrm c},\Omega_{\mathrm i}) +\leq\mathrm{TD}(\Omega_{\mathrm c},\Omega_{\mathrm i}) \leq\frac{2mn}{d^2}. -\tag{16} $$ Substituting $p\geq p_0$ and $F\geq F_0\geq d^{-2}$ proves (1). @@ -340,6 +356,8 @@ pair $U,V$, the two transformed unitaries in (14) are independent Haar unitaries. If the original instrument has Haar-average success probability $\bar p$ and Haar-average unnormalized target overlap +**Equation (17).** + $$ \bar s=\mathbb E_{U,V} \langle UV|\Lambda_{\mathrm s} @@ -351,7 +369,6 @@ Thus (16) also implies $$ \bar s-\frac{\bar p}{d^2}\leq\frac{2mn}{d^2}. -\tag{17} $$ In particular, deterministic Haar-average fidelity is covered. For heralded @@ -378,7 +395,7 @@ $d=2,(m,n)=(1,3)$ and $(2,2)$, where $m+n>d$. In the one-copy case it also checks the analytic calibration $$ -\operatorname{TD}(\Omega_{\mathrm c},\Omega_{\mathrm i}) +\mathrm{TD}(\Omega_{\mathrm c},\Omega_{\mathrm i}) =\frac{2(d^2-1)}{d^4}\qquad(m=n=1). $$ diff --git a/science/implementation.md b/science/implementation.md index 4edada0..daa2c64 100644 --- a/science/implementation.md +++ b/science/implementation.md @@ -4,8 +4,10 @@ The [collective construction](construction.md) defines a processor by the polar At global infidelity $\epsilon$, the circuit achieves the target using a copy-budget product $mn=O(d^2/\epsilon)$, chosen with the sufficient constant in (7), and uses +**Equation (1).** + $$ -\widetilde O\!\left( +\widetilde O\left( d(m^2+n^2)(\log d+\log(m+n)) \right) $$ @@ -27,8 +29,8 @@ $$ Each Choi program has a row register and a column register. All copies occupy distinct, ordered physical registers. Define $P$ to be the orthogonal projector onto $$ -\mathcal S=\operatorname{Sym}^{m}(\mathbb C^{d^2}) -\otimes\operatorname{Sym}^{n}(\mathbb C^{d^2}). +\mathcal S=\mathrm{Sym}^{m}(\mathbb C^{d^2}) +\otimes\mathrm{Sym}^{n}(\mathbb C^{d^2}). $$ The permutations defining $P$ exchange **whole two-register programs**. In particular, $P|v\rangle=|v\rangle$ for every pair $U,V$. No occupation-number encoding or bosonic hardware is assumed. @@ -45,16 +47,17 @@ $$ A=BP=JQP. $$ -Before applying $J$, the triple $(Q,I,P)$ is a projected unitary encoding: the encoded operator is $QP$, between the right subspace $\mathcal S$ and the left subspace $\operatorname{range}Q$. Both projectors are known from $d,m,n$. +Before applying $J$, the triple $(Q,I,P)$ is a projected unitary encoding: the encoded operator is $QP$, between the right subspace $\mathcal S$ and the left subspace $\mathrm{range}Q$. Both projectors are known from $d,m,n$. The Bell contraction gives the exact physical normalization $$ A|v\rangle=\frac1d|w\rangle. -\tag{1} $$ -For comparison with the [polar construction](construction.md), set $M=\sqrt{dmn}\,A$ on $\mathcal S$. Thus +For comparison with the [polar construction](construction.md), set $M=\sqrt{dmn}A$ on $\mathcal S$. Thus + +**Equation (2).** $$ M|v\rangle=\sqrt{\frac{mn}{d}}|w\rangle. @@ -78,19 +81,20 @@ G=d\sum_{r,s}E_{rs}, M^\dagger M=G_{\mathcal S}, \qquad A^\dagger A=\frac{G_{\mathcal S}}{dmn}. -\tag{2} $$ -Equation (2) also proves $\|A\|\leq1$ and $\|M\|\leq\sqrt{dmn}$. The relevant singular spectrum is that of the **restricted block** $QP$. The unrestricted Bell projector has only zero and unit singular values and cannot by itself implement this polar transformation. +Equation (2) also proves $\VertA\Vert\leq1$ and $\VertM\Vert\leq\sqrt{dmn}$. The relevant singular spectrum is that of the **restricted block** $QP$. The unrestricted Bell projector has only zero and unit singular values and cannot by itself implement this polar transformation. ## 2. Approximating the polar map on the supplied states The [moment calculation](construction.md) gives, for the spectral distribution of $G$ in $|v\rangle$, +**Equation (3).** + $$ \mu=\mathbb E G=\frac{mn}{d}, \qquad -\operatorname{Var}(G)=mn(1-d^{-2}). +\mathrm{Var}(G)=mn(1-d^{-2}). $$ Define @@ -105,13 +109,14 @@ The exact polar Kraus operator is $K=MG_{\mathcal S}^{-1/2}$, with the inverse z $$ \langle w|K|v\rangle=\mathbb E\sqrt X\geq1-\frac r2. -\tag{3} $$ For example, the scalar inequality $\sqrt{x}\geq(3x-x^2)/2$ for $x\geq0$ proves (3) using only the first two moments. A circuit need not approximate the polar map uniformly on arbitrarily small nonzero singular values. Fix $0<\eta<1/2$. The bounded odd sign-approximation polynomial of Gilyén, Su, Low and Wiebe [1, Lemma 25] can be chosen so that +**Equation (4).** + $$ |f(s)|\leq1\quad(-1\leq s\leq1), \qquad @@ -124,8 +129,7 @@ After removing the Bell ket, the successful Kraus operator is $Jf^{\mathrm{SV}}( $$ a_f=\langle w|Jf^{\mathrm{SV}}(QP)|v\rangle - =\mathbb E\left[\sqrt X\,f\!\left(\frac{\sqrt X}{d}\right)\right]. -\tag{4} + =\mathbb E\left[\sqrt Xf\left(\frac{\sqrt X}{d}\right)\right]. $$ To verify (4), use an SVD $A=L\Sigma R^\dagger$: the identity $|w\rangle=dA|v\rangle$ assigns a factor $d\sigma=\sqrt X$ to the left singular component. An odd polynomial has $f(0)=0$, so zero singular values cause no extra term. @@ -134,17 +138,18 @@ To verify (4), use an SVD $A=L\Sigma R^\dagger$: the identity $|w\rangle=dA|v\ra The polynomial approximation applies whenever $X\geq1/4$. Chebyshev's inequality and $\sqrt X\leq1/2$ on the complementary event give +**Equation (5).** + $$ \Pr[X<1/4]\leq\frac{16r}{9}, \qquad -\mathbb E[\sqrt X\,\mathbf1_{X<1/4}]\leq\frac{8r}{9}. +\mathbb E[\sqrt X\mathbf1_{X<1/4}]\leq\frac{8r}{9}. $$ On the large-singular-value event, the amplitude loss relative to (3) is at most $\eta\mathbb E\sqrt X\leq\eta$. On the complementary event, $|f|\leq1$ bounds that loss by twice its weighted mass. Thus $$ a_f\geq1-\frac{41r}{18}-\eta. -\tag{5} $$ No minimum-nonzero-singular-value promise was used. The cutoff is justified by the spectral weight of the actual program inputs. @@ -155,23 +160,25 @@ The QSVT circuit has an explicit success flag: the control qubit is projected ba Suppose the implemented circuit differs from the ideal QSVT unitary by at most $\nu$ in operator norm. Projection and removal of the Bell ket cannot increase that error. Equations (4) and (5) therefore give +**Equation (6).** + $$ F_{\mathrm{global}} \geq1-\frac{41}{9}r-2\eta-2\nu, -\tag{6} $$ whenever $41r/18+\eta+\nu\leq1$. Here fidelity means the pure-target overlap, as throughout the repository. A concrete sufficient allocation for any $0<\epsilon<1$ is +**Equation (7).** + $$ mn\geq\frac{41(d^2-1)}{3\epsilon}, \qquad \eta\leq\frac\epsilon6, \qquad \nu\leq\frac\epsilon6. -\tag{7} $$ Then (6) is at least $1-\epsilon$. The constants in (7) describe this cutoff implementation; the exact polar channel satisfies the stronger bound $1/(1+r)\geq1-r$ proved in the construction. Neither statement establishes optimal dependence on $\epsilon\to0$. @@ -180,10 +187,12 @@ Then (6) is at least $1-\epsilon$. The constants in (7) describe this cutoff imp It remains to implement the phases required by QSVT without invoking an unknown-state reflection. For a pool of $k$ whole programs, use a Fisher–Yates encoding of permutations. At step $t=2,\ldots,k$, a register $j_t$ ranges uniformly over $0,\ldots,t-1$, and the selected transposition exchanges positions $t-1$ and $j_t$. Every permutation occurs once among the $k!$ valid choice strings. -Let $F_k$ prepare the product of these uniform-range states and let $\mathrm{SELECT}_k$ apply the corresponding whole-copy permutations. Padding labels outside the valid ranges may be assigned any known unitary. They have zero initial amplitude. Define +Let $F_k$ prepare the product of these uniform-range states and let the known operator `SELECT_k` apply the corresponding whole-copy permutations. Padding labels outside the valid ranges may be assigned any known unitary. They have zero initial amplitude. Define + +**Equation (8).** $$ -V_k=(F_k^\dagger\otimes I)\,\mathrm{SELECT}_k\,(F_k\otimes I). +V_k=(F_k^\dagger\otimes I)\mathrm{SELECT}_k(F_k\otimes I). $$ Its clean-ancilla block is exactly the symmetry projector: @@ -192,15 +201,15 @@ $$ (\langle0|\otimes I)V_k(|0\rangle\otimes I) =\frac1{k!}\sum_{\pi\in S_k}U_\pi =P_k. -\tag{8} $$ For the two pools take $V=V_m\otimes V_n$ and let $\Pi_0$ project all permutation ancillas onto zero. Equation (8) gives +**Equation (9).** + $$ (\langle0|\otimes I)V^\dagger(2\Pi_0-I)V(|0\rangle\otimes I) =2P-I. -\tag{9} $$ The right-hand side is unitary. Since the full operator on the left is also unitary, there can be no norm left in nonzero ancilla states for any clean-ancilla input. Thus (9) is an exact deterministic symmetry reflection with clean ancilla return. @@ -211,7 +220,7 @@ $$ V^\dagger e^{i\phi(2\Pi_0-I)}V $$ -implements $e^{i\phi(2P-I)}$ on clean ancillas. This follows by expanding the exponential into $\cos\phi\,I+i\sin\phi(2\Pi_0-I)$ and using (9). Adding the single QSVT control qubit changes the gate count by a constant factor. The Bell-subspace phases are implemented by preparing and unpreparing the known $|\Phi_d\rangle$ and phasing the all-zero state. +implements $e^{i\phi(2P-I)}$ on clean ancillas. This follows by expanding the exponential into $\cos\phiI+i\sin\phi(2\Pi_0-I)$ and using (9). Adding the single QSVT control qubit changes the gate count by a constant factor. The Bell-subspace phases are implemented by preparing and unpreparing the known $|\Phi_d\rangle$ and phasing the all-zero state. ## 5. Charged circuit resources @@ -238,7 +247,7 @@ The resulting resources are: | QSVT degree | $O(d\log(1/\epsilon))$ | | Complete circuit | $\widetilde O(d(m^2+n^2)(\log d+\log(m+n)))$ gates | -All gate descriptions depend only on $d,m,n,\epsilon$. The polynomial and QSVT phases can be computed classically using the constructive results of [1]; this known preprocessing is separate from the quantum gate count. For a fixed finite inverse-closed universal gate set, approximate each of the $L$ known elementary gates to operator error at most $\nu/L$. A telescoping bound gives total unitary error at most $\nu$. Standard constructive gate synthesis adds a polylogarithmic factor in $L/\nu$ [2], included in the displayed soft-$O$ bounds. +All gate descriptions depend only on $d,m,n,\epsilon$. The polynomial and QSVT phases can be computed classically using the constructive results of [1]; this known preprocessing is separate from the quantum gate count. For a fixed finite inverse-closed universal gate set, approximate each of the $L$ known elementary gates to operator error at most $\nu/L$. A telescoping bound gives total unitary error at most $\nu$. Standard constructive gate synthesis adds a polylogarithmic factor in $L/\nu$ [2], included in the displayed soft-O bounds. With $m=n=O(d/\sqrt\epsilon)$ chosen large enough for (7), the circuit uses $\widetilde O(d^3/\epsilon)$ gates and $O((d/\sqrt\epsilon)\log(d/\epsilon))$ qubits. This is polynomial in the dimension and supplied-copy counts. It is not a claim of a gate complexity polynomial in $\log d$. diff --git a/science/model.md b/science/model.md index cf067b7..cf7ada4 100644 --- a/science/model.md +++ b/science/model.md @@ -8,6 +8,8 @@ This page fixes the model and exact theorem statements. The [construction](const Let $d\geq2$ and let $U,V\in U(d)$ be arbitrary fixed unitaries. In a fixed computational basis, define the normalized Choi vector +**Equation (1).** + $$ |U\rangle=(U\otimes I)|\Phi_d\rangle =\frac1{\sqrt d}\sum_{i,j=0}^{d-1}U_{ij}|i\rangle|j\rangle, @@ -37,16 +39,16 @@ $$ F_{\mathrm{global}}\geq \frac{mn}{mn+d^2-1} \geq1-\frac{d^2-1}{mn}. -\tag{1} $$ This is an unconditional output guarantee. An intermediate measurement has a successful branch, but the final map also assigns an output on failure. The successful state is generally approximate. The mathematical map is the polar normalization of a known contraction; the [finite circuit](implementation.md) attains the same copy scaling with explicit larger constants and gate-synthesis error. For $0<\epsilon<1$, the exact channel satisfies $F_{\mathrm{global}}\geq1-\epsilon$ whenever +**Equation (2).** + $$ mn\geq\frac{1-\epsilon}{\epsilon}(d^2-1). -\tag{2} $$ Equation (2) is a sufficient allocation, not an optimal dependence on a vanishing error parameter. In particular, balanced pools of $O(d/\sqrt\epsilon)$ copies suffice for this construction. @@ -55,9 +57,10 @@ Equation (2) is a sufficient allocation, not an optimal dependence on a vanishin Let a quantum instrument use at most $m$ and $n$ copies of the two programs. Suppose that for every fixed $U,V$ it declares success with probability at least $p_0>0$, and its normalized successful output has fidelity at least $F_0\geq d^{-2}$ with $|UV\rangle$. Then +**Equation (3).** + $$ mn\geq\frac{p_0}{2}(d^2F_0-1). -\tag{3} $$ The source budgets are worst-case bounds. The theorem permits arbitrary collective operations, independent ancillary memory and adaptive measurements. A protocol with bounded sequential access can precollect all its copies and is therefore included. The converse already holds when no leftover programs are requested, so it also bounds the joint-return task. It holds in every dimension and for every allocation, including $m=1$ and $n$ much larger than $d$. @@ -66,9 +69,10 @@ The proof first bounds the distinguishability of two averaged input states, then The same proof gives a precise Haar-average statement. If $\bar p$ is the average success probability and $\bar s$ is the average unnormalized successful overlap for independent Haar $U,V$, then +**Equation (4).** + $$ \bar s-\frac{\bar p}{d^2}\leq\frac{2mn}{d^2}. -\tag{4} $$ For deterministic processing, $\bar p=1$. For heralded processing, $\bar s/\bar p$ is the success-weighted conditional fidelity. An unweighted average of conditional fidelities is a different statistic; see the [converse](converse.md). @@ -77,20 +81,22 @@ For deterministic processing, $\bar p=1$. For heralded processing, $\bar s/\bar Fix an infidelity $\epsilon\in(0,1)$ independently of $d$, and consider deterministic universal processing. Equations (1) and (3) give the necessary and sufficient copy-product scale +**Equation (5).** + $$ mn=\Theta(d^2). -\tag{5} $$ Here “threshold” means that products below a suitable constant multiple of $d^2$ cannot achieve the specified fidelity, while products above another constant multiple suffice. The constants depend on the chosen fidelity. It does not mean that every allocation with product exactly $d^2$ attains every constant accuracy. Let $F^*_{\mathrm{out}}(d,m,n)$ denote the best worst-case fidelity of a deterministic processor for the composed program alone. The proved finite bounds are +**Equation (6).** + $$ \frac{mn}{mn+d^2-1} \leq F^*_{\mathrm{out}}(d,m,n) -\leq\min\left\{1,\frac{2mn+1}{d^2}\right\}. -\tag{6} +\leq\min\lbrace1,\frac{2mn+1}{d^2}\rbrace. $$ They determine the fidelity scale up to constants across copy budgets, while leaving the exact optimum and its approach to one unresolved. The lower end of (6) comes from a processor with the additional joint-return guarantee. @@ -108,7 +114,7 @@ Minimizing $m+n$ subject to the product law gives total copy complexity $\Theta( The finite implementation uses known gates with conservative cost $$ -\widetilde O\!\left(d(m^2+n^2)(\log d+\log(m+n))\right), +\widetilde O\left(d(m^2+n^2)(\log d+\log(m+n))\right), $$ where omitted factors are logarithmic in the dimensions, budgets and inverse accuracy. With balanced supplies and fixed error this is $\widetilde O(d^3)$ gates, in addition to the supplied program states. The result establishes copy efficiency, without a claimed total-runtime improvement. The dimension $d$ is the Hilbert-space dimension; for a $q$-qubit operation it equals $2^q$. diff --git a/verification/README.md b/verification/README.md index 0c2f835..ab7437f 100644 --- a/verification/README.md +++ b/verification/README.md @@ -59,3 +59,9 @@ The test distinguishes the restricted Bell block from the unrestricted binary-sp ## What these checks do not establish Finite floating-point calculations do not prove the asymptotic lower bound, certify novelty, or establish optimal small-error dependence. The circuit test does not synthesize an entire QSVT phase sequence or simulate fault-tolerant gates. Polynomial approximation, phase construction and gate synthesis use the cited primary theorems. The public proof explains their hypotheses and how the program inputs meet them. + +## Hosted mathematical display + +The separate [hosted review](hosted/README.md) visits commit-pinned GitHub pages in a fresh browser, compares the rendered mathematics with the tracked source, and saves wide and narrow screenshots. Its read-only workflow uses public pages and temporary dependencies. The report records the exact revision, page scope and expression counts, including inline formulas and table cells. + +This display check requires network access. It supplements the finite scientific checks above: matching MathML structure does not establish a proof, and screenshots still need inspection for legibility and navigation. The hosted guide documents the command, dependency versions and report files. diff --git a/verification/hosted/README.md b/verification/hosted/README.md new file mode 100644 index 0000000..525e3fc --- /dev/null +++ b/verification/hosted/README.md @@ -0,0 +1,54 @@ +# Hosted mathematics verification + +The [hosted review workflow](../../.github/workflows/hosted-review.yml) compares the mathematics in every tracked Markdown page with the actual, commit-pinned GitHub rendering at widths of 1440 and 760 pixels. It saves source inventories, rendered MathML comparisons, page HTML, screenshots and a bound `hosted-report.json`. + +The [text contract](math-contract.json) adds exact accessible-text checks for the README's headline threshold and two finite guarantees, tied to their source-expression hashes. These source-derived expectations supplement the structural checks for every formula; they are not captured host evidence and introduce no renderer exceptions. + +The browser uses a fresh anonymous context and normal certificate verification. Dependencies, browser binaries and capture output live in the runner's temporary directory, outside the source checkout. The job grants `contents: read`, disables checkout credential persistence, uses no repository secrets and does not modify the repository. Failed comparisons fail the job; the artifact step also preserves available evidence from failed captures. + +## Revisions and evidence + +The workflow runs when a pull request targeting `main` opens or its head changes. Runs for the same head SHA share a concurrency group, which cancels overlapping attempts. The checkout and capture both use `github.event.pull_request.head.sha`. GitHub documents that a pull-request event's default SHA represents its merge branch, which is why the explicit head SHA is necessary here: [workflow event reference](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#pull_request). + +There is no page filter: the collector inventories every tracked `.md`, `.markdown`, `.mdown`, `.mkdn` and `.mkd` file, case insensitively, from that exact Git commit. The output directory must be empty at the start of each capture. The workflow bounds dependency installation to eight minutes, capture to fifteen minutes and the complete job to twenty-five minutes. + +The report records both its observed commit and Git tree. A pull-request report can describe the integrated content only when the complete checked tree equals the observed merged tree and the actual merge relationship is recorded. A different tree requires a new capture. Do not substitute a moving branch URL or a synthetic pull-request merge SHA for the recorded source pin. + +Download the complete artifact directory before its retention period expires. Preserve `hosted-report.json` together with its referenced files and verify their recorded hashes. The artifact archive digest and the report file's SHA-256 are different identifiers. Inspect the screenshots separately: an automated structure pass does not establish visual correctness, mathematical correctness, originality or future rendering behavior. + +## Verifier provenance + +The two utilities are unchanged copies of the canonical hosted-math verifier, version **0.10.0**. Their recorded SHA-256 values are: + +```text +49182eaf354e86f685a4976814d672de5d7329a2d9e42f62a5227e2bc07c2d18 capture_hosted_math.cjs +edbc2d72af94e96b78166d74b66fcea150134f2f3ebaaea121e9057768e1dbfe check_rendered_math.py +``` + +The collector's only adjacent runtime dependency is `check_rendered_math.py`, which uses the Python standard library. Its external runtime dependencies are Node.js, Git, Python, Playwright **1.56.1** and MathJax **3.2.1**. This provenance record adds no license terms and does not change the repository's existing license. + +The workflow pins each official action to the full commit identified by its release: + +| Action | Verified release | +| --- | --- | +| `actions/checkout` | [v6.0.2](https://github.com/actions/checkout/releases/tag/v6.0.2) | +| `actions/setup-node` | [v6.5.0](https://github.com/actions/setup-node/releases/tag/v6.5.0) | +| `actions/setup-python` | [v6.3.0](https://github.com/actions/setup-python/releases/tag/v6.3.0) | +| `actions/upload-artifact` | [v7.0.2](https://github.com/actions/upload-artifact/releases/tag/v7.0.2) | + +Chromium and its operating-system dependencies are installed with Playwright's documented [`install --with-deps chromium` CI command](https://playwright.dev/docs/ci). + +## Local invocation + +Use an approved environment with Node.js 18 or newer, Python 3.10 or newer, Git and the pinned dependencies above. Set `NODE_PATH` to the temporary dependency directory's `node_modules`, and set `PLAYWRIGHT_BROWSERS_PATH` to the corresponding temporary browser cache. Run: + +```bash +node verification/hosted/capture_hosted_math.cjs \ + --root /absolute/path/to/checkout \ + --repository owner/name \ + --revision FULL_40_CHARACTER_COMMIT \ + --contract verification/hosted/math-contract.json \ + --output /absolute/path/to/new-empty-evidence-directory +``` + +Exit code 0 means the automated checks passed for the recorded source and page scope. Exit code 1 records failed or blocked verification; exit code 2 indicates invalid invocation or setup. Retain failed evidence and investigate its reported cause before attempting a new capture in a different empty directory. diff --git a/verification/hosted/capture_hosted_math.cjs b/verification/hosted/capture_hosted_math.cjs new file mode 100644 index 0000000..bd075f4 --- /dev/null +++ b/verification/hosted/capture_hosted_math.cjs @@ -0,0 +1,274 @@ +#!/usr/bin/env node +'use strict'; +// Read-only collector for the real GitHub host. See ../references/hosted-rendering.md. +// Importing this module has no network effects; dependencies load only in run(). +const fs = require('node:fs'); +const path = require('node:path'); +const cp = require('node:child_process'); +const crypto = require('node:crypto'); +const VIEWPORTS = [{width:1440,height:1000}, {width:760,height:1000}]; +const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); + +function argumentsFor(argv) { + const args = {pages:[], python:'python3'}; + for (let i=0; i['.','..'].includes(p))) throw new Error('Use exact owner/name'); + if (!/^[a-f0-9]{40}$/.test(args.revision)) throw new Error('Use a full lowercase commit SHA'); + if (new Set(args.pages).size!==args.pages.length || args.pages.some(p=>!safePath(p))) throw new Error('Use unique safe page paths'); + return args; +} +function safePath(p) { + return typeof p==='string' && p.length>0 && !p.includes('\\') && !p.includes('\0') && + !p.startsWith('/') && p.split('/').every(x=>x && x!=='.' && x!=='..'); +} +function git(root, argv) { + return cp.execFileSync('git',['--no-replace-objects',...argv],{cwd:root,encoding:'utf8',maxBuffer:32*1024*1024}); +} +function pinnedPages(args) { + const commit=git(args.root,['rev-parse',args.revision+'^{commit}']).trim(); + if (commit!==args.revision) throw new Error('Revision does not identify the supplied commit'); + const files=git(args.root,['ls-tree','-r','--name-only','-z',commit]).split('\0').filter(Boolean); + const pages=args.pages.length?args.pages:files.filter(p=>/\.(md|markdown|mdown|mkdn|mkd)$/i.test(p)); + if (!pages.length || pages.some(p=>!safePath(p) || !files.includes(p))) throw new Error('No pages or a page is absent from the pinned tree'); + // Git symlinks are not rendered Markdown source and must not be followed. + for (const p of pages) { + const item=git(args.root,['ls-tree',commit,'--',p]); + if (!/^100644 blob |^100755 blob /.test(item)) throw new Error('Page must be a regular tracked file: '+p); + } + return {pages,tree:git(args.root,['rev-parse',commit+'^{tree}']).trim()}; +} +function mathCompiler() { + const {mathjax}=require('mathjax-full/js/mathjax.js'); + const {TeX}=require('mathjax-full/js/input/tex.js'); + const {SVG}=require('mathjax-full/js/output/svg.js'); + const {liteAdaptor}=require('mathjax-full/js/adaptors/liteAdaptor.js'); + const {RegisterHTMLHandler}=require('mathjax-full/js/handlers/html.js'); + const {AllPackages}=require('mathjax-full/js/input/tex/AllPackages.js'); + const {SerializedMmlVisitor}=require('mathjax-full/js/core/MmlTree/SerializedMmlVisitor.js'); + const {STATE}=require('mathjax-full/js/core/MathItem.js'); + RegisterHTMLHandler(liteAdaptor()); + const doc=mathjax.document('',{InputJax:new TeX({packages:AllPackages,tags:'none'}),OutputJax:new SVG({fontCache:'none'})}); + const visitor=new SerializedMmlVisitor(); + return (tex,display)=>visitor.visitTree(doc.convert(tex,{display,end:STATE.CONVERT})); +} + +// Self-contained function executed inside the hosted page, also exercised by the +// local-browser regression fixture. It never injects styling or renders TeX there. +function inspectArticle(root, expected) { + function canonical(e, inherited='') { + const tag=e.localName; + if (['annotation','annotation-xml','mspace'].includes(tag)) return []; + const variant=e.getAttribute('mathvariant') || inherited; + if (['mi','mo','mn','mtext','ms'].includes(tag)) { + const text=e.textContent.trim(); + return text?[[tag,text,variant]]:[]; + } + // Preserve each structural child slot: flattening numerator and denominator + // together would confuse (a+b)/c with a/(b+c), and similarly for scripts. + const children=[...e.children].filter(c=>!['annotation','annotation-xml','mspace'].includes(c.localName)) + .map(c=>canonical(c,variant)); + if (['math','mrow','mstyle','semantics'].includes(tag)) return children.flat(); + const semantic={}; + for (const name of ['notation','accent','accentunder','linethickness','bevelled','open','close','separators']) if(e.hasAttribute(name)) semantic[name]=e.getAttribute(name); + // A table cell is an inferred row (a sequence), not a fixed-arity operator. + // GitHub inserts empty mrow alignment nodes; ignore those inside the cell + // while preserving the cell and row themselves, including empty cells. + return [[tag,semantic,tag==='mtd'?children.flat():children]]; + } + function plain(math) { + const copy=math.cloneNode(true); + for (const e of copy.querySelectorAll('annotation,annotation-xml')) e.remove(); + return copy.textContent; + } + function geometry(math, host) { + const boxes=[...math.querySelectorAll('mi,mo,mn,mtext,ms')].map(e=>e.getBoundingClientRect()).filter(b=>b.width && b.height); + if (!boxes.length) return {measurable:false}; + const left=Math.min(...boxes.map(b=>b.left)),right=Math.max(...boxes.map(b=>b.right)); + const top=Math.min(...boxes.map(b=>b.top)),bottom=Math.max(...boxes.map(b=>b.bottom)); + const width=right-left,height=bottom-top; + return {measurable:true,width,height,available_width:root.clientWidth, + overflow:width>root.clientWidth+4,collapsed:height>Math.max(200,3*width),host_width:host.getBoundingClientRect().width}; + } + let hosts=[...root.querySelectorAll('math-renderer')]; + // Some host versions expose native MathML without a custom-element wrapper. + if (!hosts.length) hosts=[...root.querySelectorAll('math')].filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + const pageErrors=[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')] + .map(e=>e.textContent.trim() || 'empty renderer error'); + const math=hosts.map((host,i)=>{ + const nodes=host.localName==='math'?[host]:[...host.querySelectorAll('math')].filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + const errors=[]; + if(nodes.length!==1) errors.push('Expected one accessible MathML representation; found '+nodes.length); + const actual=nodes[0],want=expected[i]; + let expectedSignature=null,actualSignature=null; + if(actual) actualSignature=JSON.stringify(canonical(actual)); + if(want) { + const parsed=new DOMParser().parseFromString(want.mml,'application/xml'); + if(parsed.querySelector('parsererror,merror')) errors.push('Source compiler returned invalid/error MathML'); + else expectedSignature=JSON.stringify(canonical(parsed.documentElement)); + } + if(!want) errors.push('Unexpected extra hosted expression'); + const match=!!actual && !!expectedSignature && expectedSignature===actualSignature; + if(!match) errors.push('Source-to-host MathML structure mismatch'); + const measure=actual?geometry(actual,host):{measurable:false}; + if(want && ['math-fence','dollar-display'].includes(want.kind) && (!measure.measurable || measure.overflow || measure.collapsed)) + errors.push('Display geometry is unmeasurable, overflowing or collapsed'); + return {rendered:!!actual,errors,text_source:'mathml',text:actual?plain(actual):'', + source_sha256:want?.source_sha256,structural_match:match, + expected_signature:expectedSignature,actual_signature:actualSignature,geometry:measure}; + }); + return {errors:pageErrors,math}; +} + +function classifyFailure(error) { + const message=String(error); + if (/ERR_BLOCKED_BY_ADMINISTRATOR|blocked by.*policy|URLBlocklist|policy denied/i.test(message)) return 'policy_denied'; + if (/HTTP (401|403)|redirected away|sign.in|authentication/i.test(message)) return 'access_required'; + if (/Cannot find module|Executable doesn't exist|browser executable/i.test(message)) return 'capability_unavailable'; + if (/ERR_NAME_NOT_RESOLVED|ENOTFOUND|ERR_CONNECTION|ERR_EMPTY_RESPONSE|ERR_INTERNET_DISCONNECTED|ECONNRESET|Timeout|timed out/i.test(message)) return 'transport_failure'; + return 'verification_failure'; +} +function writeJSON(filename, value) {fs.writeFileSync(filename,JSON.stringify(value,null,2)+'\n');} +function artifact(directory, relative, kind) { + const bytes=fs.readFileSync(path.join(directory,relative)); + return {path:relative,sha256:sha256(bytes),size_bytes:bytes.length,kind}; +} +function boundReport(inventory, tree, viewports, artifacts, failures, at) { + const boundaries=inventory.pages.map(p=>{ + const counts=viewports.map(v=>v.boundaries?.find(b=>b.path===p.path)?.captured_hosts); + return {path:p.path,url:p.url,revision:inventory.revision,source_sha256:p.source_sha256, + source_expressions:p.expressions.length, + captured_hosts:counts.length===VIEWPORTS.length && counts.every(n=>Number.isInteger(n) && n===counts[0])?counts[0]:null}; + }); + const wanted=inventory.pages.reduce((n,p)=>n+p.expressions.length,0); + failures=[...failures]; + if(JSON.stringify(viewports.map(v=>({width:v.width,height:v.height})))!==JSON.stringify(VIEWPORTS)) + failures.push('Missing, duplicate or unexpected viewport coverage'); + for(const viewport of viewports) { + if(JSON.stringify((viewport.boundaries||[]).map(b=>b.path))!==JSON.stringify(inventory.pages.map(p=>p.path))) + failures.push(viewport.width+': page coverage differs from inventory'); + for(const source of inventory.pages) { + const boundary=viewport.boundaries?.find(b=>b.path===source.path); + if(!boundary || boundary.source_sha256!==source.source_sha256 || boundary.revision!==inventory.revision || + boundary.url!==source.url || boundary.source_expressions!==source.expressions.length || boundary.captured_hosts!==source.expressions.length) + failures.push(viewport.width+': incomplete source/host coverage for '+source.path); + } + } + const structural=viewports.length===VIEWPORTS.length && viewports.every(v=>v.structural_matches===wanted); + const pass=!failures.length && structural && viewports.length===VIEWPORTS.length && viewports.every(v=>v.status==='pass'); + return {schema_version:1,kind:'hosted_math',repository:inventory.repository,revision:inventory.revision,tree, + renderer_profile:'github',captured_at:at,capture_method:'playwright-github',status:pass?'pass':'fail', + required_pages:inventory.pages.map(p=>p.path),boundaries,viewports,artifacts,failures, + structural_comparison:{status:structural?'pass':'fail',expressions_checked:structural?wanted:0}, + visual_review_required:true, + limits:'Observed GitHub MathML structure, counts, labels, relations and bounded geometry only. No independent scientific proof, exhaustive pixel review, host authenticity certificate or cross-browser guarantee.'}; +} + +async function run(args) { + const output=path.resolve(args.output); + if(fs.existsSync(output) && fs.readdirSync(output).length) throw new Error('Use an empty output directory; preserve earlier failed evidence'); + fs.mkdirSync(output,{recursive:true}); + const pinned=pinnedPages(args); + const helper=path.join(__dirname,'check_rendered_math.py'); + cp.execFileSync(args.python,[helper,'inventory','--root',args.root,'--repository',args.repository, + '--revision',args.revision,...pinned.pages.flatMap(p=>['--page',p]),'--output',path.join(output,'math-source.json')],{stdio:'pipe'}); + const inventory=JSON.parse(fs.readFileSync(path.join(output,'math-source.json'),'utf8')); + const at=new Date().toISOString(),failures=[],artifacts=[artifact(output,'math-source.json','source_inventory')],viewports=[]; + let browser; + const runtime={node:process.version}; + if(args.contract) { + fs.copyFileSync(path.resolve(args.contract),path.join(output,'math-contract.json')); + artifacts.push(artifact(output,'math-contract.json','text_contract')); + } + try { + const {chromium}=require('playwright'); + runtime.playwright=require('playwright/package.json').version; + runtime.mathjax=require('mathjax-full/package.json').version; + const compile=mathCompiler(); + const expected=Object.fromEntries(inventory.pages.map(p=>[p.path,p.expressions.map(e=>({...e, + mml:compile(e.tex,['math-fence','dollar-display'].includes(e.kind))}))])); + writeJSON(path.join(output,'expected-mathml.json'),expected); + artifacts.push(artifact(output,'expected-mathml.json','expected_mathml')); + browser=await chromium.launch({headless:true}); + runtime.browser=browser.version(); + for(const viewport of VIEWPORTS) { + const context=await browser.newContext({viewport,deviceScaleFactor:1,colorScheme:'light'}); + const capture={schema_version:1,repository:args.repository,revision:args.revision,renderer_profile:'github', + captured_at:at,capture_method:'playwright-github',pages:[]}; + let fatal=false; + try { + for(let index=0;index{ + for(let y=0,steps=0;ysetTimeout(r,50)); + } + window.scrollTo(0,0); + }); + await page.waitForTimeout(1000); + Object.assign(item,await article.evaluate(inspectArticle,expected[source.path])); + const html=prefix+'.html',png=prefix+'.png'; + fs.writeFileSync(path.join(output,html),await page.content()); + await page.screenshot({path:path.join(output,png),fullPage:true,timeout:30000}); + artifacts.push(artifact(output,html,'hosted_html'),artifact(output,png,'screenshot')); + item.artifacts={html,screenshot:png}; + } catch(error) { + item.errors.push(String(error)); + const category=classifyFailure(error); + failures.push(source.path+' at '+viewport.width+': '+category+': '+String(error)); + // Do not seek another route after an access or policy block. + fatal=['policy_denied','access_required','transport_failure'].includes(category); + } finally {capture.pages.push(item);await page.close();} + if(fatal) break; + } + } finally {await context.close();} + const captureFile='math-capture-'+viewport.width+'.json',resultFile='math-result-'+viewport.width+'.json'; + writeJSON(path.join(output,captureFile),capture);artifacts.push(artifact(output,captureFile,'hosted_capture')); + const command=[helper,'check','--inventory',path.join(output,'math-source.json'),'--capture',path.join(output,captureFile), + '--output',path.join(output,resultFile)]; + if(args.contract) command.push('--contract',path.resolve(args.contract)); + const check=cp.spawnSync(args.python,command,{encoding:'utf8'}); + if(check.error || !fs.existsSync(path.join(output,resultFile))) throw new Error('Math checker did not produce a result: '+(check.error||check.stderr)); + const result=JSON.parse(fs.readFileSync(path.join(output,resultFile),'utf8')); + artifacts.push(artifact(output,resultFile,'math_result')); + failures.push(...result.failures.map(f=>viewport.width+': '+f)); + const matches=capture.pages.reduce((n,p)=>n+p.math.filter(m=>m.structural_match && !m.errors.length).length,0); + viewports.push({...viewport,status:result.status,structural_matches:matches,capture_path:captureFile,result_path:resultFile,boundaries:result.boundaries}); + if(fatal) break; + } + } catch(error) {failures.push(classifyFailure(error)+': '+String(error));} + finally {if(browser) await browser.close();} + const report={...boundReport(inventory,pinned.tree,viewports,artifacts,failures,at),runtime}; + writeJSON(path.join(output,'hosted-report.json'),report); + console.log(JSON.stringify({status:report.status,report:path.join(output,'hosted-report.json'),sha256:sha256(fs.readFileSync(path.join(output,'hosted-report.json'))),pages:report.required_pages.length,failures:report.failures.length})); + return report.status==='pass'?0:1; +} +module.exports={argumentsFor,safePath,pinnedPages,mathCompiler,inspectArticle,classifyFailure,artifact,boundReport,VIEWPORTS,run}; +if(require.main===module) { + (async()=>{ + const args=argumentsFor(process.argv.slice(2)); + if(args.help) {console.log('capture_hosted_math.cjs --root REPO --repository owner/name --revision FULLSHA --output EMPTY_DIR [--page PATH ...] [--contract JSON] [--python python3]');return;} + process.exitCode=await run(args); + })().catch(error=>{console.error(String(error));process.exitCode=2;}); +} diff --git a/verification/hosted/check_rendered_math.py b/verification/hosted/check_rendered_math.py new file mode 100644 index 0000000..1d3bf98 --- /dev/null +++ b/verification/hosted/check_rendered_math.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +r"""Check captured mathematical text against pinned GitHub Markdown source. + +Usage (Python 3.10+, standard library only): + check_rendered_math.py inventory --root REPO --repository owner/name \ + --revision FULL_COMMIT --page README.md --page science/results.md \ + --output math-source.json + check_rendered_math.py check --inventory math-source.json \ + --capture math-capture.json [--contract math-contract.json] [--output result.json] + +Inventory reads Git objects at the requested commit, not the working tree. +It recognizes math fences, $`...`$, $$...$$ and single-dollar inline math, +excluding ordinary code fences/spans. This is a bounded Markdown scanner, +not the hosting renderer's parser. Inspect its inventory before capture. + +Capture schema (collect actual full accessible math text in document order): + {"schema_version": 1, "repository": "owner/name", "revision": "40 hex", + "renderer_profile": "github", "captured_at": "ISO-8601 with timezone", + "capture_method": "how the actual hosted DOM was inspected", + "pages": [{"path": "README.md", "url": "exact pinned inventory URL", + "revision": "40 hex", "source_sha256": "inventory source hash", + "errors": [], "math": [{"rendered": true, "errors": [], + "text_source": "mathml", "text": "full text, not a sample"}]}]} +Allowed text_source values: mathml, mathjax-assistive, katex-accessibility, +renderer-accessibility. Extract one accessible representation per host; +exclude TeX annotation nodes and duplicate visual/accessibility copies. +Native MathML is valid. Empty math lists are valid for math-free pages. + +Optional contract strengthens content checks without pretending to translate +arbitrary TeX. Each entry selects a path/index (1-based) and source_sha256 +(the expression hash in inventory), with expected_text and/or required_text: + {"schema_version": 1, "expressions": [{"path": "README.md", "index": 1, + "source_sha256": "expression hash", "required_text": ["d", "(C1)"], + "expected_text": "|A|", "le": "≤", "leq": "≤", "ge": "≥", "geq": "≥", + "ne": "≠", "neq": "≠", "in": "∈", "notin": "∉", "subset": "⊂", + "subseteq": "⊆", "supset": "⊃", "supseteq": "⊇", "approx": "≈", + "simeq": "≃", "equiv": "≡", "propto": "∝", "cong": "≅", "sim": "∼", + "to": "→", "rightarrow": "→", "Rightarrow": "⇒", "implies": "⇒", + "mapsto": "↦", "leftrightarrow": "↔", "Leftrightarrow": "⇔", "iff": "⇔", +} +RELATION_SYMBOLS = set("<>=") | set(RELATIONS.values()) +COMMAND = re.compile(r"\\([A-Za-z]+)") +LABEL = re.compile(r"\\tag(\*)?\{([^{}]+)\}|\\text\{\s*\(([^{}()]+)\)\s*\}") +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})([^\n]*)\n?$") +SHA = re.compile(r"[0-9a-f]{40}") +TEXT_SOURCES = {"mathml", "mathjax-assistive", "katex-accessibility", "renderer-accessibility"} + + +def digest(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def compact(text: str) -> str: + return "".join(c for c in unicodedata.normalize("NFKC", text) + if not c.isspace() and unicodedata.category(c) != "Cf") + + +def escaped(text: str, index: int) -> bool: + backslashes = 0 + while index > 0 and text[index - 1] == "\\": + backslashes += 1 + index -= 1 + return bool(backslashes % 2) + + +def tex_body(text: str) -> str: + """Drop unescaped TeX comments; do not expand user macros.""" + return "\n".join(line[:next((i for i, c in enumerate(line) + if c == "%" and not escaped(line, i)), len(line))] + for line in text.splitlines()) + + +def relations(tex: str) -> dict[str, int]: + expanded = COMMAND.sub(lambda m: RELATIONS.get(m.group(1), m.group(0)), tex_body(tex)) + return dict(sorted(Counter(c for c in expanded if c in RELATION_SYMBOLS).items())) + + +def labels(tex: str) -> list[str]: + return [compact(tag if star else f"({tag or text})") + for star, tag, text in LABEL.findall(tex_body(tex))] + + +def expressions(source: str) -> list[dict]: + """Return ordered source spans; reject unterminated recognized delimiters.""" + found: list[dict] = [] + + def add(tex: str, offset: int, end: int, kind: str) -> None: + found.append({"line_start": source.count("\n", 0, offset) + 1, + "line_end": source.count("\n", 0, end) + 1, + "kind": kind, "tex": tex, "source_sha256": digest(tex), + "relations": relations(tex), "labels": labels(tex)}) + + def prose(start: int, end: int) -> None: + i = start + while i < end: + if source[i] == "$" and not escaped(source, i): + opener, closer, kind = ("$`", "`$", "github-inline") if source.startswith("$`", i) else ( + ("$$", "$$", "dollar-display") if source.startswith("$$", i) + else ("$", "$", "dollar-inline")) + j = source.find(closer, i + len(opener), end) + while j >= 0 and escaped(source, j): + j = source.find(closer, j + len(closer), end) + if j < 0 or (kind == "dollar-inline" and "\n" in source[i:j]): + raise ValueError(f"unclosed {kind} at line {source.count(chr(10), 0, i) + 1}") + add(source[i + len(opener):j], i, j + len(closer) - 1, kind) + i = j + len(closer) + elif source[i] == "`" and not escaped(source, i): + n = 1 + while i + n < end and source[i + n] == "`": + n += 1 + j = source.find("`" * n, i + n, end) + i = j + n if j >= 0 else i + n + else: + i += 1 + + lines = source.splitlines(keepends=True) + offset = start = i = 0 + while i < len(lines): + match = FENCE.match(lines[i]) + if not match: + offset += len(lines[i]) + i += 1 + continue + prose(start, offset) + marker, info = match.groups() + begin = offset + offset += len(lines[i]) + body_start = offset + i += 1 + while i < len(lines): + closing = FENCE.match(lines[i]) + if closing and closing[1][0] == marker[0] and len(closing[1]) >= len(marker) and not closing[2].strip(): + break + offset += len(lines[i]) + i += 1 + if i == len(lines): + raise ValueError(f"unclosed code fence at line {source.count(chr(10), 0, begin) + 1}") + if info.strip() == "math": + add(source[body_start:offset], begin, offset, "math-fence") + offset += len(lines[i]) + i += 1 + start = offset + prose(start, len(source)) + for index, item in enumerate(found, 1): + item["index"] = index + return found + + +def safe_path(path: str) -> bool: + return isinstance(path, str) and bool(path) and "\\" not in path and not PurePosixPath(path).is_absolute() and all( + part not in {"", ".", ".."} for part in path.split("/")) + + +def make_inventory(repository: str, revision: str, sources: dict[str, str]) -> dict: + if not isinstance(repository, str) or not isinstance(revision, str) or not re.fullmatch( + r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) or not SHA.fullmatch(revision): + raise ValueError("use owner/name and an exact lowercase 40-character commit SHA") + if not isinstance(sources, dict) or not sources or not all( + safe_path(p) and isinstance(s, str) for p, s in sources.items()): + raise ValueError("supply at least one safe repository-relative page path") + return {"schema_version": 1, "repository": repository, "revision": revision, + "renderer_profile": "github", "pages": [ + {"path": path, "url": f"https://github.com/{repository}/blob/{revision}/{quote(path, safe='/')}", + "source_sha256": digest(source), "source_text": source, "expressions": expressions(source)} + for path, source in sources.items()]} + + +def validate(inventory: dict, capture: dict, contract: dict | None = None) -> dict: + """Return failures rather than equating a passing text check with readiness.""" + failures: list[str] = [] + boundaries: list[dict] = [] + exceptions: list[dict] = [] + if not isinstance(inventory, dict) or not isinstance(capture, dict): + raise ValueError("inventory and capture must be JSON objects") + if type(inventory.get("schema_version")) is not int or type(capture.get("schema_version")) is not int or inventory["schema_version"] != 1 or capture["schema_version"] != 1: + raise ValueError("unsupported inventory or capture schema_version") + pages = inventory.get("pages") + if not isinstance(pages, list) or not pages or any(not isinstance(p, dict) for p in pages): + raise ValueError("inventory needs a nonempty pages array") + paths = [p.get("path") for p in pages] + if any(not isinstance(p, str) for p in paths) or len(set(paths)) != len(paths): + raise ValueError("inventory page paths must be unique strings") + rebuilt = make_inventory(inventory.get("repository", ""), inventory.get("revision", ""), + {p["path"]: p["source_text"] for p in pages}) + if inventory != rebuilt: + raise ValueError("inventory does not match its embedded source bytes/expression inventory") + for field in ("repository", "revision", "renderer_profile"): + if capture.get(field) != inventory[field]: + failures.append(f"capture {field} mismatch") + try: + timestamp = datetime.fromisoformat(capture.get("captured_at", "").replace("Z", "+00:00")) + if timestamp.tzinfo is None: + raise ValueError() + except (ValueError, AttributeError, TypeError): + failures.append("capture needs captured_at with a timezone") + if not isinstance(capture.get("capture_method"), str) or not capture["capture_method"].strip(): + failures.append("capture needs a nonempty capture_method") + captured_pages = capture.get("pages") + if not isinstance(captured_pages, list) or any(not isinstance(p, dict) for p in captured_pages): + raise ValueError("capture pages must be an array of objects") + captured_paths = [p.get("path") for p in captured_pages] + if captured_paths != paths: + failures.append("capture page paths/order differ from inventory (missing, extra or duplicate page)") + + contract = {"schema_version": 1, "expressions": []} if contract is None else contract + if not isinstance(contract, dict) or type(contract.get("schema_version")) is not int or contract["schema_version"] != 1 or not isinstance(contract.get("expressions"), list): + raise ValueError("invalid text contract schema") + rules: dict[tuple, dict] = {} + known = {(p["path"], e["index"]): e for p in pages for e in p["expressions"]} + for rule in contract["expressions"]: + if not isinstance(rule, dict): + raise ValueError("contract expressions must be objects") + key = (rule.get("path"), rule.get("index")) + if not isinstance(key[0], str) or type(key[1]) is not int or key not in known or key in rules or rule.get("source_sha256") != known[key]["source_sha256"]: + raise ValueError("unknown, duplicate or stale expression contract") + allowed = {"path", "index", "source_sha256", "required_text", "expected_text", "relation_override", + "allow_html_like_inequality", "reason", "evidence"} + if set(rule) - allowed: + raise ValueError("unknown contract field (contracts cannot skip checks)") + if "expected_text" in rule and (not isinstance(rule["expected_text"], str) or not compact(rule["expected_text"])): + raise ValueError("expected_text must be nonempty text") + if not isinstance(rule.get("required_text", []), list) or any( + not isinstance(v, str) or not compact(v) for v in rule.get("required_text", [])): + raise ValueError("required_text must be an array of nonempty text") + if "expected_text" not in rule and not rule.get("required_text"): + raise ValueError("each expression contract needs expected_text or required_text") + if "allow_html_like_inequality" in rule and not isinstance(rule["allow_html_like_inequality"], bool): + raise ValueError("allow_html_like_inequality must be boolean") + if "relation_override" in rule: + override = rule["relation_override"] + if not isinstance(override, dict) or any(k not in RELATION_SYMBOLS or type(v) is not int or v < 0 + for k, v in override.items()): + raise ValueError("relation_override must map known symbols to nonnegative integer counts") + if "relation_override" in rule or rule.get("allow_html_like_inequality"): + if not all(isinstance(rule.get(k), str) and rule[k].strip() for k in ("expected_text", "reason", "evidence")): + raise ValueError("renderer exception requires expected_text, reason and evidence") + exceptions.append(rule) + rules[key] = rule + + by_path = {p.get("path"): p for p in captured_pages if isinstance(p.get("path"), str)} + checked = 0 + for page in pages: + path = page["path"] + current = by_path.get(path) + if current is None: + continue + boundaries.append({"path": path, "source_sha256": page["source_sha256"], "url": current.get("url"), + "revision": current.get("revision"), "source_expressions": len(page["expressions"]), + "source_spans": [{k: e[k] for k in ("index", "line_start", "line_end", "source_sha256")} + for e in page["expressions"]]}) + for field, expected in (("url", page["url"]), ("revision", inventory["revision"]), ("source_sha256", page["source_sha256"])): + if current.get(field) != expected: + failures.append(f"{path}: captured {field} mismatch") + if current.get("errors") != []: + failures.append(f"{path}: renderer errors present or error evidence missing") + hosts = current.get("math") + if not isinstance(hosts, list): + failures.append(f"{path}: missing math-host array") + continue + boundaries[-1]["captured_hosts"] = len(hosts) + if len(hosts) != len(page["expressions"]): + failures.append(f"{path}: {len(page['expressions'])} source expressions, {len(hosts)} captured hosts") + for expr, host in zip(page["expressions"], hosts): + label = f"{path}:{expr['line_start']} expression {expr['index']}" + rule = rules.get((path, expr["index"]), {}) + if not isinstance(host, dict) or host.get("rendered") is not True or host.get("errors") != []: + failures.append(f"{label}: missing/unrendered host or renderer-error evidence") + continue + if host.get("text_source") not in TEXT_SOURCES or not isinstance(host.get("text"), str) or not compact(host["text"]): + failures.append(f"{label}: missing full accessible mathematical text/source") + continue + checked += 1 + text = compact(host["text"]) + expected = {k: v for k, v in rule.get("relation_override", expr["relations"]).items() if v} + actual = dict(sorted(Counter(c for c in text if c in RELATION_SYMBOLS).items())) + if expected != actual: + failures.append(f"{label}: relation mismatch; expected {expected}, captured {actual}") + for equation_label in expr["labels"]: + if equation_label not in text: + failures.append(f"{label}: missing equation label {equation_label}") + if re.search(r"<\s*[A-Za-z]", tex_body(expr["tex"])) and not rule.get("allow_html_like_inequality"): + failures.append(f"{label}: GitHub HTML-like inequality hazard; use supported syntax or a traced exact-text exception") + if "expected_text" in rule and compact(rule["expected_text"]) != text: + failures.append(f"{label}: full expected_text mismatch") + for required in rule.get("required_text", []): + if compact(required) not in text: + failures.append(f"{label}: missing required_text {required!r}") + return {"schema_version": 1, "status": "fail" if failures else "pass", + "repository": inventory["repository"], "revision": inventory["revision"], + "renderer_profile": inventory["renderer_profile"], "captured_at": capture.get("captured_at"), + "capture_method": capture.get("capture_method"), "boundaries": boundaries, + "expressions_checked": checked, "text_contracts": len(rules), "renderer_exceptions": exceptions, + "failures": failures, "visual_review_required": True, + "limits": "Counts, supported relations/visible labels and explicit text contracts only. No arbitrary TeX equivalence, scientific correctness, capture authentication or visual-layout certification."} + + +def read_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + inv = commands.add_parser("inventory", help="read math source from an exact local Git commit") + inv.add_argument("--root", type=Path, required=True) + inv.add_argument("--repository", required=True) + inv.add_argument("--revision", required=True) + inv.add_argument("--page", action="append", required=True) + inv.add_argument("--output", type=Path, required=True) + check = commands.add_parser("check", help="check pinned extracted capture; does not fetch or render") + check.add_argument("--inventory", type=Path, required=True) + check.add_argument("--capture", type=Path, required=True) + check.add_argument("--contract", type=Path) + check.add_argument("--output", type=Path) + args = parser.parse_args(argv) + try: + if args.command == "inventory": + if not SHA.fullmatch(args.revision) or len(set(args.page)) != len(args.page) or not all(safe_path(p) for p in args.page): + raise ValueError("use an exact commit SHA and unique safe page paths") + commit = subprocess.check_output(["git", "--no-replace-objects", "rev-parse", f"{args.revision}^{{commit}}"], cwd=args.root, text=True).strip() + if commit != args.revision: + raise ValueError("revision does not identify the supplied commit") + sources = {p: subprocess.check_output(["git", "--no-replace-objects", "show", f"{commit}:{p}"], cwd=args.root).decode("utf-8") for p in args.page} + result = make_inventory(args.repository, commit, sources) + else: + result = validate(read_json(args.inventory), read_json(args.capture), read_json(args.contract) if args.contract else None) + output = json.dumps(result, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.write_text(output, encoding="utf-8") + else: + print(output, end="") + return 1 if result.get("status") == "fail" else 0 + except (OSError, UnicodeError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/verification/hosted/math-contract.json b/verification/hosted/math-contract.json new file mode 100644 index 0000000..efc64a3 --- /dev/null +++ b/verification/hosted/math-contract.json @@ -0,0 +1,23 @@ +{ + "schema_version": 1, + "expressions": [ + { + "path": "README.md", + "index": 5, + "source_sha256": "a64a80028bf8b5db548af3e7eb3d8adef3a83df468110160091bdfdec19a2251", + "expected_text": "mn=Θ(d2)," + }, + { + "path": "README.md", + "index": 9, + "source_sha256": "580fd9786ee0c9badffcaead54a0c17c8abbaf02e2b332c41e1c47630f44577c", + "expected_text": "mn/(mn+d2−1)" + }, + { + "path": "README.md", + "index": 10, + "source_sha256": "7827c577a7a64ed14eb5c2722e153dcf7648032220a59a1b18ce5aa5744cc50d", + "expected_text": "mn≥p0(d2F0−1)/2" + } + ] +}