py-quantum-verifier 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ """py-quantum-verifier: deterministic, offline pre-flight checks for quantum circuits."""
2
+ from ._optional import optional_features
3
+ from .checks import gate_synthesis_check, semantic_check, topology_check
4
+ from .compilers import diff_compilers
5
+ from .devices import Device, NoiseSpec, get_device, list_devices
6
+ from .falsify import FalsificationReport, build_control_circuit, falsify_claim
7
+ from .gradients import analyze_circuit_gradients
8
+ from .robust import find_robust_circuit
9
+ from .verdict import Verdict
10
+ from .verify import ground_truth_check, verify_experiment
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ __all__ = [
15
+ "verify_experiment", "falsify_claim", "find_robust_circuit", "gate_synthesis_check",
16
+ "analyze_circuit_gradients", "diff_compilers",
17
+ "Verdict", "FalsificationReport", "Device", "NoiseSpec", "get_device", "list_devices",
18
+ "semantic_check", "topology_check", "ground_truth_check", "build_control_circuit",
19
+ "optional_features",
20
+ ]
@@ -0,0 +1,26 @@
1
+ """Optional-dependency probes. Nothing here may fail at import time."""
2
+ from __future__ import annotations
3
+
4
+ try: # pragma: no cover - depends on environment
5
+ import pennylane as _pennylane # noqa: F401
6
+ HAS_PENNYLANE = True
7
+ except ImportError:
8
+ HAS_PENNYLANE = False
9
+
10
+ try: # pragma: no cover
11
+ import cudaq as _cudaq # noqa: F401
12
+ HAS_CUDAQ = True
13
+ except ImportError:
14
+ HAS_CUDAQ = False
15
+
16
+ try: # pragma: no cover
17
+ import pytket as _pytket # noqa: F401
18
+ from pytket.extensions.qiskit import qiskit_to_tk as _q2t # noqa: F401
19
+ HAS_TKET = True
20
+ except ImportError:
21
+ HAS_TKET = False
22
+
23
+
24
+ def optional_features() -> dict[str, bool]:
25
+ """Which optional integrations are importable in this environment."""
26
+ return {"pennylane": HAS_PENNYLANE, "cudaq": HAS_CUDAQ, "tket": HAS_TKET}
@@ -0,0 +1,144 @@
1
+ """Structural checks: semantics, topology, gate-synthesis inflation."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from collections import defaultdict
6
+
7
+ from qiskit import QuantumCircuit
8
+
9
+ from .circuits import as_circuit
10
+ from .devices import Device, get_device
11
+ from .native import ZZ_MAX_TURNS, to_native
12
+
13
+ GATE_INFLATION_MAX_RATIO = 8.0
14
+ TUNABLE_2Q_MAX_RATIO = 1.5 # native 2q gate takes any angle -> expect ~1:1
15
+ FIXED_2Q_MAX_RATIO = 2.5 # cz/cx/ecr: arbitrary-angle rzz legitimately needs 2
16
+
17
+ _NON_GATES = {"measure", "barrier", "delay"}
18
+
19
+
20
+ def semantic_check(circuit: QuantumCircuit) -> dict:
21
+ issues = []
22
+ ops = circuit.count_ops()
23
+ n_meas = ops.get("measure", 0)
24
+ if not ops or all(k in _NON_GATES for k in ops):
25
+ issues.append({"severity": "ERROR", "check": "empty_circuit",
26
+ "message": "Circuit has no quantum gates."})
27
+ if n_meas == 0:
28
+ issues.append({"severity": "ERROR", "check": "no_measurements",
29
+ "message": "Circuit has no measurements — you would get no results."})
30
+ if circuit.num_clbits < n_meas:
31
+ issues.append({"severity": "ERROR", "check": "classical_register_too_small",
32
+ "message": f"{n_meas} measurements but only {circuit.num_clbits} classical bits."})
33
+ touched, entangled = set(), set()
34
+ for inst in circuit.data:
35
+ if inst.operation.name in _NON_GATES:
36
+ continue
37
+ idx = [circuit.find_bit(q).index for q in inst.qubits]
38
+ touched.update(idx)
39
+ if len(idx) >= 2:
40
+ entangled.update(idx)
41
+ lonely = sorted(touched - entangled)
42
+ if lonely and circuit.num_qubits > 1:
43
+ issues.append({"severity": "INFO", "check": "unentangled_qubits",
44
+ "message": f"Qubit(s) {lonely} never interact with other qubits."})
45
+ return {"passed": not any(i["severity"] == "ERROR" for i in issues), "issues": issues}
46
+
47
+
48
+ def topology_check(circuit: QuantumCircuit, device: "str | Device") -> dict:
49
+ dev = get_device(device)
50
+ if dev.max_degree is None:
51
+ return {"applicable": False, "passed": True,
52
+ "note": f"{dev.name} is all-to-all connected — no routing/degree risk."}
53
+ nbrs: dict[int, set] = defaultdict(set)
54
+ for inst in circuit.data:
55
+ if len(inst.qubits) == 2 and inst.operation.name not in _NON_GATES:
56
+ a, b = (circuit.find_bit(q).index for q in inst.qubits)
57
+ nbrs[a].add(b)
58
+ nbrs[b].add(a)
59
+ violations = [
60
+ {"qubit": q, "degree": len(n), "estimated_extra_two_qubit_gates": (len(n) - dev.max_degree) * 3}
61
+ for q, n in sorted(nbrs.items()) if len(n) > dev.max_degree
62
+ ]
63
+ return {
64
+ "applicable": True, "passed": not violations, "max_degree": dev.max_degree,
65
+ "violations": violations,
66
+ "note": (f"All qubits within degree-{dev.max_degree} limit." if not violations else
67
+ f"{len(violations)} qubit(s) exceed degree {dev.max_degree}: routing will inject "
68
+ "SWAPs and can multiply the real two-qubit gate count."),
69
+ }
70
+
71
+
72
+ def _physical_ops(circuit: QuantumCircuit, virtual_z: bool) -> dict:
73
+ skip = set(_NON_GATES) | ({"rz"} if virtual_z else set())
74
+ return {k: v for k, v in circuit.count_ops().items() if k not in skip}
75
+
76
+
77
+ def _n_2q(circuit: QuantumCircuit) -> int:
78
+ return sum(1 for i in circuit.data
79
+ if len(i.qubits) == 2 and i.operation.name not in _NON_GATES)
80
+
81
+
82
+ def _min_native_zz(inst) -> int:
83
+ op = inst.operation
84
+ if op.name == "rzz" and not op.is_parameterized():
85
+ return max(1, math.ceil(abs(float(op.params[0])) / (2 * math.pi) / ZZ_MAX_TURNS))
86
+ return 1
87
+
88
+
89
+ def gate_synthesis_check(circuit, device: "str | Device" = "ionq-forte-1", *,
90
+ transpiled: QuantumCircuit | None = None,
91
+ native_rzz_equivalence: bool = True) -> dict:
92
+ """Catch silent transpiler gate blowups.
93
+
94
+ Translates ``circuit`` onto ``device``'s native gateset and compares native
95
+ gate counts with the logical ones. The canonical failure: a logical ``rzz``
96
+ (one tunable interaction) that becomes 2 native ``zz`` plus a pile of
97
+ single-qubit gates because the compiler has no *direct* ``rzz -> zz``
98
+ equivalence and falls back to a generic ``cx`` decomposition.
99
+
100
+ ``native_rzz_equivalence=False`` reproduces that unpatched-compiler
101
+ behaviour so you can see (and test against) the failure. Pass ``transpiled``
102
+ to audit a circuit your own toolchain produced instead.
103
+ """
104
+ circuit = as_circuit(circuit)
105
+ dev = get_device(device)
106
+ if transpiled is None:
107
+ dev = dev.with_native_equivalences(native_rzz_equivalence)
108
+ transpiled = to_native(circuit, dev.target)
109
+
110
+ logical = _physical_ops(circuit, virtual_z=False)
111
+ native = _physical_ops(transpiled, dev.virtual_z)
112
+ l_total, n_total = sum(logical.values()), sum(native.values())
113
+ total_ratio = n_total / l_total if l_total else 1.0
114
+ l2, n2 = _n_2q(circuit), _n_2q(transpiled)
115
+ if dev.target.two_qubit_native == "zz":
116
+ # Native ZZ only spans |turns| <= 0.25, so a large-angle rzz legitimately
117
+ # needs ceil(|turns|/0.25) native gates. That is the true minimum, not inflation.
118
+ l2 = sum(_min_native_zz(i) for i in circuit.data
119
+ if len(i.qubits) == 2 and i.operation.name not in _NON_GATES)
120
+ ratio_2q = n2 / l2 if l2 else 1.0
121
+ limit_2q = FIXED_2Q_MAX_RATIO if dev.fixed_angle_two_qubit else TUNABLE_2Q_MAX_RATIO
122
+
123
+ violations = []
124
+ if total_ratio > GATE_INFLATION_MAX_RATIO:
125
+ violations.append({
126
+ "check": "total_gate_inflation", "ratio": round(total_ratio, 2),
127
+ "message": f"Native gate count is {total_ratio:.1f}x the logical count "
128
+ f"(limit {GATE_INFLATION_MAX_RATIO}x) — likely a missing direct equivalence "
129
+ "to the native gateset, not real routing overhead."})
130
+ if l2 and ratio_2q > limit_2q:
131
+ violations.append({
132
+ "check": "two_qubit_gate_inflation", "ratio": round(ratio_2q, 2),
133
+ "message": f"{l2} logical two-qubit gate(s) became {n2} native two-qubit gate(s) "
134
+ f"({ratio_2q:.1f}x, limit {limit_2q}x for "
135
+ f"{'fixed-angle' if dev.fixed_angle_two_qubit else 'tunable'} native gates) — "
136
+ "likely a missing direct equivalence in the compiler."})
137
+ return {
138
+ "passed": not violations, "device": dev.name,
139
+ "logical_gate_count": l_total, "native_gate_count": n_total,
140
+ "inflation_ratio": round(total_ratio, 2),
141
+ "logical_two_qubit_gates": l2, "native_two_qubit_gates": n2,
142
+ "two_qubit_inflation_ratio": round(ratio_2q, 2), "two_qubit_limit": limit_2q,
143
+ "native_ops": native, "violations": violations,
144
+ }
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from qiskit import QuantumCircuit
4
+
5
+ CircuitLike = "QuantumCircuit | str"
6
+
7
+
8
+ def as_circuit(circuit) -> QuantumCircuit:
9
+ """Accept a QuantumCircuit, an OpenQASM 2 string or an OpenQASM 3 string."""
10
+ if isinstance(circuit, QuantumCircuit):
11
+ return circuit
12
+ if isinstance(circuit, str):
13
+ if "OPENQASM 3" in circuit[:200]:
14
+ from qiskit import qasm3
15
+ return qasm3.loads(circuit)
16
+ return QuantumCircuit.from_qasm_str(circuit)
17
+ raise TypeError(f"Expected QuantumCircuit or OpenQASM string, got {type(circuit).__name__}")
18
+
19
+
20
+ def normalize_counts(counts: dict) -> dict:
21
+ """Strip register separators ('01 1' -> '011')."""
22
+ out: dict[str, int] = {}
23
+ for k, v in counts.items():
24
+ k = k.replace(" ", "")
25
+ out[k] = out.get(k, 0) + int(v)
26
+ return out
@@ -0,0 +1,81 @@
1
+ """diff_compilers: Qiskit vs TKET on the same circuit, each checked for correctness."""
2
+ from __future__ import annotations
3
+
4
+ from qiskit import QuantumCircuit, transpile
5
+ from qiskit.quantum_info import Operator
6
+
7
+ from . import _optional
8
+ from .circuits import as_circuit
9
+ from .devices import Device, get_device
10
+ from .native import to_native
11
+
12
+ MAX_QUBITS_FOR_EXACT_CHECK = 12
13
+ TKET_HINT = 'TKET not installed: pip install "py-quantum-verifier[tket]"'
14
+
15
+
16
+ def _two_q(qc: QuantumCircuit) -> int:
17
+ return sum(1 for i in qc.data if len(i.qubits) == 2)
18
+
19
+
20
+ def _stats(qc: QuantumCircuit) -> dict:
21
+ return {"depth": qc.depth(), "two_qubit_gates": _two_q(qc), "total_gates": qc.size()}
22
+
23
+
24
+ def _compile_tket(circuit: QuantumCircuit, dev: Device) -> QuantumCircuit:
25
+ from pytket import OpType
26
+ from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit
27
+ from pytket.passes import AutoRebase, FullPeepholeOptimise, SequencePass
28
+ two_q = {"cz": OpType.CZ, "cx": OpType.CX, "ecr": OpType.ECR}[dev.target.two_qubit_native]
29
+ gateset = {two_q, OpType.Rz, OpType.SX, OpType.X}
30
+ tkc = qiskit_to_tk(circuit)
31
+ SequencePass([FullPeepholeOptimise(), AutoRebase(gateset)]).apply(tkc)
32
+ return tk_to_qiskit(tkc)
33
+
34
+
35
+ def diff_compilers(circuit, device: "str | Device" = "ibm-heron") -> dict:
36
+ """Compile with Qiskit and (if installed) TKET onto ``device``'s native basis.
37
+
38
+ Each output is verified against the original by exact unitary equivalence
39
+ (up to 12 qubits) before it is allowed to win; the recommendation is the
40
+ verified result with the fewest two-qubit gates. Without TKET installed the
41
+ Qiskit result is still returned, with ``tket.available == False``.
42
+ """
43
+ qc = as_circuit(circuit)
44
+ dev = get_device(device)
45
+ unitary = qc.remove_final_measurements(inplace=False) if any(
46
+ i.operation.name == "measure" for i in qc.data) else qc
47
+ can_verify = unitary.num_qubits <= MAX_QUBITS_FOR_EXACT_CHECK
48
+ ref = Operator(unitary) if can_verify else None
49
+
50
+ def run(name, fn) -> dict:
51
+ try:
52
+ out = fn()
53
+ except Exception as e:
54
+ return {"available": True, "error": str(e)}
55
+ r = {"available": True, **_stats(out)}
56
+ r["verified"] = bool(Operator(out).equiv(ref)) if can_verify else None
57
+ return r
58
+
59
+ if dev.target.two_qubit_native == "zz":
60
+ qiskit_fn = lambda: to_native(unitary, dev.target) # noqa: E731
61
+ else:
62
+ qiskit_fn = lambda: transpile(unitary, basis_gates=list(dev.target.basis_gates), # noqa: E731
63
+ optimization_level=1, seed_transpiler=0)
64
+ results = {"qiskit": run("qiskit", qiskit_fn)}
65
+
66
+ if dev.target.two_qubit_native == "zz":
67
+ results["tket"] = {"available": False, "note": "TKET comparison supports fixed-angle (cz/cx/ecr) devices only."}
68
+ elif not _optional.HAS_TKET:
69
+ results["tket"] = {"available": False, "note": TKET_HINT}
70
+ else:
71
+ results["tket"] = run("tket", lambda: _compile_tket(unitary, dev))
72
+
73
+ ok = {k: v for k, v in results.items() if v.get("verified") is True}
74
+ if ok:
75
+ win = min(ok, key=lambda k: ok[k]["two_qubit_gates"])
76
+ rec = f"{win}: verified, {ok[win]['two_qubit_gates']} two-qubit gates."
77
+ else:
78
+ rec = ("No compiler output could be verified" +
79
+ ("" if can_verify else f" ({unitary.num_qubits} qubits > {MAX_QUBITS_FOR_EXACT_CHECK}, exact check skipped)")
80
+ + " — review manually before submitting.")
81
+ return {"device": dev.name, "results": results, "recommendation": rec}
@@ -0,0 +1,79 @@
1
+ """Offline device presets: native gateset, topology rules and noise rates.
2
+
3
+ Everything is local — no tokens, no network. Noise rates are *representative*
4
+ published-order-of-magnitude figures, not live calibration; pass your own
5
+ ``Device``/``NoiseSpec`` when you have real calibration numbers.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, replace
10
+
11
+ from .native import NativeTarget
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class NoiseSpec:
16
+ p1: float = 0.0 # depolarizing error per physical 1q gate
17
+ p2: float = 0.0 # depolarizing error per 2q gate
18
+ readout: float = 0.0 # symmetric bit-flip readout error
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Device:
23
+ name: str
24
+ target: NativeTarget
25
+ noise: NoiseSpec
26
+ #: None = all-to-all. Otherwise max interaction partners per qubit.
27
+ max_degree: int | None = None
28
+ #: RZ is a free frame change (IonQ, IBM) and is not counted as a gate.
29
+ virtual_z: bool = True
30
+
31
+ @property
32
+ def fixed_angle_two_qubit(self) -> bool:
33
+ return self.target.fixed_angle_two_qubit
34
+
35
+ def with_noise(self, **kw) -> "Device":
36
+ return replace(self, noise=replace(self.noise, **kw))
37
+
38
+ def with_native_equivalences(self, direct_rzz: bool) -> "Device":
39
+ return replace(self, target=replace(self.target, direct_rzz=direct_rzz))
40
+
41
+
42
+ IONQ_FORTE_1 = Device(
43
+ name="ionq-forte-1",
44
+ target=NativeTarget("ionq-forte-1", ("rz", "sx", "x", "zz"), "zz", fixed_angle_two_qubit=False),
45
+ noise=NoiseSpec(p1=2e-4, p2=4e-3, readout=3e-3),
46
+ max_degree=None,
47
+ )
48
+
49
+ IBM_HERON = Device(
50
+ name="ibm-heron",
51
+ target=NativeTarget("ibm-heron", ("rz", "sx", "x", "cz"), "cz", fixed_angle_two_qubit=True),
52
+ noise=NoiseSpec(p1=2.5e-4, p2=3e-3, readout=1.5e-2),
53
+ max_degree=3, # heavy-hex
54
+ )
55
+
56
+ IDEAL = Device(
57
+ name="ideal",
58
+ target=NativeTarget("ideal", ("rz", "sx", "x", "cz"), "cz", fixed_angle_two_qubit=True),
59
+ noise=NoiseSpec(),
60
+ max_degree=None,
61
+ )
62
+
63
+ _DEVICES = {d.name: d for d in (IONQ_FORTE_1, IBM_HERON, IDEAL)}
64
+ _ALIASES = {"ionq": "ionq-forte-1", "forte-1": "ionq-forte-1", "forte": "ionq-forte-1",
65
+ "ibm": "ibm-heron", "heron": "ibm-heron"}
66
+
67
+
68
+ def get_device(device: "str | Device") -> Device:
69
+ if isinstance(device, Device):
70
+ return device
71
+ key = _ALIASES.get(device.lower(), device.lower())
72
+ if key not in _DEVICES:
73
+ raise ValueError(f"Unknown device {device!r}; available: {sorted(_DEVICES)} "
74
+ "(or pass a Device instance).")
75
+ return _DEVICES[key]
76
+
77
+
78
+ def list_devices() -> list[str]:
79
+ return sorted(_DEVICES)
@@ -0,0 +1,107 @@
1
+ """falsify_claim: control-circuit test that separates real entanglement from noise."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import asdict, dataclass, field
5
+
6
+ from qiskit import QuantumCircuit
7
+
8
+ from .circuits import as_circuit
9
+ from .devices import Device, get_device
10
+ from .simulation import noisy_counts
11
+ from .stats import tvd, two_proportion_pvalue
12
+
13
+ ENTANGLING_GATES = {"cx", "cz", "cy", "ch", "cp", "crx", "cry", "crz", "cu", "cu1", "cu3",
14
+ "ecr", "rzz", "rxx", "ryy", "rzx", "zz", "ms", "swap", "iswap", "cnot", "ccx", "cswap"}
15
+
16
+
17
+ def build_control_circuit(circuit: QuantumCircuit) -> QuantumCircuit:
18
+ """Same circuit with every multi-qubit gate removed (1q gates + measurements kept)."""
19
+ control = QuantumCircuit(*circuit.qregs, *circuit.cregs)
20
+ for inst in circuit.data:
21
+ if inst.operation.name.lower() in ENTANGLING_GATES:
22
+ continue
23
+ control.append(inst.operation, inst.qubits, inst.clbits)
24
+ return control
25
+
26
+
27
+ @dataclass
28
+ class FalsificationReport:
29
+ supported: bool
30
+ verdict: str # "SUPPORTED" | "NOT_SUPPORTED"
31
+ device: str
32
+ entangling_gates_removed: int
33
+ real_signal: float | None = None
34
+ control_signal: float | None = None
35
+ isolated_effect: float | None = None
36
+ p_value: float | None = None
37
+ tvd: float | None = None
38
+ tvd_noise_floor: float | None = None
39
+ most_boosted: list = field(default_factory=list)
40
+ interpretation: str = ""
41
+
42
+ def to_dict(self) -> dict:
43
+ return asdict(self)
44
+
45
+
46
+ def falsify_claim(
47
+ circuit,
48
+ device: "str | Device" = "ionq-forte-1",
49
+ marked_bitstrings: list[str] | None = None,
50
+ *,
51
+ shots: int = 4096,
52
+ alpha: float = 0.01,
53
+ min_effect: float = 0.05,
54
+ seed: int | None = 1234,
55
+ ) -> FalsificationReport:
56
+ """Test whether a circuit's claimed effect actually comes from its entangling gates.
57
+
58
+ Builds a control (entangling gates removed, everything else identical) and
59
+ runs both through the same noisy simulation. Readout bias and SPAM hit both
60
+ arms equally, so the *difference* is the effect the entanglement itself
61
+ contributes. A pretty-looking signal that the control reproduces is noise
62
+ or a product-state artifact, not entanglement.
63
+
64
+ With ``marked_bitstrings``: effect = P(marked | real) - P(marked | control),
65
+ tested with a one-sided two-proportion z-test. Without (discovery mode):
66
+ total-variation distance real-vs-control, compared with the sampling-noise
67
+ floor measured from two independent control runs.
68
+ """
69
+ qc = as_circuit(circuit)
70
+ dev = get_device(device)
71
+ removed = sum(1 for i in qc.data if i.operation.name.lower() in ENTANGLING_GATES)
72
+ if removed == 0:
73
+ raise ValueError("Circuit has no entangling gates — there is no entanglement claim to falsify.")
74
+ control = build_control_circuit(qc)
75
+ base = 0 if seed is None else seed
76
+ real = noisy_counts(qc, dev, shots, None if seed is None else base)
77
+ ctrl = noisy_counts(control, dev, shots, None if seed is None else base + 1)
78
+
79
+ rep = FalsificationReport(False, "NOT_SUPPORTED", dev.name, removed)
80
+ rt, ct = sum(real.values()), sum(ctrl.values())
81
+ if marked_bitstrings:
82
+ marked = set(marked_bitstrings)
83
+ rk = sum(c for b, c in real.items() if b in marked)
84
+ ck = sum(c for b, c in ctrl.items() if b in marked)
85
+ rep.real_signal, rep.control_signal = round(rk / rt, 4), round(ck / ct, 4)
86
+ rep.isolated_effect = round(rk / rt - ck / ct, 4)
87
+ rep.p_value = two_proportion_pvalue(rk, rt, ck, ct)
88
+ rep.supported = rep.isolated_effect >= min_effect and rep.p_value < alpha
89
+ rep.interpretation = (
90
+ f"Marked outcomes: {rep.real_signal:.3f} real vs {rep.control_signal:.3f} control "
91
+ f"(entangling gates removed); isolated effect {rep.isolated_effect:+.3f}, p={rep.p_value:.2g}. "
92
+ + ("The entangling gates produce this signal." if rep.supported else
93
+ "The control reproduces the signal — it comes from noise/readout bias or product-state "
94
+ "structure, not entanglement."))
95
+ else:
96
+ ctrl2 = noisy_counts(control, dev, shots, None if seed is None else base + 2)
97
+ rep.tvd = round(tvd(real, ctrl), 4)
98
+ rep.tvd_noise_floor = round(tvd(ctrl, ctrl2), 4)
99
+ rep.supported = rep.tvd > max(min_effect, 3 * rep.tvd_noise_floor)
100
+ rep.most_boosted = sorted(set(real) | set(ctrl), reverse=True,
101
+ key=lambda k: real.get(k, 0) / rt - ctrl.get(k, 0) / ct)[:5]
102
+ rep.interpretation = (
103
+ f"Real vs control TVD {rep.tvd:.3f} (sampling floor {rep.tvd_noise_floor:.3f}). "
104
+ + ("Entanglement measurably changes the output." if rep.supported else
105
+ "Output is indistinguishable from the entanglement-free control."))
106
+ rep.verdict = "SUPPORTED" if rep.supported else "NOT_SUPPORTED"
107
+ return rep
@@ -0,0 +1,52 @@
1
+ """analyze_circuit_gradients: barren-plateau / dead-parameter check (needs PennyLane)."""
2
+ from __future__ import annotations
3
+
4
+ PENNYLANE_HINT = ('analyze_circuit_gradients needs PennyLane. Install it with: '
5
+ 'pip install "py-quantum-verifier[pennylane]"')
6
+
7
+
8
+ def analyze_circuit_gradients(
9
+ build_circuit_fn,
10
+ params,
11
+ n_qubits: int,
12
+ observable=None,
13
+ *,
14
+ barren_plateau_threshold: float = 1e-2,
15
+ near_zero_threshold: float = 1e-3,
16
+ ) -> dict:
17
+ """Autodiff the cost at ``params`` and flag barren plateaus / dead parameters.
18
+
19
+ ``build_circuit_fn(params, wires)`` applies PennyLane gates (it is the
20
+ *parameterized* definition — once exported to QASM every angle is bound and
21
+ there is nothing left to differentiate). ``observable`` defaults to Z on
22
+ wire 0.
23
+ """
24
+ try:
25
+ import pennylane as qml
26
+ from pennylane import numpy as pnp
27
+ except ImportError as e:
28
+ raise ImportError(PENNYLANE_HINT) from e
29
+
30
+ obs = observable if observable is not None else qml.PauliZ(0)
31
+ dev = qml.device("default.qubit", wires=n_qubits)
32
+
33
+ @qml.qnode(dev)
34
+ def cost(p):
35
+ build_circuit_fn(p, wires=range(n_qubits))
36
+ return qml.expval(obs)
37
+
38
+ p = pnp.array(params, requires_grad=True)
39
+ grad = pnp.atleast_1d(qml.grad(cost)(p))
40
+ norm = float(pnp.linalg.norm(grad))
41
+ dead = [i for i, g in enumerate(grad) if abs(float(g)) < near_zero_threshold]
42
+ barren = norm < barren_plateau_threshold
43
+ return {
44
+ "n_params": len(p), "gradient_norm": round(norm, 6),
45
+ "per_parameter_gradient": [round(float(g), 6) for g in grad],
46
+ "near_zero_gradient_params": dead, "barren_plateau_risk": barren,
47
+ "verdict": (f"Gradient norm {norm:.2e} < {barren_plateau_threshold:.0e}: likely barren plateau at "
48
+ "this point; optimizing this ansatz here will make negligible progress."
49
+ if barren else
50
+ f"Gradient norm {norm:.2e} is healthy; {len(dead)}/{len(p)} parameter(s) have "
51
+ "near-zero gradient (check for redundant or cancelling gates)."),
52
+ }
@@ -0,0 +1,120 @@
1
+ """Offline model of a native gateset and the transpile path onto it.
2
+
3
+ The silent-blowup class of bug lives here: if the transpiler has no *direct*
4
+ equivalence from a logical gate (e.g. ``rzz``) to the target's native gate
5
+ (e.g. IonQ's tunable ``zz``), it falls back to a generic decomposition and
6
+ emits several native two-qubit gates where one suffices. We model both paths
7
+ so the blowup is reproducible and detectable without any vendor SDK/token.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from dataclasses import dataclass
13
+
14
+ import numpy as np
15
+ from qiskit import QuantumCircuit
16
+ from qiskit.circuit import Gate, Parameter
17
+ from qiskit.circuit.equivalence import EquivalenceLibrary
18
+ from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
19
+ from qiskit.circuit.library import CXGate, CZGate, RZZGate
20
+ from qiskit.transpiler import PassManager
21
+ from qiskit.transpiler.passes import (
22
+ BasisTranslator,
23
+ Optimize1qGatesDecomposition,
24
+ RemoveBarriers,
25
+ )
26
+ from qiskit.transpiler.passes.optimization import CommutativeCancellation
27
+
28
+
29
+ class ZZGate(Gate):
30
+ """Tunable native ZZ interaction, angle in *turns* (IonQ convention).
31
+
32
+ ``ZZ(t) == RZZ(2*pi*t)``. Valid hardware range is ``|t| <= 0.25``.
33
+ """
34
+
35
+ def __init__(self, turns, label=None):
36
+ super().__init__("zz", 2, [turns], label=label)
37
+
38
+ def _define(self):
39
+ qc = QuantumCircuit(2, name="zz")
40
+ qc.rzz(2 * math.pi * self.params[0], 0, 1)
41
+ self.definition = qc
42
+
43
+ def __array__(self, dtype=complex, copy=None):
44
+ t = float(self.params[0])
45
+ phase = np.exp(-1j * math.pi * t)
46
+ return np.diag([phase, phase.conjugate(), phase.conjugate(), phase]).astype(dtype)
47
+
48
+
49
+ ZZ_MAX_TURNS = 0.25
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class NativeTarget:
54
+ name: str
55
+ basis_gates: tuple[str, ...]
56
+ two_qubit_native: str
57
+ fixed_angle_two_qubit: bool
58
+ #: Register the direct rzz -> native-ZZ equivalence (the correct behaviour).
59
+ direct_rzz: bool = True
60
+
61
+
62
+ def _equivalence_library(target: NativeTarget) -> EquivalenceLibrary:
63
+ lib = EquivalenceLibrary(base=SessionEquivalenceLibrary)
64
+ if target.two_qubit_native == "zz":
65
+ theta = Parameter("theta")
66
+ if target.direct_rzz:
67
+ qc = QuantumCircuit(2)
68
+ qc.append(ZZGate(theta / (2 * math.pi)), [0, 1])
69
+ lib.add_equivalence(RZZGate(theta), qc)
70
+ # CZ = (S x S) . ZZ(-1/4) up to global phase (exp(-i*pi/4 ZZ))
71
+ cz = QuantumCircuit(2)
72
+ cz.append(ZZGate(-0.25), [0, 1])
73
+ cz.rz(math.pi / 2, 0)
74
+ cz.rz(math.pi / 2, 1)
75
+ lib.add_equivalence(CZGate(), cz)
76
+ cx = QuantumCircuit(2)
77
+ cx.h(1)
78
+ cx.cz(0, 1)
79
+ cx.h(1)
80
+ lib.add_equivalence(CXGate(), cx)
81
+ return lib
82
+
83
+
84
+ def _split_large_zz(circuit: QuantumCircuit) -> QuantumCircuit:
85
+ """Exact split of rzz beyond the native ZZ range into commuting chunks."""
86
+ out = circuit.copy_empty_like()
87
+ for inst in circuit.data:
88
+ if inst.operation.name == "rzz" and not inst.operation.is_parameterized():
89
+ theta = float(inst.operation.params[0])
90
+ n = max(1, math.ceil(abs(theta / (2 * math.pi)) / ZZ_MAX_TURNS))
91
+ for _ in range(n):
92
+ out.rzz(theta / n, *inst.qubits)
93
+ else:
94
+ out.append(inst.operation, inst.qubits, inst.clbits)
95
+ return out
96
+
97
+
98
+ def to_native(circuit: QuantumCircuit, target: NativeTarget) -> QuantumCircuit:
99
+ """Translate ``circuit`` to ``target``'s native basis (no routing)."""
100
+ basis = list(target.basis_gates) + ["measure", "barrier", "delay"]
101
+ if target.two_qubit_native == "zz":
102
+ circuit = _split_large_zz(circuit)
103
+ lib = _equivalence_library(target)
104
+ pm = PassManager([
105
+ BasisTranslator(lib, basis),
106
+ Optimize1qGatesDecomposition(basis=[g for g in ("rz", "sx", "x") if g in basis]),
107
+ CommutativeCancellation(basis_gates=basis),
108
+ ])
109
+ return pm.run(circuit)
110
+
111
+
112
+ def to_simulable(native: QuantumCircuit) -> QuantumCircuit:
113
+ """Rewrite custom native gates into ones Aer understands (zz -> rzz)."""
114
+ out = native.copy_empty_like()
115
+ for inst in native.data:
116
+ if inst.operation.name == "zz":
117
+ out.rzz(2 * math.pi * float(inst.operation.params[0]), *inst.qubits)
118
+ else:
119
+ out.append(inst.operation, inst.qubits, inst.clbits)
120
+ return out
File without changes
@@ -0,0 +1,64 @@
1
+ """find_robust_circuit: rank candidates by noisy performance, not ideal performance."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+
6
+ from .circuits import as_circuit
7
+ from .devices import Device, get_device
8
+ from .native import to_native
9
+ from .simulation import noisy_counts_native
10
+
11
+
12
+ def _amplification(native, dev, marked, shots, seed) -> float:
13
+ counts = noisy_counts_native(native, dev, shots, seed)
14
+ total = sum(counts.values())
15
+ n_bits = len(next(iter(counts)))
16
+ hits = sum(c for b, c in counts.items() if b in marked)
17
+ return (hits / total) / (len(marked) / 2 ** n_bits)
18
+
19
+
20
+ def find_robust_circuit(
21
+ candidates: list,
22
+ device: "str | Device" = "ionq-forte-1",
23
+ marked_bitstrings: list[str] | None = None,
24
+ *,
25
+ shots: int = 2048,
26
+ n_scoring_runs: int = 3,
27
+ variance_penalty: float = 1.0,
28
+ seed: int = 1234,
29
+ ) -> dict:
30
+ """Pick the candidate that holds up under the device's noise.
31
+
32
+ Each candidate is translated to the native gateset, scored over
33
+ ``n_scoring_runs`` independent noisy runs as ``mean - variance_penalty*std``
34
+ of amplification on ``marked_bitstrings``, and the winner is re-run once on
35
+ a fresh seed it was never scored on (train/test split). A circuit that
36
+ wins on ideal simulation but is fragile under noise loses here.
37
+ """
38
+ if len(candidates) < 2:
39
+ raise ValueError("Need at least 2 candidates to compare.")
40
+ if not marked_bitstrings:
41
+ raise ValueError("marked_bitstrings is required to define success.")
42
+ dev = get_device(device)
43
+ marked = set(marked_bitstrings)
44
+ natives = [to_native(as_circuit(c), dev.target) for c in candidates]
45
+
46
+ rows = []
47
+ for i, nat in enumerate(natives):
48
+ runs = [_amplification(nat, dev, marked, shots, seed + 100 * i + r) for r in range(n_scoring_runs)]
49
+ mean, std = float(np.mean(runs)), float(np.std(runs))
50
+ rows.append({"index": i, "runs": [round(r, 3) for r in runs], "mean": round(mean, 3),
51
+ "std": round(std, 3), "score": round(mean - variance_penalty * std, 3),
52
+ "native_two_qubit_gates": sum(1 for g in nat.data if len(g.qubits) == 2
53
+ and g.operation.name != "measure")})
54
+ best = max(rows, key=lambda r: r["score"])
55
+ validation = _amplification(natives[best["index"]], dev, marked, shots, seed + 99991)
56
+ drift = abs(validation - best["mean"]) / max(best["mean"], 1e-9)
57
+ return {
58
+ "winner_index": best["index"], "winner_score": best["score"],
59
+ "validation_amplification": round(validation, 3),
60
+ "validation_warning": (f"Validation run ({validation:.2f}) differs from scoring mean "
61
+ f"({best['mean']:.2f}) by {drift:.0%}; winner may be less robust than scored."
62
+ if drift > 0.5 else None),
63
+ "candidates": rows, "device": dev.name,
64
+ }
@@ -0,0 +1,51 @@
1
+ """Local ideal and noisy simulation via Qiskit Aer (no network, no tokens)."""
2
+ from __future__ import annotations
3
+
4
+ from qiskit import QuantumCircuit
5
+
6
+ from .circuits import normalize_counts
7
+ from .devices import Device
8
+ from .native import to_native, to_simulable
9
+
10
+
11
+ def _aer():
12
+ from qiskit_aer import AerSimulator
13
+ from qiskit_aer.noise import NoiseModel, ReadoutError, depolarizing_error
14
+ return AerSimulator, NoiseModel, ReadoutError, depolarizing_error
15
+
16
+
17
+ def ideal_counts(circuit: QuantumCircuit, shots: int = 4096, seed: int | None = None) -> dict:
18
+ AerSimulator, *_ = _aer()
19
+ res = AerSimulator().run(circuit, shots=shots, seed_simulator=seed).result()
20
+ return normalize_counts(res.get_counts())
21
+
22
+
23
+ def build_noise_model(device: Device):
24
+ AerSimulator, NoiseModel, ReadoutError, depolarizing_error = _aer()
25
+ nm = NoiseModel()
26
+ n = device.noise
27
+ if n.p1 > 0:
28
+ nm.add_all_qubit_quantum_error(depolarizing_error(n.p1, 1), ["sx", "x"])
29
+ if n.p2 > 0:
30
+ two_q = ["rzz"] if device.target.two_qubit_native == "zz" else [device.target.two_qubit_native]
31
+ nm.add_all_qubit_quantum_error(depolarizing_error(n.p2, 2), two_q)
32
+ if n.readout > 0:
33
+ r = n.readout
34
+ nm.add_all_qubit_readout_error(ReadoutError([[1 - r, r], [r, 1 - r]]))
35
+ return nm
36
+
37
+
38
+ def noisy_counts_native(native: QuantumCircuit, device: Device, shots: int = 4096,
39
+ seed: int | None = None) -> dict:
40
+ """Run an already-native circuit under the device's noise model."""
41
+ AerSimulator, *_ = _aer()
42
+ sim_circuit = to_simulable(native)
43
+ basis = sorted(set(device.target.basis_gates) - {"zz"} | ({"rzz"} if device.target.two_qubit_native == "zz" else set()))
44
+ sim = AerSimulator(noise_model=build_noise_model(device), basis_gates=basis + ["measure", "barrier", "delay"])
45
+ res = sim.run(sim_circuit, shots=shots, seed_simulator=seed).result()
46
+ return normalize_counts(res.get_counts())
47
+
48
+
49
+ def noisy_counts(circuit: QuantumCircuit, device: Device, shots: int = 4096,
50
+ seed: int | None = None) -> dict:
51
+ return noisy_counts_native(to_native(circuit, device.target), device, shots, seed)
@@ -0,0 +1,52 @@
1
+ """Small, dependency-free statistics (stdlib only — no scipy)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from statistics import NormalDist
6
+
7
+ _N = NormalDist()
8
+
9
+
10
+ def wilson_interval(successes: int, total: int, alpha: float = 0.05) -> tuple[float, float]:
11
+ """Wilson score interval at the (1 - 2*alpha) level."""
12
+ if total <= 0:
13
+ return 0.0, 1.0
14
+ z = _N.inv_cdf(1 - alpha)
15
+ p = successes / total
16
+ z2 = z * z
17
+ denom = 1 + z2 / total
18
+ center = (p + z2 / (2 * total)) / denom
19
+ half = z * math.sqrt(p * (1 - p) / total + z2 / (4 * total * total)) / denom
20
+ return max(0.0, center - half), min(1.0, center + half)
21
+
22
+
23
+ def two_proportion_pvalue(k1: int, n1: int, k2: int, n2: int) -> float:
24
+ """One-sided p-value for H1: p1 > p2 (pooled z-test)."""
25
+ if n1 <= 0 or n2 <= 0:
26
+ return 1.0
27
+ p1, p2 = k1 / n1, k2 / n2
28
+ pooled = (k1 + k2) / (n1 + n2)
29
+ se = math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))
30
+ if se == 0:
31
+ return 0.0 if p1 > p2 else 1.0
32
+ return 1 - _N.cdf((p1 - p2) / se)
33
+
34
+
35
+ def tvd(a: dict, b: dict) -> float:
36
+ ta, tb = sum(a.values()), sum(b.values())
37
+ keys = set(a) | set(b)
38
+ return 0.5 * sum(abs(a.get(k, 0) / ta - b.get(k, 0) / tb) for k in keys)
39
+
40
+
41
+ def required_shots(n_marked: int, n_qubits: int, amplification: float,
42
+ confidence: float = 0.95, power: float = 0.80) -> int | None:
43
+ """Shots needed to tell p0=n_marked/2^n from p1=amplification*p0. None if no effect claimed."""
44
+ p0 = n_marked / 2 ** n_qubits
45
+ p1 = min(amplification * p0, 1.0)
46
+ if p1 <= p0:
47
+ return None
48
+ za = _N.inv_cdf(1 - (1 - confidence) / 2)
49
+ zb = _N.inv_cdf(power)
50
+ pbar = (p0 + p1) / 2
51
+ num = za * math.sqrt(2 * pbar * (1 - pbar)) + zb * math.sqrt(p0 * (1 - p0) + p1 * (1 - p1))
52
+ return math.ceil((num / (p1 - p0)) ** 2)
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import asdict, dataclass, field
4
+
5
+
6
+ @dataclass
7
+ class Verdict:
8
+ """Structured result of :func:`verify_experiment`.
9
+
10
+ ``status`` is ``"GO"`` or ``"BLOCK"``. ``checks`` holds each pipeline
11
+ stage's raw result (in execution order); ``metrics`` the headline numbers.
12
+ """
13
+ status: str
14
+ reason: str
15
+ device: str
16
+ checks: dict = field(default_factory=dict)
17
+ metrics: dict = field(default_factory=dict)
18
+
19
+ @property
20
+ def go(self) -> bool:
21
+ return self.status == "GO"
22
+
23
+ @property
24
+ def blocked(self) -> bool:
25
+ return self.status == "BLOCK"
26
+
27
+ def to_dict(self) -> dict:
28
+ return asdict(self)
29
+
30
+ def __str__(self) -> str:
31
+ return f"{self.status} ({self.device}): {self.reason}"
@@ -0,0 +1,119 @@
1
+ """verify_experiment: the full deterministic pre-flight pipeline."""
2
+ from __future__ import annotations
3
+
4
+ from .checks import gate_synthesis_check, semantic_check, topology_check
5
+ from .circuits import as_circuit
6
+ from .devices import Device, get_device
7
+ from .native import to_native
8
+ from .simulation import ideal_counts, noisy_counts_native
9
+ from .stats import required_shots, wilson_interval
10
+ from .verdict import Verdict
11
+
12
+
13
+ def ground_truth_check(counts: dict, marked: list[str], expected_amplification: float,
14
+ tolerance: float = 0.5, alpha: float = 0.05) -> dict:
15
+ """Compare observed amplification of ``marked`` bitstrings with a known expectation.
16
+
17
+ ``amplification`` = P(marked) / uniform baseline. Passes when the observed
18
+ value is within ``expected * (1 ± tolerance)``. A Wilson interval is
19
+ reported alongside so under-sampled results can be told apart from wrong ones.
20
+ """
21
+ total = sum(counts.values())
22
+ n_bits = len(next(iter(counts)))
23
+ baseline = len(set(marked)) / 2 ** n_bits
24
+ hits = sum(c for b, c in counts.items() if b in set(marked))
25
+ observed = (hits / total) / baseline if total and baseline else 0.0
26
+ lo, hi = expected_amplification * (1 - tolerance), expected_amplification * (1 + tolerance)
27
+ ci_lo, ci_hi = wilson_interval(hits, total, alpha)
28
+ within = lo <= observed <= hi
29
+ return {
30
+ "observed_amplification": round(observed, 3),
31
+ "expected_amplification": expected_amplification,
32
+ "accepted_range": [round(lo, 3), round(hi, 3)],
33
+ "amplification_ci": [round(ci_lo / baseline, 3), round(ci_hi / baseline, 3)],
34
+ "within_tolerance": within,
35
+ "message": ("Observed signal matches the claim under the device's noise model." if within else
36
+ f"Claimed {expected_amplification}x but the noise-aware simulation gives "
37
+ f"{observed:.2f}x — the experiment cannot support this claim."),
38
+ }
39
+
40
+
41
+ def _block(checks, metrics, device, reason) -> Verdict:
42
+ return Verdict("BLOCK", reason, device, checks, metrics)
43
+
44
+
45
+ def verify_experiment(
46
+ circuit,
47
+ device: "str | Device" = "ionq-forte-1",
48
+ *,
49
+ shots: int = 4096,
50
+ expected_marked_bitstrings: list[str] | None = None,
51
+ expected_amplification: float | None = None,
52
+ tolerance: float = 0.5,
53
+ seed: int | None = 1234,
54
+ ) -> Verdict:
55
+ """Run every pre-flight check and return a GO/BLOCK :class:`Verdict`.
56
+
57
+ Pipeline: parse -> semantic -> topology -> shot-budget power check ->
58
+ ideal simulation -> native-gateset translation + gate-synthesis inflation
59
+ check -> noisy simulation under the device's noise model -> ground-truth
60
+ check (only if ``expected_marked_bitstrings`` and ``expected_amplification``
61
+ are given; otherwise use :func:`falsify_claim`).
62
+
63
+ Fully offline: uses Qiskit Aer and the preset device models; no tokens.
64
+ """
65
+ dev = get_device(device)
66
+ checks: dict = {}
67
+ metrics: dict = {"shots": shots}
68
+
69
+ try:
70
+ qc = as_circuit(circuit)
71
+ except Exception as e: # parse failures are verdicts, not crashes
72
+ return _block(checks, metrics, dev.name, f"Failed to parse circuit: {e}")
73
+ metrics["n_qubits"] = qc.num_qubits
74
+
75
+ checks["semantic"] = sem = semantic_check(qc)
76
+ if not sem["passed"]:
77
+ return _block(checks, metrics, dev.name, "Semantic check failed: " +
78
+ "; ".join(i["message"] for i in sem["issues"] if i["severity"] == "ERROR"))
79
+
80
+ checks["topology"] = topo = topology_check(qc, dev)
81
+ if not topo["passed"]:
82
+ return _block(checks, metrics, dev.name, f"Topology check failed: {topo['note']}")
83
+
84
+ claim = bool(expected_marked_bitstrings) and expected_amplification is not None
85
+ if claim:
86
+ need = required_shots(len(set(expected_marked_bitstrings)), qc.num_qubits, expected_amplification)
87
+ checks["shot_budget"] = {"required_shots": need, "requested_shots": shots,
88
+ "passed": need is None or shots >= need}
89
+ if need is not None and shots < need:
90
+ return _block(checks, metrics, dev.name,
91
+ f"{shots} shots cannot distinguish this claim from noise; need >= {need}.")
92
+
93
+ checks["ideal_simulation"] = {"top_outcomes": dict(
94
+ sorted(ideal_counts(qc, shots, seed).items(), key=lambda kv: -kv[1])[:5])}
95
+
96
+ native = to_native(qc, dev.target)
97
+ gsc = gate_synthesis_check(qc, dev, transpiled=native)
98
+ checks["gate_synthesis"] = gsc
99
+ metrics.update(logical_gate_count=gsc["logical_gate_count"], native_gate_count=gsc["native_gate_count"],
100
+ two_qubit_inflation_ratio=gsc["two_qubit_inflation_ratio"])
101
+ if not gsc["passed"]:
102
+ return _block(checks, metrics, dev.name, "Gate-synthesis check failed: " +
103
+ " ".join(v["message"] for v in gsc["violations"]))
104
+
105
+ counts = noisy_counts_native(native, dev, shots, seed)
106
+ checks["noisy_simulation"] = {"top_outcomes": dict(sorted(counts.items(), key=lambda kv: -kv[1])[:5]),
107
+ "noise": dev.noise.__dict__}
108
+
109
+ if claim:
110
+ gt = ground_truth_check(counts, expected_marked_bitstrings, expected_amplification, tolerance)
111
+ checks["ground_truth"] = gt
112
+ metrics["observed_amplification"] = gt["observed_amplification"]
113
+ if not gt["within_tolerance"]:
114
+ return _block(checks, metrics, dev.name, gt["message"])
115
+ else:
116
+ checks["ground_truth"] = {"applicable": False,
117
+ "note": "No claim supplied (discovery mode) — use falsify_claim()."}
118
+
119
+ return Verdict("GO", "All checks passed.", dev.name, checks, metrics)
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.5
2
+ Name: py-quantum-verifier
3
+ Version: 0.1.0
4
+ Summary: Deterministic pre-flight verification for quantum circuits: catches silent transpiler blowups, topology traps and noise-only 'signals' before you spend hardware time.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: noise,qiskit,quantum,transpiler,verification
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Scientific/Engineering :: Physics
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: numpy
13
+ Requires-Dist: qiskit-aer
14
+ Requires-Dist: qiskit>=2.0
15
+ Provides-Extra: all
16
+ Requires-Dist: cudaq; extra == 'all'
17
+ Requires-Dist: pennylane>=0.38; extra == 'all'
18
+ Requires-Dist: pytest>=7; extra == 'all'
19
+ Requires-Dist: pytket; extra == 'all'
20
+ Requires-Dist: pytket-qiskit; extra == 'all'
21
+ Provides-Extra: cuda
22
+ Requires-Dist: cudaq; extra == 'cuda'
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7; extra == 'dev'
25
+ Provides-Extra: pennylane
26
+ Requires-Dist: pennylane>=0.38; extra == 'pennylane'
27
+ Provides-Extra: tket
28
+ Requires-Dist: pytket; extra == 'tket'
29
+ Requires-Dist: pytket-qiskit; extra == 'tket'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # py-quantum-verifier
33
+
34
+ Deterministic, offline pre-flight checks for quantum circuits. Run them before you spend hardware time.
35
+
36
+ ```python
37
+ from py_quantum_verifier import verify_experiment, falsify_claim
38
+ from qiskit import QuantumCircuit
39
+ qc = QuantumCircuit(2, 2); qc.h(0); qc.cx(0, 1); qc.measure([0, 1], [0, 1])
40
+ print(verify_experiment(qc, "ionq-forte-1")) # GO (ionq-forte-1): All checks passed.
41
+ print(falsify_claim(qc, "ionq-forte-1", ["00", "11"]).verdict) # SUPPORTED
42
+ ```
43
+
44
+ No API tokens, no network, no GPU. Everything runs on Qiskit Aer with built-in device models.
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install py-quantum-verifier # core: qiskit>=2.0, qiskit-aer, numpy
50
+ pip install "py-quantum-verifier[pennylane]" # + analyze_circuit_gradients
51
+ pip install "py-quantum-verifier[cuda]" # + cudaq (Linux/macOS with CUDA-Q wheels)
52
+ pip install "py-quantum-verifier[tket]" # + Qiskit-vs-TKET diffing
53
+ pip install "py-quantum-verifier[all]" # everything, incl. pytest
54
+ ```
55
+
56
+ Optional integrations are imported lazily inside `try/except ImportError`, so the core
57
+ install is small and identical on macOS, Windows and Linux. `optional_features()` reports
58
+ which extras are importable.
59
+
60
+ ## Real bugs this catches
61
+
62
+ **Silent gate-synthesis blowup (`rzz` on IonQ-style native gates).** IonQ's native `ZZ`
63
+ gate is tunable, so a logical `rzz(θ)` should compile to exactly **one** native gate:
64
+ `RZZ(θ) == ZZ(θ/2π)`. If the compiler has no direct `rzz → zz` equivalence it silently falls
65
+ back to a generic `cx` decomposition: **2** native two-qubit gates plus a pile of single-qubit
66
+ gates. The circuit still runs and still "looks right"; it just carries double the two-qubit
67
+ error. `gate_synthesis_check` compares logical and native gate counts and blocks it:
68
+
69
+ ```python
70
+ from py_quantum_verifier import gate_synthesis_check, get_device, verify_experiment
71
+
72
+ device = get_device("ionq-forte-1").with_native_equivalences(direct_rzz=False) # unpatched compiler
73
+ verify_experiment(qc_with_rzz, device)
74
+ # BLOCK: 1 logical two-qubit gate(s) became 2 native two-qubit gate(s) (2.0x, limit 1.5x for tunable ...)
75
+ ```
76
+
77
+ Limits are device-aware: on CZ/CX/ECR-native hardware an arbitrary-angle `rzz` legitimately
78
+ needs 2 gates, so that is not flagged there (limit 2.5x).
79
+
80
+ **Topology traps.** On heavy-hex devices a qubit with more than 3 interaction partners forces
81
+ SWAP routing that multiplies two-qubit gate count. `topology_check` flags it before transpiling.
82
+ All-to-all devices report "not applicable" rather than silently passing.
83
+
84
+ **Noise passed off as a signal.** A forgotten `h` before a `cx` gives `00` at 99%, which looks
85
+ like a great Bell-state result. `falsify_claim` builds a control with the entangling gates removed,
86
+ runs both under the same noise model, and compares: readout bias and SPAM hit both arms equally
87
+ and cancel. If the control reproduces the signal, the claim is `NOT_SUPPORTED`.
88
+
89
+ **Claims the shot budget can't support.** `verify_experiment` computes the shots needed to separate
90
+ a claimed amplification from uniform noise and blocks under-powered runs up front.
91
+
92
+ **Fragile winners.** `find_robust_circuit` ranks candidates by mean minus variance under the device
93
+ noise model and re-validates the winner on a seed it was never scored on, so a circuit that wins
94
+ only in ideal simulation loses.
95
+
96
+ ## Benchmark (synthetic suite)
97
+
98
+ These numbers describe this 30-circuit test suite, not real hardware.
99
+
100
+ 30 circuits (Bell, GHZ incl. star fan-out, QAOA, hardware-efficient ansätze, `rzz` pairs/chains, plus
101
+ deliberately broken and buggy-compiler variants) × 2 device presets, 4096 shots, fixed seeds,
102
+ produced by `benchmarks/run_benchmark.py`:
103
+
104
+ | Metric | ibm-heron | ionq-forte-1 |
105
+ |---|---|---|
106
+ | Circuits run | 30 | 30 |
107
+ | `verify_experiment` GO | 28 (93.3%) | 22 (73.3%) |
108
+ | `verify_experiment` BLOCK | 2 (6.7%) | 8 (26.7%) |
109
+ | &nbsp;&nbsp;of which gate-synthesis inflation | 0 | 8 |
110
+ | &nbsp;&nbsp;of which topology (routing) | 2 | 0 |
111
+ | &nbsp;&nbsp;of which ground-truth claim failed | 0 | 0 |
112
+ | Buggy-compiler `rzz` variants caught | 0/8 (n/a: cz-native, 2 cz is the minimum) | 8/8 |
113
+ | Clean-compiler `rzz` circuits falsely blocked | 0/9 | 0/9 |
114
+ | Fake-entanglement circuits (missing `h`) passed by `verify_experiment` | 3/3 | 3/3 |
115
+ | Fake-entanglement circuits rejected by `falsify_claim` | 3/3 | 3/3 |
116
+ | Non-broken circuits rejected by `falsify_claim` | 2/27 | 2/27 |
117
+
118
+ Takeaways:
119
+ - The 8 IonQ blocks are exactly the 8 buggy-compiler variants; none of the 9 clean `rzz` circuits is flagged.
120
+ - The fake-entanglement circuits (a `cx` on `|0>`, or an all-zero-parameter ansatz) show a ~99% "Bell/GHZ signal", so
121
+ `verify_experiment` passes them. Only the control-circuit test in `falsify_claim` rejects them, which is why both exist.
122
+ - The 2 non-broken `falsify_claim` rejections are the `rzz(0.3)` pair and its buggy-compiler duplicate: a rotation that
123
+ small can't be separated from noise.
124
+
125
+ Reproduce:
126
+
127
+ ```bash
128
+ pip install -e ".[dev]" && python benchmarks/run_benchmark.py --json benchmarks/results.json
129
+ ```
130
+
131
+ ## API
132
+
133
+ | Function | What it does |
134
+ |---|---|
135
+ | `verify_experiment(circuit, device, *, shots, expected_marked_bitstrings, expected_amplification, tolerance)` | Parse → semantic → topology → shot-budget → ideal sim → native translation + synthesis check → noisy sim → ground truth. Returns a `Verdict`. |
136
+ | `falsify_claim(circuit, device, marked_bitstrings=None)` | Control-circuit test. With marked bitstrings: isolated effect size + one-sided z-test. Without: TVD vs. the sampling-noise floor. |
137
+ | `find_robust_circuit(candidates, device, marked_bitstrings)` | Noise-aware candidate ranking with held-out validation. |
138
+ | `gate_synthesis_check(circuit, device)` | Native-gate inflation check; can also audit your own `transpiled=` circuit. |
139
+ | `analyze_circuit_gradients(build_fn, params, n_qubits)` | Barren-plateau / dead-parameter check via PennyLane autodiff. Raises an install hint if PennyLane is missing. |
140
+ | `diff_compilers(circuit, device)` | Qiskit vs. TKET onto the device's native basis; each output is checked by exact unitary equivalence (≤12 qubits). Degrades to Qiskit-only without TKET. |
141
+
142
+ `circuit` is a `QuantumCircuit` or an OpenQASM 2/3 string. `Verdict` has `.status` (`"GO"`/`"BLOCK"`),
143
+ `.reason`, `.checks` (every stage's raw result) and `.metrics`.
144
+
145
+ ### Devices and offline noise
146
+
147
+ Presets: `ionq-forte-1` (all-to-all, native `zz`), `ibm-heron` (heavy-hex degree 3, native `cz`), `ideal`.
148
+ Noise rates are representative order-of-magnitude figures, **not live calibration data**. Supply your own:
149
+
150
+ ```python
151
+ from py_quantum_verifier import get_device
152
+ dev = get_device("ibm-heron").with_noise(p1=3e-4, p2=5e-3, readout=2e-2)
153
+ ```
154
+
155
+ The native-gate models are offline approximations (single-qubit gates compile to `rz`/`sx`/`x`, with `rz`
156
+ treated as a free frame change). They reproduce the structural failure modes above, not vendor-exact
157
+ pulse counts. Treat a `GO` as "passed these checks", not as a hardware guarantee.
158
+
159
+ ## Limitations
160
+
161
+ - The "buggy compiler" is emulated (`Device.with_native_equivalences(direct_rzz=False)`), not a run of IonQ's real software.
162
+ - Noise rates are representative presets, not live calibration data.
163
+ - A `GO` means the circuit passed these checks, not that it will work on hardware.
164
+
165
+ ## Development
166
+
167
+ ```bash
168
+ pip install -e ".[dev]"
169
+ pytest
170
+ ```
171
+
172
+ MIT licensed.
@@ -0,0 +1,19 @@
1
+ py_quantum_verifier/__init__.py,sha256=VZ4cCWM6CAYLMJcWj_WAxQDj6m6u63zvFYPBKMhAHTM,943
2
+ py_quantum_verifier/_optional.py,sha256=oCuBHCW6mED6TMQ3D1Fd2_vCQYfQlAMElmP5KGcmotM,812
3
+ py_quantum_verifier/checks.py,sha256=i_7mwIMdtv310KUwlMcmvu1XB0eLubtS3fQUfHJZMDQ,6814
4
+ py_quantum_verifier/circuits.py,sha256=cqBptwxNLfkp4s27Z9igDcYzyyINk0Xpb8EjB8P3_Fs,851
5
+ py_quantum_verifier/compilers.py,sha256=KiyHXOCb55Z9bBMm6TrdFxHME5vHSJkrM-VX4mBpFmo,3555
6
+ py_quantum_verifier/devices.py,sha256=7HPUsI3eXRkeuIJqHk7JI32f4qwGBIIs5cM3lh8ENHQ,2581
7
+ py_quantum_verifier/falsify.py,sha256=braXiTWmhvFk6rArkEVpLeFRm5vJl7Ge59VQseZIyiI,4929
8
+ py_quantum_verifier/gradients.py,sha256=FgP0HaL8arYQN8CtcMPOFimnAF8MKA6mxoA-nLUULyw,2127
9
+ py_quantum_verifier/native.py,sha256=mOdgOPBHz3_ktGbNIdyVGdCAwI_Z0-6QrFkWgHMvZIU,4350
10
+ py_quantum_verifier/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ py_quantum_verifier/robust.py,sha256=rzEkyq0D94lRRwb3Oygbw3e-N22rR2rfAGsgQogsNZA,2912
12
+ py_quantum_verifier/simulation.py,sha256=RugLoh8DMflfiNivDO7clghTo619QfqAQw1wgVuQrk8,2165
13
+ py_quantum_verifier/stats.py,sha256=iN6smh11PI4vVues-gad3mrEJ32F26B6Ol9yXjh2zfY,1841
14
+ py_quantum_verifier/verdict.py,sha256=7ZRjdxV3nfSC-bakXalX2Plof8I7EfIz6_umQxwwORg,787
15
+ py_quantum_verifier/verify.py,sha256=qCKl0KNdTduaB5yYo-V0cy7FzwvdLSmqsAVuhFCX6mE,5651
16
+ py_quantum_verifier-0.1.0.dist-info/METADATA,sha256=4lYUoj1qEg5Z2aP5hltjIL7ncQN0b14RvGmHXVp6Yek,8548
17
+ py_quantum_verifier-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
18
+ py_quantum_verifier-0.1.0.dist-info/licenses/LICENSE,sha256=pJ3Sm84pmx_3iY2EbxOl4gdmulBC5u-YAMT3AXM7zB0,698
19
+ py_quantum_verifier-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lokesh Pullakandam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.