qcert 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.
- qcert/__init__.py +26 -0
- qcert/analysis/__init__.py +1 -0
- qcert/analysis/tail_sim.py +183 -0
- qcert/backends/__init__.py +1 -0
- qcert/backends/lean4.py +313 -0
- qcert/cli.py +217 -0
- qcert/extractors/__init__.py +1 -0
- qcert/extractors/lean4_parser.py +556 -0
- qcert/frontends/__init__.py +1 -0
- qcert/frontends/adapters.py +348 -0
- qcert/frontends/openqasm.py +379 -0
- qcert/ir.py +347 -0
- qcert/reporting.py +223 -0
- qcert/verifier/__init__.py +17 -0
- qcert/verifier/runner.py +755 -0
- qcert-0.1.0.dist-info/METADATA +147 -0
- qcert-0.1.0.dist-info/RECORD +20 -0
- qcert-0.1.0.dist-info/WHEEL +4 -0
- qcert-0.1.0.dist-info/entry_points.txt +2 -0
- qcert-0.1.0.dist-info/licenses/LICENSE +201 -0
qcert/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""qcert: Bidirectional OpenQASM 3 / Qiskit / Cirq <-> DeepMind Lean 4 bridge."""
|
|
2
|
+
|
|
3
|
+
from qcert.ir import (
|
|
4
|
+
CostPolicy,
|
|
5
|
+
GateOp,
|
|
6
|
+
IfBranchOp,
|
|
7
|
+
MeasureOp,
|
|
8
|
+
QuantumProgramIR,
|
|
9
|
+
ResetOp,
|
|
10
|
+
ResourceSummary,
|
|
11
|
+
WhileLoopOp,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"CostPolicy",
|
|
18
|
+
"GateOp",
|
|
19
|
+
"IfBranchOp",
|
|
20
|
+
"MeasureOp",
|
|
21
|
+
"QuantumProgramIR",
|
|
22
|
+
"ResetOp",
|
|
23
|
+
"ResourceSummary",
|
|
24
|
+
"WhileLoopOp",
|
|
25
|
+
"__version__",
|
|
26
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Exact tail-risk & Chernoff-MGF cost distribution analyzers."""
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Exact rational cost-distribution oracle & Chernoff-MGF tail optimizer.
|
|
2
|
+
|
|
3
|
+
Provides an independent, hand-inspectable reference implementation using exact
|
|
4
|
+
`fractions.Fraction` arithmetic for calibration benchmarks, plus continuous
|
|
5
|
+
Chernoff-Cramer MGF optimization:
|
|
6
|
+
Pr(C > B) <= inf_{t > 0} exp(-t * B) * E[exp(t * C)]
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from fractions import Fraction
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class TailReport:
|
|
18
|
+
"""Exact and Chernoff-MGF resource risk profile for a discrete cost distribution."""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
budget: int
|
|
22
|
+
distribution: dict[int, Fraction]
|
|
23
|
+
total_mass: Fraction
|
|
24
|
+
expected_cost: Fraction
|
|
25
|
+
max_cost: int
|
|
26
|
+
exact_exceed_prob: Fraction
|
|
27
|
+
markov_bound: float
|
|
28
|
+
chernoff_mgf_bound: float
|
|
29
|
+
chernoff_optimal_t: float
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict[str, object]:
|
|
32
|
+
return {
|
|
33
|
+
"name": self.name,
|
|
34
|
+
"budget": self.budget,
|
|
35
|
+
"distribution": {str(k): str(v) for k, v in sorted(self.distribution.items())},
|
|
36
|
+
"total_mass": str(self.total_mass),
|
|
37
|
+
"expected_cost": str(self.expected_cost),
|
|
38
|
+
"expected_cost_float": float(self.expected_cost),
|
|
39
|
+
"max_cost": self.max_cost,
|
|
40
|
+
"exact_exceed_prob": str(self.exact_exceed_prob),
|
|
41
|
+
"exact_exceed_prob_float": float(self.exact_exceed_prob),
|
|
42
|
+
"markov_bound": self.markov_bound,
|
|
43
|
+
"chernoff_mgf_bound": self.chernoff_mgf_bound,
|
|
44
|
+
"chernoff_optimal_t": self.chernoff_optimal_t,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def analyze_cost_distribution(
|
|
49
|
+
name: str, dist: dict[int, Fraction], budget: int
|
|
50
|
+
) -> TailReport:
|
|
51
|
+
"""Compute exact P(C > B), E[C], Markov bound, and optimal Chernoff-MGF bound."""
|
|
52
|
+
if not dist:
|
|
53
|
+
raise ValueError("Cost distribution cannot be empty")
|
|
54
|
+
total_mass = sum(dist.values(), Fraction(0))
|
|
55
|
+
expected = sum((Fraction(k) * p for k, p in dist.items()), Fraction(0))
|
|
56
|
+
max_cost = max(dist.keys())
|
|
57
|
+
exact_exceed = sum((p for k, p in dist.items() if k > budget), Fraction(0))
|
|
58
|
+
|
|
59
|
+
# Markov bound for strict > B: Pr(C >= B + 1) <= E[C] / (B + 1)
|
|
60
|
+
markov = min(1.0, float(expected) / (budget + 1))
|
|
61
|
+
|
|
62
|
+
# Chernoff bound via MGF: Pr(C > B) = Pr(C >= B + 1) <= inf_{t >= 0} exp(-t * (B + 1)) * E[exp(t * C)]
|
|
63
|
+
best_bound = 1.0
|
|
64
|
+
best_t = 0.0
|
|
65
|
+
# Grid + golden-section refinement over t in [0, 5]
|
|
66
|
+
for i in range(1, 501):
|
|
67
|
+
t = i * 0.01
|
|
68
|
+
mgf = sum(float(p) * math.exp(t * k) for k, p in dist.items())
|
|
69
|
+
bound = math.exp(-t * (budget + 1)) * mgf
|
|
70
|
+
if bound < best_bound:
|
|
71
|
+
best_bound = bound
|
|
72
|
+
best_t = t
|
|
73
|
+
|
|
74
|
+
# Local refinement around best_t
|
|
75
|
+
lo = max(0.0, best_t - 0.02)
|
|
76
|
+
hi = best_t + 0.02
|
|
77
|
+
phi = (1 + math.sqrt(5)) / 2
|
|
78
|
+
for _ in range(40):
|
|
79
|
+
c1 = hi - (hi - lo) / phi
|
|
80
|
+
c2 = lo + (hi - lo) / phi
|
|
81
|
+
f1 = math.exp(-c1 * (budget + 1)) * sum(float(p) * math.exp(c1 * k) for k, p in dist.items())
|
|
82
|
+
f2 = math.exp(-c2 * (budget + 1)) * sum(float(p) * math.exp(c2 * k) for k, p in dist.items())
|
|
83
|
+
if f1 < f2:
|
|
84
|
+
hi = c2
|
|
85
|
+
else:
|
|
86
|
+
lo = c1
|
|
87
|
+
t_opt = (lo + hi) / 2
|
|
88
|
+
f_opt = math.exp(-t_opt * (budget + 1)) * sum(
|
|
89
|
+
float(p) * math.exp(t_opt * k) for k, p in dist.items()
|
|
90
|
+
)
|
|
91
|
+
if f_opt < best_bound:
|
|
92
|
+
best_bound = f_opt
|
|
93
|
+
best_t = t_opt
|
|
94
|
+
|
|
95
|
+
return TailReport(
|
|
96
|
+
name=name,
|
|
97
|
+
budget=budget,
|
|
98
|
+
distribution=dist,
|
|
99
|
+
total_mass=total_mass,
|
|
100
|
+
expected_cost=expected,
|
|
101
|
+
max_cost=max_cost,
|
|
102
|
+
exact_exceed_prob=exact_exceed,
|
|
103
|
+
markov_bound=markov,
|
|
104
|
+
chernoff_mgf_bound=min(1.0, best_bound),
|
|
105
|
+
chernoff_optimal_t=best_t,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def geometric_rus_tail_report(
|
|
110
|
+
name: str,
|
|
111
|
+
success_prob: Fraction,
|
|
112
|
+
cost_per_attempt: int,
|
|
113
|
+
budget: int,
|
|
114
|
+
max_attempts_exact: int = 30,
|
|
115
|
+
) -> dict[str, object]:
|
|
116
|
+
"""Exact & MGF closed-form tail analysis for an unbounded Repeat-Until-Success `qWhile` loop.
|
|
117
|
+
|
|
118
|
+
Each attempt costs `cost_per_attempt` and succeeds independently with probability `p`.
|
|
119
|
+
Total attempts N ~ Geometric(p) on {1, 2, ...}, total cost C = N * cost_per_attempt.
|
|
120
|
+
- Exact: Pr(C > B) = (1 - p)^floor(B / c)
|
|
121
|
+
- Closed-form MGF for t with (1 - p) * exp(t * c) < 1:
|
|
122
|
+
E[exp(t * C)] = p * exp(t * c) / (1 - (1 - p) * exp(t * c))
|
|
123
|
+
"""
|
|
124
|
+
if not (0 < success_prob <= 1):
|
|
125
|
+
raise ValueError("success_prob must be in (0, 1]")
|
|
126
|
+
if cost_per_attempt <= 0:
|
|
127
|
+
raise ValueError("cost_per_attempt must be > 0")
|
|
128
|
+
fail_prob = Fraction(1) - success_prob
|
|
129
|
+
k_allowed = budget // cost_per_attempt
|
|
130
|
+
exact_exceed = fail_prob ** k_allowed
|
|
131
|
+
expected_cost = Fraction(cost_per_attempt) / success_prob
|
|
132
|
+
|
|
133
|
+
# Optimal closed-form Chernoff bound for geometric MGF
|
|
134
|
+
p_f = float(success_prob)
|
|
135
|
+
q_f = float(fail_prob)
|
|
136
|
+
c = cost_per_attempt
|
|
137
|
+
# t_max where q * exp(t * c) < 1 => t < -ln(q) / c
|
|
138
|
+
t_sup = -math.log(q_f) / c if q_f > 0 else 10.0
|
|
139
|
+
best_chernoff = 1.0
|
|
140
|
+
best_t = 0.0
|
|
141
|
+
for i in range(1, 1000):
|
|
142
|
+
t = (i / 1000.0) * t_sup * 0.999
|
|
143
|
+
exp_tc = math.exp(t * c)
|
|
144
|
+
mgf = (p_f * exp_tc) / (1.0 - q_f * exp_tc)
|
|
145
|
+
bound = math.exp(-t * (budget + 1)) * mgf
|
|
146
|
+
if bound < best_chernoff:
|
|
147
|
+
best_chernoff = bound
|
|
148
|
+
best_t = t
|
|
149
|
+
|
|
150
|
+
truncated_dist: dict[int, Fraction] = {}
|
|
151
|
+
for attempt in range(1, max_attempts_exact + 1):
|
|
152
|
+
truncated_dist[attempt * cost_per_attempt] = (fail_prob ** (attempt - 1)) * success_prob
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
"name": name,
|
|
156
|
+
"success_prob": str(success_prob),
|
|
157
|
+
"cost_per_attempt": cost_per_attempt,
|
|
158
|
+
"budget": budget,
|
|
159
|
+
"attempts_within_budget": k_allowed,
|
|
160
|
+
"expected_cost": str(expected_cost),
|
|
161
|
+
"expected_cost_float": float(expected_cost),
|
|
162
|
+
"exact_exceed_prob": str(exact_exceed),
|
|
163
|
+
"exact_exceed_prob_float": float(exact_exceed),
|
|
164
|
+
"chernoff_mgf_bound": min(1.0, best_chernoff),
|
|
165
|
+
"chernoff_optimal_t": best_t,
|
|
166
|
+
"truncated_mass_covered": str(sum(truncated_dist.values(), Fraction(0))),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def benchmark_equal_mean_circuits(budget: int = 10) -> tuple[TailReport, TailReport]:
|
|
171
|
+
"""Canonical decision-reversal benchmark: identical mean (8) & max (12), different P(C > 10)."""
|
|
172
|
+
dist_a = {4: Fraction(1, 2), 12: Fraction(1, 2)}
|
|
173
|
+
dist_b = {4: Fraction(1, 4), 8: Fraction(1, 2), 12: Fraction(1, 4)}
|
|
174
|
+
return (
|
|
175
|
+
analyze_cost_distribution("Circuit_A_bimodal", dist_a, budget=budget),
|
|
176
|
+
analyze_cost_distribution("Circuit_B_concentrated", dist_b, budget=budget),
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def benchmark_correlated_bit(budget: int = 1) -> TailReport:
|
|
181
|
+
"""Reusing one measured fair bit twice yields {0: 1/2, 2: 1/2}, never {0:1/4, 1:1/2, 2:1/4}."""
|
|
182
|
+
dist = {0: Fraction(1, 2), 2: Fraction(1, 2)}
|
|
183
|
+
return analyze_cost_distribution("Correlated_Bit_Reuse", dist, budget=budget)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Target code generators for `qcert`."""
|
qcert/backends/lean4.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Lean 4.35 code & theorem generator targeting Google DeepMind's
|
|
2
|
+
`formal-quantum-computation` (`QuantumComputation`) library.
|
|
3
|
+
|
|
4
|
+
Emits valid Lean 4 modules with:
|
|
5
|
+
- Exact `Circuit n` terms for static circuits + machine-checked `Circuit.count` T/Toffoli theorems
|
|
6
|
+
- Exact `DynamicCircuit Var n` terms for adaptive branching circuits + `DynamicCircuit.count`
|
|
7
|
+
and `ResourceCounting.CostBound` theorems
|
|
8
|
+
- Exact `QProg Var (2 ^ n)` terms for programs with `qWhile` loops or resets
|
|
9
|
+
- Strict `#print axioms` footer hooks for automated kernel auditing
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
from qcert.ir import (
|
|
17
|
+
CostPolicy,
|
|
18
|
+
GateOp,
|
|
19
|
+
IfBranchOp,
|
|
20
|
+
MeasureOp,
|
|
21
|
+
Op,
|
|
22
|
+
QuantumProgramIR,
|
|
23
|
+
ResetOp,
|
|
24
|
+
WhileLoopOp,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _sanitize_ident(name: str) -> str:
|
|
29
|
+
cleaned = re.sub(r"[^A-Za-z0-9_]", "_", name)
|
|
30
|
+
if not cleaned or cleaned[0].isdigit():
|
|
31
|
+
cleaned = "C_" + cleaned
|
|
32
|
+
return cleaned
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _emit_gate_expr(op: GateOp) -> str:
|
|
36
|
+
g = op.gate
|
|
37
|
+
w = op.wires
|
|
38
|
+
if g in ("X", "Y", "Z", "H", "S", "T"):
|
|
39
|
+
return f"Circuit.{g} {w[0]}"
|
|
40
|
+
if g in ("CNOT", "SWAP"):
|
|
41
|
+
return f"Circuit.{g} {w[0]} {w[1]} (by decide)"
|
|
42
|
+
if g == "TOFF":
|
|
43
|
+
return f"Circuit.TOFF {w[0]} {w[1]} {w[2]} (by decide) (by decide) (by decide)"
|
|
44
|
+
raise ValueError(f"Unexpected gate {g}")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _emit_circuit_seq(gates: list[GateOp], indent: str = " ") -> str:
|
|
48
|
+
if not gates:
|
|
49
|
+
return "Circuit.identity"
|
|
50
|
+
if len(gates) == 1:
|
|
51
|
+
return _emit_gate_expr(gates[0])
|
|
52
|
+
inner = f",\n{indent} ".join(_emit_gate_expr(g) for g in gates)
|
|
53
|
+
return f"Circuit.sequence [\n{indent} {inner}\n{indent}]"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _emit_dynamic_ops(ops: tuple[Op, ...], var_ns: str, indent: str = " ") -> str:
|
|
57
|
+
if not ops:
|
|
58
|
+
return "DynamicCircuit.identity"
|
|
59
|
+
|
|
60
|
+
# Batch consecutive GateOps into a single `.circuit (...)` block
|
|
61
|
+
segments: list[str] = []
|
|
62
|
+
gate_buf: list[GateOp] = []
|
|
63
|
+
|
|
64
|
+
def _flush_gates() -> None:
|
|
65
|
+
nonlocal gate_buf
|
|
66
|
+
if gate_buf:
|
|
67
|
+
if len(gate_buf) == 1:
|
|
68
|
+
segments.append(f"DynamicCircuit.circuit ({_emit_gate_expr(gate_buf[0])})")
|
|
69
|
+
else:
|
|
70
|
+
segments.append(
|
|
71
|
+
f"DynamicCircuit.circuit ({_emit_circuit_seq(gate_buf, indent + ' ')})"
|
|
72
|
+
)
|
|
73
|
+
gate_buf = []
|
|
74
|
+
|
|
75
|
+
for op in ops:
|
|
76
|
+
if isinstance(op, GateOp):
|
|
77
|
+
gate_buf.append(op)
|
|
78
|
+
else:
|
|
79
|
+
_flush_gates()
|
|
80
|
+
if isinstance(op, MeasureOp):
|
|
81
|
+
segments.append(
|
|
82
|
+
f"DynamicCircuit.measure {var_ns}.«{op.cvar}» (QRegister.singleton {op.wire})"
|
|
83
|
+
)
|
|
84
|
+
elif isinstance(op, IfBranchOp):
|
|
85
|
+
pred = op.condition.to_lean_predicate(var_ns)
|
|
86
|
+
t_expr = _emit_dynamic_ops(op.then_ops, var_ns, indent + " ")
|
|
87
|
+
e_expr = _emit_dynamic_ops(op.else_ops, var_ns, indent + " ")
|
|
88
|
+
segments.append(
|
|
89
|
+
f"DynamicCircuit.qIf ({pred})\n{indent} ({t_expr})\n{indent} ({e_expr})"
|
|
90
|
+
)
|
|
91
|
+
else:
|
|
92
|
+
raise TypeError(f"Op {type(op).__name__} requires QProg backend")
|
|
93
|
+
_flush_gates()
|
|
94
|
+
|
|
95
|
+
expr = segments[-1]
|
|
96
|
+
for seg in reversed(segments[:-1]):
|
|
97
|
+
expr = f"DynamicCircuit.seq\n{indent}({seg})\n{indent}({expr})"
|
|
98
|
+
return expr
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _emit_qprog_ops(
|
|
102
|
+
ops: tuple[Op, ...], num_qubits: int, reset_scratch: str, indent: str = " "
|
|
103
|
+
) -> str:
|
|
104
|
+
"""Lower local resets to the register reset measurement followed by `.assign scratch 0`.
|
|
105
|
+
|
|
106
|
+
Their ControlCostModel cost is
|
|
107
|
+
`measurementCost(register.resetMeasurement.toMeasurement) + assignmentCost`.
|
|
108
|
+
The lowering introduces neither a `qIf` nor a unitary X.
|
|
109
|
+
"""
|
|
110
|
+
if not ops:
|
|
111
|
+
return "QProg.skip"
|
|
112
|
+
|
|
113
|
+
segments: list[str] = []
|
|
114
|
+
gate_buf: list[GateOp] = []
|
|
115
|
+
|
|
116
|
+
def _flush_gates() -> None:
|
|
117
|
+
nonlocal gate_buf
|
|
118
|
+
if gate_buf:
|
|
119
|
+
circuit = _emit_circuit_seq(gate_buf, indent + " ")
|
|
120
|
+
segments.append(f"({circuit} : Circuit {num_qubits}).compile")
|
|
121
|
+
gate_buf = []
|
|
122
|
+
|
|
123
|
+
for op in ops:
|
|
124
|
+
if isinstance(op, GateOp):
|
|
125
|
+
gate_buf.append(op)
|
|
126
|
+
else:
|
|
127
|
+
_flush_gates()
|
|
128
|
+
if isinstance(op, MeasureOp):
|
|
129
|
+
segments.append(
|
|
130
|
+
f"QProg.measureRegister CVar.«{op.cvar}» "
|
|
131
|
+
f"(QRegister.singleton (n := {num_qubits}) {op.wire})"
|
|
132
|
+
)
|
|
133
|
+
elif isinstance(op, ResetOp):
|
|
134
|
+
if op.wire is None:
|
|
135
|
+
segments.append("QProg.qSet")
|
|
136
|
+
else:
|
|
137
|
+
segments.append(
|
|
138
|
+
f"QProg.resetRegister CVar.{reset_scratch} "
|
|
139
|
+
f"(QRegister.singleton (n := {num_qubits}) {op.wire})"
|
|
140
|
+
)
|
|
141
|
+
elif isinstance(op, IfBranchOp):
|
|
142
|
+
pred = op.condition.to_lean_predicate("CVar")
|
|
143
|
+
t_expr = _emit_qprog_ops(op.then_ops, num_qubits, reset_scratch, indent + " ")
|
|
144
|
+
e_expr = _emit_qprog_ops(op.else_ops, num_qubits, reset_scratch, indent + " ")
|
|
145
|
+
segments.append(f"QProg.qIf ({pred})\n{indent} ({t_expr})\n{indent} ({e_expr})")
|
|
146
|
+
elif isinstance(op, WhileLoopOp):
|
|
147
|
+
pred = op.condition.to_lean_predicate("CVar")
|
|
148
|
+
b_expr = _emit_qprog_ops(op.body_ops, num_qubits, reset_scratch, indent + " ")
|
|
149
|
+
segments.append(f"QProg.qWhile ({pred})\n{indent} ({b_expr})")
|
|
150
|
+
_flush_gates()
|
|
151
|
+
|
|
152
|
+
return f" ;;\n{indent}".join(segments)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def emit_lean4(
|
|
156
|
+
ir: QuantumProgramIR,
|
|
157
|
+
namespace: str | None = None,
|
|
158
|
+
policy: CostPolicy | None = None,
|
|
159
|
+
include_axiom_audit: bool = True,
|
|
160
|
+
) -> str:
|
|
161
|
+
"""Generate a self-contained Lean 4.35 module compatible with
|
|
162
|
+
`google-deepmind/formal-quantum-computation`."""
|
|
163
|
+
ns = _sanitize_ident(namespace or ir.name)
|
|
164
|
+
summary = ir.summarize()
|
|
165
|
+
_ = policy or CostPolicy.t_count()
|
|
166
|
+
|
|
167
|
+
if ir.is_static_circuit:
|
|
168
|
+
return _emit_static_module(ir, ns, summary, include_axiom_audit)
|
|
169
|
+
if not ir.has_loops and not ir.has_resets:
|
|
170
|
+
return _emit_dynamic_module(ir, ns, summary, include_axiom_audit)
|
|
171
|
+
return _emit_qprog_module(ir, ns, summary, include_axiom_audit)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _emit_static_module(
|
|
175
|
+
ir: QuantumProgramIR, ns: str, summary: object, include_axiom_audit: bool
|
|
176
|
+
) -> str:
|
|
177
|
+
from qcert.ir import ResourceSummary
|
|
178
|
+
|
|
179
|
+
assert isinstance(summary, ResourceSummary)
|
|
180
|
+
gates = [op for op in ir.ops if isinstance(op, GateOp)]
|
|
181
|
+
body = _emit_circuit_seq(gates, indent=" ")
|
|
182
|
+
|
|
183
|
+
audit = ""
|
|
184
|
+
if include_axiom_audit:
|
|
185
|
+
audit = (
|
|
186
|
+
f"\n#print axioms {ns}.t_count_eq\n"
|
|
187
|
+
f"#print axioms {ns}.toff_count_eq\n"
|
|
188
|
+
f"#print axioms {ns}.size_eq\n"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
return f"""/-
|
|
192
|
+
Auto-generated by `qcert` for `google-deepmind/formal-quantum-computation` (Lean 4.35).
|
|
193
|
+
Source format: {ir.source_format} | Qubits: {ir.num_qubits} | T-count: {summary.t_count} | Toffoli: {summary.toffoli_count}
|
|
194
|
+
-/
|
|
195
|
+
import QuantumComputation.Circuits.ResourceCounting
|
|
196
|
+
|
|
197
|
+
open Operator
|
|
198
|
+
open scoped Circuit.Notation
|
|
199
|
+
|
|
200
|
+
namespace {ns}
|
|
201
|
+
|
|
202
|
+
/-- Static `{ir.num_qubits}`-qubit Clifford+T circuit lowered by `qcert`. -/
|
|
203
|
+
def circuit : Circuit {ir.num_qubits} :=
|
|
204
|
+
{body}
|
|
205
|
+
|
|
206
|
+
/-- Machine-checked primitive T-gate count. -/
|
|
207
|
+
theorem t_count_eq : circuit.count PrimitiveGate.T = {summary.t_count} := by
|
|
208
|
+
decide
|
|
209
|
+
|
|
210
|
+
/-- Machine-checked primitive Toffoli-gate count. -/
|
|
211
|
+
theorem toff_count_eq : circuit.count PrimitiveGate.TOFF = {summary.toffoli_count} := by
|
|
212
|
+
decide
|
|
213
|
+
|
|
214
|
+
/-- Machine-checked total primitive gate size. -/
|
|
215
|
+
theorem size_eq : circuit.size = {summary.total_gates} := by
|
|
216
|
+
decide
|
|
217
|
+
|
|
218
|
+
end {ns}
|
|
219
|
+
{audit}"""
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _emit_dynamic_module(
|
|
223
|
+
ir: QuantumProgramIR, ns: str, summary: object, include_axiom_audit: bool
|
|
224
|
+
) -> str:
|
|
225
|
+
from qcert.ir import ResourceSummary
|
|
226
|
+
|
|
227
|
+
assert isinstance(summary, ResourceSummary)
|
|
228
|
+
var_constructors = "\n".join(f" | «{v}»" for v in ir.classical_vars) or " | c0"
|
|
229
|
+
body = _emit_dynamic_ops(ir.ops, "CVar", indent=" ")
|
|
230
|
+
audit = ""
|
|
231
|
+
if include_axiom_audit:
|
|
232
|
+
audit = (
|
|
233
|
+
f"\n#print axioms {ns}.worst_case_t_count\n"
|
|
234
|
+
f"#print axioms {ns}.worst_case_toff_count\n"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
return f"""/-
|
|
238
|
+
Auto-generated by `qcert` for `google-deepmind/formal-quantum-computation` (Lean 4.35).
|
|
239
|
+
Dynamic circuit | Qubits: {ir.num_qubits} | Measurements: {summary.measurements} | Branches: {summary.branches}
|
|
240
|
+
-/
|
|
241
|
+
import QuantumComputation.Circuits.ResourceCounting
|
|
242
|
+
import QuantumComputation.QuantumHoareLogic.ResourceCounting.CostBounds
|
|
243
|
+
|
|
244
|
+
open Operator QProg
|
|
245
|
+
open scoped QProg.Notation
|
|
246
|
+
|
|
247
|
+
namespace {ns}
|
|
248
|
+
|
|
249
|
+
/-- Classical variables storing mid-circuit measurement outcomes. -/
|
|
250
|
+
inductive CVar where
|
|
251
|
+
{var_constructors}
|
|
252
|
+
deriving DecidableEq, Repr
|
|
253
|
+
|
|
254
|
+
/-- Adaptive `{ir.num_qubits}`-qubit dynamic circuit lowered by `qcert`. -/
|
|
255
|
+
def circuit : DynamicCircuit CVar {ir.num_qubits} :=
|
|
256
|
+
{body}
|
|
257
|
+
|
|
258
|
+
/-- Compiled QHL program preserving gate and measurement boundaries. -/
|
|
259
|
+
noncomputable def prog : QProg CVar (2 ^ {ir.num_qubits}) :=
|
|
260
|
+
circuit.compile
|
|
261
|
+
|
|
262
|
+
/-- Machine-checked worst-case T-gate count across all classical branches. -/
|
|
263
|
+
theorem worst_case_t_count : circuit.count PrimitiveGate.T = {summary.t_count} := by
|
|
264
|
+
decide
|
|
265
|
+
|
|
266
|
+
/-- Machine-checked worst-case Toffoli count across all classical branches. -/
|
|
267
|
+
theorem worst_case_toff_count : circuit.count PrimitiveGate.TOFF = {summary.toffoli_count} := by
|
|
268
|
+
decide
|
|
269
|
+
|
|
270
|
+
end {ns}
|
|
271
|
+
{audit}"""
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _emit_qprog_module(
|
|
275
|
+
ir: QuantumProgramIR, ns: str, summary: object, include_axiom_audit: bool
|
|
276
|
+
) -> str:
|
|
277
|
+
from qcert.ir import ResourceSummary
|
|
278
|
+
|
|
279
|
+
assert isinstance(summary, ResourceSummary)
|
|
280
|
+
reset_scratch = "c_reset_scratch"
|
|
281
|
+
while reset_scratch in ir.classical_vars:
|
|
282
|
+
reset_scratch += "_"
|
|
283
|
+
constructors = [f" | «{v}»" for v in ir.classical_vars]
|
|
284
|
+
if ir.has_local_resets:
|
|
285
|
+
constructors.append(f" | {reset_scratch}")
|
|
286
|
+
var_constructors = "\n".join(constructors) or " | c0"
|
|
287
|
+
body = _emit_qprog_ops(ir.ops, ir.num_qubits, reset_scratch)
|
|
288
|
+
|
|
289
|
+
return f"""/-
|
|
290
|
+
Auto-generated by `qcert` for `google-deepmind/formal-quantum-computation` (Lean 4.35).
|
|
291
|
+
QHL program | Qubits: {ir.num_qubits} | Loops: {summary.loops} | Measurements: {summary.measurements}
|
|
292
|
+
-/
|
|
293
|
+
import QuantumComputation.Circuits.Basic
|
|
294
|
+
import QuantumComputation.Registers.Measurement
|
|
295
|
+
import QuantumComputation.Registers.Reset
|
|
296
|
+
import QuantumComputation.QuantumHoareLogic.ResourceCounting.Loops
|
|
297
|
+
|
|
298
|
+
open Operator QProg
|
|
299
|
+
open scoped QProg.Notation
|
|
300
|
+
|
|
301
|
+
namespace {ns}
|
|
302
|
+
|
|
303
|
+
/-- Classical variables for measurement, guards, and reset scratch storage. -/
|
|
304
|
+
inductive CVar where
|
|
305
|
+
{var_constructors}
|
|
306
|
+
deriving DecidableEq, Repr
|
|
307
|
+
|
|
308
|
+
/-- Full QHL program (supporting `qWhile` repeat-until-success loops) lowered by `qcert`. -/
|
|
309
|
+
noncomputable def prog : QProg CVar (2 ^ {ir.num_qubits}) :=
|
|
310
|
+
{body}
|
|
311
|
+
|
|
312
|
+
end {ns}
|
|
313
|
+
"""
|