Metadata-Version: 2.4
Name: qtwist
Version: 7.5.3
Summary: Q-TWIST v7.5: certified noisy quantum simulation SDK -- every number ships with a typed error bound and a machine-checkable certificate, or the request is refused with a reasoned argument.
Author-email: Jayanth Kopparthi <jayanthkopparthi595@gmail.com>
License: Proprietary
Project-URL: Homepage, https://pypi.org/project/qtwist/
Keywords: quantum,simulation,noise,certification,digital-twin,tensor-networks,MPS,error-budget
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: cryptography>=41.0
Provides-Extra: dev
Provides-Extra: viz
Requires-Dist: matplotlib>=3.6; extra == "viz"
Provides-Extra: verify
Requires-Dist: scipy>=1.10; extra == "verify"
Requires-Dist: matplotlib>=3.6; extra == "verify"
Dynamic: license-file

# Q-TWIST v7.5.3 — 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.5.3 AUDIT COMPLETE. ZERO SILENT FAILURES. PRODUCTION READY.
```

- Runtime dependencies: **numpy** and **cryptography**. Python 3.10+.
  (`scipy` + `matplotlib` are audit-only and ride in the `verify`
  extra; interactive visuals also ride in `qtwist[viz]`.)
- Audit: `pip install -e '.[verify]'` once, then `make verify` (or
  `python3 tests/v7_audit.py`) — 151 v7 + 80 v5 adversarial checks,
  deterministic, exit code 0/1. scipy powers the independent LP
  cross-check; matplotlib the visual-render tests.
- Demo: `python3 examples/demo.py` (~1 min, nine showcases); the
  Qiskit-idiom demo: `python3 examples/qiskit_style_demo.py`

## Install

```bash
pip install qtwist                # runtime only (numpy + cryptography)
pip install "qtwist[viz]"         # + interactive visuals (matplotlib)
pip install "qtwist[verify]"      # + run the 151-check audit (scipy, matplotlib)
```

Python 3.10+.

## How to use it

Three steps from install to a certified answer.

**1. Start a twin** (the deterministic mock needs no account):

```python
from qtwist import QTWIST, MockQPUProvider

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

**2. Ask a question** — the Qiskit-shaped loop, or a *certified* number
with a typed error bound:

```python
from qtwist import Circuit, Observable

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

counts = backend.run(ghz, shots=4096).result().get_counts()   # {bitstring: count}

out = sdk.query(ghz, Observable.zz(0, 2), eps_target=0.05)
print(out.result.value, out.result.error_bound)               # value + typed bound
```

**3. Verify without re-running** — every certificate is standalone and
machine-checkable:

```python
print(sdk.verify(out.result.certificate, program=ghz))        # True
```

If the request is intractable you get a fast, loud `RejectionResult`
instead of a silently-wrong number. Run the demos or the audit:

```bash
python examples/demo.py            # nine showcases (~1 min)
python examples/qiskit_style_demo.py
python tests/v7_audit.py           # 151 adversarial checks (needs qtwist[verify])
```

## Quickstart — the Qiskit-shaped loop

Build, validate, draw, round-trip, and sample exactly the way the
hopsworks-versus-Qiskit muscle memory expects — the transport is the
certified twin:

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

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

qc = Circuit(3).h(0).cx(0, 1).cx(1, 2).measure_all()
qc.validate()                                # True, or a typed error
print(qc.draw())                             # textual circuit diagram

imported = Circuit.from_qasm3(qc.to_qasm3()) # QASM3 round-trip
assert imported.ops == qc.ops

job = backend.run(qc, shots=4096)            # backend.run(qc, N)
counts = job.result().get_counts()           # {bitstring: count}
```

Underneath the Qiskit-shaped surface, every number still ships with
its typed bound and certificate, or is refused with a reasoned
argument — Qiskit gives you one noisy sample and no guarantee; the
twin gives you the number *and* the proof:

```python
from qtwist import Circuit, Observable

ghz = Circuit(3).h(0).cx(0, 1).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,
                         deadline_s=120)         # hard wall budget
```

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 |
| L3 | `qtwist.cca` | Certified Claim Algebra (The Bridge Theorem v4.0): composes Pauli evidence intervals into target bounds — Rules 8/9 + the classical facet family at O(1), an exact block-LP closure for commuting evidence, gap analysis vs the SDP optimum, and the two-question noise routing (5a/5b) |
| 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**.

New in v7.1: **`sdk.compose()`** — one call turns measured Pauli
evidence (`{"XX": [0.95, 1.0], ...}`) into the tightest sound
interval on a target observable, certifies whether it equals the
global SDP optimum (gap = 0), and reports the full gap analysis with
remediation when it isn't.  2-qubit correlation composition and
3-qubit anticommutation are closed **exactly** at O(1) cost; commuting
evidence closes exactly via the block LP (`pip install scipy`
optional); non-commuting corners are reported sound-but-not-exact,
never silently wrong.

## 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. **Noisy per-circuit cost is twin-construction dominated** — for
   10–12 qubit noisy sampling the ~11–19 s is the per-circuit twin
   build, not per-shot (1024 vs 4096 shots are nearly identical).
   Certified one-shots are fine; interactive iteration on nearby
   circuits would benefit from a twin warm-cache (roadmap).

## Package layout

```
qtwist/
  calculus.py       L3 typed ε-calculus + allocator
  cca.py            L3 Certified Claim Algebra (Bridge Theorem v4.0):
                    Rules 8/9 + Boole facets, exact commuting closure,
                    gap analysis vs the SDP optimum, 5a/5b noise routing
  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)
  qpu.py            QPU layer (7.1.0): QASM3 export, job cost floors,
                    provider contract (mock + IBM REST adapter),
                    counts ingestion into the twin loop, real-device
                    calibration ingestion
tests/v7_audit.py   the 151-check adversarial audit
examples/demo.py    the nine-showcase demo
```

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