Metadata-Version: 2.4
Name: qtwist
Version: 7.0.3
Summary: Q-TWIST v7: certified-methodology quantum emulation SDK -- every number ships with its typed error bound and a machine-checkable certificate, or the request is refused. (Supersedes the 5.x legacy line.)
Author: Q-TWIST
License: Proprietary
Keywords: quantum,simulation,certified,error-budget,digital-twin,benchmarking
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Dynamic: license-file

# Q-TWIST v7.0.3 (Beta) — Certified Noisy Quantum Simulation SDK

**The Honest Oracle, rebuilt as a Proof-Carrying Emulation platform.**
Every number ships with its typed error bound and its
machine-checkable **Emulation Certificate** — or the request is refused
in milliseconds with a reasoned argument.

```
Q-TWIST V7.0 AUDIT COMPLETE. ZERO SILENT FAILURES. PRODUCTION READY.
```

- Runtime dependency: **numpy only** (scipy optional, used by nothing
  at runtime). Python 3.10+.
- Audit: `python3 tests/v7_audit.py` (75 adversarial checks, ~5 min,
  deterministic, exit code 0/1)
- Demo: `python3 examples/demo.py` (~1 min, nine showcases)

## Quickstart

```python
from qtwist import QTWIST, Circuit, Observable

sdk = QTWIST(backend="fake-heron", seed=7)     # deterministic mock twin

ghz = Circuit(3)
ghz.h(0); ghz.cx(0, 1); ghz.cx(1, 2)

out = sdk.query(ghz, Observable.zz(0, 2), eps_target=0.05)
print(out.result)                # value + typed 12-term budget + certificate
print(sdk.verify(out.result.certificate, program=ghz))   # standalone, no rerun

counts = sdk.get_counts(ghz, shots=4096)        # certified per-outcome halfwidth
```

This Quickstart runs as-is and certifies **+0.910750** with typed bound
**0.024500** (`CERTIFIED`); `verify()` returns `True`, no rerun needed.

If the request is intractable you get a `RejectionResult` — fast,
loud, and actionable:

```
NO_ADMISSIBLE_ENGINE in 20 ms
"No engine in the fleet can execute this program within the wall
budget: n=2000, lightcone>26, depth>30, n_ops=58617. The MPS engines'
own cost model lower-bounds the run at ~4.61e+04 s (x10 safety
margin > 120 s wall budget)."
```

## The seven layers

| Layer | Module | What it is |
|---|---|---|
| L0 | `qtwist.calibration` | Calibration Lake: append-only provenance ledger, CI-carrying records, content hashes, noise factory, device adapters |
| L1 | `qtwist.qtir` | Quantum Twin IR: OP / ANALOG / NOISE / LOGICAL / MEAS / FEED node families, exact native-decomposition pass, lightcones |
| L2 | `qtwist.engines` | The eight-engine fleet (below) |
| L3 | `qtwist.calculus` | Typed ε-calculus: CERTIFIED / STATISTICAL / HEURISTIC / UNBOUNDED; twelve terms; Composition Theorem; budget allocator |
| L4 | `qtwist.oracle` | Certified oracle: plan enumeration, cost gates, anytime escalation, reasoned rejection (≤10 ms SLA on the standard adversarial suite) |
| L5 | `qtwist.twin` | Twin loop: SPRT drift monitors, statistical self-invalidation, recalibration |
| L6 | `qtwist.certify` | Emulation Certificates (`qtwist.cert.v1`), HMAC signing, standalone verifier |

## The engine fleet

| Engine | Regime | Certified bound species |
|---|---|---|
| **A** Trajectories | sampling, n ≤ statevector cap | STATISTICAL (empirical Bernstein) |
| **B** Exact MPDO | ground truth, n ≤ RAM cap | CERTIFIED (roundoff model) |
| **C** Pauli-DAOE | lightcone-bounded, 1024+ qubits | CERTIFIED (Pauli-drop ledger) |
| **D** Adaptive MPS | deep circuits, any geometry via routing | CERTIFIED (discarded-SV ledger) |
| **H** TDVP-style | accuracy-first MPS | CERTIFIED (svd-ledger); χ-ladder mode degrades to HEURISTIC |
| **X** CHIMERA | mixed/unknown geometry | cartography → geometry synthesis → certified MPS on the synthesized chain |
| **Q** Analog DAQC | digital-analog programs | CERTIFIED (Trotter remainder from commutator norms) |
| **L** Logical FTQC | error-corrected programs | correlated logical noise; CERTIFIED with device calibration, HEURISTIC with analytic scaling |

New in v7.0 vs v5.0 (capabilities): MPS **SWAP routing** (the fleet no
longer requires born-1D circuits — Engine X synthesizes the chain),
**analog Hamiltonian blocks** with certified product-formula bounds,
**logical FTQC programs** with time- and space-correlated logical
noise, **component-factorized sampling** (Bell pairs are one
component, not two independent qubits), and **certificates**.

## The twelve-term typed budget

`eps_method, eps_stat, eps_model, eps_drift, eps_spam,
eps_readout_xtalk, eps_leakage, eps_compile, eps_trotter,
eps_logical, eps_roundoff, eps_gen` — composed by the L1 rule
(triangle-inequality sum), the type lattice (weakest link), and the
union bound over per-term δ. The certificate carries every term's
propagation rule and provenance; the verifier re-derives the
arithmetic without rerunning anything.

## Honesty notes & errata

1. **Engine H typing** — the v7 architecture document types Engine H
   "UNBOUNDED alone; HEURISTIC with χ-ladder". That typing is correct
   for *continuous-projector* TDVP (a P2 kernel). The v7.0 kernel
   actually shipped is two-site gate absorption + optimal local SVD
   truncation, whose per-step discarded weight is the variational
   residual **and** a rigorous bound — so it is typed CERTIFIED
   (`svd-ledger`). The opt-in χ-ladder mode demonstrates the
   HEURISTIC degrade path.
2. **Dense MPDO scaling** — the architecture document's "~10 GB at
   n=24" for Engine B is wrong: a dense density matrix at n=24 needs
   16·4²⁴ bytes ≈ 4.5 PB. The code derives Engine B's qubit cap from
   the actual RAM budget (≈ 12 qubits on a 4 GB-class machine).
3. **Two v5.0 bugs found and fixed by this redesign** (both caught by
   the v7 audit's cross-engine checks):
   - v5.0's MPS ledger charged `sqrt(w)` per truncation but skipped
     the renormalization term `1 − sqrt(1−w)`; v7.0 charges the
     complete `sqrt(w) + 1 − sqrt(1−w)` and renormalizes the state.
   - v5.0's factorized-marginals path dropped the readout identity
     shift `(e1 − e0)` from the per-qubit extraction (a small bias
     hidden under the 2/√shots sampling bound); v7.0 walks each
     Z-string separately and matches exact Engine B to 1e-15.
4. **Rejection SLA** — the ≤10 ms promise holds on the standard
   adversarial suite (3k-op 2000-qubit global query: 4.3 ms). The
   rejection path scales at ~0.5 µs/op through the compile scan;
   a 59k-op stress circuit rejects in ~20 ms. Documented, not hidden.
5. **Cost models are advisory with a 10× safety margin** — model error
   can make us slower or over-conservative, never wrongly accepting.
6. **Signing is HMAC-SHA256 (demo grade)** — the schema reserves
   `key_id` for asymmetric signatures (Ed25519 per the roadmap).
7. **The mock adapter is honestly labeled** — every certificate from
   `fake-heron` carries status `Uncertified [Mock Calibration]`.
8. **7.0.1 hotfix (2026-09)** — the deep audit of the published 7.0.0
   found two happy-path defects, both fixed here:
   - `Circuit.sx(q)` crashed with `TypeError` on 7.0.0 (a one-character
     tuple bug in the QTIR appender). Fixed; the v7 audit now covers
     **every** gate in the registry (section 1.9) so this class cannot
     return.
   - non-integer qubit indices were silently `int()`-truncated on
     7.0.0 (`Circuit(2.9)` became 2 qubits, `h(0.9)` became qubit 0,
     `h(True)` became qubit 1, `Observable.z(0.7)` became qubit 0).
     They now refuse loudly with reason `NON_INTEGER_INDEX`, wherever a
     qubit index enters (gates, relabel, observables, programs,
     constructed circuits). Integral reals (`h(1.0)`, `Circuit(4.0)`)
     still work as before.
   Nothing else in the code changed (see the kit's delta proof);
   7.0.0 is superseded and should be yanked after this release lands.
9. **7.0.2 hotfix (2026-09)** — the real-user test of the published
   7.0.1 caught an import-time failure on Python 3.10/3.11: two
   f-strings (`qtwist/oracle.py`, `qtwist/results.py`) used multi-line
   expressions that only Python 3.12+ accepts (PEP 701), so pip users on
   3.10/3.11 could not import qtwist at all despite the package declaring
   `Requires-Python: >=3.10`. Both collapsed to pre-3.12-safe form;
   behavior is unchanged on 3.12+ (verified byte-equivalent output). The
   two `_validate_op` guard messages also now interpolate the gate name
(`Gate {gname}` was showing literally). 7.0.1 remains live but is
    superseded by this release.
10. **7.0.3 hotfix (2026-09)** — the real-user mega battery (178 checks
    against the published 7.0.2 wheel) caught two defects, both fixed here:
    - `query()` without an observable crashed with a raw `AttributeError`
      from inside an engine instead of a typed refusal, despite the API
      advertising `observable: Optional`. It now refuses loudly with
      reason `INVALID_PARAMETER` and guidance (pass an `Observable`).
    - `Program.coupling_weights()` documented itself as "gate-count"
      but returned a binary adjacency (set-dedupe), collapsing how many
      times an edge is exercised (fidelity of Engine X's circuit-proxy
      mutual information). It now counts per-operation multiplicity.
    Nothing else in the code changed (delta proof + preflight + the
    178-check battery all re-run ALL GREEN); 7.0.2 remains live but is
    superseded by this release.

## Package layout

```
qtwist/
  calculus.py       L3 typed ε-calculus + allocator
  qtir.py           L1 Quantum Twin IR + passes
  calibration.py    L0 calibration lake + noise factory
  noise.py          channel physics (Pauli + amplitude damping)
  gates.py          verified gate registry (exact decompositions)
  engines/          L2: A, B, C, D, H, X (CHIMERA), Q, L
  twin.py           L5 SPRT drift monitors
  certify.py        L6 certificates + standalone verifier
  oracle.py         L4 certified query planner
  api.py            QTWIST facade (query / predict / get_counts / verify)
tests/v7_audit.py   the 75-check adversarial audit
examples/demo.py    the nine-showcase demo
```

See `ARCHITECTURE.md` for the full design (composition theorem,
certificate schema, cost models, roadmap).
