diff --git a/.github/workflows/hosted-render.yml b/.github/workflows/hosted-render.yml index f066f96..ac8fc98 100644 --- a/.github/workflows/hosted-render.yml +++ b/.github/workflows/hosted-render.yml @@ -3,7 +3,7 @@ on: pull_request: paths: - '**.md' - - 'tools/inspect_hosted_render.py' + - 'verification/tools/inspect_hosted_render.py' - '.github/workflows/hosted-render.yml' workflow_dispatch: permissions: @@ -23,7 +23,7 @@ jobs: python-version: '3.13' - run: python -m pip install playwright==1.55.0 - run: python -m playwright install --with-deps chromium - - run: python tools/inspect_hosted_render.py --ref "$RENDER_REF" + - run: python verification/tools/inspect_hosted_render.py --ref "$RENDER_REF" - uses: actions/upload-artifact@v4 if: always() with: diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index a424fca..1bb740f 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -18,7 +18,8 @@ jobs: with: python-version: '3.13' cache: pip - - run: python -m pip install -r requirements.txt + cache-dependency-path: verification/requirements.txt + - run: python -m pip install -r verification/requirements.txt - run: python check_repository.py - - run: python tools/test_release_checks.py - - run: python verify.py + - run: python verification/tools/test_structure.py + - run: python verification/run_all.py diff --git a/.gitignore b/.gitignore index eaf7eb0..65d0ea8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,5 @@ __pycache__/ *.py[cod] .venv/ build/ -checks/*.json +verification/checks/*.json .pytest_cache/ diff --git a/AGENTS.md b/AGENTS.md index ae38b5e..fb718d4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,37 +1,35 @@ -# Guidance for research assistants +# Research repository guidance -## Scope and canonical material +## Scope and authoritative account -Modify only `GoGoKo699/Quantum-Routing-Bandwidth`. Read the README, `docs/theorem-map.md`, and `docs/related-work.md` before changing a scientific claim. Canonical statements are in `docs/bandwidth.md`, `docs/mixed-helpers.md`, `docs/entropy-flow.md`, and `docs/accuracy-and-resources.md`; control-cost results are in `docs/control-models.md`. Keep one canonical proof per statement and link to it. +Modify only `GoGoKo699/Quantum-Routing-Bandwidth` under the current project's grant. Read the root README, `science/README.md`, `science/theorem-map.md`, and `references/RELATED_WORK.md` before altering a scientific claim. The topic pages in `science/` own the definitions, theorems, proofs, constructions, examples, and physical interpretation. Give each result one canonical proof and cross-link it rather than maintaining a second full account. -The scientific core is the matched independent-helper fixed-error law, its exact clean/unknown endpoints, the full-rank zero-error boundary, and the correlated-helper counterexample. Furnishing improves navigation, teaching, attribution, and display; it does not authorize new models, altered claims, or a manuscript. Retain the MIT license and exact README purpose/contact paragraph. Do not copy private cross-project records into this public repository. +Keep the scientific presentation focused on its question and contribution. Preserve motivation, assumptions, quantifiers, imported theorem attribution, proof domains, and reproduction pointers. Exclude publication planning, development diaries, and private cross-project records. Bibliographic source titles and references to an author's manuscript edition remain accurate source descriptions. -## Scientific invariants +## Essential scientific distinctions -- Both module–bus interfaces are bounded. The bus belongs to neither freely controlled module. The main norm budget is per physical two-qubit contact, not a fixed global norm. Changed aggregate budgets must be labeled. -- Payload and bus inputs may have arbitrary reference entanglement. Exact unknown-helper identities hold on arbitrary helpers and references; clean-helper identities hold on their initialized subspace. -- For independent mixed helpers, distinguish exact physical helper marginal return in the construction from approximate joint/reference restoration and bus accuracy. The error is a half diamond distance with fixed inserted helper purifications, not arbitrary replacement helper inputs. -- Preparations are known and independent of payload/bus. There is no measurement, reset, input-dependent control, or unlisted clean workspace. Compression is reversible; all entropy-bearing qubits remain in the device. -- The fixed-error law holds for all nonnegative helper counts and fixed error between zero and 0.1, uniformly in the stated iid bias. Constants may deteriorate as error tends to zero. The older direct full-cut continuity estimate is not a restriction of the stronger law. -- Free internal controls define the matching interaction-time result. The bounded-strength compiler is a separate construction, not a universal finite-speed lower bound. Preparation cost, contact count, contact time, and total time differ. -- Entropy deficit is lack of entropy relative to the maximally mixed state, not work or quadratic purity. The converse is general; saturation from entropy alone is false for arbitrary correlated helpers. -- The one-design argument uses a common input-independent unitary. It is not a bound on every selected collective state. High process fidelity is not equivalent to worst-case diamond accuracy. -- Nonaccumulating preparation error under ideal reuse comes from one invariant favorable sector. New synthesis and dynamical errors generally accumulate. A finite numerical certificate is not a large-circuit simulation or hardware validation. +- Both module–bus interfaces are bounded; the bus belongs to neither freely controlled module. The main budget is per physical two-qubit contact. Label every changed aggregate-strength convention. +- Payload and bus inputs can have arbitrary reference entanglement. The exact unknown-helper task covers arbitrary helpers; the clean-helper identity has an initialized input subspace. +- The mixed-helper law uses known independent product preparations and a half diamond distance with their fixed inserted purifications. Exact physical helper marginal return in the construction is distinct from approximate joint/reference restoration and bus accuracy. +- Compression is reversible and retains entropy-bearing qubits as occupied spectators. There is no measurement, reset, input-dependent control, or extra clean workspace. +- The fixed-error theorem holds for all nonnegative helper counts, uniformly in the preparation bias at fixed error between zero and 0.1. Its constants may deteriorate in the zero-error limit. Full rank and correlated preparation have the separately stated consequences. +- Entropy deficit is relative entropy to the maximally mixed state, not work or quadratic purity. The general converse does not imply entropy-only achievability for arbitrary helper spectra. +- The one-design bound requires a common input-independent unitary. It does not bound every specially prepared state. High Choi fidelity is not a dimension-independent worst-case channel guarantee. +- Contact count, contact time, and finite-control runtime are distinct. The displayed compiler's linear duration at fixed strength ratio is not a universal finite-speed impossibility theorem. +- Nonaccumulation under ideal reuse concerns one invariant preparation sector. New synthesis and dynamical errors generally accumulate. Finite certificates evaluate proved bounds; they are not large-register circuit simulations or experimental data. -## Learning and coaching +## Shared learning and attribution -John Watrous, *The Theory of Quantum Information* (2018), is the single educational anchor. Use `docs/learning.md` for sections, errata, and notation, and `docs/learning-bridges.md` for the project-specific examples. Research citations remain essential but are not extra prerequisite textbooks. Supply explanations in the conversation instead of assigning prerequisite cover-to-cover reading. Do not redistribute the linked manuscript. +John Watrous, *The Theory of Quantum Information* (2018), remains the sole educational anchor. `learning/WATROUS_BRIDGE.md` owns its section pointers, errata, and notation. `learning/WORKED_EXAMPLES.md` supplies complete local examples. Primary research citations are not additional prerequisite courses. -The canonical common map is `docs/milestones.md`: QRB-W18-30-v1, exactly 30 milestones, with 14 background and 16 narrative targets. It describes the project, not a learner's self-assessment. Adapt teaching inside milestones, not the count or targets. Keep attempts and progress out of the public scientific files. +`learning/MILESTONES.md` is QRB-W18-30-v1: exactly 30 project-defined targets, with 14 background and 16 narrative milestones. Preserve their stable IDs, earlier dependencies, conceptual connections, and final synthesis. This public map contains no personal assessment procedure or learner state. Personal coaching instructions, answers, and progress remain outside the research repository; do not copy private guidance into public learning files or require readers to access a private source. -Follow `docs/coaching.md` as the single protocol. Every round has Revise → Learn → Test. Each milestone starts with a two-question challenge; all answers in one attempt must be correct. After a failed challenge, give 1–3 targeted learning rounds with one-question tests and immediate feedback. Only failed challenges increase the next challenge size, capped at six. Challenge feedback follows the full-attempt rule. Prefer genuine answer-selection controls; ordinary links or expandable answer panels are not quiz submissions. Do not launch coaching during maintenance or infer passes from approval messages. Passing M01–M30 completes the conceptual tutorial, not independent proof review. +Preserve the MIT license and exact purpose/contact paragraph. Add a foundational source to both `references/RELATED_WORK.md` and `references/references.bib`. Keep imported tools distinct from the contribution and numerical checks distinct from proof or independent review. -## Attribution, presentation, and verification +## Verification and display -Credit conditional variance, entropy-fluctuation speed limits, Hamiltonian averaging, reversible compression, concentration inequalities, and prior routing/initialization work. Add foundational sources to both `docs/related-work.md` and `references.bib`. Keep journal-target judgments and development diaries out of reader-facing science. Preserve assumptions, proof domains, source provenance, and load-bearing limitations when removing redundancy. +From the root, run `python check_repository.py`, `python verification/tools/test_structure.py`, and `python verification/run_all.py`. Scientific programs and pinned requirements are under `verification/`; detailed generated outputs go to the ignored `build/verification/`. Update tracked source provenance only from an executed run when paths or programs change. Preserve deterministic certificate bytes when the calculations are unchanged. -Run `python check_repository.py`, `python tools/test_release_checks.py`, and `python verify.py`. The repository checker includes `tools/check_learning.py`, which validates the map, dependencies, source links, and learning entrypoints. Release checks also validate reading-page tables, equation tags, and tracked certificate integrity. The ten numerical suites remain separate. Replace tracked numerical results only after a relevant executed source change; furnishing alone does not justify new scientific provenance. Passing checks is not outside endorsement. +Use protected GitHub inline mathematics and fenced `math` blocks. Preserve equation labels as ordinary `\qquad\text{(n)}` content, not legacy `\tag{n}` output that can produce unsupported native MathML rows. Keep table pipes unambiguous and starred subscripts explicitly braced. These are repository-hosting precautions, not universal TeX restrictions. -For mathematical pages, prefer GitHub fenced math blocks and its backtick-protected inline math syntax, with blank lines around display blocks and no displays inside tables. Use supported upright commands such as `\mathrm{Tr}` and brace starred subscripts as `_{\ast}`. This repository's hosted checks exposed Markdown consumption of backslashes and a rejected `\operatorname` macro; local MathJax success alone is insufficient. These are hosting-specific precautions, not universal restrictions on TeX. The [official syntax](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions) describes protected forms. - -Inspect rendered README, learning pages, and representative math-heavy science pages for macro errors, missing subscripts, bra–ket rendering, and overflow. Use the separate `Inspect hosted mathematics` workflow to check actual GitHub at a pinned commit and retain screenshots. A local MathJax preview is local, not hosting verification. Report which checks actually ran; blocked access or unfinished rendering is not a pass. +The separate hosted-render workflow reads the current immutable commit and checks root, science, learning, reference, and verification pages at desktop/mobile widths. Retain source hashes, diagnostics, and screenshots. Visually inspect representative pages; a parser-ready expression can still have broken layout. A local preview or a blocked request is not an actual-host pass. Do not broaden the checks into a claim of independent scientific validation. diff --git a/README.md b/README.md index 4b77600..935196f 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,10 @@ # Quantum Routing Bandwidth -**Reusable initialization and the optimal bandwidth of a quantum bottleneck.** +**How much does reusable initialization increase the amount of unknown quantum information that can pass through a one-qubit interface?** Two internally controllable modules exchange complete registers through a shared bus. Occupied qubits can assist a selected contact without losing their data; independently polarized helpers provide a further improvement even when their preparation is imperfect. -Two internally controllable modules exchange arbitrary quantum data through one bus qubit. Occupied qubits strengthen a selected contact while retaining their information. Independently prepared helpers supply an additional, quantifiable improvement even when their initialization is imperfect. +Each module has $`n\ge1`$ payload qubits and $`s\ge0`$ helpers. Both module–bus interfaces are bounded: every pairwise contact has operator norm at most $`J`$, and contacts may operate simultaneously. Internal module operations and bus-only rotations have zero charged duration. There are no measurements, resets, or extra initialized qubits. -## Start here - -| Purpose | Route | -|---|---| -| Learn the project | [30-milestone map](docs/milestones.md) and [Watrous anchor and notation](docs/learning.md) | -| Connect foundations to the result | [Three worked bridges](docs/learning-bridges.md); [coaching protocol](docs/coaching.md) | -| Read the science directly | [Theorem map](docs/theorem-map.md) → [fixed-error law](docs/mixed-helpers.md) | -| Check implementation and resources | [Accuracy and resources](docs/accuracy-and-resources.md); [control models](docs/control-models.md) | -| Inspect attribution | [Related work](docs/related-work.md) and [references](references.bib) | -| Reproduce the checks | [Verification](docs/verification.md) and [recorded results](results/verification.json) | - -The single educational anchor is **John Watrous, *The Theory of Quantum Information* (2018)**. The common map has 14 background milestones and 16 research milestones; its sections, notation translations, and local examples provide the bridge to the result. Specialist proofs remain directly accessible. [LLM reading guide](llms.txt). - -## Main result - -Each module contains $`n\ge1`$ payload qubits and $`s\ge0`$ helpers. Every module-qubit–bus interaction has operator norm at most $`J`$; all contacts may act simultaneously. Internal operations confined to either module or the bus have zero charged duration. Both interfaces remain bounded. There are no measurements, resets, or extra initialized qubits. - -For helpers independently prepared in the known state $`\rho_p=(1-p)|0\rangle\langle0|+p|1\rangle\langle1|`$, with $`0\le p\le1/2`$, the optimal fixed-error interaction time is +For independent known preparations $`\rho_p=(1-p)|0\rangle\langle0|+p|1\rangle\langle1|`$, with $`0\le p\le1/2`$, the optimal fixed-error interaction time is ```math T_{\epsilon,p}(n,s) @@ -30,51 +13,55 @@ T_{\epsilon,p}(n,s) \right). ``` -For every fixed $`0\lt \epsilon\le0.1`$, the constants are uniform in $`n,s,p`$. The error is a complete-operation half diamond distance, including arbitrary reference-entangled payload/bus inputs and the fixed helpers' inaccessible preparation references. The physical helper density matrix returns exactly in the construction; remaining correlations and bus errors are included in the error budget. Compression, routing, and decompression share one invariant high-probability sector, so initial preparation error does not accumulate gate by gate. +For every fixed $`0\lt\epsilon\le0.1`$, the constants are uniform in $`n,s,p`$. The error is a **complete-operation half diamond distance**, including arbitrary reference-entangled payload/bus inputs and the fixed helpers' inaccessible preparation references. The construction returns the physical helper density matrix exactly; remaining joint correlations and bus errors are included in the accuracy guarantee. -The [full proof](docs/mixed-helpers.md) distinguishes zero error from fixed nonzero error. A correlated-state counterexample shows why entropy deficit alone is not a complete bandwidth invariant for arbitrary helper states. +| Helper promise on the same hardware | Accuracy | Optimal interaction time | +|---|---|---| +| Pure helpers, returned clean | Exact | $`\Theta(n/[J\sqrt{(n+s)(s+1)}])`$ | +| Arbitrary unknown helpers, all information preserved | Exact | $`\Theta(n/[J\sqrt{n+s}])`$ | +| Independent known mixed helpers | Fixed complete-operation error | The entropy-deficit law above | -## Exact endpoints +The exact tasks restore an arbitrary bus and all reference correlations. A full-rank mixed preparation has the unknown-helper scale at **zero** error; the fixed-error law is not uniform as the error tends to zero. At $`s=0`$, the routing time is $`\Theta(\sqrt n/J)`$. -On identical hardware with the same payload, +## Read the science -```math -T_{\mathrm{clean}}(n,s) -=\Theta\!\left(\frac{n}{J\sqrt{(n+s)(s+1)}}\right), -``` +Start with the [scientific account](science/README.md), then follow the [information-flow bound](science/entropy-flow.md), [exact helper laws and contact construction](science/bandwidth.md), and [imperfect initialization](science/mixed-helpers.md). The [physical interpretation](science/interpretation.md) joins their mechanisms and resource consequences. Specialists can use the [theorem and proof map](science/theorem-map.md) directly. -```math -T_{\mathrm{unknown}}(n,s) -=\Theta\!\left(\frac{n}{J\sqrt{n+s}}\right). -``` - -These exact tasks restore helpers and an arbitrary bus, including reference correlations. The changed resource is the initial helper promise, not extra wiring. At $`s=0`$, the time is $`\Theta(\sqrt n/J)`$. Any full-rank mixed preparation has the unknown-helper scale at zero error; the fixed-error law is not uniform as $`\epsilon\to0`$. - -## Quantitative realization and scope +| Question | Authoritative account | +|---|---| +| Why can arbitrary internal processing not eliminate the bottleneck? | [Conditional entropy and weighted interfaces](science/entropy-flow.md) | +| How do occupied qubits assist without sacrificing their information? | [Coherent block construction and exact laws](science/bandwidth.md) | +| What survives imperfect initialization, including helper references? | [Matched mixed-helper law](science/mixed-helpers.md) | +| Is there a finite advantage against the entire unknown-helper class? | [Exact certificates, error composition, and resource budgets](science/accuracy-and-resources.md) | +| What changes when internal gates have finite duration? | [Control models and the bounded-strength compiler](science/control-models.md) | +| Which ingredients are established prior work? | [Related work](references/RELATED_WORK.md) and [bibliography](references/references.bib) | -After concentration into $`r`$ near-clean leader bits, balanced blocks need only +The converse combines a conditional entropy-rate estimate with a conserved physical entropy deficit. The construction concentrates preparation weight reversibly, uses all remaining qubits as occupied spectators, and decompresses after routing. One common high-probability sector controls preparation error for the entire operation; new control errors have a separate composition bound. -```math -K_{\mathrm{exact}}=2^{\lceil(n+s)/(r+1)\rceil-1} -``` +## Learn the project -exact interaction intervals per Ising gate. Synchronizing each block's translations suffices because the contact is an additive sum. For fixed nonzero polarization and $`s=\Theta(n)`$, this gives $`O(n)`$ total **exact contact intervals**. Global internal compression is still free in this theorem, and no efficient elementary implementation of every encoding is implied. +The single educational anchor is **John Watrous, *The Theory of Quantum Information* (2018)**. The [Watrous bridge](learning/WATROUS_BRIDGE.md) identifies relevant sections, the author's errata, and the notation changes needed for this project. [Three worked examples](learning/WORKED_EXAMPLES.md) connect references, coherent contact amplification, and preparation concentration to the proofs. -Exact rational spectral certificates demonstrate finite-size advantages over every allowed unknown-helper protocol at the same complete-operation accuracy, not just over one selected implementation. The [resource analysis](docs/accuracy-and-resources.md) also shows that a fixed sum of contact norms removes the parametric initialization advantage, while a fixed quadratic contact budget retains it. +The [30-milestone map](learning/MILESTONES.md) retains **14 background/preliminary** and **16 narrative/innovation** targets. Each milestone has a central question, an understanding target, earlier dependencies, a conceptual connection, and scientific sources. The [learning entrypoint](learning/README.md) provides the route; the [LLM guide](llms.txt) maps study and research questions to authoritative files. -The main normalization is **per contact**, not a fixed total Hamiltonian norm. Helper preparation is an input resource. The displayed finite-strength compiler has linear total duration at fixed internal/contact strength ratio. Preparation robustness is not robustness to ongoing decoherence or noisy pulses; their errors have a separate composition bound. +## Reproduce the checks -## Reproduce - -Using Python 3.13 in a virtual environment: +From the repository root, using Python 3.13: ```bash -python -m pip install -r requirements.txt +python -m pip install -r verification/requirements.txt python check_repository.py -python verify.py +python verification/tools/test_structure.py +python verification/run_all.py ``` -Ten deterministic suites run in an isolated temporary directory, with detailed results and logs written to `build/verification/`. Tracked results are not silently overwritten. Checks include full input isometries, entropy-rate interaction optimization, noncommuting entropy budgets, exact integer preparation certificates, synchronized averaging, fresh-payload reuse, and a bounded-strength compiler. Proofs establish the scaling laws; numerical checks are not independent review or hardware evidence. +The [verification guide](verification/README.md) describes ten deterministic scientific suites, structural regression tests, and the separate actual-GitHub rendering check. Executed scientific outputs and source hashes are in [verification/results](verification/results/verification.json). Finite numerical identities support the implementations; the written proofs and cited theorems establish universal and asymptotic claims. + +## Scope and physical resources + +The matching results charge **contact time with free internal controls**, under a per-contact rather than fixed total-norm budget. Initialization and internal compression are resources, not cost-free device operations. The displayed bounded-strength compiler has linear total duration at fixed internal/contact strength ratio; that is not a universal finite-speed impossibility theorem. + +Synchronized block translations substantially shorten the exact contact list. With fixed nonzero polarization and $`s=\Theta(n)`$, the route uses $`O(n)`$ exact contact intervals, while global compression is still assigned zero duration. A fixed quadratic contact budget retains the initialization enhancement; a fixed sum of contact strengths removes its parametric growth. A correlated-helper counterexample shows why entropy deficit alone cannot determine achievable bandwidth for arbitrary helper states. Preparation robustness does not imply robustness to ongoing decoherence or noisy pulses. ## Purpose and contact diff --git a/check_repository.py b/check_repository.py index f84441d..0b9477f 100644 --- a/check_repository.py +++ b/check_repository.py @@ -1,4 +1,4 @@ -"""Check navigation, math delimiters, source provenance, syntax and the learning map.""" +"""Check canonical navigation, learning boundaries, syntax, and executed provenance.""" from __future__ import annotations import ast import hashlib @@ -6,64 +6,77 @@ from pathlib import Path import re from urllib.parse import unquote, urlsplit -from verify import SUITES -from tools.check_learning import check_learning -from tools.check_release import check_release +from verification.run_all import SUITES +from verification.tools.check_learning import check_learning +from verification.tools.check_release import check_release, reading_pages ROOT = Path(__file__).resolve().parent CONTACT = 'This repository serves as a record of the work and a guide for the author’s self-directed learning. For discussion or potential collaboration, please contact Ruge Lin at [gogoko699@gmail.com](mailto:gogoko699@gmail.com).' + def anchors(text: str) -> set[str]: found = set() + occurrences = {} + in_fence = False for line in text.splitlines(): - if re.match(r'^#{1,6} ', line): + if line.startswith('```'): + in_fence = not in_fence + if not in_fence and re.match(r'^#{1,6} ', line): title = re.sub(r'^#{1,6} ', '', line).lower() - found.add(re.sub(r'[^\w\- ]', '', title).replace(' ', '-')) + slug = re.sub(r'[^\w\- ]', '', title).replace(' ', '-') + count = occurrences.get(slug, 0) + occurrences[slug] = count+1 + found.add(slug if count == 0 else f'{slug}-{count}') return found + def main() -> None: if not __debug__: - raise RuntimeError('Repository checks require Python assertions.') - markdown = [ROOT/'README.md', ROOT/'AGENTS.md', ROOT/'llms.txt', *sorted((ROOT/'docs').glob('*.md'))] - link_count = 0 - for path in markdown: + raise RuntimeError('Repository checks require assertions.') + pages = reading_pages(ROOT) + links = 0 + for path in pages: text = path.read_text() clean = re.sub(r'```.*?```', '', text, flags=re.S) - assert '\\[' not in clean and '\\]' not in clean, f'Use dollar math: {path}' - assert len(re.findall(r'^\$\$$', clean, flags=re.M)) % 2 == 0, f'Unclosed display math: {path}' + assert '/mnt/data/' not in text and 'sandbox:' not in text, f'Runtime path in {path}' + assert not re.search(r'GoGoKo699/Guinevere|preferences/TUTORIALS', text), f'Private dependency in {path}' inline = re.sub(r'\$\$.*?\$\$', '', clean, flags=re.S) assert len(re.findall(r'(? Reusable initialization and the optimal interaction-time bandwidth of a bounded qubit interface. One educational anchor, a common 30-milestone learning map, and canonical scientific proofs. +> Matched interaction-time laws for exchanging unknown registers through a bounded qubit bus, with reusable clean or independently mixed helpers. -## Learning +## Story and scientific results -- [Milestone map](docs/milestones.md): QRB-W18-30-v1; exactly M01–M30, with 14 background and 16 narrative targets. This is the shared project map, not a learner's progress record. -- [Watrous anchor](docs/learning.md): The Theory of Quantum Information (2018), selected sections, notation/normalization translations, author access and errata. The only educational anchor. -- [Worked bridges](docs/learning-bridges.md): Reference-assisted information flow, occupied-data amplification, and reversible mixed-helper preparation. -- [Coaching](docs/coaching.md): Revise → Learn → Test, challenge retries, immediate learning feedback, answer-selection interface, and completion rules. Do not start or score a lesson during repository maintenance. +- [Scientific account](science/README.md): Physical question, model, principal result, and connected reading route. +- [Theorem map](science/theorem-map.md): Exact quantifiers, proof dependencies, and canonical statement locations. +- [Information flow](science/entropy-flow.md): Conditional variance, singular-state support, and weighted-interface ensemble bounds. +- [Exact helper laws](science/bandwidth.md): Physical entropy budget and spectator-preserving coherent constructions. +- [Imperfect preparation](science/mixed-helpers.md): Fixed-error iid law, joint/reference restoration, full-rank zero-error boundary, and correlated-state counterexample. +- [Accuracy and resources](science/accuracy-and-resources.md): Finite certificates against the full comparator class, synchronized lists, fresh-payload reuse, and alternate contact budgets. +- [Finite control](science/control-models.md): An explicit bounded-strength compiler, separate from the free-internal-control theorem. +- [Physical interpretation](science/interpretation.md): How contact geometry, unknown data, and reusable preparation determine the operational comparison. -## Authoritative research +## Study -- [Theorem map](docs/theorem-map.md): Claims, assumptions, proof dependencies, and direct specialist route. -- [Mixed helpers](docs/mixed-helpers.md): Matched fixed-error law and exact/full-rank and correlated-state boundaries. -- [Bandwidth](docs/bandwidth.md): Exact clean/unknown endpoints, entropy-deficit converse, and coherent construction. -- [Entropy flow](docs/entropy-flow.md): Conditional variance, supports, weighted interfaces, and input-ensemble requirements. -- [Accuracy and resources](docs/accuracy-and-resources.md): Finite certificates, synchronized sequences, error composition, and changed strength budgets. -- [Control models](docs/control-models.md): Separate finite-strength compiler and contact-count results. -- [Related work](docs/related-work.md): Primary attribution; these papers are not additional prerequisite courses. -- [Bibliography](references.bib): Source metadata, including W18 for the anchor. +- [Learning route](learning/README.md): Common foundations-to-result route. +- [Watrous bridge](learning/WATROUS_BRIDGE.md): The sole educational anchor, relevant sections, errata, and normalization conventions. +- [Thirty milestones](learning/MILESTONES.md): Stable project-defined M01–M30, with 14 background and 16 narrative targets, dependencies, conceptual connections, and sources. +- [Worked examples](learning/WORKED_EXAMPLES.md): Reference-assisted swap, three-qubit coherent amplification, and preparation concentration. -## Verification and editing +## Sources and reproduction -- [Verification guide](docs/verification.md): Executed numerical checks, their scope, and reproduction. -- [Recorded results](results/verification.json): Scientific check-source provenance. Numerical checks are not external scientific review. -- [Agent guidance](AGENTS.md): Repository boundary, claim invariants, editing and teaching instructions. +- [Related work](references/RELATED_WORK.md): Established ingredients and model-level literature comparisons. +- [Bibliography](references/references.bib): Source metadata, including W18 for the anchor. +- [Verification](verification/README.md): Commands, suite coverage, expected outputs, and their evidence limits. +- [Executed summary](verification/results/verification.json): Scientific source and output hashes from an executed run. +- [Exact certificates](verification/results/scientific-closure.json): Finite quantitative and reuse checks. +- [Research guidance](AGENTS.md): Authorized scope, scientific invariants, presentation, and checks. -Preserve free internal-control interaction time versus total runtime, per-contact versus aggregate budgets, and exact helper marginal return versus approximate joint/reference restoration. The fixed inserted helper purification is not an arbitrary helper input. Do not infer progress from file access or from a request to continue. Do not redistribute the linked textbook or private records. This guide aids navigation; it does not guarantee indexing. +Essential distinctions: both interfaces are bounded; the main budget is per contact; internal unitaries are free only in the interaction-time theorem. Unknown helpers and fixed inserted helper purifications are different input promises. Exact helper marginal return is not exact joint/reference restoration in the mixed case. The entropy-budget converse does not establish arbitrary-state entropy-only saturation. The finite-strength compiler is not a universal no-go theorem. Proofs establish general claims; finite verification is not independent endorsement or hardware validation. + +This guide maps common scientific and study questions to public authoritative files. It contains no personal assessment contract or learner record and requires no private source for the shared learning route. It aids retrieval without guaranteeing indexing. diff --git a/docs/related-work.md b/references/RELATED_WORK.md similarity index 86% rename from docs/related-work.md rename to references/RELATED_WORK.md index 4ced84e..2dd3ba8 100644 --- a/docs/related-work.md +++ b/references/RELATED_WORK.md @@ -1,6 +1,6 @@ # Related work and attribution -The contribution is a matched full-register bandwidth characterization, including fixed-error independent mixed helpers, under a specified internal-control model. Existing results already connect initialization, collective interactions, and transfer speed. The source comparisons delimit the claim rather than certify the absence of all prior work. The [theorem map](theorem-map.md) identifies how these ingredients enter the central proof. +The contribution is a matched full-register bandwidth characterization, including fixed-error independent mixed helpers, under a specified internal-control model. Existing results already connect initialization, collective interactions, and transfer speed. The source comparisons delimit the claim rather than certify the absence of all prior work. The [theorem map](../science/theorem-map.md) identifies how these ingredients enter the central proof. ## D26 @@ -8,7 +8,7 @@ D. Devulapalli, C. Yin, A. Y. Guo, E. Schoute, A. M. Childs, A. V. Gorshkov, and In the final published paper, Section V, Theorem 5, Equation (48), printed page 010310-13, bounds average entanglement with a minimum segment width, an additive term, and a small exponent loss. Section VI discusses restrictions on time dependence and internal terms. The matching square-root construction concerns free particles. Our direct conditional-rate proof permits arbitrary well-defined switching and internal control for pairwise qubit contacts. Its matching qubit construction uses filled, internally controllable modules, not a bare star with unavailable leaf-to-leaf gates. -The final paper's own per-edge norm convention is explicit in Section II A. The different [normalizations analyzed here](accuracy-and-resources.md#6-what-changes-under-a-different-interaction-budget) prevent a per-edge result from being read as a fixed-total-strength advantage. +The final paper's own per-edge norm convention is explicit in Section II A. The different [normalizations analyzed here](../science/accuracy-and-resources.md#6-what-changes-under-a-different-interaction-budget) prevent a per-edge result from being read as a fixed-total-strength advantage. ## UHMG26 @@ -18,13 +18,13 @@ Theorem 1 on page 3 relates exact robust-subspace transfer to commutator Schatte Applying a separate necessary commutator condition to each payload qubit gives simultaneous conditions, not an additive transfer-time requirement. An extensive throughput conclusion needs an additional aggregate information-flow argument; the $2n$-bit reference-assisted entropy requirement supplies that step here. This is not a proof that no alternative derivation from existing tools is possible. -Neither initialization-assisted transfer, compression before transfer, nor the full-rank obstruction is a novelty claim. The distinct statement is the matched extensive fixed-error time on two bounded interfaces, with complete preparation-reference restoration accuracy and a same-hardware unknown-helper comparator. The [mixed-helper proof](mixed-helpers.md) addresses this model, not all power-law thermal transfer. The source's theorem and Outlook were checked directly; no unpublished version or private correspondence is relied on. +Neither initialization-assisted transfer, compression before transfer, nor the full-rank obstruction is a novelty claim. The distinct statement is the matched extensive fixed-error time on two bounded interfaces, with complete preparation-reference restoration accuracy and a same-hardware unknown-helper comparator. The [mixed-helper proof](../science/mixed-helpers.md) addresses this model, not all power-law thermal transfer. The source's theorem and Outlook were checked directly; no unpublished version or private correspondence is relied on. ## DF19 F. Dupuis and O. Fawzi, **Entropy accumulation with improved second-order term**, *IEEE Transactions on Information Theory* **65**(11), 7596–7612 (2019). [DOI](https://doi.org/10.1109/TIT.2019.2929564) · [arXiv:1805.11652v2](https://arxiv.org/abs/1805.11652v2). -Corollary III.5 on page 6 bounds conditional entropy variance. Relabeling its small subsystem as the bus gives $V(C|A)\le\log_2^2(2d_C^2+1)$ independent of register/reference dimension. This published ingredient suffices for the bandwidth exponents. Its equation and definitions were checked, including the rendered corollary. The [elementary qubit alternative](entropy-flow.md#2-elementary-qubit-constant) improves a constant, not the general-dimensional variance theorem. +Corollary III.5 on page 6 bounds conditional entropy variance. Relabeling its small subsystem as the bus gives $V(C|A)\le\log_2^2(2d_C^2+1)$ independent of register/reference dimension. This published ingredient suffices for the bandwidth exponents. Its equation and definitions were checked, including the rendered corollary. The [elementary qubit alternative](../science/entropy-flow.md#2-elementary-qubit-constant) improves a constant, not the general-dimensional variance theorem. ## GP22 @@ -48,7 +48,7 @@ Hamiltonian routing, initialized storage ancillas, and fast internal operations G. Vidal and J. I. Cirac, **Optimal simulation of nonlocal Hamiltonians using local operations and classical communication**, *Physical Review A* **66**, 022315 (2002). [DOI](https://doi.org/10.1103/PhysRevA.66.022315) · [arXiv:quant-ph/0108076v2](https://arxiv.org/abs/quant-ph/0108076v2). -Local-unitary Hamiltonian simulation, majorization, and local ancilla resources are established. The [trace-norm argument](control-models.md#5-optimal-gain-within-a-specified-averaging-class) proves optimal gain only inside a specified averaging class, not arbitrary optimal control of the router. Synchronized averaging exploits additive block structure; no new general averaging theorem is claimed. +Local-unitary Hamiltonian simulation, majorization, and local ancilla resources are established. The [trace-norm argument](../science/control-models.md#5-optimal-gain-within-a-specified-averaging-class) proves optimal gain only inside a specified averaging class, not arbitrary optimal control of the router. Synchronized averaging exploits additive block structure; no new general averaging theorem is claimed. ## K07 @@ -60,7 +60,7 @@ Reversible three-bit majority compression and recursive small compression gates L. J. Schulman and U. Vazirani, **Scalable NMR Quantum Computation**, [arXiv:quant-ph/9804060v1](https://arxiv.org/abs/quant-ph/9804060v1) (1998). -Section 2 and Theorem 1 develop reversible polarization concentration without initially available clean workspace. This is the compression precedent for [Mixed helpers, Section 3](mixed-helpers.md#3-reversible-concentration-at-finite-error). We retain entropy-bearing qubits as occupied spectators and control the complete compression–route–decompression isometry. An efficient implementation result for another compression method is not silently transferred to our global encoding. +Section 2 and Theorem 1 develop reversible polarization concentration without initially available clean workspace. This is the compression precedent for [Mixed helpers, Section 3](../science/mixed-helpers.md#3-reversible-concentration-at-finite-error). We retain entropy-bearing qubits as occupied spectators and control the complete compression–route–decompression isometry. An efficient implementation result for another compression method is not silently transferred to our global encoding. ## A07 diff --git a/references.bib b/references/references.bib similarity index 100% rename from references.bib rename to references/references.bib diff --git a/science/README.md b/science/README.md new file mode 100644 index 0000000..25a643d --- /dev/null +++ b/science/README.md @@ -0,0 +1,38 @@ +# Quantum information through a bounded interface + +A small interface need not behave as a sequence of independent wires. Several bounded contacts can act simultaneously, and internal reversible processing can organize the information already stored in a module so that it assists communication. The question is how much **unknown quantum data** can be exchanged this way, and how the answer changes when some qubits have a known preparation. + +The model has three separately controlled regions: a left module, one bus qubit, and a right module. Neither interface is free. Each module contains the same number of payload and helper qubits in every comparison. The task includes arbitrary payload correlations with inaccessible references; the bus and helper resources must satisfy the specified return guarantee. The time charged is the duration of bounded pairwise contacts, with module-internal unitaries treated as instantaneous. + +## Connected reading route + +| Step | Scientific question | Account | +|---|---|---| +| 1 | What is transferred, what is held fixed, and what counts as accurate return? | [Exact task](bandwidth.md#1-result-model-and-comparison) and [fixed-preparation error](mixed-helpers.md#1-task-and-matching-law) | +| 2 | How can a small bus limit entropy flow even with strong internal controls? | [Conditional entropy rate, supports, and weighted interfaces](entropy-flow.md) | +| 3 | How does the preparation budget limit usable contact strength? | [Entropy-deficit moment bound](bandwidth.md#2-entropy-deficit-controls-contact-second-moments) | +| 4 | Can occupied data attain the permitted scaling without being discarded? | [Sign encoding, block averaging, and returned helpers](bandwidth.md#5-matching-exact-construction-with-returned-clean-helpers) | +| 5 | Does imperfect preparation retain the advantage at complete-operation accuracy? | [Reversible concentration, routing, and decompression](mixed-helpers.md) | +| 6 | Which comparisons remain valid at finite size and under other strength budgets? | [Finite certificates and accuracy](accuracy-and-resources.md); [finite-duration controls](control-models.md) | +| 7 | What do these results establish about the physical resource? | [Interpretation and boundaries](interpretation.md) | + +The [theorem map](theorem-map.md) gives a shorter dependency-based route. The [learning route](../learning/README.md) supplies foundations and complete small examples before these specialist arguments. + +## Main result and its endpoints + +Write $`N=n+s`$ for module size and $`d(p)=1-h_2(p)`$ for the entropy deficit of a known independently prepared helper. For fixed complete-operation error $`0\lt\epsilon\le0.1`$, + +```math +T_{\epsilon,p}(n,s) +=\Theta_\epsilon\!\left(\frac{n}{J\sqrt{N[1+sd(p)]}}\right). +``` + +The upper and lower constants are independent of $`n,s,p`$. The lower bound combines an extensive reference-assisted information requirement with a preparation-dependent rate. The upper bound reversibly concentrates the helpers and uses entropy-bearing qubits as occupied spectators. It is exact on one common high-probability sector; this controls the entire inserted-preparation channel rather than a sum of input-specific gate errors. + +Exactly clean helpers give time $`\Theta(n/[J\sqrt{N(s+1)}])`$. Arbitrary unknown helpers give $`\Theta(n/[J\sqrt N])`$. These [exact laws](bandwidth.md) are proved separately from the fixed-error result. Full rank prevents a growing initialization advantage in the zero-error task, while [correlated preparations](mixed-helpers.md#7-why-the-product-state-assumption-cannot-be-dropped) show that a scalar entropy deficit is not a sufficient achievability invariant for every helper spectrum. + +## Attribution and verification + +Conditional-variance estimates, reversible polarization concentration, Hamiltonian simulation by conjugation, and initialization-sensitive transfer all have established precedents. The [related-work account](../references/RELATED_WORK.md) identifies their roles and the exact comparison to the closest routing results. The contribution studied here is the matched extensive-throughput characterization in this model, not the invention of those tools. + +The [verification guide](../verification/README.md) connects each finite check to a proof or construction. Exact rational certificates establish finite comparisons using proved bounds; they are not simulations of the corresponding large register. Neither these tests nor the ideal interaction-time model establishes device performance or independent proof validation. diff --git a/docs/accuracy-and-resources.md b/science/accuracy-and-resources.md similarity index 92% rename from docs/accuracy-and-resources.md rename to science/accuracy-and-resources.md index 6091f8d..ec5bca5 100644 --- a/docs/accuracy-and-resources.md +++ b/science/accuracy-and-resources.md @@ -24,9 +24,9 @@ The payload-sized mutual-information argument in [Mixed helpers, Section 2](mixe \qquad c_0=2\sqrt2/\ln2.}\qquad\text{(1)} ``` -The published [DF19](related-work.md#df19) route proves the same inequality with $`c_0`$ replaced by $`c_{\mathrm{DF}}=2\log_2 9`$. At $`e=0`$, (1) has coefficient $`\ln2/\sqrt2`$. The maximally mixed bus is a legitimate reference test because this comparator must work on an arbitrary bus. This coefficient must not be silently used for a task that promises one fixed pure bus input. +The published [DF19](../references/RELATED_WORK.md#df19) route proves the same inequality with $`c_0`$ replaced by $`c_{\mathrm{DF}}=2\log_2 9`$. At $`e=0`$, (1) has coefficient $`\ln2/\sqrt2`$. The maximally mixed bus is a legitimate reference test because this comparator must work on an arbitrary bus. This coefficient must not be silently used for a task that promises one fixed pure bus input. -If only payload Choi infidelity $`\zeta`$ is specified, projection of a purification onto the ideal Choi vector gives payload trace distance at most $`\sqrt\zeta`$. Replace $`e`$ in $`B_e`$ by $`\sqrt\zeta`$ whenever it is at most $`0.1`$. This is a necessary-condition argument, not an equivalence between Choi fidelity and diamond accuracy. The entropy-continuity step is the [Audenaert bound](related-work.md#a07); its use on payload-sized subsystems is why no factor proportional to $`s`$ appears. +If only payload Choi infidelity $`\zeta`$ is specified, projection of a purification onto the ideal Choi vector gives payload trace distance at most $`\sqrt\zeta`$. Replace $`e`$ in $`B_e`$ by $`\sqrt\zeta`$ whenever it is at most $`0.1`$. This is a necessary-condition argument, not an equivalence between Choi fidelity and diamond accuracy. The entropy-continuity step is the [Audenaert bound](../references/RELATED_WORK.md#a07); its use on payload-sized subsystems is why no factor proportional to $`s`$ appears. Equation (1) also makes the correlated-helper counterexample precise for arbitrary $`s`$. A both-maximally-mixed component with weight $`w`$ and total payload infidelity at most $`\epsilon`$ has conditional infidelity at most $`\epsilon/w`$. Its physical state has at most the chosen pure bus's one-bit entropy deficit. The same proof, with an extra $`\sqrt2`$ in the rate, gives $`\Omega(n/[J\sqrt N])`$ for sufficiently small fixed $`\epsilon/w`$, without any restriction $`s\le n`$. @@ -68,7 +68,7 @@ satisfy $`JT_{\mathrm{mixed}}\lt U`$ and $`JT_{\mathrm{unknown},e}\gt L`$. The s Displayed upper values are rounded upward; lower values and advantage factors are rounded downward. These examples use the same number of contacts, the same payload, and the same error budget. Their helper input promises differ, exactly as in the resource comparison. Large systems are evaluated by exact spectral sums and proven timing formulas, **not simulated as large quantum circuits**. -The certificate does not depend on the smaller elementary entropy constant: replacing $`41/10`$ by $`32/5\gt c_{\mathrm{DF}}`$ still certifies an advantage at $`n=s=1024`$ and $`2048`$. In the latter case the factor exceeds $`1.55`$ using the published variance bound alone. The exact rational numbers and tail certificates are generated by [verify_scientific_closure.py](../checks/verify_scientific_closure.py). +The certificate does not depend on the smaller elementary entropy constant: replacing $`41/10`$ by $`32/5\gt c_{\mathrm{DF}}`$ still certifies an advantage at $`n=s=1024`$ and $`2048`$. In the latter case the factor exceeds $`1.55`$ using the published variance bound alone. The exact rational numbers and tail certificates are generated by [verify_scientific_closure.py](../verification/checks/verify_scientific_closure.py). The simple constant bounds themselves have elementary certificates: $`\ln2\gt 56/81`$, $`\sqrt2\lt 99/70`$, and $`9^5\lt 2^{16}`$. Also $`\ln100\lt 5`$ and $`-\ln(0.99)\le1/99`$ give $`h_2(0.01)\lt 0.1`$. The decimal table is therefore not needed to decide the strict speed comparison. @@ -95,11 +95,11 @@ Cross-block independence is not required because there are no products of the bl The full route uses $`3(2n+1)K_{\mathrm{exact}}`$ raw contact intervals. For the three finite certificates in Section 2, the exact lengths are respectively 32, 16, and 16 intervals per Ising gate; their total contact counts are 98,400, 98,352, and 196,656. At fixed $`p\lt 1/2`$, fixed accuracy, and $`s`$ proportional to $`n`$, the compression theorem allows $`r=\Theta(s)`$, so the **exact** contact count is $`O(n)`$. At $`r=0`$, the no-helper length remains $`2^{N-1}`$. -This reduction does not assign a small elementary-gate cost to compression or the internal block encodings. It removes an unnecessary product of averaging-list lengths, not the distinction between contact time and physical control time. [The raw-contact verifier](../checks/verify_workspace_construction.py) implements the synchronized schedule; the closure suite compares it with full joint averaging on every basis label in its finite tests. +This reduction does not assign a small elementary-gate cost to compression or the internal block encodings. It removes an unnecessary product of averaging-list lengths, not the distinction between contact time and physical control time. [The raw-contact verifier](../verification/checks/verify_workspace_construction.py) implements the synchronized schedule; the closure suite compares it with full joint averaging on every basis label in its finite tests. ## 4. Polynomial contact lists at fixed uniform accuracy -A polynomial alternative is available even where (3) is long. Choose $`K`$ independent uniform synchronized translation labels offline, then fix that list for every input and every gate. For any module basis label $`x`$, the dimensionless diagonal contact coefficient $`F_\ell(x)`$ lies in $`[-N,N]`$ and has the exact averaged coefficient as its mean. [Hoeffding's inequality](related-work.md#h63) and a union bound over the $`2^N`$ labels give +A polynomial alternative is available even where (3) is long. Choose $`K`$ independent uniform synchronized translation labels offline, then fix that list for every input and every gate. For any module basis label $`x`$, the dimensionless diagonal contact coefficient $`F_\ell(x)`$ lies in $`[-N,N]`$ and has the exact averaged coefficient as its mean. [Hoeffding's inequality](../references/RELATED_WORK.md#h63) and a union bound over the $`2^N`$ labels give ```math \Pr\!\left(\|\overline F_K-F_{\ast}\|\gt a\right) @@ -123,7 +123,7 @@ The compressed helper density is diagonal. Each translated, encoded, decoded int ## 5. Error composition and reuse -For physical unitaries $`U,V`$ and any inserted pure preparation, operator error $`\|U-V\|\le\eta`$ implies half diamond error at most $`\eta`$. For pure input outputs $`|u\rangle,|v\rangle`$, this follows from their trace distance being bounded by $`\|u-v\|`$; reference extensions and mixed inputs follow by purification. It is also consistent with the completely bounded trace-norm framework in [W18, Chapter 3](related-work.md#w18). +For physical unitaries $`U,V`$ and any inserted pure preparation, operator error $`\|U-V\|\le\eta`$ implies half diamond error at most $`\eta`$. For pure input outputs $`|u\rangle,|v\rangle`$, this follows from their trace distance being bounded by $`\|u-v\|`$; reference extensions and mixed inputs follow by purification. It is also consistent with the completely bounded trace-norm framework in [W18, Chapter 3](../references/RELATED_WORK.md#w18). If a route is exact on one invariant favorable preparation sector of bad weight $`\Delta`$, any number of ideal coherent uses on fresh payloads still agrees with the ideal on that same sector and differs by at most $`2\sqrt\Delta`$ on the inserted-preparation isometry. The bound includes references to all batches; it is not a claim that successive errors are independent. The fresh-batch check explicitly keeps two distinct payload pairs and the common bus, rather than just applying a power to one payload state. @@ -171,4 +171,4 @@ Equations (8)-(9) identify precisely which bandwidth enhancement follows from wh The matched law says that, for the specified independent preparations, the entropy deficit can be reversibly concentrated into a larger useful interface coupling while preserving all unknown data. The entropy-flow converse fixes the optimum scaling. The correlated-helper counterexample prevents treating entropy as a complete invariant for arbitrary resource states. The finite certificates distinguish a universal comparator exclusion from an illustrative protocol ratio. -The mathematical package consists of the [main fixed-error law](mixed-helpers.md), [exact endpoints and conserved-budget proof](bandwidth.md), [conditional and weighted entropy flow](entropy-flow.md), the finite guarantees here, and the [bounded-strength compiler analysis](control-models.md). The [theorem map](theorem-map.md) specifies their logical dependencies and the [related-work guide](related-work.md) specifies attribution. This is a closed set of claims for the stated theoretical model, not a claim that every extension or implementation problem has been solved. +The mathematical package consists of the [main fixed-error law](mixed-helpers.md), [exact endpoints and conserved-budget proof](bandwidth.md), [conditional and weighted entropy flow](entropy-flow.md), the finite guarantees here, and the [bounded-strength compiler analysis](control-models.md). The [theorem map](theorem-map.md) specifies their logical dependencies and the [related-work guide](../references/RELATED_WORK.md) specifies attribution. This is a closed set of claims for the stated theoretical model, not a claim that every extension or implementation problem has been solved. diff --git a/docs/bandwidth.md b/science/bandwidth.md similarity index 98% rename from docs/bandwidth.md rename to science/bandwidth.md index 2ab360e..2c29ed1 100644 --- a/docs/bandwidth.md +++ b/science/bandwidth.md @@ -138,7 +138,7 @@ Only the physical part of A is acted on by h; hence its second moment is the sam ### 3.1 Published foundation and attribution -Dupuis and Fawzi [DF19](related-work.md#df19), Corollary III.5, established +Dupuis and Fawzi [DF19](../references/RELATED_WORK.md#df19), Corollary III.5, established ```math V(C|A)_\rho\le\log_2^2(2d_C^2+1). @@ -156,7 +156,7 @@ This published-lemma route gives the same n,s exponents with a different numeric For the smaller constant c_0, the elementary argument in [Entropy flow](entropy-flow.md) uses rho_AC <= d_C(rho_A tensor I_C). In the spectral-overlap distribution of rho and sigma=rho_A tensor I_C, X=ln r_i-ln s_j satisfies E exp(X)<=d_C and E exp(-X)<=d_C. The scalar inequality X^2<=exp(X)+exp(-X)-2 then yields Tr rho(ln rho-ln sigma)^2<=2(d_C-1). At d_C=2 the commutator estimate gives (11). Noncommuting logarithms are handled through the overlap distribution, not by assuming simultaneous diagonalizability. For singular rho, off-support contributions of log sigma must not be discarded before squaring; the support treatment is given in [Entropy flow](entropy-flow.md). -Conditional-variance and entropy-fluctuation ingredients have prior precedents [DF19](related-work.md#df19), [GP22](related-work.md#gp22). Their role here is the combination with (10), the specified physical initialization budget, and a matching routing construction. +Conditional-variance and entropy-fluctuation ingredients have prior precedents [DF19](../references/RELATED_WORK.md#df19), [GP22](../references/RELATED_WORK.md#gp22). Their role here is the combination with (10), the specified physical initialization budget, and a matching routing construction. ### 3.2 Entropy-deficit cut rate diff --git a/docs/control-models.md b/science/control-models.md similarity index 99% rename from docs/control-models.md rename to science/control-models.md index 4a3166c..93d6ba0 100644 --- a/docs/control-models.md +++ b/science/control-models.md @@ -180,4 +180,4 @@ The target-bus gain is $`(3/2)^k`$ with $`4^k`$ contact intervals per Ising gate ## 5. Optimal gain within a specified averaging class -For the fixed collective contact $`H=JZ_C\sum_{j=1}^nZ_j`$, the normalized trace norm is $`\|H\|_{1,\mathrm{norm}}=J\mu_n`$. It is invariant under local conjugation and convex. A convex average equal to $`gZ_qZ_C\otimes I`$ must therefore have $`|g|\le J\mu_n`$. The exact sign-encoding construction attains this value. This is optimal amplification within convex Hamiltonian averaging of that fixed contact, not an optimal finite-gate synthesis theorem for arbitrary time-dependent contacts. Hamiltonian simulation by local conjugations and majorization is established prior work [VC02](related-work.md#vc02). +For the fixed collective contact $`H=JZ_C\sum_{j=1}^nZ_j`$, the normalized trace norm is $`\|H\|_{1,\mathrm{norm}}=J\mu_n`$. It is invariant under local conjugation and convex. A convex average equal to $`gZ_qZ_C\otimes I`$ must therefore have $`|g|\le J\mu_n`$. The exact sign-encoding construction attains this value. This is optimal amplification within convex Hamiltonian averaging of that fixed contact, not an optimal finite-gate synthesis theorem for arbitrary time-dependent contacts. Hamiltonian simulation by local conjugations and majorization is established prior work [VC02](../references/RELATED_WORK.md#vc02). diff --git a/docs/entropy-flow.md b/science/entropy-flow.md similarity index 98% rename from docs/entropy-flow.md rename to science/entropy-flow.md index ae8cfbe..d3a7432 100644 --- a/docs/entropy-flow.md +++ b/science/entropy-flow.md @@ -17,7 +17,7 @@ up to the irrelevant sign convention for the commutator. Since rho commutes with \le 2\sqrt{V(B|A)_\rho}\,\Delta_\rho h. ``` -Using [DF19](related-work.md#df19), Corollary III.5, yields +Using [DF19](../references/RELATED_WORK.md#df19), Corollary III.5, yields ```math \boxed{|\dot S_A|\le @@ -122,7 +122,7 @@ The same theorem follows using published bound (1) with c_0 replaced by c_DF. In \qquad\text{(5)} ``` -For uniform contacts, this is at most c_0 J |C| sqrt(|L|) T. There is no additive constant, factor n^delta, minimum segment length, or derivative condition. Compare the restricted-time-dependence average-input bound of [D26](related-work.md#d26). +For uniform contacts, this is at most c_0 J |C| sqrt(|L|) T. There is no additive constant, factor n^delta, minimum segment length, or derivative condition. Compare the restricted-time-dependence average-input bound of [D26](../references/RELATED_WORK.md#d26). This is not an input-uniform O(sqrt n) rate bound. For example, a GHZ logical qubit in the leaves under Z_C sum_j Z_j can have instantaneous entropy rate proportional to nJ. The proof neither assumes nor implies S(average rho)=average S(rho). It uses the linearity of the second moment and concavity of the square root. It also fails if the control schedule is selected using the unknown input's classical label: then the average evolved state need not stay maximally mixed. diff --git a/science/interpretation.md b/science/interpretation.md new file mode 100644 index 0000000..6b2df95 --- /dev/null +++ b/science/interpretation.md @@ -0,0 +1,57 @@ +# Initialization, information flow, and usable bandwidth + +The results distinguish three resources that can otherwise be conflated: the number and strength of physical contacts, the quantum information already occupying the module, and the known part of its preparation. Their optimal-time comparison holds the contacts and payload fixed while changing the helper input promise. + +## Unknown information is not an idle obstacle + +An unknown spectator cannot simply be set to a favorable spin orientation: doing so would destroy its information or require an additional storage resource. The occupied-data construction instead encodes the sign of a collective contact into a selected target and then removes its dependence on spectator labels through a coherent sequence of commuting interactions. + +The completed operation acts as identity on every spectator subsystem, including correlations with references. For a block of $`b`$ occupied qubits, the effective contact gain is the average absolute magnetization $`\mu_b=\Theta(\sqrt b)`$. The spectators help without being measured or consumed. This is an operator identity, not a statement limited to single-excitation states or favorable computational-basis inputs. The [construction](bandwidth.md#51-an-occupied-data-block) supplies its explicit encoding and averaging sequence. + +This explains why no-helper register exchange can take $`\Theta(\sqrt n/J)`$ in the free-internal-control model, whereas a time-division bus with at most one active contact has a linear lower bound. Simultaneous contacts and internal processing are essential to that comparison; a bare star with no usable internal module operations is a different model. + +## A preparation promise changes usable collective strength + +The largest collective contact eigenvalue can scale linearly with the number of contacts. An accurate operation on an unknown register cannot assume that its physical state occupies only that extremal sector. The reference-assisted input test and the conserved physical entropy deficit constrain how much weight can reach the strongly interacting part of the spectrum. + +For independently prepared helpers, that deficit is + +```math +\mathcal I(\omega)=1+2s[1-h_2(p)] +``` + +on the pure-bus lower-bound test. The [conditional entropy rate](entropy-flow.md) and [contact moment estimate](bandwidth.md#2-entropy-deficit-controls-contact-second-moments) turn it into an information-flow limit. This limits arbitrary internal processing without imposing a minimum switching interval. + +The upper bound reaches the same scaling by concentrating preparation weight reversibly into useful leader bits. The remaining entropy stays in the device, in qubits that the occupied-data construction already knows how to preserve. Thus initialization is useful not because entropy is erased during routing, but because a known distribution permits coherent concentration into a large favorable subspace. + +At fixed hardware, define one-direction throughput as $`\mathcal B=n/T`$. The [matching law](mixed-helpers.md#1-task-and-matching-law) gives throughput of order $`J\sqrt{(n+s)[1+s(1-h_2(p))]}`$ at fixed nonzero error. Counting both directions multiplies throughput by two. No frequency bandwidth or unrestricted channel-capacity statement is intended. + +## Returned resources and reference correlations + +Returning a helper marginal is weaker than returning its complete quantum state together with its correlations. The [fixed-preparation maps](mixed-helpers.md#1-task-and-matching-law) include inaccessible helper purifications in the output comparison and allow arbitrary reference-entangled payload and bus inputs. + +For the specified diagonal mixed preparation, the construction returns the physical helper density matrix exactly. Joint correlations and bus inaccuracies are bounded by the complete-operation half diamond error. On one common favorable helper sector the full route agrees exactly with the ideal operation, including one common phase. That is the reason initial preparation error does not grow gate by gate in the ideal sequence. + +Coherent reuse on fresh payloads retains the same favorable sector. It therefore retains the same initial-sector error bound in the absence of new physical noise. This is not a collection of independent error-free calls: unfavorable-sector errors may be correlated across uses. Pulse errors, Hamiltonian perturbations, and list-approximation errors have their own [composition bound](accuracy-and-resources.md#5-error-composition-and-reuse). + +## Two limits on an entropy-only interpretation + +**Zero error tests the full support.** A full-rank helper preparation gives nonzero weight to every helper eigenstate. An exactly unitary output channel has a pure Choi state, so every such component must implement the same operation; exact preparation-reference return then forces the unknown-helper operation on the full space. A nonzero bias can improve fixed-error scaling without improving the zero-error law. The constants of the fixed-error result need not remain bounded as the error goes to zero. + +**Equal entropy does not imply equal concentration.** A state with a small pure spike and a substantial maximally mixed component can have extensive entropy deficit but still require the unknown-helper time scale at small fixed error. The [correlated-helper example](mixed-helpers.md#7-why-the-product-state-assumption-cannot-be-dropped) makes this distinction explicit. Entropy deficit gives a general converse; independent preparation supplies the spectral concentration used to attain it. Neither statement warrants a universal entropy-only law for arbitrary mixed helpers. + +## The contact budget determines the operational comparison + +Under a per-contact bound, adding module qubits increases the quadratic contact strength. The clean and unknown comparisons nevertheless use identical wiring and the same strengths, so their relative initialization enhancement is not an extra-wire advantage. + +The [alternative-budget analysis](accuracy-and-resources.md#6-what-changes-under-a-different-interaction-budget) isolates this issue. With a fixed quadratic edge budget $`\Lambda_2`$, the matched time is $`\Theta_\epsilon(n/[\Lambda_2\sqrt{1+sd(p)}])`$, and the preparation enhancement survives. With a fixed sum of edge strengths $`\Lambda_1`$, the optimum is $`\Theta_\epsilon(n/\Lambda_1)`$, regardless of the helper initialization class. In that normalization there is no parametrically growing enhancement. + +The [finite certificates](accuracy-and-resources.md#2-finite-size-advantage-against-every-unknown-helper-protocol) compare a constructed upper bound with a lower bound for every allowed unknown-helper protocol, not just with one convenient implementation. Their input promises differ exactly as stated in the resource comparison. + +## Interaction time is not an apparatus runtime + +Synchronized block translations remove an unnecessary product of control-list lengths. With fixed nonzero polarization, fixed accuracy, and an extensive helper pool, the route has a linear number of exact contact intervals. This does not assign zero physical cost to concentration, global encoding, or pulses. + +The [displayed finite-strength compiler](control-models.md#24-finite-control-consequence) has linear total duration at a fixed internal/contact strength ratio. Its constants can improve in suitable regimes, but it does not establish a sublinear fixed-hardware runtime. Conversely, its limitation is not a theorem excluding every better finite-speed implementation. + +The scientific conclusion is a matched characterization of a bounded quantum interface under explicit preparation, control, and accuracy assumptions. The information-flow converse, coherent realization, exact endpoints, and counterexamples jointly identify which resource is quantified and which changes of task alter the answer. diff --git a/docs/mixed-helpers.md b/science/mixed-helpers.md similarity index 92% rename from docs/mixed-helpers.md rename to science/mixed-helpers.md index 4688c9f..974aa47 100644 --- a/docs/mixed-helpers.md +++ b/science/mixed-helpers.md @@ -66,7 +66,7 @@ This entropy deficit is conserved by every admissible physical unitary, even whi \qquad\text{(4)} ``` -where $`A`$ includes the entire physical left module, its payload references, and its helper-preparation references. Initially $`S_A=0`$. The underlying conditional entropy-rate estimate may equivalently use the published conditional-variance bound [DF19](related-work.md#df19), changing only a universal constant. +where $`A`$ includes the entire physical left module, its payload references, and its helper-preparation references. Initially $`S_A=0`$. The underlying conditional entropy-rate estimate may equivalently use the published conditional-variance bound [DF19](../references/RELATED_WORK.md#df19), changing only a universal constant. It is unnecessary to pay an error-continuity factor proportional to the helper dimension. Let $`a`$ consist of the left payload and its original payload references, and let $`b`$ be the corresponding right subsystem. Each has dimension $`2^{2n}`$. The ideal exchanged-payload Choi vector is maximally entangled across $`a:b`$, so its mutual information is $`4n`$ bits. @@ -246,7 +246,7 @@ T_{0,p}(n,s)=\Theta\!\left(\frac{n}{J\sqrt{n+s}}\right), \qquad\text{(16)} ``` -This exact/full-rank obstruction is already explicitly noted in the Outlook of [UHMG26](related-work.md#uhmg26), which identifies approximate transfer with thermal ancillas as a further direction. Equation (2) supplies a matched answer for this modular routing problem, not a claim to have first noticed the obstruction. +This exact/full-rank obstruction is already explicitly noted in the Outlook of [UHMG26](../references/RELATED_WORK.md#uhmg26), which identifies approximate transfer with thermal ancillas as a further direction. Equation (2) supplies a matched answer for this modular routing problem, not a claim to have first noticed the obstruction. For any fixed allowed error and fixed $`p\lt 1/2`$, increasing $`s`$ supplies a growing advantage. For zero error, no positive full-rank bias alone changes the unknown-helper exponent. The two statements are compatible because the constants and the tolerated rare input sectors change with the error requirement. @@ -256,7 +256,7 @@ For $`n=s=256`$, $`p=0.1`$, and complete-operation half diamond budget $`\epsilo These large-size figures are calculations of spectral probabilities and proven timing formulas, not simulation of a 1,025-qubit circuit. The compressed prefix has high **joint** zero probability; it is not a set of independent perfectly clean qubits. -The executable check [verify_mixed_helpers.py](../checks/verify_mixed_helpers.py) compares exact shell sums against complete spectra, checks the uniform concentration estimates, and propagates all helper sectors and payload/bus columns for small systems using the existing raw-contact implementation. Its largest full physical system has 11 qubits. For the purification-inclusive error, it evaluates the exact Gram operator +The executable check [verify_mixed_helpers.py](../verification/checks/verify_mixed_helpers.py) compares exact shell sums against complete spectra, checks the uniform concentration estimates, and propagates all helper sectors and payload/bus columns for small systems using the existing raw-contact implementation. Its largest full physical system has 11 qubits. For the purification-inclusive error, it evaluates the exact Gram operator ```math \sum_x q_x(V_x-U_{\ast})^\dagger(V_x-U_{\ast}), @@ -285,7 +285,7 @@ Thus a fixed low-weight pure spike plus a large maximally mixed component can ha ## 8. Relation to existing work -[UHMG26](related-work.md#uhmg26) proves a general relationship between exact robust-subspace transfer and commutator Schatten norms, includes multiple transferred qubits, and gives a symmetric-subspace compression construction. Compression before transfer and mixed states supported in a favorable subspace therefore are not new mechanisms here. Its stated exact theorem and power-law light cones do not themselves supply an extensive full-register throughput bound or an iid full-rank fixed-error optimal-time law for the three-region bounded-bus model. The direct entropy budget and its matched coherent construction supply those additional steps. +[UHMG26](../references/RELATED_WORK.md#uhmg26) proves a general relationship between exact robust-subspace transfer and commutator Schatten norms, includes multiple transferred qubits, and gives a symmetric-subspace compression construction. Compression before transfer and mixed states supported in a favorable subspace therefore are not new mechanisms here. Its stated exact theorem and power-law light cones do not themselves supply an extensive full-register throughput bound or an iid full-rank fixed-error optimal-time law for the three-region bounded-bus model. The direct entropy budget and its matched coherent construction supply those additional steps. The arXiv PDF's Outlook explicitly identifies approximate transfer with thermal ancillas as a further direction. The comparison refers to those theorem statements and that Outlook, rather than asserting the absence of related work elsewhere. diff --git a/docs/theorem-map.md b/science/theorem-map.md similarity index 84% rename from docs/theorem-map.md rename to science/theorem-map.md index 781c060..0ca21bb 100644 --- a/docs/theorem-map.md +++ b/science/theorem-map.md @@ -58,7 +58,7 @@ For a register/reference subsystem $`A`$ and a qubit bus $`C`$, the contact cont |\dot S_A|\le c\sqrt{\mathrm{Tr}(\omega H_{\mathrm{int}}^2)}. ``` -A published conditional-variance inequality, [DF19, Corollary III.5](related-work.md#df19), suffices with $`c=2\log_2 9`$. The [elementary qubit argument](entropy-flow.md#2-elementary-qubit-constant) improves the constant to $`2\sqrt2/\ln2`$ without changing the scaling. The two routes are alternatives, not successive assumptions. The conditional logarithms need not commute, and the support treatment matters for reference tests. See [Entropy flow, Sections 1–3](entropy-flow.md#1-published-conditional-variance-bound). +A published conditional-variance inequality, [DF19, Corollary III.5](../references/RELATED_WORK.md#df19), suffices with $`c=2\log_2 9`$. The [elementary qubit argument](entropy-flow.md#2-elementary-qubit-constant) improves the constant to $`2\sqrt2/\ln2`$ without changing the scaling. The two routes are alternatives, not successive assumptions. The conditional logarithms need not commute, and the support treatment matters for reference tests. See [Entropy flow, Sections 1–3](entropy-flow.md#1-published-conditional-variance-bound). ### L2. Geometry and conserved initialization budget @@ -95,7 +95,7 @@ A fixed helper-basis permutation puts probability at least $`1-\delta`$ into a z r+1\ge c_\delta[1+s\,d(p)]. ``` -The remaining entropy stays in the other helper qubits. Reversible polarization concentration is established prior machinery [SV98](related-work.md#sv98); no measurement or purity creation is being asserted. See [Mixed helpers, Section 3](mixed-helpers.md#3-reversible-concentration-at-finite-error). +The remaining entropy stays in the other helper qubits. Reversible polarization concentration is established prior machinery [SV98](../references/RELATED_WORK.md#sv98); no measurement or purity creation is being asserted. See [Mixed helpers, Section 3](mixed-helpers.md#3-reversible-concentration-at-finite-error). ### U2. Use occupied spectators and compressed leaders @@ -115,7 +115,7 @@ This is not a per-gate error estimate. Exact helper marginal return follows from ## 5. Boundaries that belong beside the main result -**Exact versus approximate.** For $`0\lt p\le1/2`$, full rank and exact preparation-reference return force the full unknown-helper operation. Thus the exact law has no polarization enhancement. This obstruction is already identified in the Outlook of [UHMG26](related-work.md#uhmg26); A is a matched fixed-error answer in the present architecture. +**Exact versus approximate.** For $`0\lt p\le1/2`$, full rank and exact preparation-reference return force the full unknown-helper operation. Thus the exact law has no polarization enhancement. This obstruction is already identified in the Outlook of [UHMG26](../references/RELATED_WORK.md#uhmg26); A is a matched fixed-error answer in the present architecture. **Entropy versus spectral concentration.** A correlated helper state $`(1-a)I/2^s+a|0^s\rangle\langle0^s|`$ can have extensive entropy deficit while retaining a substantial maximally mixed component. At small fixed error it obeys the unknown-helper routing scale. The converse is entropy-based, but its saturation requires more than entropy alone. See [Mixed helpers, Section 7](mixed-helpers.md#7-why-the-product-state-assumption-cannot-be-dropped). @@ -127,13 +127,13 @@ This is not a per-gate error estimate. Exact helper marginal return follows from A focused technical reading can proceed from the [main task](mixed-helpers.md#1-task-and-matching-law), through L1–L3 and U1–U3, to the scope boundaries above. The potentially consequential proof checks are the noncommuting conditional-log estimate, the removal of local terms without an invalid norm claim, the payload-sized continuity argument, and the one common good-sector phase needed for complete reference preservation. Every dependency has a canonical proof location rather than a separate duplicate derivation here. -For the originality comparison, [D26](related-work.md#d26) supplies the closest restricted-time bottleneck bound; [UHMG26](related-work.md#uhmg26) supplies the robustness–commutator framework, including multiple payload qubits. Merely invoking compression or changing architecture is not the claimed contribution. The additional statement is the matched extensive throughput law with fixed complete-operation error and returned preparation resources. +For the originality comparison, [D26](../references/RELATED_WORK.md#d26) supplies the closest restricted-time bottleneck bound; [UHMG26](../references/RELATED_WORK.md#uhmg26) supplies the robustness–commutator framework, including multiple payload qubits. Merely invoking compression or changing architecture is not the claimed contribution. The additional statement is the matched extensive throughput law with fixed complete-operation error and returned preparation resources. -The [verification guide](verification.md) maps those proofs to ten deterministic suites. Passing tests and source hashes establish reproducibility of the finite checks, not outside scientific endorsement. No external technical assessment is recorded by this map. +The [verification guide](../verification/README.md) maps those proofs to ten deterministic suites. Passing tests and source hashes establish reproducibility of the finite checks, not outside scientific endorsement. No external technical assessment is recorded by this map. -## 7. Exposition structure +## 7. Physical synthesis -A compact presentation can lead with the physical question and Theorem A, explain L1–L3 as the information-flow mechanism, and show U1–U3 as the matching realization. Result B fixes the exact endpoints. Result C explains why exact and approximate initialization differ and why general helper entropy is not a complete operational invariant. Keep the weighted-interface statement, support details, spectral certificates, and finite-control compilation available as supporting material rather than competing main stories. +The [interpretation](interpretation.md) connects the interface geometry, reusable initialization, and complete-operation error to the exact endpoints and resource-budget comparisons. It separates achievable bandwidth from finite-control runtime. ## 8. Quantitative accuracy and resource guarantees diff --git a/tools/check_learning.py b/tools/check_learning.py deleted file mode 100644 index 6d2b117..0000000 --- a/tools/check_learning.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Validate the common learning map; this does not assess learner progress.""" -from __future__ import annotations -from pathlib import Path -import re - - -def check_learning(root: Path) -> dict[str, int]: - text = (root/'docs/milestones.md').read_text() - headers = list(re.finditer(r'^### (M\d{2})\. (.+)$', text, re.M)) - expected = [f'M{i:02d}' for i in range(1, 31)] - assert [h[1] for h in headers] == expected, 'Expected exactly M01-M30 in order' - split = text.index('## Narrative and innovation') - assert sum(h.start() < split for h in headers) == 14, 'Background allocation changed' - assert sum(h.start() > split for h in headers) == 16, 'Narrative allocation changed' - assert 'QRB-W18-30-v1' in text - edges = 0 - for i, header in enumerate(headers): - end = headers[i+1].start() if i+1 < len(headers) else len(text) - section = text[header.end():end] - for field in ('Central question', 'Understanding target', 'Dependencies', 'Sources', 'Story role'): - assert f'**{field}:**' in section, f'{header[1]} lacks {field}' - match = re.search(r'\*\*Dependencies:\*\* (.*?)\. \*\*Teaching intensity:\*\* ([123])\.', section) - assert match, f'{header[1]} lacks valid dependencies/intensity' - deps = re.findall(r'M\d{2}', match[1]) - assert len(deps) == len(set(deps)) - assert all(d in expected[:i] for d in deps), f'{header[1]} has forward/cyclic dependency' - assert deps or (i == 0 and match[1] == 'None') - sources = section.split('**Sources:**', 1)[1].split('\n', 1)[0] - assert re.search(r'\[[^\]]+\]\([^\s)]+\)', sources), f'{header[1]} needs a source pointer' - edges += len(deps) - learning = (root/'docs/learning.md').read_text() - coaching = (root/'docs/coaching.md').read_text() - agents = (root/'AGENTS.md').read_text() - for name in ('README.md', 'llms.txt'): - entry = (root/name).read_text() - for target in ('docs/milestones.md', 'docs/learning.md', 'docs/coaching.md'): - assert target in entry, f'{name} omits {target}' - assert 'John Watrous' in learning and '2018' in learning - assert 'https://jhwatrous.github.io/TQI.errata.pdf' in learning - assert 'docs/coaching.md' in agents and 'docs/milestones.md' in agents - assert 'q=\\min(2+f,6)' in coaching - assert '1–3 targeted learning rounds' in coaching - assert '60 challenge questions' in coaching - assert 'M01–M30' in coaching - assert '
' not in learning, 'Do not reintroduce a competing expandable-answer course' - # Raw pipes inside a math cell can split a GitHub Markdown table before - # MathJax sees it. Keep cell delimiters unambiguous in the new reading pages. - for name in ('README.md', 'docs/learning.md', 'docs/learning-bridges.md'): - columns = None - for line in (root/name).read_text().splitlines(): - if line.startswith('|'): - count = len(re.findall(r'(? list[str]: - """Use inline number text, not legacy MathML table rows, for equation labels.""" - if re.search(r'\\tag\*?\s*\{', line): - raise AssertionError(f'{label}:{index}: legacy equation tag is unsafe in native MathML') - return re.findall(r'\\qquad\s*\\text\{\(([^(){}]+)\)\}', line) - - -def check_reading_text(text: str, label: str) -> int: - """Check Markdown structures that can silently change mathematical meaning.""" - fenced = re.compile(r'^([`~]{3,}).*$') - in_fence = None - math_fence = False - display = False - table_width = None - tables = 0 - tags = [] - for index, line in enumerate(text.splitlines(), 1): - stripped = line.strip() - match = fenced.fullmatch(stripped) - if match: - mark = match[1] - if in_fence is None: - in_fence = mark[0] - math_fence = stripped[len(mark):].strip() == 'math' - elif mark[0] == in_fence: - in_fence = None - math_fence = False - table_width = None - continue - if in_fence: - if math_fence: - tags.extend(equation_labels(line, label, index)) - continue - if stripped == '$$': - display = not display - table_width = None - continue - if display: - tags.extend(equation_labels(line, label, index)) - continue - if stripped.startswith('|'): - width = len(re.findall(r'(? dict[str, int]: - pages = [root/'README.md', root/'AGENTS.md', root/'llms.txt', *sorted((root/'docs').glob('*.md'))] - tables = 0 - for page in pages: - if page.is_symlink(): - raise AssertionError(f'Reading file is a symbolic link: {page}') - tables += check_reading_text(page.read_text(), str(page.relative_to(root))) - report = json.loads((root/'results/verification.json').read_text()) - if report.get('all_passed') is not True: - raise AssertionError('Recorded verification does not explicitly report success') - for suite in report['suites']: - summary = suite['summary'] - flags = (summary.get('all_passed'), summary.get('all_assertions_passed'), - summary.get('summary', {}).get('all_passed')) - if not any(flag is True for flag in flags): - raise AssertionError(f"No explicit success flag: {suite['script']}") - closure = next(x for x in report['suites'] if x['script'] == 'verify_scientific_closure.py') - certificate = root/'results/scientific-closure.json' - if hashlib.sha256(certificate.read_bytes()).hexdigest() != closure['output_sha256']: - raise AssertionError('Tracked scientific certificates differ from the recorded executed output') - return {'reading_files': len(pages), 'tables': tables, 'tracked_certificate_files': 1} - - -if __name__ == '__main__': - print('PASS:', check_release(Path(__file__).resolve().parents[1])) diff --git a/tools/inspect_hosted_render.py b/tools/inspect_hosted_render.py deleted file mode 100644 index 8da7dfb..0000000 --- a/tools/inspect_hosted_render.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Inspect actual GitHub Markdown in Chromium; save screenshots and DOM diagnostics. - -Run separately from the offline scientific checks. It uses no credentials and -only reads public pages of this repository at a supplied immutable commit. -A blocked or unrendered page is a failure, never a successful visual check. -""" -from __future__ import annotations -import argparse -import hashlib -import json -from pathlib import Path -import re -import sys -from urllib.parse import quote - -REPOSITORY = 'GoGoKo699/Quantum-Routing-Bandwidth' -PAGES = ('README.md', 'docs/learning.md', 'docs/learning-bridges.md', - 'docs/milestones.md', 'docs/bandwidth.md', 'docs/mixed-helpers.md', - 'docs/accuracy-and-resources.md', 'docs/theorem-map.md', - 'docs/entropy-flow.md', 'docs/control-models.md', 'docs/coaching.md', - 'docs/related-work.md', 'docs/verification.md') - -SNAPSHOT = r'''() => { - const article = document.querySelector('article.markdown-body') || document.querySelector('.markdown-body'); - if (!article) return {article: false}; - function elements(root) { - let out = [...root.querySelectorAll('*')]; - for (const item of [...out]) if (item.shadowRoot) out.push(...elements(item.shadowRoot)); - return out; - } - const all = elements(article); - const markers = all.filter(x => x.localName === 'math-renderer'); - const errors = all.filter(x => x.matches('mjx-merror,merror,.MathJax_Error,.flash-error,[data-mjx-error],[data-mml-node="merror"]')); - // MathML Core does not support the legacy mlabeledtr numbering element. - // Its presence can stack every token vertically without a parse error. - const nativeLayoutErrors = all.filter(x => - x.namespaceURI === 'http://www.w3.org/1998/Math/MathML' && - (x.localName === 'mlabeledtr' || - (x.localName === 'mtd' && x.parentElement?.localName !== 'mtr')) - ).map(x => ({element:x.localName, parent:x.parentElement?.localName, - text:(x.textContent || '').trim().slice(0,180)})); - const nodes = markers.map(x => { - const inner = elements(x.shadowRoot || x); - const rectangle = x.getBoundingClientRect(); - return {markup: x.outerHTML.slice(0,1800), shadow: x.shadowRoot?.innerHTML.slice(0,1800), ready: inner.some(y => y.matches('mjx-container,svg,math,img')), - width:rectangle.width, height:rectangle.height, - error: /Math rendering failed|Undefined control sequence|ParseError|Unable to render expression|macros are not allowed|Missing (open|close) brace/i.test(x.textContent || '')}; - }); - const copy = article.cloneNode(true); - copy.querySelectorAll('math-renderer,pre,code').forEach(x => x.remove()); - const literal = (copy.textContent || '').split('\n').filter(x => x.includes('$')); - return {unready_details: nodes.filter(x => !x.ready), sample_ready: nodes.find(x => x.ready), - literal_math_lines: literal, article: true, heading: article.querySelector('h1')?.textContent?.trim(), - markers: markers.length, ready: nodes.filter(x => x.ready).length, - errors: errors.map(x => (x.getAttribute('data-mjx-error') || x.textContent || '').slice(0,180)), - marker_errors: nodes.filter(x => x.error).length, native_layout_errors:nativeLayoutErrors, - equation_geometry:nodes.map(x => ({width:x.width,height:x.height})), - rendered_containers: all.filter(x => x.localName === 'mjx-container').length, - page_width: document.documentElement.scrollWidth, viewport: window.innerWidth, - table_columns: [...article.querySelectorAll('table')].map(t => [...t.rows].map(row => row.cells.length))}; -}''' - - -def source_math_count(text: str) -> int: - math_fences = len(re.findall(r'^```math\s*\n.*?^```\s*$', text, flags=re.S|re.M)) - text = re.sub(r'```.*?```', '', text, flags=re.S) - displays = re.findall(r'\$\$.*?\$\$', text, re.S) - text = re.sub(r'\$\$.*?\$\$', '', text, flags=re.S) - return math_fences + len(displays) + len(re.findall(r'(? list[str]: - problems = [] - if state.get('heading') != title: - problems.append('missing expected document title') - if state.get('markers') != expected or state.get('ready', 0) < expected: - problems.append('missing or unfinished mathematics') - if state.get('literal_math_lines'): - problems.append('unprocessed math delimiters') - if state.get('errors') or state.get('marker_errors'): - problems.append('mathematical rendering error') - if state.get('native_layout_errors'): - problems.append('unsupported native MathML equation layout') - if state.get('page_width', 0) > width+3: - problems.append('page-level horizontal overflow') - if any(len(set(cols)) > 1 for cols in state.get('table_columns', [])): - problems.append('inconsistent rendered table cells') - return [f'{width}px: {x}' for x in problems] - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--ref', required=True) - parser.add_argument('--output', type=Path, default=Path('build/hosted-render')) - args = parser.parse_args() - if not re.fullmatch(r'[0-9a-f]{40}', args.ref): - parser.error('--ref must be a full immutable Git commit SHA') - from playwright.sync_api import sync_playwright - root = Path(__file__).resolve().parents[1] - args.output.mkdir(parents=True, exist_ok=True) - report = {'repository': REPOSITORY, 'ref': args.ref, - 'scope': 'Actual public GitHub rendering; automated DOM/layout checks and screenshot evidence, not scientific review.', - 'source_sha256': {}, 'pages': []} - # Keep the exact public source associated with each inspected page alongside - # the screenshots. No authentication data or private repository is included. - for name in PAGES: - raw = (root/name).read_bytes() - destination = args.output/'sources'/name - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_bytes(raw) - report['source_sha256'][name] = hashlib.sha256(raw).hexdigest() - with sync_playwright() as p: - browser = p.chromium.launch() - context = browser.new_context(viewport={'width': 1180, 'height': 900}, color_scheme='light') - page = context.new_page() - for name in PAGES: - row = {'file': name, 'checks': [], 'problems': []} - expected = source_math_count((root/name).read_text()) - row['expected_math'] = expected - url = f'https://github.com/{REPOSITORY}/blob/{args.ref}/{quote(name)}' - row['url'] = url - try: - response = page.goto(url, wait_until='domcontentloaded', timeout=45000) - row['http_status'] = response.status if response else None - if not response or response.status != 200: - raise RuntimeError(f'GitHub returned {row["http_status"]}') - page.locator('article.markdown-body, .markdown-body').first.wait_for(timeout=30000) - for width in (1180, 390): - page.set_viewport_size({'width': width, 'height': 900}) - markers = page.locator('math-renderer') - for i in range(markers.count()): - markers.nth(i).scroll_into_view_if_needed(timeout=5000) - page.wait_for_timeout(50) - for _ in range(20): - state = page.evaluate(SNAPSHOT) - if state.get('ready', 0) >= expected: - break - page.wait_for_timeout(250) - state = page.evaluate(SNAPSHOT) - title = (root/name).read_text().splitlines()[0].removeprefix('# ') - row['problems'].extend(snapshot_problems(state, expected, title, width)) - row['checks'].append(state) - page.evaluate('window.scrollTo(0,0)') - page.screenshot(path=str(args.output/f'{name.replace("/", "_")}-{width}.png'), full_page=True) - except Exception as exc: - row['problems'].append(str(exc)[:1000]) - row['passed'] = not row['problems'] - report['pages'].append(row) - print(json.dumps(row), flush=True) - if row.get('http_status') in (403, 429) or any('ERR_' in x for x in row['problems']): - break - context.close(); browser.close() - report['all_passed'] = len(report['pages']) == len(PAGES) and all(x['passed'] for x in report['pages']) - (args.output/'report.json').write_text(json.dumps(report, indent=2)+'\n') - print('HOSTED_RENDER_RESULT='+json.dumps(report), flush=True) - if not report['all_passed']: - sys.exit(1) - - -if __name__ == '__main__': - main() diff --git a/tools/test_release_checks.py b/tools/test_release_checks.py deleted file mode 100644 index 159bcf0..0000000 --- a/tools/test_release_checks.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Regression tests for release validation, distinct from scientific suites.""" -from __future__ import annotations -import hashlib -import json -from pathlib import Path -import tempfile -import unittest -from check_release import check_reading_text, check_release -from inspect_hosted_render import snapshot_problems - - -class ReadingChecks(unittest.TestCase): - def test_valid_math_and_table(self): - text = '| A | B |\n|---|---|\n| $\\lvert x\\rangle$ | $\\lVert X\\rVert$ |\n\n$$\n|x|\\qquad\\text{(1)}\n$$\n' - self.assertEqual(check_reading_text(text, 'fixture'), 1) - - def test_unescaped_ket_in_table(self): - with self.assertRaisesRegex(AssertionError, 'table cells'): - check_reading_text('| A | B |\n|---|---|\n| $|x\\rangle$ | yes |\n', 'fixture') - - def test_duplicate_label(self): - with self.assertRaisesRegex(AssertionError, 'repeated equation'): - check_reading_text('$$\nx\\qquad\\text{(1)}\n$$\n\n$$\ny\\qquad\\text{(1)}\n$$\n', 'fixture') - - def test_labels_in_math_fences(self): - with self.assertRaisesRegex(AssertionError, 'repeated equation'): - check_reading_text('```math\nx\\qquad\\text{(1)}\n```\n\n```math\ny\\qquad\\text{(1)}\n```\n', 'fixture') - - def test_fenced_examples_are_not_tables(self): - self.assertEqual(check_reading_text('```text\n| a |\n| a | b |\n$$\n```\n', 'fixture'), 0) - - def test_unclosed_fence(self): - with self.assertRaisesRegex(AssertionError, 'code fence'): - check_reading_text('```python\nx=1\n', 'fixture') - - def test_unclosed_math(self): - with self.assertRaisesRegex(AssertionError, 'display mathematics'): - check_reading_text('$$\nx\n', 'fixture') - - def test_result_integrity_and_explicit_success(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - (root/'docs').mkdir(); (root/'results').mkdir() - for name in ('README.md', 'AGENTS.md', 'llms.txt'): - (root/name).write_text('# Fixture\n') - content = b'{"all_passed": true}\n' - path = root/'results/scientific-closure.json'; path.write_bytes(content) - result = {'all_passed': True, 'suites': [{'script': 'verify_scientific_closure.py', - 'output_sha256': hashlib.sha256(content).hexdigest(), 'summary': {'all_passed': True}}]} - summary = root/'results/verification.json'; summary.write_text(json.dumps(result)) - self.assertEqual(check_release(root)['tracked_certificate_files'], 1) - path.write_bytes(content+b' ') - with self.assertRaisesRegex(AssertionError, 'certificates differ'): - check_release(root) - path.write_bytes(content) - result['suites'][0]['summary']['all_passed'] = 'true' - summary.write_text(json.dumps(result)) - with self.assertRaisesRegex(AssertionError, 'explicit success flag'): - check_release(root) - - def test_legacy_tag_in_math_fence(self): - with self.assertRaisesRegex(AssertionError, 'legacy equation tag'): - check_reading_text('```math\nx=y\\tag{1}\n```\n', 'fixture') - - def test_legacy_tag_in_dollar_display(self): - with self.assertRaisesRegex(AssertionError, 'legacy equation tag'): - check_reading_text('$$\nx=y\\tag{1}\n$$\n', 'fixture') - - def test_ready_math_with_unsupported_layout_is_not_a_pass(self): - state = {'heading': 'Fixture', 'markers': 1, 'ready': 1, - 'page_width': 1180, 'errors': [], 'marker_errors': 0, - 'native_layout_errors': [{'element': 'mlabeledtr'}]} - self.assertEqual(snapshot_problems(state, 1, 'Fixture', 1180), - ['1180px: unsupported native MathML equation layout']) - - def test_valid_hosted_snapshot(self): - state = {'heading': 'Fixture', 'markers': 1, 'ready': 1, - 'page_width': 390, 'errors': [], 'marker_errors': 0, - 'native_layout_errors': [], 'table_columns': [[2, 2]]} - self.assertEqual(snapshot_problems(state, 1, 'Fixture', 390), []) - - -if __name__ == '__main__': - unittest.main() diff --git a/docs/verification.md b/verification/README.md similarity index 64% rename from docs/verification.md rename to verification/README.md index 1291e6d..e221e71 100644 --- a/docs/verification.md +++ b/verification/README.md @@ -1,21 +1,21 @@ # Verification and reproduction -Proofs are in [Bandwidth](bandwidth.md), [Mixed helpers](mixed-helpers.md), [Entropy flow](entropy-flow.md), [Accuracy and resources](accuracy-and-resources.md), and [Control models](control-models.md). Programs check finite identities and stated numerical inequalities. They are not experiments, independent review, or numerical proofs of asymptotic theorems. +Proofs are in [Bandwidth](../science/bandwidth.md), [Mixed helpers](../science/mixed-helpers.md), [Entropy flow](../science/entropy-flow.md), [Accuracy and resources](../science/accuracy-and-resources.md), and [Control models](../science/control-models.md). Programs check finite identities and stated numerical inequalities. They are not experiments, independent review, or numerical proofs of asymptotic theorems. ## Run Use Python 3.13 with the pinned NumPy 2.3.5 and SciPy 1.17.0 dependencies: ```bash -python -m pip install -r requirements.txt +python -m pip install -r verification/requirements.txt python check_repository.py -python tools/test_release_checks.py -python verify.py +python verification/tools/test_structure.py +python verification/run_all.py ``` -The verifier copies check sources into a temporary directory, runs each with one BLAS thread and assertions enabled, and writes complete JSON outputs, logs, and a summary under `build/verification/`. Use `--output PATH` for another directory. A failed assertion, nonzero exit, missing success flag, or timeout fails the run. Optimization mode is rejected. +Run the commands from the repository root. The scientific programs are in `verification/checks/`; the runner copies check sources into a temporary directory, runs each with one BLAS thread and assertions enabled, and writes complete JSON outputs, logs, and a summary under `build/verification/`. Use `--output PATH` for another directory. A failed assertion, nonzero exit, missing success flag, or timeout fails the run. Optimization mode is rejected. -The [finite certificates and full closure checks](../results/scientific-closure.json) retain the quantitative examples. The [tracked summary](../results/verification.json) records source hashes, output hashes, environment, counts, and diagnostic residuals from an executed run. Timing and raw-output hashes can differ between runs; they are provenance, not portable numerical targets. Normal verification never replaces this tracked record. +The [finite certificates and full closure checks](results/scientific-closure.json) retain the quantitative examples. The [tracked summary](results/verification.json) records source hashes, output hashes, environment, counts, and diagnostic residuals from an executed run. Timing and raw-output hashes can differ between runs; they are provenance, not portable numerical targets. Normal verification never replaces this tracked record. ## Coverage @@ -42,20 +42,20 @@ The ensemble suite includes a selected collective state that violates an incorre ## Maintenance -`check_repository.py` checks syntax, local links and citation anchors, math delimiters, bibliography keys, the contact paragraph, the original license, the 30-milestone map, exact suite coverage, and all check-source hashes. The release checker additionally checks table-cell consistency across every reading page, duplicate equation labels in dollar displays and math fences, unsafe legacy numbering syntax, explicit success flags, and the digest of the tracked finite-size certificate file against its executed-output record. Twelve regression tests exercise valid input and deliberately malformed material, including a ready-but-invalid native MathML layout; these are structural tests, not extra scientific suites. CI runs these checks and the ten numerical suites. Update tracked scientific results only from a successful associated run after changing scientific check sources. Keep generated cases in the ignored build directory or export them as a verification bundle. +`check_repository.py` checks syntax, local links and citation anchors, math delimiters, bibliography keys, the contact paragraph, the original license, the 30-milestone map, exact suite coverage, and all check-source hashes. The release checker additionally checks table-cell consistency across every reading page, duplicate equation labels in dollar displays and math fences, unsafe legacy numbering syntax, explicit success flags, and the digest of the tracked finite-size certificate file against its executed-output record. Structural regression tests exercise valid input and deliberately malformed material, including a ready-but-invalid native MathML layout and a shared learning map contaminated by personal assessment rules; these are structural tests, not extra scientific suites. CI runs these checks and the ten numerical suites. Update tracked scientific provenance only from a successful associated run when paths or source programs change. Preserve numerical certificate bytes when their calculation is unchanged. Keep generated cases in the ignored build directory or export them as a verification bundle. Use protected GitHub mathematical syntax for formulas that contain Markdown-sensitive characters. Fenced math blocks preserve backslashes in norm and spacing commands; backtick-protected inline math preserves starred subscripts and punctuation boundaries. Prefer supported upright commands and explicitly braced starred indices. Preserve equation numbers with ordinary `\qquad\text{(n)}` content rather than `\tag{n}`. The latter can emit legacy `mlabeledtr` rows that stack tokens in native browser MathML even when parsing succeeds; the source checker rejects that numbering syntax in mathematical blocks. The [official syntax reference](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions) and the hosted check are complementary to local source validation. ## Hosted rendering -The separate `Inspect hosted mathematics` workflow opens thirteen actual public GitHub pages at an immutable commit in Chromium. It checks entrypoint, learning, and scientific pages at desktop and mobile widths, verifies the expected mathematics has rendered, detects GitHub and MathJax error messages and unprocessed delimiters, checks table structure, rejects unsupported native MathML table rows, and records equation geometry and page-level overflow. Screenshots, the exact inspected public sources with SHA-256 hashes, and a JSON report are retained as workflow artifacts for 14 days. It needs network access and a separate Playwright installation; it is not a dependency of the offline scientific verifier. +The separate `Inspect hosted mathematics` workflow opens the root README and every science, learning, reference, and verification Markdown page at an immutable commit in Chromium. It checks entrypoint, learning, and scientific pages at desktop and mobile widths, verifies the expected mathematics has rendered, detects GitHub and MathJax error messages and unprocessed delimiters, checks table structure, rejects unsupported native MathML table rows, and records equation geometry and page-level overflow. Screenshots, the exact inspected public sources with SHA-256 hashes, and a JSON report are retained as workflow artifacts for 14 days. It needs network access and a separate Playwright installation; it is not a dependency of the offline scientific verifier. To invoke the same check in a network-enabled environment: ```bash python -m pip install playwright==1.55.0 python -m playwright install chromium -python tools/inspect_hosted_render.py --ref COMMIT_SHA +python verification/tools/inspect_hosted_render.py --ref COMMIT_SHA ``` Replace `COMMIT_SHA` with a full 40-character commit hash in this repository. The script uses no authentication and only reads this repository's public pages. A blocked host or unfinished render fails the check; it is not silently replaced by a local preview. A hosted-browser diagnostic and a screenshot review are different evidence from mathematical verification. Neither establishes independent scientific review or validates a different hosting renderer. diff --git a/checks/audit_conditional_rate.py b/verification/checks/audit_conditional_rate.py similarity index 100% rename from checks/audit_conditional_rate.py rename to verification/checks/audit_conditional_rate.py diff --git a/checks/audit_ensemble_cut.py b/verification/checks/audit_ensemble_cut.py similarity index 100% rename from checks/audit_ensemble_cut.py rename to verification/checks/audit_ensemble_cut.py diff --git a/checks/audit_translation_approximation.py b/verification/checks/audit_translation_approximation.py similarity index 100% rename from checks/audit_translation_approximation.py rename to verification/checks/audit_translation_approximation.py diff --git a/checks/finite_control.py b/verification/checks/finite_control.py similarity index 100% rename from checks/finite_control.py rename to verification/checks/finite_control.py diff --git a/checks/recursive_three.py b/verification/checks/recursive_three.py similarity index 100% rename from checks/recursive_three.py rename to verification/checks/recursive_three.py diff --git a/checks/verify_entropy_budget.py b/verification/checks/verify_entropy_budget.py similarity index 98% rename from checks/verify_entropy_budget.py rename to verification/checks/verify_entropy_budget.py index 4eb80a0..24ece0a 100644 --- a/checks/verify_entropy_budget.py +++ b/verification/checks/verify_entropy_budget.py @@ -1,6 +1,6 @@ """Adversarial finite-dimensional checks of the entropy-deficit moment bound. -The universal claims rest on the analytical proof in docs/bandwidth.md. +The universal claims rest on the analytical proof in science/bandwidth.md. Tests include exact maximization over fixed-spectrum unitary orbits, Gibbs states of H^2 (entropy-constrained moment maximizers), and noncommuting states. """ diff --git a/checks/verify_finite_control.py b/verification/checks/verify_finite_control.py similarity index 100% rename from checks/verify_finite_control.py rename to verification/checks/verify_finite_control.py diff --git a/checks/verify_full_nine.py b/verification/checks/verify_full_nine.py similarity index 100% rename from checks/verify_full_nine.py rename to verification/checks/verify_full_nine.py diff --git a/checks/verify_mixed_helpers.py b/verification/checks/verify_mixed_helpers.py similarity index 100% rename from checks/verify_mixed_helpers.py rename to verification/checks/verify_mixed_helpers.py diff --git a/checks/verify_scientific_closure.py b/verification/checks/verify_scientific_closure.py similarity index 100% rename from checks/verify_scientific_closure.py rename to verification/checks/verify_scientific_closure.py diff --git a/checks/verify_workspace_construction.py b/verification/checks/verify_workspace_construction.py similarity index 100% rename from checks/verify_workspace_construction.py rename to verification/checks/verify_workspace_construction.py diff --git a/requirements.txt b/verification/requirements.txt similarity index 100% rename from requirements.txt rename to verification/requirements.txt diff --git a/results/scientific-closure.json b/verification/results/scientific-closure.json similarity index 94% rename from results/scientific-closure.json rename to verification/results/scientific-closure.json index 7386b05..f36169f 100644 --- a/results/scientific-closure.json +++ b/verification/results/scientific-closure.json @@ -289,7 +289,7 @@ "p": 0.01, "payload_bus_input_columns": 32, "helper_sectors": 64, - "purified_isometry_operator_error": 0.04228054853002728, + "purified_isometry_operator_error": 0.042280548530027266, "same_preparation_bound": 0.04882258477385236 }, { @@ -309,69 +309,69 @@ "p": 0.4, "payload_bus_input_columns": 32, "helper_sectors": 64, - "purified_isometry_operator_error": 1.2713709136204083, + "purified_isometry_operator_error": 1.2713709136204088, "same_preparation_bound": 1.523280670132724 } ], "perturbation_checks": [ { "time": 0.6413895334877393, - "operator_error": 0.017068530294159712, + "operator_error": 0.017068530294159705, "Duhamel_upper": 0.02112885840578925 }, { "time": 0.07384639959688252, - "operator_error": 0.002085233770911831, + "operator_error": 0.0020852337709118315, "Duhamel_upper": 0.002088518438619112 }, { "time": 1.7129631722724368, - "operator_error": 0.02938512320997811, + "operator_error": 0.029385123209977822, "Duhamel_upper": 0.05033711297919295 }, { "time": 1.5264082231101628, - "operator_error": 0.036816320350972216, + "operator_error": 0.036816320350972195, "Duhamel_upper": 0.042710437623595596 }, { "time": 1.6182812521287437, - "operator_error": 0.02917270209243977, + "operator_error": 0.029172702092439995, "Duhamel_upper": 0.04645824983778291 }, { "time": 1.4308817167826757, - "operator_error": 0.02997651091563912, + "operator_error": 0.02997651091563916, "Duhamel_upper": 0.04652593781143633 }, { "time": 1.540247490272937, - "operator_error": 0.03446275926605976, - "Duhamel_upper": 0.04462872453184362 + "operator_error": 0.034462759266059816, + "Duhamel_upper": 0.044628724531843626 }, { "time": 0.8742319016315779, - "operator_error": 0.018621709484664777, + "operator_error": 0.01862170948466487, "Duhamel_upper": 0.021696219045081004 }, { "time": 1.5731952035922157, - "operator_error": 0.024368602975132006, + "operator_error": 0.024368602975131957, "Duhamel_upper": 0.040608811947598515 }, { "time": 0.2032475488523221, - "operator_error": 0.009520774279861224, - "Duhamel_upper": 0.009539615448033403 + "operator_error": 0.009520774279861244, + "Duhamel_upper": 0.009539615448033402 }, { "time": 1.8671045194284732, - "operator_error": 0.0352720059424501, + "operator_error": 0.035272005942450384, "Duhamel_upper": 0.06537201088549645 }, { "time": 0.7856828169294799, - "operator_error": 0.028901618543840157, + "operator_error": 0.028901618543840293, "Duhamel_upper": 0.03632336699100447 } ], diff --git a/results/verification.json b/verification/results/verification.json similarity index 64% rename from results/verification.json rename to verification/results/verification.json index 6db4412..fb77d77 100644 --- a/results/verification.json +++ b/verification/results/verification.json @@ -1,12 +1,12 @@ { "scope": "Deterministic numerical consistency checks; not independent proof review or hardware data.", - "python": "3.13.5", - "platform": "Linux-6.18.44-x86_64-with-glibc2.41", + "python": "3.13.16", + "platform": "Linux-6.17.0-1022-azure-x86_64-with-glibc2.39", "suites": [ { "script": "verify_workspace_construction.py", - "elapsed_seconds": 1.23, - "output_sha256": "1732f227f519b6f47eccfee696b9a8ffbc8c59e589acd9af8d97c72a620706f1", + "elapsed_seconds": 0.963, + "output_sha256": "bcf2d5dea4711dd1d3da5c41b91fee2ae77fb0cf4a9056cacf3fbdc059e83b41", "summary": { "model": "Free internal controls, J=1 per contact, s initialized helpers per module, arbitrary bus", "all_passed": true, @@ -14,8 +14,8 @@ "gate_count": 12, "route_count": 8, "scaling_count": 16, - "max_swap_isometry_error": 1.3071221847431714e-15, - "max_route_isometry_error": 8.99933488754697e-15, + "max_swap_isometry_error": 1.3063632377895411e-15, + "max_route_isometry_error": 8.858715569395616e-15, "largest_route": { "n": 3, "s": 2, @@ -23,7 +23,7 @@ "input_columns": 128, "bus_swaps": 7, "time": 5.497787143782138, - "isometry_operator_error": 5.5857234926833385e-15, + "isometry_operator_error": 5.59366902760566e-15, "full_data_and_bus_process_fidelity": 0.9999999999999905, "helpers_returned": true } @@ -31,8 +31,8 @@ }, { "script": "verify_entropy_budget.py", - "elapsed_seconds": 1.359, - "output_sha256": "c3353e0598cce58e22ad2a65423ebece6bb07073b5ca18794fb8b505f8002098", + "elapsed_seconds": 1.689, + "output_sha256": "73d6a7a7b571d704f2c7c91c7279c3db8ea65365ef1d54a6421d4eaab3936477", "summary": { "seed": 2026101607, "group_scaling_tests": 16512, @@ -43,7 +43,7 @@ "scalar_mgfs": 54, "balanced_partitions": 16512, "min_operator_square_difference_eigenvalue": 0.0, - "max_conditional_rate_ratio": 0.20993163216153346, + "max_conditional_rate_ratio": 0.2099316321615335, "all_passed": true }, "gibbs_tests_count": 120, @@ -54,16 +54,16 @@ }, { "script": "audit_conditional_rate.py", - "elapsed_seconds": 0.945, - "output_sha256": "5aa826199704fad562539b276d5a9526c9249a8fed329738e84fff8c11687c5a", + "elapsed_seconds": 0.422, + "output_sha256": "fd209cd43acf84c7fb8af2a5afc0c0ca905a355124c4e8c8f0a517a0e9597fe8", "summary": { "all_assertions_passed": true, "states_tested": 204, "qubit_bus_states_tested": 114, - "max_qubit_bus_optimized_rate_nats": 1.6151941802831211, - "max_ratio_to_elementary_bound": 0.5710573789056209, - "max_spectral_formula_residual": 3.419486915845482e-14, - "max_dual_optimum_residual": 1.887379141862766e-15, + "max_qubit_bus_optimized_rate_nats": 1.6151941802831218, + "max_ratio_to_elementary_bound": 0.5710573789056211, + "max_spectral_formula_residual": 7.238654120556021e-14, + "max_dual_optimum_residual": 1.9984014443252818e-15, "scope": "For every sampled state, optimize over all Hermitian h with Tr(rho h^2)=1. Not a global state optimization.", "seed": 2026101601, "cases_count": 204 @@ -71,15 +71,15 @@ }, { "script": "audit_ensemble_cut.py", - "elapsed_seconds": 1.225, - "output_sha256": "f964a263505649b72ef5ea5ba827de56cef7e8a49f09dd0111f0969a705f651d", + "elapsed_seconds": 0.922, + "output_sha256": "ff82a5c9d1a0593ab6cf6492796f52ad7cef06df3d1aa449ebb4ff0db100e218", "summary": { "all_assertions_passed": true, "segments": 18, "pure_states_checked": 1152, - "maximum_finite_difference_residual": 1.554406963227839e-06, - "maximum_flat_moment_residual": 6.661338147750939e-16, - "maximum_observed_bound_ratio": 0.08755567546472029, + "maximum_finite_difference_residual": 1.7497813687532282e-06, + "maximum_flat_moment_residual": 7.771561172376096e-16, + "maximum_observed_bound_ratio": 0.08755567546472015, "selected_GHZ_state": { "n": 64, "p": 0.1, @@ -94,7 +94,7 @@ }, { "script": "audit_translation_approximation.py", - "elapsed_seconds": 0.694, + "elapsed_seconds": 0.132, "output_sha256": "9de84e02911247a9ab54a736d0a98c5562396ac8e839ed823703262af94b26c5", "summary": { "all_assertions_passed": true, @@ -110,7 +110,7 @@ }, { "script": "recursive_three.py", - "elapsed_seconds": 0.682, + "elapsed_seconds": 0.099, "output_sha256": "4000ad570b792060da3a22050aef5cfd4e524ad056237aefb60268ce688629de", "summary": { "all_passed": true, @@ -121,7 +121,7 @@ }, { "script": "verify_finite_control.py", - "elapsed_seconds": 0.793, + "elapsed_seconds": 0.28, "output_sha256": "f664a6fea3ef22ff7b2f415474330578f97a4fd3593820d1fef5618c5ee1ded2", "summary": { "all_passed": true, @@ -140,23 +140,23 @@ }, { "script": "verify_full_nine.py", - "elapsed_seconds": 2.956, - "output_sha256": "479dffb9c24d659344c2b34c36b9afa35a594a73b8d452ae62f6b3af4c06a01e", + "elapsed_seconds": 3.579, + "output_sha256": "c0e58ab769999a61849d242bc163452dcd5637e1d395490c6320930b375e3d36", "summary": { "data_qubits": 9, "bus_qubits": 1, "full_input_columns": 1024, "explicit_two_qubit_control_gates": 390, - "operator_error_upper_bound_by_unnormalized_Frobenius": 6.639096555949766e-15, - "maximum_entry_error": 3.510833468576701e-16, - "runtime_seconds": 2.3003544910000073, + "operator_error_upper_bound_by_unnormalized_Frobenius": 8.273281641021161e-15, + "maximum_entry_error": 8.326672684688674e-16, + "runtime_seconds": 3.474018029, "all_passed": true } }, { "script": "verify_mixed_helpers.py", - "elapsed_seconds": 2.118, - "output_sha256": "b9043d5748f4b025c0cb5d127543e599891b2b5184cbe5af576091fcfffcf1d5", + "elapsed_seconds": 2.202, + "output_sha256": "264dfc2e5e5e1770950242c2629f2d6c72be8e666598383ea45f963c4f2a439a", "summary": { "all_passed": true, "scope": "Analytical spectral sums and full helper-block operator checks; not physical noise simulation or independent proof review.", @@ -166,14 +166,14 @@ "complete_routes_count": 6, "finite_examples_count": 9, "same_entropy_counterexamples_count": 3, - "max_good_subspace_error": 9.154722157333965e-15, + "max_good_subspace_error": 9.119947107586788e-15, "max_helper_block_leakage": 0.0 } }, { "script": "verify_scientific_closure.py", - "elapsed_seconds": 1.57, - "output_sha256": "1069745656f8c44f6d30b12457df83babd566e9d7fcdc73124939af12e136d3e", + "elapsed_seconds": 1.141, + "output_sha256": "ce3cecc0796037897ae0855c0fb11362e50df58aab7d45c1f22f9f1aa4e51f1c", "summary": { "all_passed": true, "scope": "Exact rational spectral certification, finite operator checks and analytical timing bounds; no external review or hardware performance claim.", @@ -187,17 +187,17 @@ } ], "source_sha256": { - "checks/audit_conditional_rate.py": "e855c858fd9074c0565d3b51e6a8fc1177e31b2ee737e5fd3e3619c155c953e7", - "checks/audit_ensemble_cut.py": "cc562292fb567f23285e622d930b5a382996a6128e9bf6f612d14b7c568cadd5", - "checks/audit_translation_approximation.py": "9eecaf60ef95dd145020bb4bf7b6256d1b85748ddd98f0c5c5b4951cedf828aa", - "checks/finite_control.py": "d2dd789a8172b3fbd1b1fb7641e0fcdd5a87fe5b182992a3a984a5e16a550226", - "checks/recursive_three.py": "f4577aca7fad831b5e3628c662a13d0c75caec6759a10effec4f68143e180149", - "checks/verify_entropy_budget.py": "6e6d514c73822f88f8c34f1ffa7d797d616b6706ac353492a625fbd8b80db7a5", - "checks/verify_finite_control.py": "a51ecda7a4433bab18931ece1932e7fa6274c49bc4b6c02e1e4b6a9bf2806642", - "checks/verify_full_nine.py": "5921e758407b8ca5e10329b9b5136853aa4f4b7a354f660a800cb0cde341c362", - "checks/verify_mixed_helpers.py": "106277889eeacc211804b4a233e32d35aa7a9aa768d9adc480ed2f892a5e31a1", - "checks/verify_scientific_closure.py": "7836c6a751d9a07eb9462ce9d5eea12a979f47b60b7035fca7923de8923bc4d9", - "checks/verify_workspace_construction.py": "7553585f54782505ec513df840c1ed6d8b3a1c359dc6b8bfa239ce6b120c3698" + "verification/checks/audit_conditional_rate.py": "e855c858fd9074c0565d3b51e6a8fc1177e31b2ee737e5fd3e3619c155c953e7", + "verification/checks/audit_ensemble_cut.py": "cc562292fb567f23285e622d930b5a382996a6128e9bf6f612d14b7c568cadd5", + "verification/checks/audit_translation_approximation.py": "9eecaf60ef95dd145020bb4bf7b6256d1b85748ddd98f0c5c5b4951cedf828aa", + "verification/checks/finite_control.py": "d2dd789a8172b3fbd1b1fb7641e0fcdd5a87fe5b182992a3a984a5e16a550226", + "verification/checks/recursive_three.py": "f4577aca7fad831b5e3628c662a13d0c75caec6759a10effec4f68143e180149", + "verification/checks/verify_entropy_budget.py": "ea88ff42d5afe902432befb66a79fd0c1cd921ccee6b8b00cc9a80ef8d5110ea", + "verification/checks/verify_finite_control.py": "a51ecda7a4433bab18931ece1932e7fa6274c49bc4b6c02e1e4b6a9bf2806642", + "verification/checks/verify_full_nine.py": "5921e758407b8ca5e10329b9b5136853aa4f4b7a354f660a800cb0cde341c362", + "verification/checks/verify_mixed_helpers.py": "106277889eeacc211804b4a233e32d35aa7a9aa768d9adc480ed2f892a5e31a1", + "verification/checks/verify_scientific_closure.py": "7836c6a751d9a07eb9462ce9d5eea12a979f47b60b7035fca7923de8923bc4d9", + "verification/checks/verify_workspace_construction.py": "7553585f54782505ec513df840c1ed6d8b3a1c359dc6b8bfa239ce6b120c3698" }, "numpy": "2.3.5", "scipy": "1.17.0", diff --git a/verify.py b/verification/run_all.py similarity index 94% rename from verify.py rename to verification/run_all.py index cb74214..28c74c7 100644 --- a/verify.py +++ b/verification/run_all.py @@ -12,7 +12,8 @@ import tempfile import time -ROOT = Path(__file__).resolve().parent +ROOT = Path(__file__).resolve().parent.parent +CHECKS = ROOT/'verification'/'checks' SUITES = ( ('verify_workspace_construction.py', 'verify_workspace_construction.json'), ('verify_entropy_budget.py', 'verify_entropy_budget.json'), @@ -33,19 +34,19 @@ def main() -> None: if not __debug__ or os.environ.get('PYTHONOPTIMIZE'): parser.error('Assertions are part of verification; do not enable Python optimization.') output = args.output.resolve() - if output == ROOT or output == ROOT/'checks': + if output == ROOT or output == CHECKS: parser.error('Use a dedicated output directory.') output.mkdir(parents=True, exist_ok=True) env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', MKL_NUM_THREADS='1') report = {'scope': 'Deterministic numerical consistency checks; not independent proof review or hardware data.', 'python': platform.python_version(), 'platform': platform.platform(), 'suites': [], 'source_sha256': {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() - for p in sorted((ROOT/'checks').glob('*.py'))}} + for p in sorted((CHECKS).glob('*.py'))}} for package in ('numpy', 'scipy'): report[package] = __import__(package).__version__ with tempfile.TemporaryDirectory(prefix='qrb-checks-') as temporary: work = Path(temporary) - for p in (ROOT/'checks').glob('*.py'): + for p in (CHECKS).glob('*.py'): shutil.copy2(p, work/p.name) for script, filename in SUITES: print(f'Running {script}', flush=True) diff --git a/verification/tools/check_learning.py b/verification/tools/check_learning.py new file mode 100644 index 0000000..ee75407 --- /dev/null +++ b/verification/tools/check_learning.py @@ -0,0 +1,49 @@ +"""Validate the reader-independent 30-milestone map and public learning boundary.""" +from __future__ import annotations +from pathlib import Path +import re + +MAP_ID = 'QRB-W18-30-v1' +PERSONAL = re.compile(r'Revise\s*(?:→|->|–|-)\s*Learn|teaching intensity|learning rounds|challenge questions|failed challenges|retry rules|question count|passing requirement', re.I) + +def validate_map(text: str) -> dict[str, int]: + headers = list(re.finditer(r'^### (M\d{2})\. (.+)$', text, re.M)) + expected = [f'M{i:02d}' for i in range(1, 31)] + assert [h[1] for h in headers] == expected, 'Expected exactly M01-M30 in order' + assert MAP_ID in text, 'Missing stable map identifier' + split = text.index('## Narrative and innovation') + assert sum(h.start() < split for h in headers) == 14, 'Background allocation changed' + assert sum(h.start() > split for h in headers) == 16, 'Narrative allocation changed' + assert not PERSONAL.search(text), 'Personal assessment procedure in the common map' + edges = 0 + for i, h in enumerate(headers): + end = headers[i+1].start() if i+1 < len(headers) else len(text) + section = text[h.end():end] + for field in ('Central question', 'Understanding target', 'Dependencies', 'Conceptual connection', 'Sources', 'Story role'): + assert f'**{field}:**' in section, f'{h[1]} lacks {field}' + dep = re.search(r'\*\*Dependencies:\*\* ([^\n]+)', section) + assert dep, f'{h[1]} lacks dependencies' + ids = re.findall(r'M\d{2}', dep[1]) + assert len(ids) == len(set(ids)) and all(d in expected[:i] for d in ids), 'Forward/cyclic dependency' + assert ids or (i == 0 and dep[1].strip() == 'None.'), 'Missing prerequisite' + sources = section.split('**Sources:**', 1)[1].split('\n', 1)[0] + assert re.search(r'\[[^\]]+\]\([^\s)]+\)', sources), 'Missing scientific source pointer' + connection = section.split('**Conceptual connection:**', 1)[1].split('\n', 1)[0] + assert len(connection.split()) >= 12, 'Conceptual connection is not explanatory' + edges += len(ids) + return {'milestones': 30, 'background': 14, 'narrative': 16, 'dependency_edges': edges} + +def check_learning(root: Path) -> dict[str, int]: + report = validate_map((root/'learning/MILESTONES.md').read_text()) + for p in (root/'learning').glob('*.md'): + assert not PERSONAL.search(p.read_text()), f'Personal assessment procedure in {p.name}' + for name in ('README.md', 'llms.txt'): + text = (root/name).read_text() + for target in ('learning/MILESTONES.md', 'learning/WATROUS_BRIDGE.md', 'science/README.md', 'verification/README.md'): + assert target in text, f'{name} omits {target}' + anchor = (root/'learning/WATROUS_BRIDGE.md').read_text() + assert 'John Watrous' in anchor and '2018' in anchor + assert 'https://jhwatrous.github.io/TQI.errata.pdf' in anchor + assert not (root/'docs').exists(), 'Obsolete documentation tree retained' + assert not any('coach' in p.name.lower() for p in root.rglob('*.md') if 'build' not in p.parts), 'Public personal guide retained' + return report diff --git a/verification/tools/check_release.py b/verification/tools/check_release.py new file mode 100644 index 0000000..43107fd --- /dev/null +++ b/verification/tools/check_release.py @@ -0,0 +1,73 @@ +"""Dependency-free reading syntax and executed-certificate integrity checks.""" +from __future__ import annotations +import hashlib +import json +from pathlib import Path +import re + + +def reading_pages(root: Path) -> list[Path]: + return [root/'README.md', root/'AGENTS.md', root/'llms.txt', + *sorted((root/'science').glob('*.md')), *sorted((root/'learning').glob('*.md')), + *sorted((root/'references').glob('*.md')), root/'verification/README.md'] + + +def check_reading_text(text: str, label: str) -> int: + fence = None + math_fence = False + display = False + table_width = None + tables = 0 + labels = [] + for index, line in enumerate(text.splitlines(), 1): + stripped = line.strip() + match = re.fullmatch(r'([`~]{3,})(.*)', stripped) + if match: + marks, info = match.groups() + if fence is None: + fence = marks + math_fence = info.strip() == 'math' + elif marks[0] == fence[0] and len(marks) >= len(fence) and not info.strip(): + fence = None + math_fence = False + table_width = None + continue + if stripped == '$$' and fence is None: + display = not display + table_width = None + continue + if math_fence or display: + assert not re.search(r'\\tag\*?\{', line), f'{label}:{index}: unsafe native equation numbering' + labels += re.findall(r'\\text\{\((\d+)\)\}', line) + if fence or display: + continue + if stripped.startswith('|'): + width = len(re.findall(r'(? dict[str, int]: + tables = 0 + pages = reading_pages(root) + for page in pages: + assert not page.is_symlink(), f'Reading file is a symbolic link: {page}' + tables += check_reading_text(page.read_text(), str(page.relative_to(root))) + report = json.loads((root/'verification/results/verification.json').read_text()) + assert report.get('all_passed') is True, 'No explicit overall success' + for suite in report['suites']: + summary = suite['summary'] + flags = (summary.get('all_passed'), summary.get('all_assertions_passed'), summary.get('summary', {}).get('all_passed')) + assert any(f is True for f in flags), 'No explicit suite success flag' + closure = next(x for x in report['suites'] if x['script'] == 'verify_scientific_closure.py') + raw = (root/'verification/results/scientific-closure.json').read_bytes() + assert hashlib.sha256(raw).hexdigest() == closure['output_sha256'], 'Tracked certificates differ from executed output' + return {'reading_files': len(pages), 'tables': tables, 'tracked_certificate_files': 1} diff --git a/verification/tools/inspect_hosted_render.py b/verification/tools/inspect_hosted_render.py new file mode 100644 index 0000000..71fe49d --- /dev/null +++ b/verification/tools/inspect_hosted_render.py @@ -0,0 +1,154 @@ +"""Inspect public GitHub Markdown at an immutable ref; retain source and screenshots. + +This network-only check is separate from scientific verification. A blocked or +unrendered page fails; local preview output is never substituted for GitHub. +""" +from __future__ import annotations +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +from urllib.parse import quote + +REPOSITORY = 'GoGoKo699/Quantum-Routing-Bandwidth' +ROOT = Path(__file__).resolve().parents[2] + + +def page_names(root: Path) -> tuple[str, ...]: + files = [root/'README.md', *sorted((root/'science').glob('*.md')), + *sorted((root/'learning').glob('*.md')), *sorted((root/'references').glob('*.md')), + root/'verification/README.md'] + return tuple(str(p.relative_to(root)) for p in files) + + +SNAPSHOT = r'''() => { + const article = document.querySelector('article.markdown-body') || document.querySelector('.markdown-body'); + if (!article) return {article: false}; + function elements(root) { + const out = [...root.querySelectorAll('*')]; + for (const item of [...out]) if (item.shadowRoot) out.push(...elements(item.shadowRoot)); + return out; + } + const all = elements(article); + const markers = all.filter(x => x.localName === 'math-renderer'); + const errors = all.filter(x => x.matches('mjx-merror,merror,.MathJax_Error,.flash-error,[data-mjx-error],[data-mml-node="merror"]')); + const nativeErrors = all.filter(x => x.namespaceURI === 'http://www.w3.org/1998/Math/MathML' && + (x.localName === 'mlabeledtr' || (x.localName === 'mtd' && x.parentElement?.localName !== 'mtr')) + ).map(x => ({element:x.localName,parent:x.parentElement?.localName,text:(x.textContent || '').trim().slice(0,180)})); + const nodes = markers.map(x => { + const inside = elements(x.shadowRoot || x); + const box = x.getBoundingClientRect(); + return {ready:inside.some(y => y.matches('mjx-container,svg,math,img')),width:box.width,height:box.height, + error:/Math rendering failed|Undefined control sequence|ParseError|Unable to render expression|macros are not allowed|Missing (open|close) brace/i.test(x.textContent || '')}; + }); + const copy = article.cloneNode(true); + copy.querySelectorAll('math-renderer,pre,code').forEach(x => x.remove()); + return {article:true, heading:article.querySelector('h1')?.textContent?.trim(),markers:markers.length, + ready:nodes.filter(x => x.ready).length, + errors:errors.map(x => (x.getAttribute('data-mjx-error') || x.textContent || '').slice(0,180)), + marker_errors:nodes.filter(x => x.error).length,native_layout_errors:nativeErrors, + literal_math_lines:(copy.textContent || '').split('\n').filter(x => x.includes('$')), + equation_geometry:nodes.map(x => ({width:x.width,height:x.height})), + page_width:document.documentElement.scrollWidth,viewport:window.innerWidth, + table_columns:[...article.querySelectorAll('table')].map(t => [...t.rows].map(row => row.cells.length))}; +}''' + + +def source_math_count(text: str) -> int: + count = len(re.findall(r'^```math\s*\n.*?^```\s*$', text, re.S|re.M)) + text = re.sub(r'```.*?```', '', text, flags=re.S) + count += len(re.findall(r'\$\$.*?\$\$', text, re.S)) + text = re.sub(r'\$\$.*?\$\$', '', text, flags=re.S) + return count+len(re.findall(r'(? list[str]: + problems = [] + if not state.get('article') or state.get('heading') != title: + problems.append('missing expected document title') + if state.get('markers') != expected or state.get('ready', 0) < expected: + problems.append('missing or unfinished mathematics') + if state.get('literal_math_lines'): + problems.append('unprocessed math delimiters') + if state.get('errors') or state.get('marker_errors'): + problems.append('mathematical rendering error') + if state.get('native_layout_errors'): + problems.append('unsupported native MathML equation layout') + if state.get('page_width', 0) > width+3: + problems.append('page-level horizontal overflow') + if any(len(set(cols)) > 1 for cols in state.get('table_columns', [])): + problems.append('inconsistent rendered table cells') + return [f'{width}px: {p}' for p in problems] + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--ref', required=True) + parser.add_argument('--output', type=Path, default=ROOT/'build/hosted-render') + args = parser.parse_args() + if not re.fullmatch(r'[0-9a-f]{40}', args.ref): + parser.error('--ref must be a full immutable commit SHA') + from playwright.sync_api import sync_playwright + names = page_names(ROOT) + args.output.mkdir(parents=True, exist_ok=True) + report = {'repository':REPOSITORY,'ref':args.ref,'source_sha256':{},'pages':[], + 'scope':'Actual public GitHub DOM/layout and screenshots, not scientific review.'} + for name in names: + raw = (ROOT/name).read_bytes() + dest = args.output/'sources'/name + dest.parent.mkdir(parents=True,exist_ok=True) + dest.write_bytes(raw) + report['source_sha256'][name] = hashlib.sha256(raw).hexdigest() + with sync_playwright() as p: + browser = p.chromium.launch() + context = browser.new_context(viewport={'width':1180,'height':900},color_scheme='light') + page = context.new_page() + for name in names: + text = (ROOT/name).read_text() + expected = source_math_count(text) + title = text.splitlines()[0].removeprefix('# ') + url = f'https://github.com/{REPOSITORY}/blob/{args.ref}/{quote(name)}' + row = {'file':name,'url':url,'expected_math':expected,'checks':[],'problems':[]} + try: + response = page.goto(url,wait_until='domcontentloaded',timeout=45000) + row['http_status'] = response.status if response else None + if not response or response.status != 200: + raise RuntimeError(f'GitHub returned {row["http_status"]}') + page.locator('article.markdown-body, .markdown-body').first.wait_for(timeout=30000) + for width in (1180,390): + page.set_viewport_size({'width':width,'height':900}) + markers = page.locator('math-renderer') + for i in range(markers.count()): + markers.nth(i).scroll_into_view_if_needed(timeout=5000) + page.wait_for_timeout(50) + for _ in range(20): + state = page.evaluate(SNAPSHOT) + if state.get('ready',0) >= expected: + break + page.wait_for_timeout(250) + state = page.evaluate(SNAPSHOT) + row['problems'] += snapshot_problems(state,expected,title,width) + row['checks'].append(state) + page.evaluate('window.scrollTo(0,0)') + page.screenshot(path=str(args.output/f'{name.replace("/","_")}-{width}.png'),full_page=True) + except Exception as exc: + row['problems'].append(str(exc)[:1000]) + row['passed'] = not row['problems'] + report['pages'].append(row) + print(json.dumps({'file':name,'expected_math':expected,'passed':row['passed'],'problems':row['problems']}),flush=True) + if row.get('http_status') in (403,429) or any('ERR_' in s for s in row['problems']): + break + context.close() + browser.close() + report['all_passed'] = len(report['pages']) == len(names) and all(x['passed'] for x in report['pages']) + (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n') + print('HOSTED_RENDER_RESULT='+json.dumps({'ref':args.ref,'pages':len(report['pages']), + 'all_passed':report['all_passed']}),flush=True) + if not report['all_passed']: + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/verification/tools/test_structure.py b/verification/tools/test_structure.py new file mode 100644 index 0000000..4790632 --- /dev/null +++ b/verification/tools/test_structure.py @@ -0,0 +1,130 @@ +"""Structural regressions; not additional scientific verification suites.""" +from __future__ import annotations +import hashlib +import json +from pathlib import Path +import tempfile +import unittest +from check_release import check_reading_text, check_release +from check_learning import validate_map, check_learning +from inspect_hosted_render import snapshot_problems, source_math_count, page_names + +ROOT = Path(__file__).resolve().parents[2] + + +class ReadingChecks(unittest.TestCase): + def test_valid_table_and_math(self): + text = '| A | B |\n|---|---|\n| $`\\lvert x\\rangle`$ | y |\n\n```math\nx\\qquad\\text{(1)}\n```\n' + self.assertEqual(check_reading_text(text,'fixture'),1) + + def test_unescaped_pipe(self): + with self.assertRaisesRegex(AssertionError,'table cells'): + check_reading_text('| A | B |\n|---|---|\n| $|x\\rangle$ | y |\n','fixture') + + def test_unsafe_numbering(self): + with self.assertRaisesRegex(AssertionError,'unsafe native'): + check_reading_text('```math\nx\\tag{1}\n```','fixture') + + def test_duplicate_label(self): + with self.assertRaisesRegex(AssertionError,'repeated equation'): + check_reading_text('$$\nx\\text{(1)}\n$$\n\n```math\ny\\text{(1)}\n```','fixture') + + def test_nonmath_fence(self): + self.assertEqual(check_reading_text('```text\n| a |\n| a | b |\n$$\n```','fixture'),0) + + def test_unclosed_fence(self): + with self.assertRaisesRegex(AssertionError,'code fence'): + check_reading_text('```python\nx=1','fixture') + + def test_short_closing_fence(self): + with self.assertRaisesRegex(AssertionError,'code fence'): + check_reading_text('````text\nx\n```','fixture') + + def test_unclosed_display(self): + with self.assertRaisesRegex(AssertionError,'display mathematics'): + check_reading_text('$$\nx','fixture') + + def test_result_integrity(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for folder in ('science','learning','references','verification/results'): + (root/folder).mkdir(parents=True) + for name in ('README.md','AGENTS.md','llms.txt','verification/README.md'): + (root/name).write_text('# Fixture\n') + raw = b'{"all_passed":true}\n' + path = root/'verification/results/scientific-closure.json' + path.write_bytes(raw) + result = {'all_passed':True,'suites':[{'script':'verify_scientific_closure.py','output_sha256':hashlib.sha256(raw).hexdigest(),'summary':{'all_passed':True}}]} + record = root/'verification/results/verification.json' + record.write_text(json.dumps(result)) + self.assertEqual(check_release(root)['tracked_certificate_files'],1) + path.write_bytes(raw+b' ') + with self.assertRaisesRegex(AssertionError,'certificates differ'): + check_release(root) + path.write_bytes(raw) + result['suites'][0]['summary']['all_passed']='true' + record.write_text(json.dumps(result)) + with self.assertRaisesRegex(AssertionError,'explicit suite success'): + check_release(root) + + +class HostedChecks(unittest.TestCase): + def state(self): + return {'article':True,'heading':'Title','markers':1,'ready':1,'errors':[], + 'marker_errors':0,'native_layout_errors':[],'literal_math_lines':[], + 'page_width':390,'table_columns':[[2,2]]} + + def test_ready_valid(self): + self.assertEqual(snapshot_problems(self.state(),1,'Title',390),[]) + + def test_ready_invalid_native(self): + state = self.state();state['native_layout_errors']=[{'element':'mlabeledtr'}] + self.assertTrue(any('native MathML' in p for p in snapshot_problems(state,1,'Title',390))) + + def test_unfinished(self): + state=self.state();state['ready']=0 + self.assertTrue(snapshot_problems(state,1,'Title',390)) + + def test_overflow_and_table(self): + state=self.state();state['page_width']=500;state['table_columns']=[[2,3]] + self.assertEqual(len(snapshot_problems(state,1,'Title',390)),2) + + def test_math_count(self): + self.assertEqual(source_math_count('$`x_1`$\n\n```math\ny\n```\n\n$$z$$'),3) + + def test_new_pages(self): + names=page_names(ROOT) + self.assertIn('science/interpretation.md',names) + self.assertIn('learning/MILESTONES.md',names) + self.assertFalse(any('docs/' in name or 'coaching' in name for name in names)) + + +class LearningChecks(unittest.TestCase): + def text(self): + return (ROOT/'learning/MILESTONES.md').read_text() + + def test_current_map(self): + result=check_learning(ROOT) + self.assertEqual((result['milestones'],result['background'],result['narrative']),(30,14,16)) + + def test_missing_connection(self): + with self.assertRaisesRegex(AssertionError,'Conceptual connection'): + validate_map(self.text().replace('**Conceptual connection:**','**Other:**',1)) + + def test_forward_dependency(self): + with self.assertRaisesRegex(AssertionError,'Forward/cyclic'): + validate_map(self.text().replace('**Dependencies:** M01.','**Dependencies:** M30.',1)) + + def test_personal_procedure(self): + with self.assertRaisesRegex(AssertionError,'Personal assessment'): + validate_map(self.text()+'\nTeaching intensity: 3 learning rounds.\n') + + def test_missing_milestone(self): + with self.assertRaisesRegex(AssertionError,'exactly M01'): + validate_map(self.text().replace('### M30.','### M31.')) + + +if __name__ == '__main__': + if not __debug__: + raise RuntimeError('Structural tests require assertions.') + unittest.main()