From 0c825b9ea520b5bdb3b580efc3651161ce068a8c Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sat, 7 Nov 2026 12:19:56 +0800 Subject: [PATCH 1/2] Add the Watrous learning route and hosted mathematics verification --- .github/workflows/hosted-mathematics.yml | 56 +++ .gitignore | 3 + README.md | 12 +- learning/ANCHOR.md | 89 ++++ learning/MILESTONES.md | 437 ++++++++++++++++++++ learning/TUTORIAL.md | 148 +++++++ llms.txt | 10 + references/RELATED_WORK.md | 8 +- references/references.bib | 9 + science/converse.md | 6 +- science/interpretation.md | 4 +- science/model.md | 10 +- science/parallel_program.md | 8 +- science/resources.md | 4 +- verification/README.md | 2 + verification/hosted/README.md | 28 ++ verification/hosted/capture_hosted_math.cjs | 274 ++++++++++++ verification/hosted/check_rendered_math.py | 370 +++++++++++++++++ verification/hosted/math-contract.json | 125 ++++++ verification/hosted/package-lock.json | 134 ++++++ verification/hosted/package.json | 13 + 21 files changed, 1728 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/hosted-mathematics.yml create mode 100644 .gitignore create mode 100644 learning/ANCHOR.md create mode 100644 learning/MILESTONES.md create mode 100644 learning/TUTORIAL.md create mode 100644 verification/hosted/README.md create mode 100644 verification/hosted/capture_hosted_math.cjs create mode 100644 verification/hosted/check_rendered_math.py create mode 100644 verification/hosted/math-contract.json create mode 100644 verification/hosted/package-lock.json create mode 100644 verification/hosted/package.json diff --git a/.github/workflows/hosted-mathematics.yml b/.github/workflows/hosted-mathematics.yml new file mode 100644 index 0000000..707dea6 --- /dev/null +++ b/.github/workflows/hosted-mathematics.yml @@ -0,0 +1,56 @@ +name: Hosted mathematics + +on: + pull_request: + types: [opened, synchronize, reopened] + workflow_dispatch: + +permissions: {} + +concurrency: + group: hosted-mathematics-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: false + +jobs: + inspect: + if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + env: + SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - name: Check out the exact source commit + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ env.SOURCE_SHA }} + persist-credentials: false + fetch-depth: 1 + - name: Set up Node.js + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '22' + - name: Install pinned collector dependencies + working-directory: verification/hosted + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Install the collector browser + working-directory: verification/hosted + run: node node_modules/playwright/cli.js install --with-deps chromium + - name: Compare the hosted mathematics with its source + run: | + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + node verification/hosted/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$SOURCE_SHA" \ + --contract verification/hosted/math-contract.json \ + --output "$RUNNER_TEMP/hosted-mathematics" + - name: Save the report and actual hosted captures + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: hosted-mathematics-${{ env.SOURCE_SHA }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/hosted-mathematics + if-no-files-found: warn + retention-days: 7 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e8b8e7a --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +__pycache__/ +*.py[cod] diff --git a/README.md b/README.md index 0a64d9f..9f38f42 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ How many copies of an unknown quantum state are needed to program the same refle ## Main result -Let $`N_*(d,r,k,\epsilon)`$ be the smallest hard specimen budget of a deterministic, unconditional processor that achieves error at most $`\epsilon`$ uniformly over all rank-$`r`$ projectors. For $`1\le r + +### M01. States, support, and a flat spectrum + +**Central question.** What information is fixed, and what remains unknown, in a state of the form $`\rho_P=P/r`$? + +**Understanding target.** Interpret a density operator as a positive operator of trace one, a projector $`P`$ as a subspace, and $`r`$ as its dimension. Explain why $`P/r`$ has a known flat nonzero spectrum while its supporting subspace can remain unknown. + +**Dependencies and story role.** None. This introduces the local object from which every program specimen is drawn. + +**Conceptual connection.** The spectrum normalizes the source and sets a scale for its dynamics; knowing that spectrum does not supply the basis needed to describe the target operation classically. + +**Sources.** Anchor: Watrous [§1.1.2][W1] and [§2.1.2][W2]. Project: [source, processor, and output](../science/model.md#source-processor-and-output). + + + +### M02. A reflection as a quantum channel + +**Central question.** What does the reflection $`R_P=I-2P`$ do to a state, and which of its phases are observable? + +**Understanding target.** Explain the opposite phases on the range and kernel of $`P`$, the channel $`X\mapsto R_PXR_P`$, and the cancellation of a global unitary phase. Distinguish this ordinary channel from a controlled reflection. + +**Dependencies and story role.** [M01](#m01). This turns the unknown subspace into a concrete local operation before introducing a batch. + +**Conceptual connection.** The same projector specifies both the supplied mixed state and the desired coherent action. The channel description also explains the zero-specimen endpoint when $`r=d`$. + +**Sources.** Anchor: Watrous [§1.1.2][W1] and [§2.2.1][W2]. Project: [target channel](../science/model.md#source-processor-and-output) and [endpoints](../science/model.md#availability-and-endpoints). + + + +### M03. Composite registers, reductions, and references + +**Central question.** What must be retained in the description when the program interacts with several possibly entangled targets? + +**Understanding target.** Identify the data space $`A=(\mathbb C^d)^{\otimes k}`$, the program register, and an inaccessible reference $`Z`$. Explain tensor products, entanglement, and the partial trace used to discard a program without discarding the data correlations it created. + +**Dependencies and story role.** [M01](#m01), [M02](#m02). This expands a local operation into the composite physical setting of the project. + +**Conceptual connection.** Independent source specimens do not imply independent target outputs. Reduced dynamics must preserve the distinction between an environment that is discarded and a reference against which accuracy is evaluated. + +**Sources.** Anchor: Watrous [§1.1.1][W1] and [§§2.1.1, 2.1.3][W2]. Project: [joint accuracy](../science/model.md#joint-accuracy) and [the collision channel](../science/collision_bound.md#lemma). + + + +### M04. Deterministic processors and quantum channels + +**Central question.** How can one mathematical map include joint gates, measurements, classical randomness, and discarded systems? + +**Understanding target.** Interpret a completely positive, trace-preserving map as the unconditional physical processor. Explain why complete positivity includes entangled inputs and why retaining all outcome branches differs from guaranteeing accuracy only after a successful postselection. + +**Dependencies and story role.** [M02](#m02), [M03](#m03). This establishes the admissible operations and the object to which both bounds apply. + +**Conceptual connection.** The upper bound constructs one allowed channel; the converse constrains every allowed channel. Internal measurement choices do not create an exception to a uniform unconditional guarantee. + +**Sources.** Anchor: Watrous [§2.2.1][W2]. Project: [processor definition](../science/model.md#source-processor-and-output) and [converse scope](../science/converse.md#scope-of-the-conclusion). + + + +### M05. Purification and channel representations + +**Central question.** How can a mixed program and its reduced channel be analyzed using a pure environment and an isometry? + +**Understanding target.** Relate purification, Kraus operators, and an isometric dilation followed by a partial trace. Understand the proof isometry $`V`$ that appends a fixed purification, while keeping separate the mathematical representation and the physical program access actually supplied. + +**Dependencies and story role.** [M03](#m03), [M04](#m04). This supplies a common representation for coherent evolution and its discarded-environment branches. + +**Conceptual connection.** The collision proof separates a compressed Kraus operator from leakage. Introducing a purification for this argument does not grant the processor a purification oracle. + +**Sources.** Anchor: Watrous [§2.1.3][W2] and [§2.2.2][W2]. Project: [conditional expectation and variance](../science/collision_bound.md#conditional-expectation-and-variance) and [channel decomposition](../science/collision_bound.md#proof). + + + +### M06. Operator norms and positive operator bounds + +**Central question.** Which operator estimates can control a physical error without introducing a dimension factor? + +**Understanding target.** Distinguish the operator norm $`\|\cdot\|_\infty`$ from the trace norm $`\|\cdot\|_1`$. Use positive-operator order, the largest eigenvalue of a positive operator, unitary invariance, and trace-norm product bounds to interpret compression and leakage estimates. + +**Dependencies and story role.** [M01](#m01), [M05](#m05). This introduces the quantitative language used in both the local channel estimate and the exact variance calculation. + +**Conceptual connection.** A bound on a compressed operator can remain much smaller than a bound on the full interaction. Positivity makes that difference usable in a channel estimate. + +**Sources.** Anchor: Watrous [§§1.1.2–1.1.3][W1]. Project: [variance positivity](../science/collision_bound.md#conditional-expectation-and-variance) and [operator estimates in the proof](../science/collision_bound.md#proof). + + + +### M07. Trace distance and binary discrimination + +**Central question.** How does distance between two states limit the ability to tell them apart? + +**Understanding target.** Interpret $`T(\alpha,\beta)=\tfrac12\|\alpha-\beta\|_1`$ through optimal binary discrimination. Explain its contractivity under a fixed channel and keep its factor of one-half distinct from the project's unhalved channel-error convention. + +**Dependencies and story role.** [M04](#m04), [M06](#m06). This gives an operational meaning to a state-distance bound. + +**Conceptual connection.** A processor cannot turn nearly indistinguishable program states into easily distinguishable outputs unless enough specimens were supplied. This principle will constrain all possible implementations. + +**Sources.** Anchor: Watrous [§3.1.1][W3]. Project: [program-state distances](../science/converse.md#a-nearby-pair-of-program-states) and [data processing](../science/converse.md#processor-error-and-data-processing). + + + +### M08. Fidelity and independent program copies + +**Central question.** How can single-specimen overlap control the distinguishability of many independent specimens? + +**Understanding target.** Use root fidelity $`f(\alpha,\beta)=\|\sqrt\alpha\sqrt\beta\|_1`$, its multiplicativity on tensor products, and the inequality $`T\le\sqrt{1-f^2}`$. Explain why the iid source promise permits a single-copy fidelity calculation to control the full program input. + +**Dependencies and story role.** [M05](#m05), [M07](#m07). This turns local state overlap into a quantitative constraint on a source budget. + +**Conceptual connection.** Watrous's fidelity convention is the unsquared quantity used here. Keeping that convention explicit prevents a factor-of-two error in the later small-angle estimate. + +**Sources.** Anchor: Watrous [§3.2][W3], especially Definition 3.11, Proposition 3.16, and Theorem 3.33. Project: [the exact program fidelity](../science/converse.md#a-nearby-pair-of-program-states). + + + +### M09. The diamond norm and joint accuracy + +**Central question.** What error criterion remains meaningful when the batch is entangled with another system? + +**Understanding target.** Interpret the diamond norm as a channel distance optimized over joint input-reference states. Explain the unhalved convention and distinguish a guarantee for the complete $`k`$-register channel from guarantees for individual marginals. + +**Dependencies and story role.** [M03](#m03), [M04](#m04), [M06](#m06), [M07](#m07). This upgrades state-level distinguishability to the accuracy criterion required by the project. + +**Conceptual connection.** Correlations produced by a shared program are part of the error being bounded. The reference system makes the guarantee suitable for later use inside a larger computation. + +**Sources.** Anchor: Watrous [§§3.3.2–3.3.3][W3]. Project: [joint accuracy](../science/model.md#joint-accuracy) and [the reduced-channel lemma](../science/collision_bound.md#lemma). + + + +### M10. Composition and a complete error budget + +**Central question.** How do local channel errors bound the error of an entire circuit or a tensor product of channels? + +**Understanding target.** Explain channel norm one, contractivity under preparation and discarding, and telescoping bounds that add individual errors. Apply the same principle to sequential collisions, separate data groups, and repeated processor calls with known intervening gates. + +**Dependencies and story role.** [M04](#m04), [M09](#m09). This connects local estimates to full input-output guarantees. + +**Conceptual connection.** The same stability property supports the constructive upper bound and the converse. An explicit budget records which approximation produces each part of the final error. + +**Sources.** Anchor: Watrous [§3.3.2][W3], including Proposition 3.48. Project: [fresh-collision composition](../science/parallel_program.md#fresh-collisions-implement-the-product-channel) and [the full implementation budget](../science/resources.md#4-group-size-finite-gates-and-the-final-error). + + + +### M11. Specimen access and charged resources + +**Central question.** What computational access is supplied by a specimen, and what additional resources must an implementation provide? + +**Understanding target.** Distinguish copies of $`P/r`$ from a classical eigenbasis, a preparation unitary, its inverse, and a purification oracle. Separate a hard copy budget from an expected budget, and identify source preparation, storage, known gates, and synthesis precision as additional costs. + +**Dependencies and story role.** [M04](#m04), [M05](#m05), [M10](#m10). This puts the information-theoretic channel model into its computational setting. + +**Conceptual connection.** A mathematical channel representation does not supply free physical access to its dilation. The source contract determines which constructions and lower bounds are comparable. + +**Sources.** Anchor: Watrous [§§2.2.1–2.2.2][W2] for channel inputs and representations. Project: [source access](../science/model.md#source-processor-and-output) and [copy, gate, and memory counts](../science/resources.md#5-copy-gate-and-memory-counts). + + + +### M12. The complete parallel programming task + +**Central question.** What exactly is minimized, over which processors, and under which uniform guarantee? + +**Understanding target.** Assemble known rank and exact flatness, iid source specimens, jointly available data, unconditional processing, a hard specimen budget, and uniform joint diamond accuracy into the definition of $`N_*(d,r,k,\epsilon)`$. + +**Dependencies and story role.** [M02](#m02), [M03](#m03), [M04](#m04), [M08](#m08), [M09](#m09), [M10](#m10), [M11](#m11). This closes the background phase by joining its objects and tools into one operational problem. + +**Conceptual connection.** The upper and lower arguments must address the same source, output channel, error convention, and availability requirement. Those quantifiers are part of the result. + +**Sources.** Anchor: Watrous [§2.2.1][W2] and [§§3.3.2–3.3.3][W3]. Project: [the complete model](../science/model.md) and [proof dependencies](../science/README.md). + +## Narrative/innovation: M13–M30 + + + +### M13. The shared-swap interaction and its mean + +**Central question.** How can one program specimen generate the intended action on several data registers? + +**Understanding target.** Identify $`H_*=\sum_jS_{a,j}`$, where $`S_{a,j}`$ swaps program register $`a`$ with target $`j`$. Interpret the program-weighted partial trace $`\mathcal E_\rho`$ and its mean $`h=\mathcal E_\rho(H_*)=\sum_j\rho_j`$, where $`\rho_j`$ acts on target $`j`$. + +**Dependencies and story role.** [M03](#m03), [M06](#m06), [M12](#m12). This introduces the local physical interaction underlying the construction. + +**Conceptual connection.** HME supplies this interaction for the linear map $`B\mapsto\sum_jB_j`$. The project analyzes its actual program-dependent error; it does not introduce a new interaction framework. + +**Sources.** Anchor: Watrous [§§2.1.3, 2.2.2][W2]. Project: [interaction and moments](../science/parallel_program.md#the-interaction-and-its-moments); primary attribution: [HME](../references/RELATED_WORK.md#hme-supplies-the-collective-interaction). + + + +### M14. Ordered swaps and the second program moment + +**Central question.** Which correlations appear when the same specimen participates in two different target interactions? + +**Understanding target.** Track the order in $`\mathcal E_\rho(S_{a,i}S_{a,j})=\rho_jS_{i,j}`$ and interpret the second moment $`M=\mathcal E_\rho(H_*^2)`$. Explain the separate single-swap and cross-target contributions to $`\|M\|_\infty=k+k(k-1)/r`$. + +**Dependencies and story role.** [M06](#m06), [M13](#m13). This identifies the rank-dependent structure that a full interaction-norm bound would discard. + +**Conceptual connection.** Shared specimens create correlated target noise. The factor $`1/r`$ enters through the actual mixed program and must be retained before bounding the resulting channel. + +**Sources.** Anchor: Watrous [§1.1.2][W1] and [§2.1.3][W2]. Project: [ordered swap identities and second moment](../science/parallel_program.md#the-interaction-and-its-moments). + + + +### M15. Centering the program interaction + +**Central question.** Which part of the joint interaction differs from the desired mean evolution? + +**Understanding target.** Interpret the positive operator $`M-h^2`$ and its norm $`v=\|M-h^2\|_\infty`$. Use the purification isometry $`V`$ to relate this variance to coupling out of the fixed-environment subspace, and understand why subtracting the mean isolates the relevant fluctuation. + +**Dependencies and story role.** [M05](#m05), [M06](#m06), [M13](#m13), [M14](#m14). This converts the raw moment calculation into the quantity that controls the error. + +**Conceptual connection.** A variance bound keeps the supplied state's structure while allowing arbitrary data inputs. Its positivity follows from a dilation identity, without giving the implementation access to that purification. + +**Sources.** Anchor: Watrous [§§1.1.2–1.1.3][W1] and [§§2.1.3, 2.2.2][W2]. Project: [conditional expectation and variance](../science/collision_bound.md#conditional-expectation-and-variance). + + + +### M16. Compression, leakage, and the collision bound + +**Central question.** How does the centered fluctuation produce a nonasymptotic channel-error estimate? + +**Understanding target.** Connect the compressed Kraus operator's deviation from the intended unitary with the remaining completely positive leakage map. Explain why the two contributions give $`\|\Phi_\delta-\mathcal U_\delta\|_\diamond\le2\delta^2v`$ for a collision of duration $`\delta`$, including every reference input. + +**Dependencies and story role.** [M05](#m05), [M06](#m06), [M09](#m09), [M15](#m15). This completes the local analytical mechanism before specializing its variance. + +**Conceptual connection.** The proof controls the full remainder through compression and leakage. The error estimate is therefore stronger than a formal second-order expansion with an unspecified remainder. + +**Sources.** Anchor: Watrous [§2.2.2][W2] and [§3.3.2][W3]. Project: [the collision lemma](../science/collision_bound.md#lemma) and [its proof](../science/collision_bound.md#proof). + + + +### M17. Variance across sectors of fixed support count + +**Central question.** Why can the exact worst-case variance be found without learning the orientation of the support? + +**Understanding target.** Use $`C_P=\sum_jP_j`$ to separate sectors with $`m`$ targets in the support. Explain the sector upper bound and the symmetric vectors that attain it, giving $`v_{r,k}=\max_{0\le m\le k}[k+(k-1)m/r-m^2/r^2]`$ over integer $`m`$. + +**Dependencies and story role.** [M01](#m01), [M06](#m06), [M14](#m14), [M15](#m15), [M16](#m16). This supplies the task-specific value needed by the local channel lemma. + +**Conceptual connection.** Permutation symmetry and positive-operator order replace any need for a classical basis of $`P`$. A nonempty range and kernel provide the attaining vectors, explaining the condition $`r\lt d`$. + +**Sources.** Anchor: Watrous [§§1.1.2–1.1.3][W1]. Project: [exact variance](../science/parallel_program.md#exact-variance). + + + +### M18. Fresh collisions produce the reflection batch + +**Central question.** How does a small accurate collision become the desired complete batch operation? + +**Understanding target.** Explain why fresh specimens give a composition of reduced channels, why $`t=\pi r`$ turns $`e^{-it\rho}`$ into $`R_P`$, and how diamond telescoping gives joint error at most $`2\pi^2r^2v_{r,k}/N`$ after $`N`$ collisions. + +**Dependencies and story role.** [M02](#m02), [M10](#m10), [M13](#m13), [M16](#m16), [M17](#m17). This connects the local mechanism to an entire output channel. + +**Conceptual connection.** The program states are fresh and independent, while the data remain coherent and may stay entangled throughout. The composition argument does not reset or factorize the targets. + +**Sources.** Anchor: Watrous [§2.2.1][W2] and [§3.3.2][W3]. Project: [fresh collisions](../science/parallel_program.md#fresh-collisions-implement-the-product-channel). + + + +### M19. Symmetric sweeps from known pair gates + +**Central question.** How is the collective interaction implemented without treating its exponential as a free operation? + +**Understanding target.** Relate a partial swap to a known Hermitian-involution rotation. Explain the symmetric $`2k-1`$-gate sweep, the cancellation of its second-order product error, and the operator remainder at most $`k^3|\delta|^3/3`$. + +**Dependencies and story role.** [M06](#m06), [M11](#m11), [M18](#m18). This replaces an abstract collective evolution by an explicit circuit. + +**Conceptual connection.** A physically available implementation must preserve the variance gain. The symmetric sweep and its remainder estimate are supplied by the project, with the collision architecture attributed to prior work. + +**Sources.** Anchor: Watrous [§1.1.3][W1] and [§2.2.1][W2] for norms and unitary channels. Project: [partial-swap gadget](../science/resources.md#1-a-partial-swap-with-returned-work), [symmetric sweep](../science/resources.md#2-a-symmetric-sweep-implements-the-collective-collision), and [implementation antecedents](../references/RELATED_WORK.md#collective-collisions-and-gate-implementation). + + + +### M20. An explicit uniform specimen upper bound + +**Central question.** How many specimens suffice after both reduced-channel error and sweep error are included? + +**Understanding target.** Combine the terms proportional to $`1/N`$ and $`1/N^2`$ and interpret the sufficient count $`N=\lceil4\pi^2rk(r+k-1)/\epsilon\rceil`$ for $`0\lt \epsilon\le1`$. Keep the integer budget and the exact-known-rotation convention visible. + +**Dependencies and story role.** [M10](#m10), [M17](#m17), [M18](#m18), [M19](#m19). This completes the constructive specimen bound before optimizing its gate realization. + +**Conceptual connection.** A finite, uniform choice of $`N`$ closes the passage from an infinitesimal collision picture to a deterministic channel with a specified accuracy. + +**Sources.** Anchor: Watrous [§1.1.3][W1] and [§3.3.2][W3]. Project: [explicit upper bound](../science/parallel_program.md#known-pair-gates-and-an-explicit-upper-bound) and [one-group error budget](../science/resources.md#3-one-group-with-a-complete-error-budget). + + + +### M21. Batching without losing the sample order + +**Central question.** How can smaller jointly processed groups retain the specimen saving while controlling the gate count? + +**Understanding target.** Partition the $`k`$ targets into $`q=\lceil k/r\rceil`$ groups of size at most $`r`$. Explain why group errors add even on entangled inputs, why specimen counts retain order $`(r^2k+rk^2)/\epsilon`$, and why pair partial swaps have order $`r^2k^2/\epsilon`$. + +**Dependencies and story role.** [M10](#m10), [M20](#m20). This turns the full-batch construction into an efficient explicit implementation. + +**Conceptual connection.** Independent program supplies for different groups are compatible with entanglement across those groups because the error contract is a channel bound. + +**Sources.** Anchor: Watrous [§3.3.2][W3]. Project: [batching](../science/parallel_program.md#batching-preserves-the-specimen-order) and [copy and gate counts](../science/resources.md#5-copy-gate-and-memory-counts). + + + +### M22. Finite precision, preparation, and storage + +**Central question.** Which resources remain once a sufficient specimen count has been established? + +**Understanding target.** Account for finite rotation synthesis, elementary gates, source preparation, data storage, and program storage. Distinguish exact work-qubit return with ideal rotations from approximate joint return after synthesis, and distinguish specimens stored before the targets arrive from specimens streamed during execution. + +**Dependencies and story role.** [M11](#m11), [M19](#m19), [M21](#m21). This closes the constructive side with a complete physical resource interpretation. + +**Conceptual connection.** The specimen law is compatible with explicit gate and memory charges. The anchor supplies channel-error composition; the gate-synthesis guarantee and delivery schedules are specified in the project and its primary references. + +**Sources.** Anchor: Watrous [§2.2.2][W2] and [§3.3.2][W3]. Project: [finite-gate budget and joint work return](../science/resources.md#4-group-size-finite-gates-and-the-final-error), [storage and preparation](../science/resources.md#5-copy-gate-and-memory-counts), and [synthesis attribution](../references/RELATED_WORK.md#collective-collisions-and-gate-implementation). + + + +### M23. Nearby supports and program indistinguishability + +**Central question.** Which pair of admissible supports makes every processor confront a source-information limitation? + +**Understanding target.** Follow the pair $`P_0,P_\theta`$ obtained by rotating one support direction through an angle $`\theta`$ into the complement. Explain their root fidelity $`f=(r-1+\cos\theta)/r`$ and how tensor-product fidelity bounds the trace distance of their many-specimen programs. + +**Dependencies and story role.** [M01](#m01), [M07](#m07), [M08](#m08), [M12](#m12). This begins the converse with a local pair inside the fixed-rank promise. + +**Conceptual connection.** The spectrum remains fixed in both hypotheses. The lower bound uses uncertainty in the support, so a varying-spectrum worst-case theorem cannot replace this task-specific comparison. + +**Sources.** Anchor: Watrous [§3.2][W3]. Project: [nearby program states](../science/converse.md#a-nearby-pair-of-program-states) and [discrimination-method attribution](../references/RELATED_WORK.md#the-converse-uses-program-distinguishability). + + + +### M24. Relative reflections and a two-dimensional rotation + +**Central question.** How can ordinary reflection channels reveal the small rotation between the chosen supports? + +**Understanding target.** Explain the eigenphases $`e^{\pm2i\theta}`$ of $`R_0R_\theta`$ on the distinguished two-dimensional plane, where $`R_0=I-2P_0`$. Identify the known comparison gate and the fixed eigenvectors used by the discrimination experiment. + +**Dependencies and story role.** [M02](#m02), [M23](#m23). This converts a small support change into a coherent phase signal. + +**Conceptual connection.** The comparison reflection is known because the proof chooses its two hypotheses. The reduction needs neither a controlled unknown reflection nor an extra supplied reference sector. + +**Sources.** Anchor: Watrous [§1.1.2][W1] and [§2.2.1][W2]. Project: [relative-reflection geometry](../science/converse.md#the-relative-reflection-accumulates-phase). + + + +### M25. An entangled batch amplifies the phase + +**Central question.** How does the same small rotation become more distinguishable when the operation acts on a coherent batch? + +**Understanding target.** Interpret the superposition of the tensor powers of the two relative-reflection eigenvectors. Explain why one batch invocation produces relative phase $`4k\theta`$ and why the uniform joint-channel guarantee covers this input. + +**Dependencies and story role.** [M03](#m03), [M09](#m09), [M24](#m24). This introduces the batch-size dependence of the converse. + +**Conceptual connection.** The target operation can accumulate a coherent phase across the batch while the supplied program states remain close. The lower bound compares these two distinguishability scales. + +**Sources.** Anchor: Watrous [§1.1.1][W1], [§3.1.1][W3], and [§3.3.3][W3]. Project: [entangled batch and phase accumulation](../science/converse.md#the-relative-reflection-accumulates-phase). + + + +### M26. Repetition and the unrestricted converse + +**Central question.** How does a uniformly accurate processor force the inverse-accuracy specimen lower bound? + +**Understanding target.** Join the hard $`N`$-copy budget per invocation, $`m=\lfloor1/(4\epsilon)\rfloor`$ repetitions, the choice $`\theta=\pi/(4km)`$, and diamond-error accumulation. Explain how orthogonal ideal outputs and trace-distance contractivity imply $`N\ge9rk^2/(8\pi^2\epsilon)`$ for $`0\lt \epsilon\le1/8`$. + +**Dependencies and story role.** [M07](#m07), [M08](#m08), [M10](#m10), [M12](#m12), [M23](#m23), [M24](#m24), [M25](#m25). This closes the converse for every deterministic unconditional processor in the model. + +**Conceptual connection.** The repeated experiment consumes $`Nm`$ specimens and uses one hypothesis-independent physical map. Internal measurements or a classically estimated program do not evade data processing. + +**Sources.** Anchor: Watrous [§§3.1.1, 3.2, 3.3.2][W3]. Project: [processor error and data processing](../science/converse.md#processor-error-and-data-processing) and [converse scope](../science/converse.md#scope-of-the-conclusion). + + + +### M27. The matched large-batch theorem + +**Central question.** In which parameter regime do the upper and lower constructions settle the specimen complexity? + +**Understanding target.** Compare the upper dependence $`r^2k+rk^2`$ with the lower dependence $`rk^2`$. Explain why they match for $`k\ge r`$, uniformly in $`d>r`$ and for $`0\lt \epsilon\le1/8`$, and why finite-gate resource accounting preserves this specimen order. + +**Dependencies and story role.** [M20](#m20), [M22](#m22), [M26](#m26). This joins the constructive and unrestricted arguments into the central theorem. + +**Conceptual connection.** The statement $`N_*=\Theta(rk^2/\epsilon)`$ needs both achievability and impossibility under the same contract. Dimension-independent specimen constants do not remove dimension-dependent gate or storage costs. + +**Sources.** Anchor: Watrous [§§3.1.1, 3.3.2–3.3.3][W3] for the two operational distance tools. Project: [the theorem](../science/model.md#the-copy-complexity-theorem) and [resource counts](../science/resources.md#5-copy-gate-and-memory-counts). + + + +### M28. The sample saving and its precise baseline + +**Central question.** What established construction does collective programming improve, and which methods does it inherit? + +**Understanding target.** Reconstruct the separate-DME budget $`O(r^2k^2/\epsilon)`$ from a per-target error $`\epsilon/k`$. Explain the factor-$`r`$ specimen improvement for $`k\ge r`$, the retained pair-gate order, and the distinction between this explicit comparison and a universal separation from independent or classical processors. + +**Dependencies and story role.** [M10](#m10), [M21](#m21), [M22](#m22), [M27](#m27). This places the theorem in its computational and research context. + +**Conceptual connection.** The contribution is a sharper rank-sensitive law within established HME and discrimination methods. Correct attribution is necessary to identify what the comparison actually establishes. + +**Sources.** Anchor: Watrous [§3.3.2][W3] for error composition. Project: [comparison with separate DME](../science/interpretation.md#comparison-with-separate-dme), [resource comparison](../science/resources.md#6-what-the-sample-saving-compares), and [related work](../references/RELATED_WORK.md). + + + +### M29. Boundaries of the established result + +**Central question.** Which changes in rank, output interface, or resource claim would require a different theorem? + +**Understanding target.** Locate the unresolved $`k\lt r`$ regime, the trivial $`r=d`$ endpoint, the known-rank flat-spectrum promise, and the need for jointly available inputs within each group. Distinguish the proved channel from a controlled unknown gate, a returned catalyst, an online adaptive oracle, or a guaranteed runtime improvement. + +**Dependencies and story role.** [M02](#m02), [M11](#m11), [M12](#m12), [M22](#m22), [M27](#m27), [M28](#m28). This integrates the theorem's load-bearing assumptions and its resource interpretation. + +**Conceptual connection.** Strong accuracy on a parallel channel does not supply a different causal interface. A specimen saving also remains distinct from a saving in all physical costs. + +**Sources.** Anchor: Watrous [§2.2.1][W2] and [§3.3.3][W3] for precisely specified channels. Project: [availability and endpoints](../science/model.md#availability-and-endpoints), [interpretation](../science/interpretation.md), and [converse scope](../science/converse.md#scope-of-the-conclusion). + + + +### M30. The complete contribution and proof structure + +**Central question.** How do the physical mechanism, the mathematical bounds, and the implementation costs support one coherent conclusion? + +**Understanding target.** Connect the source contract to the shared-swap mean, rank-sensitive variance, complete-channel upper, charged implementation, and fidelity-based converse. Explain the optimal large-batch specimen law together with its explicit benchmark, inherited methods, and unresolved boundaries. + +**Dependencies and story role.** [M12](#m12), [M16](#m16), [M17](#m17), [M22](#m22), [M26](#m26), [M27](#m27), [M28](#m28), [M29](#m29). This completes the narrative phase by integrating the proof structure and operational meaning. + +**Conceptual connection.** The channel, dilation, norm, and distinguishability tools from the anchor meet in a single result about quantum states used as instructions. The project's canonical proofs supply the specific mechanism and quantitative law. + +**Sources.** Anchor: Watrous [§2.2.2][W2] and [§3.1.1, §3.2, §§3.3.2–3.3.3][W3]. Project: [scientific account](../science/README.md), [model and theorem](../science/model.md), [interpretation](../science/interpretation.md), and [attribution](../references/RELATED_WORK.md). + +[W1]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.1.pdf +[W2]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf +[W3]: https://cs.uwaterloo.ca/~watrous/TQI/TQI.3.pdf diff --git a/learning/TUTORIAL.md b/learning/TUTORIAL.md new file mode 100644 index 0000000..c20c8ae --- /dev/null +++ b/learning/TUTORIAL.md @@ -0,0 +1,148 @@ +# A worked route through the batch law + +A source can prepare specimens of a state whose supporting subspace is unknown. We want those specimens to control a coherent operation on other quantum systems. The operation is simple to describe: reverse the phase inside that subspace and preserve the phase outside it. The resource question is how many specimens a whole batch of inputs consumes. + +Follow this route alongside the [30 milestones](MILESTONES.md). The [Watrous bridge](ANCHOR.md) identifies the relevant sections of the single educational anchor, *The Theory of Quantum Information* (2018), and translates its notation. The scientific pages linked below contain the full statements and proofs. + +## 1. From a specimen to an operation + +**Milestones [M01–M06](MILESTONES.md#m01).** Let $`P`$ be an orthogonal projector of known rank $`r`$ on a $`d`$-dimensional register. A specimen has density operator $`\rho_P=P/r`$. It assigns equal weight to every direction in the range of $`P`$, and zero weight to its orthogonal complement. Its trace is one because $`\operatorname{Tr}P=r`$. + +The desired unitary is $`R_P=I-2P`$. A vector in the range of $`P`$ acquires phase $`-1`$; a vector in the complement acquires phase $`+1`$. The ordinary channel acts on a density operator $`X`$ as $`X\mapsto R_PXR_P`$. A common phase on the entire vector cancels in this expression, while a relative phase between its components can change the state. + +The processor receives $`N`$ independent specimens of the same unknown $`P/r`$ and $`k`$ data registers. It may perform joint operations, use ancillas, measure and use the measurement records. Its complete output, averaged over all internal outcomes, must be accurate. A channel representation that introduces a purification helps prove this property; it does not supply an extra physical resource to the processor. The [model](../science/model.md) states the access and output contract. + +## 2. Why the guarantee is about the whole batch + +**Milestones [M07–M12](MILESTONES.md#m07).** The data registers may be entangled with each other and with an external system retained by someone else. A correct processor must preserve the promised operation on these correlations as well as on each register separately. The sample bounds below assume $`1\le r\lt d`$, $`k\ge1`$ and $`0\lt \epsilon\le1/8`$. + +Write $`\mathcal E_{P,N}`$ for its implemented batch channel and $`\mathcal R_P^{(k)}`$ for the ideal channel of $`R_P^{\otimes k}`$. The requirement is + +```math +\sup_{\operatorname{rank}P=r} +\|\mathcal E_{P,N}-\mathcal R_P^{(k)}\|_\diamond +\le\epsilon. +``` + +The diamond norm allows an arbitrary reference at the input. This project uses its unhalved convention. Therefore, for any particular input-reference state, the conventional trace distance between the two outputs is at most $`\epsilon/2`$. This conversion matters in the lower bound. + +The input resource is a hard budget of independent specimens. Knowing $`r`$ does not reveal the support basis, and a formula for $`P/r`$ does not provide a preparation unitary or its inverse. All $`k`$ data registers are available for the parallel task. The construction may divide them into groups, but each group's members must be present together. + +## 3. One concrete two-target example + +**Milestones [M13–M15](MILESTONES.md#m13).** Take $`d=3`$, $`r=2`$ and $`k=2`$. For explaining the action, choose coordinates in which + +```math +P=\operatorname{diag}(1,1,0),\qquad +\rho_P=\operatorname{diag}(1/2,1/2,0),\qquad +R_P=\operatorname{diag}(-1,-1,1). +``` + +The implementation is not supplied these coordinates. Its gates are swaps, which work for every orientation of the unknown support. + +For the entangled data state $`|\psi\rangle=(|00\rangle+|12\rangle)/\sqrt2`$ in the basis $`|0\rangle,|1\rangle,|2\rangle`$, the two-target reflection gives + +```math +R_P^{\otimes2}|\psi\rangle +=\frac{|00\rangle-|12\rangle}{\sqrt2}. +``` + +The component with both targets in the support acquires two minus signs. The component with only the first target in the support acquires one. Their relative sign changes, and the output is orthogonal to the input. This is one illustrative input; the theorem must control every input and reference. + +Let $`S_{a,j}`$ swap the program register $`a`$ with target $`j`$. One collective collision uses the known interaction $`H_*=S_{a,1}+S_{a,2}`$. Averaging over the specimen gives the effective data Hamiltonian + +```math +h=\rho_{P,1}+\rho_{P,2},\qquad +e^{-i\pi r h}=R_P^{\otimes2}. +``` + +Here $`\rho_{P,j}`$ acts on target $`j`$ and as the identity on the other target. The two terms commute. Each eigenvalue $`1/r`$ therefore acquires phase $`e^{-i\pi}=-1`$ after time $`\pi r`$. + +A finite collision also fluctuates around this mean action. Define $`M`$ as the program expectation of $`H_*^2`$ and $`v=\|M-h^2\|_\infty`$. In an analytical purification, this variance measures the coupling out of the subspace in which the purified environment remains fixed. + +## 4. Turning local error into a specimen count + +**Milestones [M16–M20](MILESTONES.md#m16).** The [collision lemma](../science/collision_bound.md) proves, for every real collision duration $`\delta`$, + +```math +\|\Phi_\delta-\operatorname{Ad}_{e^{-i\delta h}}\|_\diamond +\le2\delta^2v. +``` + +The proof uses an analytical purification and divides the joint evolution into its projection onto the fixed-environment subspace and its orthogonal contribution. After removing the intended mean evolution, the compressed change vanishes to first order; the leakage probability is also quadratic. Both terms are bounded in a way that retains an arbitrary reference. This is why the inequality controls the whole reduced channel, beyond a formal expansion of its first derivative. + +For our two-target example, the [exact variance formula](../science/parallel_program.md#exact-variance) becomes + +```math +v_{2,2}=\max_{m\in\{0,1,2\}} +\left(2+\frac m2-\frac{m^2}{4}\right) +=\frac94. +``` + +The integer $`m`$ counts data factors lying in the support sector. The values are $`2`$, $`9/4`$ and $`2`$. This calculation shows how the actual program state enters the bound; replacing it by the interaction norm alone would lose that information. + +Use a fresh specimen for each of $`N`$ collisions and set $`\delta=\pi r/N`$. Channel errors add under composition, so the total collision contribution is at most + +```math +N\,(2\delta^2v)=\frac{2\pi^2r^2v}{N}. +``` + +For the example above this is $`18\pi^2/N`$. For general $`r,k`$, the proved inequality $`v\le k+k(k-1)/r`$ gives the order $`(r^2k+rk^2)/N`$. Sharing a specimen introduces target correlations, but the same global error bound already accounts for them. + +The collective exponential also needs implementation. A symmetric sweep of known pair partial swaps matches it through second order. The [resource proof](../science/resources.md#2-a-symmetric-sweep-implements-the-collective-collision) bounds the remainder for every step size. Including that error, exact known rotations give the explicit sufficient budget + +```math +N=\left\lceil\frac{4\pi^2rk(r+k-1)}{\epsilon}\right\rceil. +``` + +The variance estimate controls the source-induced error. The sweep estimate separately controls how the known interaction is implemented. Combining both is necessary for this constructive bound. + +## 5. Real gates and the size of a group + +**Milestones [M21–M22](MILESTONES.md#m21).** When $`k`$ is much larger than $`r`$, one need not make every specimen touch every target. Split the targets into $`q=\lceil k/r\rceil`$ groups, each of size at most $`r`$. Allocate the channel error across all groups, retaining other targets as references while a group is processed. The [finite-gate allocation](../science/resources.md#4-group-size-finite-gates-and-the-final-error) reserves half of the final error for the group constructions and half for rotation synthesis. + +The pair-gate construction from [M19](MILESTONES.md#m19) implements a partial swap $`e^{-i\alpha S}`$ by coherently recording the swap eigenvalue in one work qubit, applying a known phase rotation, and uncomputing that record. Ideal rotations return the work qubit exactly. Finite-gate synthesis gives a small joint error, including the work qubit; comparing the complete gadget unitaries permits that same work qubit to be reused. + +This preserves the sample order and uses $`O(r^2k^2/\epsilon)`$ pair partial swaps. A register occupies $`\lceil\log_2d\rceil`$ qubits, and synthesizing the rotations has an additional precision cost. Source preparation and storage also matter: specimens supplied throughout execution can be streamed, while specimens supplied only before the data arrive must be retained. The [resource account](../science/resources.md#5-copy-gate-and-memory-counts) separates these quantities. + +## 6. Why every processor pays a quadratic batch cost + +**Milestones [M23–M26](MILESTONES.md#m23).** For a lower bound, compare two possible sources. Start from a rank-$`r`$ support and rotate just one support direction through angle $`\theta`$ into its complement. The resulting flat states have root fidelity + +```math +f(\rho_0,\rho_\theta)=\frac{r-1+\cos\theta}{r}. +``` + +For small $`\theta`$, the sources are very similar. Tensor-product fidelity and the trace-distance bound from Watrous imply that $`Nm`$ specimens obey + +```math +T(\rho_0^{\otimes Nm},\rho_\theta^{\otimes Nm}) +\le\sqrt{\frac{Nm\theta^2}{r}}. +``` + +Now suppose an accurate $`N`$-specimen processor is available. After each use, apply a known comparison reflection corresponding to the first support. Under that source the ideal combined operation is the identity. Under the rotated source it is a rotation with eigenphases $`\pm2\theta`$ in a two-dimensional subspace. + +An entangled superposition of $`k`$ copies of the two eigenvectors multiplies their relative phase by $`k`$. Repeating the experiment with $`m`$ fresh processor instances multiplies it by $`m`$. Choose + +```math +m=\left\lfloor\frac1{4\epsilon}\right\rfloor, +\qquad \theta=\frac{\pi}{4km}. +``` + +The ideal final outputs are orthogonal. Under each source hypothesis, the actual output is within conventional trace distance $`m\epsilon/2`$ of its ideal output. Thus the two actual outputs have trace distance at least $`1-m\epsilon\ge3/4`$. + +Yet the complete experiment is a fixed channel of the supplied program specimens. Such processing cannot increase their distinguishability. Comparing the last two bounds forces + +```math +N\ge\frac{9}{8\pi^2}\frac{rk^2}{\epsilon}. +``` + +The [full converse](../science/converse.md) gives the basis vectors, phase calculation and constants. Its force comes from the unconditional channel guarantee and hard specimen budget, so it includes processors with internal measurements and feedforward. The known comparison reflection is not a controlled unknown operation. + +## 7. Putting the contribution together + +**Milestones [M27–M30](MILESTONES.md#m27).** For $`1\le r\lt d`$ and $`0\lt \epsilon\le1/8`$, the upper order is $`(r^2k+rk^2)/\epsilon`$ and the lower order is $`rk^2/\epsilon`$. They match when $`k\ge r`$. This comparison identifies the optimal specimen law in that regime; for $`k\lt r`$ a gap remains. + +Separate density matrix exponentiation at error $`\epsilon/k`$ per target uses $`O(r^2k^2/\epsilon)`$ specimens. The large-batch construction improves that explicit bound by a factor of order $`r`$. Its pair-gate order remains $`O(r^2k^2/\epsilon)`$, so a specimen saving alone does not establish a runtime saving. At $`r=d`$ the desired ordinary channel is already the identity and consumes no specimens. + +HME supplies the collective interaction; previous work supplies moment-sensitive analysis, collision architectures and the fidelity/query method. The [related-work account](../references/RELATED_WORK.md) makes those dependencies explicit. The result here combines a rank-sensitive construction with a matching large-batch converse and an implementation whose resources are charged. The [scientific index](../science/README.md) gives the complete proof route, and the [finite checks](../verification/README.md) illustrate the matrix identities without replacing their proofs. diff --git a/llms.txt b/llms.txt index 08bb79f..bb34c57 100644 --- a/llms.txt +++ b/llms.txt @@ -21,6 +21,16 @@ - [Verification code](verification/verify.py): Small-dimensional matrix checks. - [Recorded results](verification/results.json): Actual output of the documented run. +## Learning route + +The single educational anchor is John Watrous, The Theory of Quantum Information (2018), using the author's standard-layout manuscript for section and page pointers. + +- [Source bridge](learning/ANCHOR.md): Targeted sections, notation, root-fidelity and unhalved-diamond conventions, and the steps supplied by this project. +- [Thirty milestones](learning/MILESTONES.md): M01–M12 background/preliminaries and M13–M30 narrative/innovation; stable understanding targets, earlier dependencies and source pointers. +- [Worked tutorial](learning/TUTORIAL.md): A connected pass through the settled map, including a rank-two qutrit example, total-error accounting, gates and the converse. + +Use the milestone map for the project-wide dependency order, the source bridge for textbook connections, and the scientific pages for complete proofs and exact domains. The map is independent of any reader's progress or assessment history. + ## Claim boundaries The matching law N*=Theta(r k^2/epsilon) holds for k>=r, 1<=r 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..79d865f --- /dev/null +++ b/verification/hosted/math-contract.json @@ -0,0 +1,125 @@ +{ + "schema_version": 1, + "expressions": [ + { + "path": "README.md", + "index": 10, + "source_sha256": "5b33ad9082b9527561ef6200036fa8dc48c9f73bd0b0713f8885b457b0aff2d9", + "expected_text": "1≤r=18" + } + }, + "node_modules/@xmldom/xmldom": { + "version": "0.9.12", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz", + "integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==", + "license": "MIT", + "engines": { + "node": ">=14.6" + } + }, + "node_modules/commander": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz", + "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/esm": { + "version": "3.2.25", + "resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz", + "integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/mathjax-full": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/mathjax-full/-/mathjax-full-3.2.1.tgz", + "integrity": "sha512-aUz9o16MGZdeiIBwZjAfUBTiJb7LRqzZEl1YOZ8zQMGYIyh1/nxRebxKxjDe9L+xcZCr2OHdzoFBMcd6VnLv9Q==", + "license": "Apache-2.0", + "dependencies": { + "esm": "^3.2.25", + "mhchemparser": "^4.1.0", + "mj-context-menu": "^0.6.1", + "speech-rule-engine": "^4.0.6" + } + }, + "node_modules/mhchemparser": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/mhchemparser/-/mhchemparser-4.2.1.tgz", + "integrity": "sha512-kYmyrCirqJf3zZ9t/0wGgRZ4/ZJw//VwaRVGA75C4nhE60vtnIzhl9J9ndkX/h6hxSN7pjg/cE0VxbnNM+bnDQ==", + "license": "Apache-2.0" + }, + "node_modules/mj-context-menu": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/mj-context-menu/-/mj-context-menu-0.6.1.tgz", + "integrity": "sha512-7NO5s6n10TIV96d4g2uDpG7ZDpIhMh0QNfGdJw/W47JswFcosz457wqz/b5sAKvl12sxINGFCn80NZHKwxQEXA==", + "license": "Apache-2.0" + }, + "node_modules/playwright": { + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz", + "integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.56.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz", + "integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/speech-rule-engine": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/speech-rule-engine/-/speech-rule-engine-4.1.5.tgz", + "integrity": "sha512-Nx4d44Ca0FQ4ve9WS8Ja6w2zkI9q7JvH1+3nI9zh4aU/vICXTZWzzYR4MyYRkk/5vcF7OMkwjYkX3qrfahfOgg==", + "license": "Apache-2.0", + "dependencies": { + "@xmldom/xmldom": "^0.9.12", + "commander": "13.1.0", + "wicked-good-xpath": "1.3.0" + }, + "bin": { + "sre": "bin/sre" + } + }, + "node_modules/wicked-good-xpath": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/wicked-good-xpath/-/wicked-good-xpath-1.3.0.tgz", + "integrity": "sha512-Gd9+TUn5nXdwj/hFsPVx5cuHHiF5Bwuc30jZ4+ronF1qHK5O7HD0sgmXWSEgwKquT3ClLoKPVbO6qGwVwLzvAw==", + "license": "MIT" + } + } +} diff --git a/verification/hosted/package.json b/verification/hosted/package.json new file mode 100644 index 0000000..93ffa71 --- /dev/null +++ b/verification/hosted/package.json @@ -0,0 +1,13 @@ +{ + "name": "collective-quantum-programming-hosted-check", + "version": "1.0.0", + "private": true, + "description": "Compare public GitHub mathematics with its exact committed source", + "engines": { + "node": ">=18" + }, + "dependencies": { + "mathjax-full": "3.2.1", + "playwright": "1.56.1" + } +} From 82601f17d23b6ec47bf3e652ffe416770a98d021 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sat, 7 Nov 2026 12:29:33 +0800 Subject: [PATCH 2/2] Repair hosted operator and norm notation without changing the mathematics --- learning/ANCHOR.md | 20 +++++++------- learning/MILESTONES.md | 12 ++++----- learning/TUTORIAL.md | 16 ++++++------ references/RELATED_WORK.md | 6 ++--- science/collision_bound.md | 36 +++++++++++++------------- science/converse.md | 4 +-- science/interpretation.md | 2 +- science/model.md | 10 +++---- science/parallel_program.md | 22 ++++++++-------- science/resources.md | 28 ++++++++++---------- verification/README.md | 2 +- verification/hosted/math-contract.json | 18 ++++++------- 12 files changed, 88 insertions(+), 88 deletions(-) diff --git a/learning/ANCHOR.md b/learning/ANCHOR.md index 28031d5..3a772c5 100644 --- a/learning/ANCHOR.md +++ b/learning/ANCHOR.md @@ -24,17 +24,17 @@ These are foundations for the local arguments. The compressed-variance estimate, | A vector $`u`$, its outer product $`uu^*`$, and an adjoint $`X^*`$ | $`\lvert u\rangle`$, $`\lvert u\rangle\langle u\rvert`$, and $`X^\dagger`$. These are changes of notation. | | $`\mathrm L(\mathcal X)`$ and $`\mathrm D(\mathcal X)`$ | $`\mathsf L(A)`$ and $`\mathsf D(A)`$: operators and density operators on the indicated space. | | A projection $`\Pi`$ onto a subspace | $`P`$ is the unknown support projector; $`\rho_P=P/r`$ is the supplied state. | -| Schatten norms $`\|X\|_1`$ and $`\|X\|_\infty`$ | The same trace and operator norms. The subscript identifies which norm is used. | -| Fidelity $`F(\rho,\sigma)`$ in Definition 3.11 | Root fidelity $`f(\rho,\sigma)=\|\sqrt\rho\sqrt\sigma\|_1`$. Thus $`F=f`$, not $`f^2`$. | -| Completely bounded trace norm $`\lvert\!\lvert\!\lvert\Phi\rvert\!\rvert\!\rvert_1`$ in Definition 3.43 | Diamond norm $`\|\Phi\|_\diamond`$, with no factor of one-half. | +| Schatten norms $`\Vert X\Vert_1`$ and $`\Vert X\Vert_\infty`$ | The same trace and operator norms. The subscript identifies which norm is used. | +| Fidelity $`F(\rho,\sigma)`$ in Definition 3.11 | Root fidelity $`f(\rho,\sigma)=\Vert\sqrt\rho\sqrt\sigma\Vert_1`$. Thus $`F=f`$, not $`f^2`$. | +| Completely bounded trace norm $`\lvert\!\lvert\!\lvert\Phi\rvert\!\rvert\!\rvert_1`$ in Definition 3.43 | Diamond norm $`\Vert\Phi\Vert_\diamond`$, with no factor of one-half. | -The [model](../science/model.md) measures channel error by the unhalved diamond norm, while the [converse](../science/converse.md) writes state trace distance as $`T(\rho,\sigma)=\frac12\|\rho-\sigma\|_1`$. Consequently, for any input-reference state $`\omega`$, +The [model](../science/model.md) measures channel error by the unhalved diamond norm, while the [converse](../science/converse.md) writes state trace distance as $`T(\rho,\sigma)=\frac12\Vert\rho-\sigma\Vert_1`$. Consequently, for any input-reference state $`\omega`$, ```math -\|\Phi-\Psi\|_\diamond\le\epsilon +\Vert\Phi-\Psi\Vert_\diamond\le\epsilon \quad\Longrightarrow\quad -T\!\left((\Phi\otimes\operatorname{id})(\omega), - (\Psi\otimes\operatorname{id})(\omega)\right) +T\!\left((\Phi\otimes\mathrm{id})(\omega), + (\Psi\otimes\mathrm{id})(\omega)\right) \le\frac{\epsilon}{2}. ``` @@ -57,11 +57,11 @@ M-h^2 =V^\dagger\widehat H(I-VV^\dagger)\widehat H V ``` -measures coupling out of the fixed-program subspace. This is the bridge from channel representation to the local variance estimate. The proof separates the Kraus contribution that remains in that subspace from a completely positive leakage contribution. Both contribute at second order, giving $`\|\Phi_\tau-\mathcal U_\tau\|_\diamond\le2\tau^2\|M-h^2\|_\infty`$ for collision duration $`\tau`$. Here $`\Phi_\tau`$ is the reduced collision channel and $`\mathcal U_\tau`$ is the unitary channel generated by $`h`$. The interaction-picture estimate and its constant are supplied by the project, rather than by the representation theorem alone. +measures coupling out of the fixed-program subspace. This is the bridge from channel representation to the local variance estimate. The proof separates the Kraus contribution that remains in that subspace from a completely positive leakage contribution. Both contribute at second order, giving $`\Vert\Phi_\tau-\mathcal U_\tau\Vert_\diamond\le2\tau^2\Vert M-h^2\Vert_\infty`$ for collision duration $`\tau`$. Here $`\Phi_\tau`$ is the reduced collision channel and $`\mathcal U_\tau`$ is the unitary channel generated by $`h`$. The interaction-picture estimate and its constant are supplied by the project, rather than by the representation theorem alone. ## From a shared specimen to the parallel law -The [parallel construction](../science/parallel_program.md) uses one fresh program register $`a`$ in the interaction $`H_* = \sum_j S_{a,j}`$, where $`S_{a,j}`$ swaps that register with target $`j`$. The program state is $`\rho=P/r`$, and the register is discarded after the collision. Its mean is $`h=\sum_j\rho_j`$, where $`\rho_j`$ acts as $`\rho`$ on target $`j`$ and as the identity on the other targets. The intended evolution therefore factors into the same operation on every target. The second moment contains cross terms whose norm is controlled by $`\|\rho\|_\infty=1/r`$. Evaluating those terms is the project-specific step that improves the copy count. +The [parallel construction](../science/parallel_program.md) uses one fresh program register $`a`$ in the interaction $`H_* = \sum_j S_{a,j}`$, where $`S_{a,j}`$ swaps that register with target $`j`$. The program state is $`\rho=P/r`$, and the register is discarded after the collision. Its mean is $`h=\sum_j\rho_j`$, where $`\rho_j`$ acts as $`\rho`$ on target $`j`$ and as the identity on the other targets. The intended evolution therefore factors into the same operation on every target. The second moment contains cross terms whose norm is controlled by $`\Vert\rho\Vert_\infty=1/r`$. Evaluating those terms is the project-specific step that improves the copy count. Proposition 3.48 supplies the composition rule needed to accumulate the collision errors. Its use is reference-stable: other targets can remain part of the reference while one group is processed. Fresh specimens give repeated copies of the same reduced channel; independent groups give a product of group channels. The resulting $`O((r^2k+rk^2)/\epsilon)`$ bound concerns the complete parallel output. Joint availability of the targets within a group remains part of the construction. @@ -80,7 +80,7 @@ Channel composition bounds the error of the implemented experiment, while trace- ## From channel accuracy to finite gates -The norm inequalities in §1.1.3 and the composition rule in Proposition 3.48 connect an implementation error to the promised output error. The [resource account](../science/resources.md) makes this connection explicit through $`\|\operatorname{Ad}_U-\operatorname{Ad}_V\|_\diamond\le2\|U-V\|_\infty`$, then allocates error among collisions, symmetric sweeps, and rotation synthesis. +The norm inequalities in §1.1.3 and the composition rule in Proposition 3.48 connect an implementation error to the promised output error. The [resource account](../science/resources.md) makes this connection explicit through $`\Vert\mathrm{Ad}_U-\mathrm{Ad}_V\Vert_\diamond\le2\Vert U-V\Vert_\infty`$, then allocates error among collisions, symmetric sweeps, and rotation synthesis. The controlled-swap gadget, its returned work qubit, the sweep remainder, and the gate counts are developed in that account. Finite-gate synthesis uses the attributed Dawson–Nielsen result. Ideal rotations return the work qubit exactly; approximate synthesis controls its return jointly with the data-channel error. Source preparation and storage remain separately charged resources. diff --git a/learning/MILESTONES.md b/learning/MILESTONES.md index bbdcc19..34c6b0e 100644 --- a/learning/MILESTONES.md +++ b/learning/MILESTONES.md @@ -86,7 +86,7 @@ Dependencies refer only to earlier milestone IDs. They describe mathematical and **Central question.** Which operator estimates can control a physical error without introducing a dimension factor? -**Understanding target.** Distinguish the operator norm $`\|\cdot\|_\infty`$ from the trace norm $`\|\cdot\|_1`$. Use positive-operator order, the largest eigenvalue of a positive operator, unitary invariance, and trace-norm product bounds to interpret compression and leakage estimates. +**Understanding target.** Distinguish the operator norm $`\Vert\cdot\Vert_\infty`$ from the trace norm $`\Vert\cdot\Vert_1`$. Use positive-operator order, the largest eigenvalue of a positive operator, unitary invariance, and trace-norm product bounds to interpret compression and leakage estimates. **Dependencies and story role.** [M01](#m01), [M05](#m05). This introduces the quantitative language used in both the local channel estimate and the exact variance calculation. @@ -100,7 +100,7 @@ Dependencies refer only to earlier milestone IDs. They describe mathematical and **Central question.** How does distance between two states limit the ability to tell them apart? -**Understanding target.** Interpret $`T(\alpha,\beta)=\tfrac12\|\alpha-\beta\|_1`$ through optimal binary discrimination. Explain its contractivity under a fixed channel and keep its factor of one-half distinct from the project's unhalved channel-error convention. +**Understanding target.** Interpret $`T(\alpha,\beta)=\tfrac12\Vert\alpha-\beta\Vert_1`$ through optimal binary discrimination. Explain its contractivity under a fixed channel and keep its factor of one-half distinct from the project's unhalved channel-error convention. **Dependencies and story role.** [M04](#m04), [M06](#m06). This gives an operational meaning to a state-distance bound. @@ -114,7 +114,7 @@ Dependencies refer only to earlier milestone IDs. They describe mathematical and **Central question.** How can single-specimen overlap control the distinguishability of many independent specimens? -**Understanding target.** Use root fidelity $`f(\alpha,\beta)=\|\sqrt\alpha\sqrt\beta\|_1`$, its multiplicativity on tensor products, and the inequality $`T\le\sqrt{1-f^2}`$. Explain why the iid source promise permits a single-copy fidelity calculation to control the full program input. +**Understanding target.** Use root fidelity $`f(\alpha,\beta)=\Vert\sqrt\alpha\sqrt\beta\Vert_1`$, its multiplicativity on tensor products, and the inequality $`T\le\sqrt{1-f^2}`$. Explain why the iid source promise permits a single-copy fidelity calculation to control the full program input. **Dependencies and story role.** [M05](#m05), [M07](#m07). This turns local state overlap into a quantitative constraint on a source budget. @@ -200,7 +200,7 @@ Dependencies refer only to earlier milestone IDs. They describe mathematical and **Central question.** Which correlations appear when the same specimen participates in two different target interactions? -**Understanding target.** Track the order in $`\mathcal E_\rho(S_{a,i}S_{a,j})=\rho_jS_{i,j}`$ and interpret the second moment $`M=\mathcal E_\rho(H_*^2)`$. Explain the separate single-swap and cross-target contributions to $`\|M\|_\infty=k+k(k-1)/r`$. +**Understanding target.** Track the order in $`\mathcal E_\rho(S_{a,i}S_{a,j})=\rho_jS_{i,j}`$ and interpret the second moment $`M=\mathcal E_\rho(H_*^2)`$. Explain the separate single-swap and cross-target contributions to $`\Vert M\Vert_\infty=k+k(k-1)/r`$. **Dependencies and story role.** [M06](#m06), [M13](#m13). This identifies the rank-dependent structure that a full interaction-norm bound would discard. @@ -214,7 +214,7 @@ Dependencies refer only to earlier milestone IDs. They describe mathematical and **Central question.** Which part of the joint interaction differs from the desired mean evolution? -**Understanding target.** Interpret the positive operator $`M-h^2`$ and its norm $`v=\|M-h^2\|_\infty`$. Use the purification isometry $`V`$ to relate this variance to coupling out of the fixed-environment subspace, and understand why subtracting the mean isolates the relevant fluctuation. +**Understanding target.** Interpret the positive operator $`M-h^2`$ and its norm $`v=\Vert M-h^2\Vert_\infty`$. Use the purification isometry $`V`$ to relate this variance to coupling out of the fixed-environment subspace, and understand why subtracting the mean isolates the relevant fluctuation. **Dependencies and story role.** [M05](#m05), [M06](#m06), [M13](#m13), [M14](#m14). This converts the raw moment calculation into the quantity that controls the error. @@ -228,7 +228,7 @@ Dependencies refer only to earlier milestone IDs. They describe mathematical and **Central question.** How does the centered fluctuation produce a nonasymptotic channel-error estimate? -**Understanding target.** Connect the compressed Kraus operator's deviation from the intended unitary with the remaining completely positive leakage map. Explain why the two contributions give $`\|\Phi_\delta-\mathcal U_\delta\|_\diamond\le2\delta^2v`$ for a collision of duration $`\delta`$, including every reference input. +**Understanding target.** Connect the compressed Kraus operator's deviation from the intended unitary with the remaining completely positive leakage map. Explain why the two contributions give $`\Vert\Phi_\delta-\mathcal U_\delta\Vert_\diamond\le2\delta^2v`$ for a collision of duration $`\delta`$, including every reference input. **Dependencies and story role.** [M05](#m05), [M06](#m06), [M09](#m09), [M15](#m15). This completes the local analytical mechanism before specializing its variance. diff --git a/learning/TUTORIAL.md b/learning/TUTORIAL.md index c20c8ae..09ae8ff 100644 --- a/learning/TUTORIAL.md +++ b/learning/TUTORIAL.md @@ -6,7 +6,7 @@ Follow this route alongside the [30 milestones](MILESTONES.md). The [Watrous bri ## 1. From a specimen to an operation -**Milestones [M01–M06](MILESTONES.md#m01).** Let $`P`$ be an orthogonal projector of known rank $`r`$ on a $`d`$-dimensional register. A specimen has density operator $`\rho_P=P/r`$. It assigns equal weight to every direction in the range of $`P`$, and zero weight to its orthogonal complement. Its trace is one because $`\operatorname{Tr}P=r`$. +**Milestones [M01–M06](MILESTONES.md#m01).** Let $`P`$ be an orthogonal projector of known rank $`r`$ on a $`d`$-dimensional register. A specimen has density operator $`\rho_P=P/r`$. It assigns equal weight to every direction in the range of $`P`$, and zero weight to its orthogonal complement. Its trace is one because $`\mathrm{Tr}\,P=r`$. The desired unitary is $`R_P=I-2P`$. A vector in the range of $`P`$ acquires phase $`-1`$; a vector in the complement acquires phase $`+1`$. The ordinary channel acts on a density operator $`X`$ as $`X\mapsto R_PXR_P`$. A common phase on the entire vector cancels in this expression, while a relative phase between its components can change the state. @@ -19,8 +19,8 @@ The processor receives $`N`$ independent specimens of the same unknown $`P/r`$ a Write $`\mathcal E_{P,N}`$ for its implemented batch channel and $`\mathcal R_P^{(k)}`$ for the ideal channel of $`R_P^{\otimes k}`$. The requirement is ```math -\sup_{\operatorname{rank}P=r} -\|\mathcal E_{P,N}-\mathcal R_P^{(k)}\|_\diamond +\sup_{\mathrm{rank}\,P=r} +\Vert\mathcal E_{P,N}-\mathcal R_P^{(k)}\Vert_\diamond \le\epsilon. ``` @@ -33,9 +33,9 @@ The input resource is a hard budget of independent specimens. Knowing $`r`$ does **Milestones [M13–M15](MILESTONES.md#m13).** Take $`d=3`$, $`r=2`$ and $`k=2`$. For explaining the action, choose coordinates in which ```math -P=\operatorname{diag}(1,1,0),\qquad -\rho_P=\operatorname{diag}(1/2,1/2,0),\qquad -R_P=\operatorname{diag}(-1,-1,1). +P=\mathrm{diag}(1,1,0),\qquad +\rho_P=\mathrm{diag}(1/2,1/2,0),\qquad +R_P=\mathrm{diag}(-1,-1,1). ``` The implementation is not supplied these coordinates. Its gates are swaps, which work for every orientation of the unknown support. @@ -58,14 +58,14 @@ e^{-i\pi r h}=R_P^{\otimes2}. Here $`\rho_{P,j}`$ acts on target $`j`$ and as the identity on the other target. The two terms commute. Each eigenvalue $`1/r`$ therefore acquires phase $`e^{-i\pi}=-1`$ after time $`\pi r`$. -A finite collision also fluctuates around this mean action. Define $`M`$ as the program expectation of $`H_*^2`$ and $`v=\|M-h^2\|_\infty`$. In an analytical purification, this variance measures the coupling out of the subspace in which the purified environment remains fixed. +A finite collision also fluctuates around this mean action. Define $`M`$ as the program expectation of $`H_*^2`$ and $`v=\Vert M-h^2\Vert_\infty`$. In an analytical purification, this variance measures the coupling out of the subspace in which the purified environment remains fixed. ## 4. Turning local error into a specimen count **Milestones [M16–M20](MILESTONES.md#m16).** The [collision lemma](../science/collision_bound.md) proves, for every real collision duration $`\delta`$, ```math -\|\Phi_\delta-\operatorname{Ad}_{e^{-i\delta h}}\|_\diamond +\Vert\Phi_\delta-\mathrm{Ad}_{e^{-i\delta h}}\Vert_\diamond \le2\delta^2v. ``` diff --git a/references/RELATED_WORK.md b/references/RELATED_WORK.md index e289f01..18a151d 100644 --- a/references/RELATED_WORK.md +++ b/references/RELATED_WORK.md @@ -25,13 +25,13 @@ For $`\rho_P=P/r`$, evolution for time $`t=\pi r`$ gives $`e^{-it\rho_P}=R_P`$. ## HME supplies the collective interaction -[Wei et al. (2024)](https://doi.org/10.1038/s41534-024-00949-z) introduced Hermitian-preserving map exponentiation (HME). For a Hermitian-preserving linear map $`\mathcal N`$, their processor uses the interaction $`H=\operatorname{Choi}(\mathcal N)^{T_{\mathrm{in}}}`$ to simulate $`e^{-it\mathcal N(\rho)}`$. Taking $`\mathcal N(\rho)=\sum_{j=1}^k\rho_j`$ gives exactly +[Wei et al. (2024)](https://doi.org/10.1038/s41534-024-00949-z) introduced Hermitian-preserving map exponentiation (HME). For a Hermitian-preserving linear map $`\mathcal N`$, their processor uses the interaction $`H=\mathrm{Choi}(\mathcal N)^{T_{\mathrm{in}}}`$ to simulate $`e^{-it\mathcal N(\rho)}`$. Taking $`\mathcal N(\rho)=\sum_{j=1}^k\rho_j`$ gives exactly ```math -H_\star=\sum_{j=1}^k\operatorname{SWAP}_{a,j}, +H_\star=\sum_{j=1}^k\mathrm{SWAP}_{a,j}, ``` -where $`a`$ is the program register. Thus HME already supplies the interaction used here. Its generic $`O(t^2\|H\|_\infty^2/\varepsilon)`$ sample bound gives $`O(r^2k^2/\varepsilon)`$ for this choice. +where $`a`$ is the program register. Thus HME already supplies the interaction used here. Its generic $`O(t^2\Vert H\Vert_\infty^2/\varepsilon)`$ sample bound gives $`O(r^2k^2/\varepsilon)`$ for this choice. State-sensitive improvements also have a direct HME precedent. Appendix C.2, Proposition 3 and Lemma 6 of the [2023 preprint, v1](https://arxiv.org/html/2308.07956v1#A3.SS2), improve the partial-transpose simulation bound from a quadratic to a linear factor in the transposed subsystem dimension. That analysis controls mixed higher moments and retains a marginal-state operator norm. The refinement here evaluates the compressed variance of $`H_\star`$ for $`P/r`$, producing the different dependence $`r^2k+rk^2`$. It uses this established approach to obtain the parallel programming law. diff --git a/science/collision_bound.md b/science/collision_bound.md index 8e6ed16..5a35d12 100644 --- a/science/collision_bound.md +++ b/science/collision_bound.md @@ -8,7 +8,7 @@ Let $`A`$ and $`E`$ be finite-dimensional data and environment spaces. Fix a sta ```math \mathcal E_\sigma(Y) -=\operatorname{Tr}_E\!\left[ +=\mathrm{Tr}_E\!\left[ (I_A\otimes\sigma^{1/2})Y(I_A\otimes\sigma^{1/2}) \right]. ``` @@ -17,8 +17,8 @@ Partial-trace cyclicity on the environment also gives ```math \mathcal E_\sigma(Y) -=\operatorname{Tr}_E\!\left[(I_A\otimes\sigma)Y\right] -=\operatorname{Tr}_E\!\left[Y(I_A\otimes\sigma)\right]. +=\mathrm{Tr}_E\!\left[(I_A\otimes\sigma)Y\right] +=\mathrm{Tr}_E\!\left[Y(I_A\otimes\sigma)\right]. ``` This is a unital completely positive map. It is an analytical expectation, not an operation that the processor must evaluate. Define operators on $`A`$ and a scalar by @@ -26,7 +26,7 @@ This is a unital completely positive map. It is an analytical expectation, not a ```math h=\mathcal E_\sigma(H),\qquad M=\mathcal E_\sigma(H^2),\qquad -v=\|M-h^2\|_\infty. +v=\Vert M-h^2\Vert_\infty. ``` The operator $`M-h^2`$ is positive. To see its meaning, choose an auxiliary space $`F`$ and a purification $`|s\rangle\in E\otimes F`$ of $`\sigma`$. Let $`V:A\to A\otimes E\otimes F`$ be the isometry $`V|x\rangle=|x\rangle\otimes|s\rangle`$, and put $`\widehat H=H\otimes I_F`$. Then @@ -51,7 +51,7 @@ For real $`\tau`$, define the physical collision channel and its intended unitar ```math \Phi_\tau(X) -=\operatorname{Tr}_E\!\left[ +=\mathrm{Tr}_E\!\left[ e^{-i\tau H}(X\otimes\sigma)e^{i\tau H} \right],\qquad \mathcal U_\tau(X)=e^{-i\tau h}Xe^{i\tau h}. @@ -60,7 +60,7 @@ e^{-i\tau H}(X\otimes\sigma)e^{i\tau H} **Lemma.** For every real $`\tau`$, ```math -\|\Phi_\tau-\mathcal U_\tau\|_\diamond\le2\tau^2v. +\Vert\Phi_\tau-\mathcal U_\tau\Vert_\diamond\le2\tau^2v. ``` The norm is unhalved. The statement has no small-time assumption, dimension factor, or omitted higher-order remainder. @@ -86,7 +86,7 @@ Each $`K_s`$ is Hermitian. Define $`C=\widehat H V-Vh`$. The relations $`V^\dagg ```math V^\dagger K_sV=0,\qquad K_sV=(u_s^\dagger\otimes I_{EF})Cu_s,\qquad -\|K_sV\|_\infty=\sqrt v. +\Vert K_sV\Vert_\infty=\sqrt v. ``` Let $`U_K(s,a)`$ denote the unitary propagator generated by $`K_s`$ between times $`a`$ and $`s`$. Variation of constants, with the fixed isometry $`V`$ as comparison, gives @@ -98,7 +98,7 @@ W_s-V=-i\int_0^s U_K(s,a)K_aV\,da. Consequently, ```math -\|W_s-V\|_\infty\le s\sqrt v. +\Vert W_s-V\Vert_\infty\le s\sqrt v. ``` Now compress back to the fixed-environment subspace. The operator $`B_s=V^\dagger W_s`$ acts on $`A`$ and is a contraction. Since $`V^\dagger K_sV=0`$, @@ -108,10 +108,10 @@ B_\tau-I_A =-i\int_0^\tau V^\dagger K_s(W_s-V)\,ds. ``` -Hermiticity of $`K_s`$ gives $`\|V^\dagger K_s\|_\infty=\|K_sV\|_\infty=\sqrt v`$. It follows that +Hermiticity of $`K_s`$ gives $`\Vert V^\dagger K_s\Vert_\infty=\Vert K_sV\Vert_\infty=\sqrt v`$. It follows that ```math -\|B_\tau-I_A\|_\infty +\Vert B_\tau-I_A\Vert_\infty \le\int_0^\tau sv\,ds =\frac{\tau^2v}{2}. ``` @@ -127,16 +127,16 @@ Choose an orthonormal basis of $`E\otimes F`$ whose first vector is $`|s\rangle` where $`\mathcal L_\tau`$ is the completely positive contribution from the remaining environment basis vectors. Define its Stinespring operator $`F_\tau=(I-VV^\dagger)W_\tau`$. Then ```math -\mathcal L_\tau(X)=\operatorname{Tr}_{EF}(F_\tau X F_\tau^\dagger),\qquad +\mathcal L_\tau(X)=\mathrm{Tr}_{EF}(F_\tau X F_\tau^\dagger),\qquad F_\tau^\dagger F_\tau=I_A-B_\tau^\dagger B_\tau. ``` -For a completely positive map of this form, its diamond norm equals $`\|F_\tau^\dagger F_\tau\|_\infty`$. The upper bound follows by tracing its positive output on an arbitrary input-reference state, and equality is attained by an eigenvector of $`F_\tau^\dagger F_\tau`$ with maximal eigenvalue. Because $`(I-VV^\dagger)V=0`$, +For a completely positive map of this form, its diamond norm equals $`\Vert F_\tau^\dagger F_\tau\Vert_\infty`$. The upper bound follows by tracing its positive output on an arbitrary input-reference state, and equality is attained by an eigenvector of $`F_\tau^\dagger F_\tau`$ with maximal eigenvalue. Because $`(I-VV^\dagger)V=0`$, ```math -\|\mathcal L_\tau\|_\diamond -=\|F_\tau\|_\infty^2 -\le\|W_\tau-V\|_\infty^2 +\Vert\mathcal L_\tau\Vert_\diamond +=\Vert F_\tau\Vert_\infty^2 +\le\Vert W_\tau-V\Vert_\infty^2 \le\tau^2v. ``` @@ -151,11 +151,11 @@ B_\tau X B_\tau^\dagger-X and the trace-norm product inequality remain valid after tensoring every operator with the identity on a reference. Hence ```math -\|X\mapsto B_\tau X B_\tau^\dagger-X\|_\diamond -\le(\|B_\tau\|_\infty+1)\|B_\tau-I_A\|_\infty +\Vert X\mapsto B_\tau X B_\tau^\dagger-X\Vert_\diamond +\le(\Vert B_\tau\Vert_\infty+1)\Vert B_\tau-I_A\Vert_\infty \le\tau^2v. ``` -Adding the leakage contribution gives $`\|\Psi_\tau-\operatorname{id}_A\|_\diamond\le2\tau^2v`$. Unitary postprocessing preserves diamond distance, so the same bound holds between $`\Phi_\tau`$ and $`\mathcal U_\tau`$. +Adding the leakage contribution gives $`\Vert\Psi_\tau-\mathrm{id}_A\Vert_\diamond\le2\tau^2v`$. Unitary postprocessing preserves diamond distance, so the same bound holds between $`\Phi_\tau`$ and $`\mathcal U_\tau`$. This estimate retains a program-dependent variance instead of replacing it immediately by the norm of the full interaction. Moment-sensitive analysis already appears in HME; its relation to the present application is described in [RELATED_WORK.md](../references/RELATED_WORK.md). The next step is the explicit variance evaluation for [parallel reflections](parallel_program.md). diff --git a/science/converse.md b/science/converse.md index 59ade91..6b211b9 100644 --- a/science/converse.md +++ b/science/converse.md @@ -34,8 +34,8 @@ The second sum is empty when $`r=1`$. Both projectors have rank $`r`$; the direc For states $`\alpha`$ and $`\beta`$, define the root fidelity and trace distance by ```math -f(\alpha,\beta)=\|\sqrt\alpha\sqrt\beta\|_1,\qquad -T(\alpha,\beta)=\frac12\|\alpha-\beta\|_1. +f(\alpha,\beta)=\Vert\sqrt\alpha\sqrt\beta\Vert_1,\qquad +T(\alpha,\beta)=\frac12\Vert\alpha-\beta\Vert_1. ``` The nonzero singular values of $`P_0P_\theta`$ are $`r-1`$ copies of one and one value $`\cos\theta`$. Therefore the exact single-specimen root fidelity is diff --git a/science/interpretation.md b/science/interpretation.md index d1b4ce3..6241c99 100644 --- a/science/interpretation.md +++ b/science/interpretation.md @@ -15,7 +15,7 @@ The statement is uniform in the register dimension $`d>r`$. It concerns the copi One program register interacts with several targets before it is discarded. Its mean action generates the desired product unitary. Its fluctuations introduce error, including correlations among the targets. For the swap-star interaction on $`k`$ targets, the conditional second moment is ```math -\|M\|_\infty=k+\frac{k(k-1)}r. +\Vert M\Vert_\infty=k+\frac{k(k-1)}r. ``` The first term comes from using each individual swap twice. The second comes from pairs of different target interactions and is suppressed by the flat program's eigenvalue $`1/r`$. After evolution for time $`\pi r`$, the resulting sample upper bound is diff --git a/science/model.md b/science/model.md index 7dc642f..63eb6fe 100644 --- a/science/model.md +++ b/science/model.md @@ -41,12 +41,12 @@ The hard source budget is $`N`$ specimens. A processor may discard unused specim ## Joint accuracy -For an operator $`X`$, write $`\|X\|_1=\operatorname{Tr}\sqrt{X^\dagger X}`$ and let $`\|X\|_\infty`$ denote its operator norm. The error convention is the **unhalved diamond norm**. For the difference $`\Delta`$ of two channels on $`A`$, +For an operator $`X`$, write $`\Vert X\Vert_1=\mathrm{Tr}\,\sqrt{X^\dagger X}`$ and let $`\Vert X\Vert_\infty`$ denote its operator norm. The error convention is the **unhalved diamond norm**. For the difference $`\Delta`$ of two channels on $`A`$, ```math -\|\Delta\|_\diamond +\Vert\Delta\Vert_\diamond =\sup_{\omega\in\mathsf D(A\otimes Z)} -\left\|(\Delta\otimes\operatorname{id}_Z)(\omega)\right\|_1, +\left\Vert(\Delta\otimes\mathrm{id}_Z)(\omega)\right\Vert_1, \qquad \dim Z=\dim A=d^k. ``` @@ -55,8 +55,8 @@ The set $`\mathsf D(B)`$ contains the density operators on $`B`$. The reference A processor is $`\epsilon`$-accurate if ```math -\sup_{P:\,P^2=P=P^\dagger,\ \operatorname{rank}P=r} -\left\|\widetilde{\mathcal R}_P-\mathcal R_P^{(k)}\right\|_\diamond +\sup_{P:\,P^2=P=P^\dagger,\ \mathrm{rank}\,P=r} +\left\Vert\widetilde{\mathcal R}_P-\mathcal R_P^{(k)}\right\Vert_\diamond \le\epsilon. ``` diff --git a/science/parallel_program.md b/science/parallel_program.md index 3a48a3a..5e42515 100644 --- a/science/parallel_program.md +++ b/science/parallel_program.md @@ -16,7 +16,7 @@ Use the data-first tensor order and the program expectation ```math \mathcal E_\rho(Y) -=\operatorname{Tr}_a\!\left[(I_A\otimes\rho)Y\right] +=\mathrm{Tr}_a\!\left[(I_A\otimes\rho)Y\right] ``` defined in [collision_bound.md](collision_bound.md). The swap identities are @@ -39,10 +39,10 @@ M=\mathcal E_\rho(H_*^2) =kI_A+\sum_{1\le i\lt j\le k}(\rho_i+\rho_j)S_{i,j}. ``` -The pair factor $`\rho_i+\rho_j`$ commutes with $`S_{i,j}`$. Since $`\|\rho\|_\infty=1/r`$, the triangle inequality gives $`\|M\|_\infty\le k+k(k-1)/r`$. Equality is attained on $`|v\rangle^{\otimes k}`$ for any unit vector $`|v\rangle`$ in the range of $`P`$. Therefore +The pair factor $`\rho_i+\rho_j`$ commutes with $`S_{i,j}`$. Since $`\Vert\rho\Vert_\infty=1/r`$, the triangle inequality gives $`\Vert M\Vert_\infty\le k+k(k-1)/r`$. Equality is attained on $`|v\rangle^{\otimes k}`$ for any unit vector $`|v\rangle`$ in the range of $`P`$. Therefore ```math -\|M\|_\infty=k+\frac{k(k-1)}{r}. +\Vert M\Vert_\infty=k+\frac{k(k-1)}{r}. ``` ## Exact variance @@ -72,7 +72,7 @@ The left side is positive by the collision lemma. In the sector with support cou \left(k+\frac{(k-1)m}{r}-\frac{m^2}{r^2}\right)I_A. ``` -Every sector bound is attained. Choose unit vectors $`|v\rangle\in\operatorname{ran}P`$ and $`|w\rangle\in\ker P`$. For a subset $`T\subseteq\{1,\ldots,k\}`$, define $`|x_j(T)\rangle=|v\rangle`$ when $`j\in T`$ and $`|x_j(T)\rangle=|w\rangle`$ otherwise. The normalized symmetric vector +Every sector bound is attained. Choose unit vectors $`|v\rangle\in\mathrm{ran}\,P`$ and $`|w\rangle\in\ker P`$. For a subset $`T\subseteq\{1,\ldots,k\}`$, define $`|x_j(T)\rangle=|v\rangle`$ when $`j\in T`$ and $`|x_j(T)\rangle=|w\rangle`$ otherwise. The normalized symmetric vector ```math |D_{k,m}\rangle @@ -83,7 +83,7 @@ Every sector bound is attained. Choose unit vectors $`|v\rangle\in\operatorname{ satisfies $`C_P|D_{k,m}\rangle=m|D_{k,m}\rangle`$ and $`S_{i,j}|D_{k,m}\rangle=|D_{k,m}\rangle`$ for every pair. It attains equality in the summed inequality above. The exact variance is consequently ```math -v_{r,k}:=\|M-h^2\|_\infty +v_{r,k}:=\Vert M-h^2\Vert_\infty =\max_{m\in\{0,\ldots,k\}} \left(k+\frac{(k-1)m}{r}-\frac{m^2}{r^2}\right). ``` @@ -102,7 +102,7 @@ For real $`\delta`$, one exact collective collision is ```math \Phi_\delta(X) -=\operatorname{Tr}_a\!\left[ +=\mathrm{Tr}_a\!\left[ e^{-i\delta H_*}(X\otimes\rho)e^{i\delta H_*} \right]. ``` @@ -110,7 +110,7 @@ e^{-i\delta H_*}(X\otimes\rho)e^{i\delta H_*} The intended one-step channel is $`\mathcal U_\delta(X)=e^{-i\delta h}Xe^{i\delta h}`$. The [variance lemma](collision_bound.md) gives ```math -\|\Phi_\delta-\mathcal U_\delta\|_\diamond +\Vert\Phi_\delta-\mathcal U_\delta\Vert_\diamond \le2\delta^2v_{r,k}. ``` @@ -119,8 +119,8 @@ Take $`N\ge1`$ fresh specimens, let $`t`$ be the total intended evolution time, Telescoping the two channel products and using diamond norm one for every channel gives ```math -\|\Phi_{t/N}^N-\mathcal U_{t/N}^N\|_\diamond -\le N\|\Phi_{t/N}-\mathcal U_{t/N}\|_\diamond +\Vert\Phi_{t/N}^N-\mathcal U_{t/N}^N\Vert_\diamond +\le N\Vert\Phi_{t/N}-\mathcal U_{t/N}\Vert_\diamond \le\frac{2t^2v_{r,k}}{N}. ``` @@ -133,7 +133,7 @@ e^{-ith}=\bigotimes_{j=1}^k e^{-it\rho}. At $`t=\pi r`$, each factor is $`e^{-i\pi P}=I-2P=R_P`$. Therefore ```math -\|\Phi_{\pi r/N}^N-\mathcal R_P^{(k)}\|_\diamond +\Vert\Phi_{\pi r/N}^N-\mathcal R_P^{(k)}\Vert_\diamond \le\frac{2\pi^2r^2v_{r,k}}{N} \le\frac{2\pi^2rk(r+k-1)}{N}. ``` @@ -147,7 +147,7 @@ The collective exponential is implemented by a symmetric sweep of known pair par Let $`\widehat\Phi_\delta`$ denote the collision channel obtained from this sweep, with its program discarded. Unitary-channel distance is at most twice the operator distance, and preparing or discarding a program cannot increase it. Over $`N`$ specimens at $`\delta=\pi r/N`$, ```math -\|\widehat\Phi_{\pi r/N}^N-\mathcal R_P^{(k)}\|_\diamond +\Vert\widehat\Phi_{\pi r/N}^N-\mathcal R_P^{(k)}\Vert_\diamond \le\frac{2\pi^2rk(r+k-1)}{N} +\frac{2\pi^3r^3k^3}{3N^2}. ``` diff --git a/science/resources.md b/science/resources.md index 686e373..bd2a43d 100644 --- a/science/resources.md +++ b/science/resources.md @@ -28,7 +28,7 @@ W_S\bigl(|0\rangle_a|\psi_s\rangle\bigr) =\left|\frac{1-s}{2}\right\rangle_a|\psi_s\rangle. ``` -With the convention $`R_z(\theta)=\operatorname{diag}(e^{-i\theta/2},e^{i\theta/2})`$, the circuit +With the convention $`R_z(\theta)=\mathrm{diag}(e^{-i\theta/2},e^{i\theta/2})`$, the circuit ```math W_S\bigl(R_z(2\alpha)_a\otimes I\bigr)W_S @@ -72,7 +72,7 @@ This sweep contains $`2b-1`$ pair partial swaps. For $`b=1`$, it is the exact co The operator-norm estimate ```math -\left\|T_b(\delta)-e^{-i\delta H_b}\right\|_\infty +\left\Vert T_b(\delta)-e^{-i\delta H_b}\right\Vert_\infty \le \frac{b^3|\delta|^3}{3} ``` @@ -88,13 +88,13 @@ T_b''(0)=-H_b^2. The first derivative follows by differentiating the factors. The palindromic order gives $`T_b(\delta)T_b(-\delta)=I`$; expanding this identity to second order gives the second derivative. -Every factor is unitary, every swap has norm one, and the sum of the absolute generator weights in the product is $`b`$. The Leibniz expansion therefore bounds the norm of its third derivative by $`b^3`$, at every real argument. The exact exponential has the same derivative bound because $`\|H_b\|_\infty\le b`$. Both functions have identical Taylor terms through second order. Applying the integral remainder to each gives the displayed $`b^3|\delta|^3/3`$ estimate. +Every factor is unitary, every swap has norm one, and the sum of the absolute generator weights in the product is $`b`$. The Leibniz expansion therefore bounds the norm of its third derivative by $`b^3`$, at every real argument. The exact exponential has the same derivative bound because $`\Vert H_b\Vert_\infty\le b`$. Both functions have identical Taylor terms through second order. Applying the integral remainder to each gives the displayed $`b^3|\delta|^3/3`$ estimate. For unitaries $`U,V`$, ```math -\|\operatorname{Ad}_U-\operatorname{Ad}_V\|_\diamond -\le 2\|U-V\|_\infty. +\Vert\mathrm{Ad}_U-\mathrm{Ad}_V\Vert_\diamond +\le 2\Vert U-V\Vert_\infty. ``` Preparing and discarding a program register are channel contractions. Consequently, replacing one exact collective collision by its symmetric sweep changes the resulting data channel by at most $`2b^3|\delta|^3/3`$ in unhalved diamond norm. Symmetry removes the second-order product error that a first-order sweep would introduce. @@ -104,8 +104,8 @@ Preparing and discarding a program register are channel contractions. Consequent The [collision bound](collision_bound.md) gives the ideal reduced-channel error for $`N`$ fresh programs, each interacting for $`\delta=\pi r/N`$: ```math -\left\|\Phi_{\pi r/N}^{N} - -\operatorname{Ad}_{R_P^{\otimes b}}\right\|_\diamond +\left\Vert\Phi_{\pi r/N}^{N} + -\mathrm{Ad}_{R_P^{\otimes b}}\right\Vert_\diamond \le \frac{2\pi^2r^2v_b}{N}, ``` @@ -121,8 +121,8 @@ v_b Replacing every collision by a symmetric sweep and telescoping over the $`N`$ steps yields ```math -\left\|\widetilde\Phi_{b,N} - -\operatorname{Ad}_{R_P^{\otimes b}}\right\|_\diamond +\left\Vert\widetilde\Phi_{b,N} + -\mathrm{Ad}_{R_P^{\otimes b}}\right\Vert_\diamond \le \frac{2\pi^2 r b(r+b-1)}{N} +\frac{2\pi^3r^3b^3}{3N^2}. @@ -192,18 +192,18 @@ be the numbers of program copies and partial-swap gadgets. There is one variable up to an irrelevant global phase. Exact surrounding gates preserve that error, so each gadget contributes at most $`2\zeta`$ in diamond norm. A telescoping bound for the complete circuit gives at most $`2L\zeta=\epsilon/2`$ of synthesis error. Together with the program and sweep errors, ```math -\left\|\mathcal C_P - -\operatorname{Ad}_{R_P^{\otimes k}}\right\|_\diamond +\left\Vert\mathcal C_P + -\mathrm{Ad}_{R_P^{\otimes k}}\right\Vert_\diamond \le\epsilon. ``` The synthesis estimate can retain the work qubit at the output. Ideal rotations return it exactly. With approximate finite gates, its return to $`|0\rangle`$, its decoupling from the data, and the data-channel accuracy hold jointly within the same complete-channel error budget. Exact work return is therefore asserted in the ideal-rotation model; approximate synthesis does not silently inherit an exact-return promise. The theorem requires no measurement, postselection or success flag. -For a fixed universal gate set such as Clifford+T, the [Solovay–Kitaev construction of Dawson and Nielsen](https://arxiv.org/abs/quant-ph/0505030) gives a conservative $`\operatorname{polylog}(L/\epsilon)`$ synthesis cost per variable rotation. Fixed controlled swaps have exact constant-size decompositions at the qubit level. The resulting total gate bound is +For a fixed universal gate set such as Clifford+T, the [Solovay–Kitaev construction of Dawson and Nielsen](https://arxiv.org/abs/quant-ph/0505030) gives a conservative $`\mathrm{polylog}(L/\epsilon)`$ synthesis cost per variable rotation. Fixed controlled swaps have exact constant-size decompositions at the qubit level. The resulting total gate bound is ```math O\!\left( -L\left[n+\operatorname{polylog}\!\left(\frac L\epsilon\right)\right] +L\left[n+\mathrm{polylog}\!\left(\frac L\epsilon\right)\right] \right). ``` @@ -255,7 +255,7 @@ for all $`k\ge1`$. When $`k\le r`$, use $`b=k`$ and $`N_{\mathrm{tot}}=O(r^2k/\e | Pair partial-swap gadgets | $`L=\sum_j(2b_j-1)N_j`$ | | Variable rotations | $`L`$ | | Gates with ideal rotations | $`O(Ln)`$ | -| Gates from a fixed universal set | $`O(L[n+\operatorname{polylog}(L/\epsilon)])`$ | +| Gates from a fixed universal set | $`O(L[n+\mathrm{polylog}(L/\epsilon)])`$ | | Work in addition to data and the active program | One qubit, with the return accuracy specified above | | Registers actively participating in one group | At most $`(b+1)n+1`$ qubits | | Total retained quantum state with streamed programs | $`(k+1)n+1`$ qubits | diff --git a/verification/README.md b/verification/README.md index f05c65e..d13672e 100644 --- a/verification/README.md +++ b/verification/README.md @@ -20,7 +20,7 @@ Seven instances are included: (3,1,2), (3,2,1), (3,2,2). ``` -Each projector has a complex orientation obtained by QR factorization. Independent tensor-permutation matrices construct the program-target swaps. Partial contractions of those matrices are compared with the formulas for $`h`$, $`M`$ and $`\|M-h^2\|_\infty`$ in the [construction](../science/parallel_program.md). The maximum first/second-moment residual in the stored run is below $`1.8\times10^{-15}`$; the maximum variance discrepancy is below $`9\times10^{-16}`$. +Each projector has a complex orientation obtained by QR factorization. Independent tensor-permutation matrices construct the program-target swaps. Partial contractions of those matrices are compared with the formulas for $`h`$, $`M`$ and $`\Vert M-h^2\Vert_\infty`$ in the [construction](../science/parallel_program.md). The maximum first/second-moment residual in the stored run is below $`1.8\times10^{-15}`$; the maximum variance discrepancy is below $`9\times10^{-16}`$. At each of $`\delta=0.03,0.12,0.4`$, the script checks both terms in the [reduced-unitary proof](../science/collision_bound.md): the compressed propagator error and the leakage effect. These are 21 local checks. The finite matrices satisfy the analytical upper bounds within the stated floating-point tolerances. diff --git a/verification/hosted/math-contract.json b/verification/hosted/math-contract.json index 79d865f..a313640 100644 --- a/verification/hosted/math-contract.json +++ b/verification/hosted/math-contract.json @@ -40,14 +40,14 @@ { "path": "science/parallel_program.md", "index": 59, - "source_sha256": "d874df9d5e8ee962ebf8515b3c5885626d02d7c91d370b66abee3eeedc2b74dd", - "expected_text": "vr,k:=∥M−h2∥∞=maxm∈{0,...,k}(k+(k−1)mr−m2r2)." + "source_sha256": "9c3be042a7c255f72596a63d8b2196e986859b9f3bf5dac3a0196a7137fa8ddf", + "expected_text": "vr,k:=‖M−h2‖∞=maxm∈{0,...,k}(k+(k−1)mr−m2r2)." }, { "path": "science/collision_bound.md", "index": 25, - "source_sha256": "128e8dcaa4b8c0fe39547c7891f64b07f267fe5c31a8f2149c46261703b71a97", - "expected_text": "∥Φτ−Uτ∥⋄≤2τ2v." + "source_sha256": "4290f5c7664140845ceb06b06d5f227c9da7bc1e1e3d7e3e3b6d5f96b3735692", + "expected_text": "‖Φτ−Uτ‖⋄≤2τ2v." }, { "path": "science/converse.md", @@ -82,8 +82,8 @@ { "path": "learning/ANCHOR.md", "index": 19, - "source_sha256": "c4d2943f6e2df16710964b2992dd5658358303d52543cf8bfb8f2c64e9c6f54d", - "expected_text": "f(ρ,σ)=∥ρσ∥1" + "source_sha256": "b4d9e6cf2f893c7dcfc97e3b37370bbd40dfd552fd7fda40e1dd600a58698a09", + "expected_text": "f(ρ,σ)=‖ρσ‖1" }, { "path": "learning/ANCHOR.md", @@ -100,13 +100,13 @@ { "path": "learning/ANCHOR.md", "index": 23, - "source_sha256": "23ad85c708f3a6a9131b5590c23663aa97fa8d883cc7b85e5cd2c63295891e57", - "expected_text": "∥Φ∥⋄" + "source_sha256": "04065d3c54e62832a84474cdbcd2bc63aad73e50023898fc9970160598e461fb", + "expected_text": "‖Φ‖⋄" }, { "path": "learning/TUTORIAL.md", "index": 30, - "source_sha256": "3601313b2aaf95e8cc0c6a5f996e15d67072998a80b1ed10bf89d67956c93a9d", + "source_sha256": "0c0075082ba2a42985f418036f29d6cd492bb30e55bc29a45ee9d9b7b7935238", "expected_text": "P=diag(1,1,0),ρP=diag(1/2,1/2,0),RP=diag(−1,−1,1)." }, {