ffmit 0.1.1__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.
ffmit/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """ffmit: exact noise absorption for free-fermion (matchgate) circuits under learned Pauli-Lindblad noise.
2
+
3
+ For 1D circuits made of X-rotations and nearest-neighbour ZZ couplings (transverse-field Ising and relatives),
4
+ the Jordan-Wigner transformation keeps every quadratic observable inside a space of n(2n-1) Majorana pairs, and
5
+ Pauli noise only rescales those pairs. The inverse of the learned noise can therefore be absorbed into the
6
+ observable exactly, with no truncation (unlike Pauli-propagation PNA).
7
+ """
8
+ from .mitigation import absorb_noise, is_free_fermion, FreeFermionAbsorption
9
+ from .majorana import NotFreeFermionError
10
+ from .chain import find_chain_order
11
+ __all__ = ["absorb_noise", "is_free_fermion", "FreeFermionAbsorption", "NotFreeFermionError", "find_chain_order"]
12
+ __version__ = "0.1.1"
ffmit/chain.py ADDED
@@ -0,0 +1,29 @@
1
+ """Find the 1D order of a set of qubits from the two-qubit gates of a circuit."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def find_chain_order(circuit, qubits):
6
+ """Order `qubits` (circuit indices) along the path formed by the two-qubit gates acting among them.
7
+ Raises ValueError if those gates do not form a single path."""
8
+ qs = set(qubits); adj = {q: set() for q in qs}
9
+
10
+ def visit(insts, outer_of):
11
+ for inst in insts:
12
+ op = inst.operation
13
+ if op.name == "box":
14
+ outer = outer_of(inst)
15
+ visit(op.body.data, lambda g, o=outer, b=op.body: [o[b.find_bit(q).index] for q in g.qubits])
16
+ continue
17
+ idx = outer_of(inst)
18
+ if len(idx) == 2 and idx[0] in qs and idx[1] in qs:
19
+ adj[idx[0]].add(idx[1]); adj[idx[1]].add(idx[0])
20
+ visit(circuit.data, lambda g: [circuit.find_bit(q).index for q in g.qubits])
21
+ ends = [q for q in qs if len(adj[q]) == 1]
22
+ if any(len(a) > 2 for a in adj.values()) or len(ends) != 2:
23
+ raise ValueError("two-qubit gates among these qubits do not form a single 1D path")
24
+ order, prev, cur = [min(ends)], None, min(ends)
25
+ while len(order) < len(qs):
26
+ nxt = [q for q in adj[cur] if q != prev]
27
+ if not nxt: raise ValueError("path is disconnected")
28
+ prev, cur = cur, nxt[0]; order.append(cur)
29
+ return order
ffmit/engine.py ADDED
@@ -0,0 +1,258 @@
1
+ """Free-fermion (Majorana covariance) engine: circuit parsing, Gaussian steps, exact noise absorption."""
2
+ from __future__ import annotations
3
+ from dataclasses import dataclass, field
4
+ import numpy as np
5
+ from qiskit.circuit import QuantumCircuit
6
+ from qiskit.quantum_info import Operator, Pauli, SparsePauliOp
7
+ from .majorana import (majorana_symplectic, pair_pauli, quadratic_from_pauli, to_sparse_pauli_op,
8
+ zero_state_expectations, expectation, NotFreeFermionError)
9
+
10
+ _Z = np.array([[1, 0], [0, -1]], dtype=complex)
11
+ _Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
12
+ _X = np.array([[0, 1], [1, 0]], dtype=complex)
13
+ _SKIP = {"barrier", "measure", "delay", "id", "reset_if_needed"}
14
+
15
+
16
+ def _rz(t):
17
+ return np.diag([np.exp(-0.5j * t), np.exp(0.5j * t)])
18
+
19
+
20
+ # ---------------------------------------------------------------- steps
21
+ @dataclass
22
+ class Givens: # U = exp(-i th/2 * s * i g_p g_q) -> U^dag g_p U = c g_p + s' g_q
23
+ p: int; q: int; c: float; s: float
24
+
25
+ @dataclass
26
+ class Block: # single-qubit Gaussian on qubit k: 2x2 block on (2k, 2k+1), sign on later modes
27
+ k: int; M: np.ndarray; sign: float
28
+
29
+ @dataclass
30
+ class Noise: # Pauli-Lindblad channel: H_ab *= exp(-2 L_ab)
31
+ L: np.ndarray; where: str = ""
32
+
33
+
34
+ def _heis(X, st, inverse=False):
35
+ """Heisenberg (inverse=False): X -> R^T X R. inverse=True / Schroedinger: X -> R X R^T."""
36
+ if isinstance(st, Givens):
37
+ p, q, c, s = st.p, st.q, st.c, st.s
38
+ if inverse: s = -s # R^{-1} = R^T: (c, s) -> (c, -s) in the R^T X R form
39
+ rp, rq = X[p].copy(), X[q].copy()
40
+ X[p], X[q] = c * rp - s * rq, s * rp + c * rq
41
+ cp, cq = X[:, p].copy(), X[:, q].copy()
42
+ X[:, p], X[:, q] = c * cp - s * cq, s * cp + c * cq
43
+ elif isinstance(st, Block):
44
+ k, M, sg = st.k, st.M, st.sign
45
+ A = M if inverse else M.T # rows: R^T X uses M^T ; R X uses M
46
+ idx = [2 * k, 2 * k + 1]
47
+ X[idx] = A @ X[idx]
48
+ X[:, idx] = X[:, idx] @ A.T
49
+ if sg < 0:
50
+ X[2 * k + 2:] *= -1; X[:, 2 * k + 2:] *= -1
51
+ else:
52
+ raise TypeError(st)
53
+ return X
54
+
55
+
56
+ # ---------------------------------------------------------------- parsing
57
+ _PAULI1 = {"I": np.eye(2, dtype=complex), "X": _X, "Y": _Y, "Z": _Z}
58
+
59
+
60
+ def _coeffs(A):
61
+ """Real Pauli coefficients (x, y, z) of a traceless Hermitian 2x2 matrix."""
62
+ return np.array([np.trace(_X @ A).real / 2, np.trace(_Y @ A).real / 2, np.trace(_Z @ A).real / 2])
63
+
64
+
65
+ class _Builder:
66
+ """Accumulates single-qubit operations lazily. Diagonal (Z) rotations float: they commute with ZZ couplings and,
67
+ when Clifford (multiples of pi/2), pass through Pauli noise by relabelling it. Everything else must be an
68
+ X-rotation (times a Pauli) at the points where it meets a coupling or noise."""
69
+
70
+ def __init__(self, n):
71
+ self.n = n; self.steps = []
72
+ self.pending = [np.eye(2, dtype=complex) for _ in range(n)]
73
+ self.xg, self.zg = majorana_symplectic(n)
74
+
75
+ def one_qubit(self, v, U):
76
+ self.pending[v] = U @ self.pending[v]
77
+
78
+ def _emit_gaussian(self, v, G):
79
+ GdZG = G.conj().T @ _Z @ G; GdYG = G.conj().T @ _Y @ G; GdXG = G.conj().T @ _X @ G
80
+ sx = _coeffs(GdXG)[0]
81
+ cz, cy = _coeffs(GdZG), _coeffs(GdYG)
82
+ M = np.array([[cz[2], cz[1]], [cy[2], cy[1]]])
83
+ if not np.allclose(M, np.eye(2), atol=1e-12) or sx < 0:
84
+ self.steps.append(Block(v, M, float(np.sign(sx))))
85
+
86
+ @staticmethod
87
+ def _is_gaussian(P):
88
+ return abs(abs(_coeffs(P.conj().T @ _X @ P)[0]) - 1) < 1e-9
89
+
90
+ @staticmethod
91
+ def _is_diagonal(P):
92
+ return abs(P[0, 1]) < 1e-12 and abs(P[1, 0]) < 1e-12
93
+
94
+ @staticmethod
95
+ def _is_clifford(P):
96
+ for A in (_X, _Z):
97
+ c = _coeffs(P.conj().T @ A @ P)
98
+ if abs(np.max(np.abs(c)) - 1) > 1e-9: return False
99
+ return True
100
+
101
+ def split_diagonal(self, v, where):
102
+ """pending = D . G with G Gaussian (emitted now) and D = Rz(phi) kept pending."""
103
+ P = self.pending[v]
104
+ if self._is_diagonal(P): return
105
+ x, y, z = _coeffs(P @ _X @ P.conj().T)
106
+ if abs(z) > 1e-9:
107
+ raise NotFreeFermionError(f"single-qubit operation on chain position {v} {where} is not an X-rotation "
108
+ "up to Z-rotations; it breaks the free-fermion structure")
109
+ phi = np.arctan2(y, x)
110
+ G = _rz(-phi) @ P
111
+ self._emit_gaussian(v, G)
112
+ self.pending[v] = _rz(phi)
113
+
114
+ def flush_all(self, where=""):
115
+ for v in range(self.n):
116
+ P = self.pending[v]
117
+ if self._is_gaussian(P):
118
+ self._emit_gaussian(v, P); self.pending[v] = np.eye(2, dtype=complex)
119
+ elif not (self._is_diagonal(P) and self._is_clifford(P)):
120
+ self.split_diagonal(v, where)
121
+
122
+ def zz(self, a, b, theta, where=""):
123
+ if abs(a - b) != 1:
124
+ raise NotFreeFermionError(f"two-qubit gate between chain positions {a} and {b} {where}: only nearest "
125
+ "neighbours along the chain are free-fermion")
126
+ k = min(a, b)
127
+ P, s = pair_pauli(self.n, 2 * k + 1, 2 * k + 2) # i g g = s * Z_k Z_k+1
128
+ th = theta * s
129
+ self.steps.append(Givens(2 * k + 1, 2 * k + 2, np.cos(th), np.sin(th)))
130
+
131
+ def two_qubit(self, name, params, a, b, where=""):
132
+ if name not in ("cz", "rzz"):
133
+ raise NotFreeFermionError(f"two-qubit gate '{name}' {where} is not supported (cz, rzz only)")
134
+ self.split_diagonal(a, where); self.split_diagonal(b, where)
135
+ if name == "cz": # CZ = Rz(pi/2) x Rz(pi/2) . Rzz(-pi/2) (global phase dropped)
136
+ self.zz(a, b, -np.pi / 2, where)
137
+ self.one_qubit(a, _rz(np.pi / 2)); self.one_qubit(b, _rz(np.pi / 2))
138
+ else:
139
+ self.zz(a, b, float(params[0]), where)
140
+
141
+ def noise(self, gens, where=""):
142
+ """gens: list of (Pauli on the n chain qubits, rate). Pending single-qubit Cliffords are moved past the
143
+ noise by relabelling the generators (N . P = P . N' with N' generated by P^dag Q P)."""
144
+ if not gens: return
145
+ self.flush_all(where)
146
+ moved = []
147
+ for v in range(self.n):
148
+ P = self.pending[v]
149
+ if self._is_diagonal(P) and abs(P[0, 0] - P[1, 1]) < 1e-12:
150
+ continue # identity (up to phase)
151
+ if not self._is_clifford(P):
152
+ raise NotFreeFermionError(f"a non-Clifford Z-rotation on chain position {v} is separated from its "
153
+ f"coupling by noise {where}; it breaks the free-fermion structure")
154
+ moved.append(v)
155
+ if moved:
156
+ new = []
157
+ for Q, r in gens:
158
+ lab = list(Q.to_label())
159
+ for v in moved:
160
+ c = lab[self.n - 1 - v]
161
+ if c == "I": continue
162
+ P = self.pending[v]
163
+ co = _coeffs(P.conj().T @ _PAULI1[c] @ P)
164
+ lab[self.n - 1 - v] = "XYZ"[int(np.argmax(np.abs(co)))]
165
+ new.append((Pauli("".join(lab)), r))
166
+ gens = new
167
+ xp = np.array([P.x for P, _ in gens], dtype=np.int64); zp = np.array([P.z for P, _ in gens], dtype=np.int64)
168
+ lam = np.array([r for _, r in gens], dtype=float)
169
+ C = ((xp @ self.zg.T.astype(np.int64) + zp @ self.xg.T.astype(np.int64)) % 2).astype(float) # (G, 2n)
170
+ u = lam @ C
171
+ W = C.T @ (lam[:, None] * C)
172
+ L = u[:, None] + u[None, :] - 2 * W
173
+ self.steps.append(Noise(L, where))
174
+
175
+ def finish(self, where="(end of circuit)"):
176
+ """Gaussian leftovers are emitted; diagonal leftovers are returned (they act on the observable)."""
177
+ leftovers = {}
178
+ for v in range(self.n):
179
+ P = self.pending[v]
180
+ if self._is_gaussian(P):
181
+ self._emit_gaussian(v, P)
182
+ elif self._is_diagonal(P):
183
+ leftovers[v] = P
184
+ else:
185
+ self.split_diagonal(v, where); leftovers[v] = self.pending[v]
186
+ return leftovers
187
+
188
+
189
+ def _gate_matrix(op):
190
+ return Operator(op).data
191
+
192
+
193
+ def build_steps(circuit: QuantumCircuit, chain, refs=None, ref_qubits=None, noise_site="after",
194
+ include_noise_without_2q=False):
195
+ """Translate a (boxed) circuit into free-fermion steps for the qubits in `chain` (physical/circuit indices, in
196
+ chain order). `refs`: {InjectNoise ref: PauliLindbladMap}; `ref_qubits`: {ref: sorted circuit qubit indices}."""
197
+ try:
198
+ from samplomatic.annotations import InjectNoise
199
+ from samplomatic.utils import get_annotation
200
+ except ImportError: # plain circuits only
201
+ InjectNoise = get_annotation = None
202
+ n = len(chain); p2v = {p: v for v, p in enumerate(chain)}
203
+ B = _Builder(n)
204
+ refs = refs or {}
205
+
206
+ def project(ref):
207
+ gens = []
208
+ for s, qs, r in refs[ref].to_sparse_list():
209
+ ops = {p2v[ref_qubits[ref][i]]: c for c, i in zip(s, qs) if ref_qubits[ref][i] in p2v}
210
+ if ops:
211
+ lab = ["I"] * n
212
+ for v, c in ops.items(): lab[n - 1 - v] = c
213
+ gens.append((Pauli("".join(lab)), float(r)))
214
+ return gens
215
+
216
+ for idx, inst in enumerate(circuit.data):
217
+ op = inst.operation
218
+ where = f"(instruction {idx})"
219
+ outer = [circuit.find_bit(q).index for q in inst.qubits]
220
+ if op.name == "box":
221
+ body = op.body
222
+ items = [(g.operation, [outer[body.find_bit(q).index] for q in g.qubits]) for g in body.data]
223
+ ann = get_annotation(op, InjectNoise) if get_annotation else None
224
+ else:
225
+ items = [(op, outer)]; ann = None
226
+ has_2q = any(len(qs) == 2 and any(p in p2v for p in qs) for _, qs in items)
227
+ noise_here = (ann is not None and ann.ref in refs and (has_2q or include_noise_without_2q)
228
+ and any(p in p2v for p in outer))
229
+ site = getattr(ann, "site", noise_site) if ann is not None else noise_site
230
+ if noise_here and site == "before":
231
+ B.noise(project(ann.ref), where)
232
+ for g, qs in items:
233
+ if g.name in _SKIP: continue
234
+ inside = [p in p2v for p in qs]
235
+ if not any(inside): continue
236
+ if not all(inside):
237
+ raise NotFreeFermionError(f"gate '{g.name}' {where} couples the chain to qubits outside it")
238
+ vs = [p2v[p] for p in qs]
239
+ g = getattr(g, "_quantum_error", g) # qiskit-aer appends errors wrapped
240
+ if hasattr(g, "generators") and hasattr(g, "rates"): # qiskit-aer PauliLindbladError
241
+ gens = []
242
+ for P, r in zip(g.generators, g.rates):
243
+ lab = ["I"] * n
244
+ for j, v in enumerate(vs):
245
+ c = P[j].to_label()
246
+ lab[n - 1 - v] = c if c != "I" else "I"
247
+ gens.append((Pauli("".join(lab)), float(r)))
248
+ B.noise(gens, where); continue
249
+ if len(vs) == 1:
250
+ B.one_qubit(vs[0], _gate_matrix(g))
251
+ elif len(vs) == 2:
252
+ B.two_qubit(g.name, g.params, vs[0], vs[1], where)
253
+ else:
254
+ raise NotFreeFermionError(f"gate '{g.name}' {where} acts on {len(vs)} qubits")
255
+ if noise_here and site != "before":
256
+ B.noise(project(ann.ref), where)
257
+ leftovers = B.finish()
258
+ return B.steps, n, leftovers
ffmit/majorana.py ADDED
@@ -0,0 +1,113 @@
1
+ """Jordan-Wigner Majorana operators along a 1D chain (X-type mapping).
2
+
3
+ For a chain of n qubits (virtual indices 0..n-1, in chain order):
4
+ gamma_{2k} = X_0 ... X_{k-1} Z_k
5
+ gamma_{2k+1} = X_0 ... X_{k-1} Y_k
6
+ With this mapping X_k = i gamma_{2k} gamma_{2k+1} and Z_k Z_{k+1} = i gamma_{2k+1} gamma_{2k+2},
7
+ so the transverse-field Ising / XY family is quadratic (free-fermion).
8
+
9
+ A quadratic Hermitian observable is stored as a real antisymmetric matrix H (2n x 2n):
10
+ O = i * sum_{a<b} H[a, b] gamma_a gamma_b
11
+ """
12
+ from __future__ import annotations
13
+ import numpy as np
14
+ from qiskit.quantum_info import Pauli, SparsePauliOp
15
+
16
+
17
+ def majorana_symplectic(n: int):
18
+ """(x, z) bit arrays of shape (2n, n) for the 2n Majorana operators."""
19
+ x = np.zeros((2 * n, n), dtype=bool)
20
+ z = np.zeros((2 * n, n), dtype=bool)
21
+ for k in range(n):
22
+ x[2 * k, :k] = True; z[2 * k, k] = True # ...X Z
23
+ x[2 * k + 1, :k] = True; x[2 * k + 1, k] = True; z[2 * k + 1, k] = True # ...X Y
24
+ return x, z
25
+
26
+
27
+ def majorana_pauli(n: int, a: int) -> Pauli:
28
+ lab = ["I"] * n
29
+ k = a // 2
30
+ for j in range(k):
31
+ lab[n - 1 - j] = "X"
32
+ lab[n - 1 - k] = "Z" if a % 2 == 0 else "Y"
33
+ return Pauli("".join(lab))
34
+
35
+
36
+ def pair_pauli(n: int, a: int, b: int):
37
+ """Return (Pauli P, sign s) with i * gamma_a gamma_b = s * P, for a < b (analytic, O(n))."""
38
+ if a > b:
39
+ P, s = pair_pauli(n, b, a); return P, -s
40
+ j, al = divmod(a, 2); k, be = divmod(b, 2)
41
+ lab = ["I"] * n
42
+ if j == k: # i g_2j g_2j+1 = X_j
43
+ lab[n - 1 - j] = "X"; return Pauli("".join(lab)), 1.0
44
+ lab[n - 1 - j] = "Y" if al == 0 else "Z" # Z.X = iY , Y.X = -iZ
45
+ for q in range(j + 1, k): lab[n - 1 - q] = "X"
46
+ lab[n - 1 - k] = "Z" if be == 0 else "Y"
47
+ return Pauli("".join(lab)), (-1.0 if al == 0 else 1.0)
48
+
49
+
50
+ def decode_pair(p: Pauli):
51
+ """Inverse of pair_pauli for a phase-free Pauli: (a, b, s) or None if it is not a Majorana pair."""
52
+ n = p.num_qubits
53
+ sup = [q for q in range(n) if p.x[q] or p.z[q]]
54
+ if not sup: return None
55
+ def L(q):
56
+ x, z = p.x[q], p.z[q]
57
+ return "X" if (x and not z) else "Z" if (z and not x) else "Y" if (x and z) else "I"
58
+ j, k = sup[0], sup[-1]
59
+ if j == k:
60
+ return (2 * j, 2 * j + 1, 1.0) if L(j) == "X" else None
61
+ if any(L(q) != "X" for q in range(j + 1, k)) or len(sup) != k - j + 1:
62
+ return None
63
+ first, last = L(j), L(k)
64
+ if first not in "YZ" or last not in "YZ": return None
65
+ al = 0 if first == "Y" else 1; be = 0 if last == "Z" else 1
66
+ return 2 * j + al, 2 * k + be, (-1.0 if al == 0 else 1.0)
67
+
68
+
69
+ def quadratic_from_pauli(op: SparsePauliOp, n: int) -> np.ndarray:
70
+ """Antisymmetric H for an observable that is a sum of quadratic Majorana monomials. Raises if it is not."""
71
+ H = np.zeros((2 * n, 2 * n))
72
+ for p, c in zip(op.paulis, op.coeffs):
73
+ ph = (-1j) ** p.phase
74
+ val_c = c * ph
75
+ if abs(val_c.imag) > 1e-12:
76
+ raise ValueError("observable must be Hermitian with real coefficients")
77
+ d = decode_pair(Pauli((p.z, p.x)))
78
+ if d is None:
79
+ if not (p.x.any() or p.z.any()):
80
+ raise NotFreeFermionError("identity terms are not supported; subtract the constant first")
81
+ raise NotFreeFermionError(f"observable term {p} is not a quadratic Majorana monomial in this chain order")
82
+ a, b, s = d
83
+ val = val_c.real * s # c P = c s (i g_a g_b)
84
+ H[a, b] += val; H[b, a] -= val
85
+ return H
86
+
87
+
88
+ def to_sparse_pauli_op(H: np.ndarray, atol: float = 1e-12) -> SparsePauliOp:
89
+ n = H.shape[0] // 2
90
+ paulis, coeffs = [], []
91
+ for a, b in np.argwhere(np.abs(np.triu(H, 1)) > atol):
92
+ p, s = pair_pauli(n, int(a), int(b))
93
+ paulis.append(p); coeffs.append(H[a, b] * s)
94
+ if not paulis:
95
+ return SparsePauliOp("I" * n, 0.0)
96
+ return SparsePauliOp(paulis, coeffs)
97
+
98
+
99
+ def zero_state_expectations(n: int) -> np.ndarray:
100
+ """E[a, b] = <0...0| i gamma_a gamma_b |0...0>. Only i g_{2k+1} g_{2k+2} = Z_k Z_{k+1} is non-zero (= 1)."""
101
+ E = np.zeros((2 * n, 2 * n))
102
+ for k in range(n - 1):
103
+ E[2 * k + 1, 2 * k + 2] = 1.0; E[2 * k + 2, 2 * k + 1] = -1.0
104
+ return E
105
+
106
+
107
+ def expectation(H: np.ndarray, E: np.ndarray) -> float:
108
+ """<O> for O = i sum_{a<b} H_ab g_a g_b, given E_ab = <i g_a g_b>."""
109
+ return float(0.5 * np.sum(H * E))
110
+
111
+
112
+ class NotFreeFermionError(ValueError):
113
+ """The circuit or observable is not free-fermion in the chosen qubit order; exact absorption does not apply."""
ffmit/mitigation.py ADDED
@@ -0,0 +1,120 @@
1
+ """Exact noise-absorbing observables for free-fermion circuits under learned Pauli-Lindblad noise."""
2
+ from __future__ import annotations
3
+ import numpy as np
4
+ from qiskit.circuit import QuantumCircuit
5
+ from qiskit.quantum_info import SparsePauliOp
6
+ from .engine import build_steps, _heis, Noise
7
+ from .majorana import (quadratic_from_pauli, to_sparse_pauli_op, zero_state_expectations, expectation,
8
+ pair_pauli, NotFreeFermionError)
9
+
10
+
11
+ class FreeFermionAbsorption:
12
+ """Result of `absorb_noise`.
13
+
14
+ Attributes
15
+ ----------
16
+ H : antisymmetric matrix of the noise-absorbing observable O~ (Majorana form)
17
+ E_noisy : <i g_a g_b> at the end of the circuit under the noise model
18
+ E_ideal : same without noise
19
+ """
20
+
21
+ def __init__(self, H, E_noisy, E_ideal, n, chain):
22
+ self.H, self.E_noisy, self.E_ideal, self.n, self.chain = H, E_noisy, E_ideal, n, list(chain)
23
+
24
+ @property
25
+ def num_terms(self):
26
+ return int(np.count_nonzero(np.abs(np.triu(self.H, 1)) > 1e-12))
27
+
28
+ def observable(self, atol=1e-12) -> SparsePauliOp:
29
+ """O~ as a SparsePauliOp on the chain (virtual qubit v = position v in `chain`)."""
30
+ return to_sparse_pauli_op(self.H, atol)
31
+
32
+ def model_value(self) -> float:
33
+ """<O~> under the learned noise model; equals the ideal <O> (exactness check)."""
34
+ return expectation(self.H, self.E_noisy)
35
+
36
+ def ideal_value_of_original(self, O_H) -> float:
37
+ return expectation(O_H, self.E_ideal)
38
+
39
+ def split_for_measurement(self, max_bases, get_bases=None):
40
+ """Measure the terms with the largest modelled contribution |c_k <P_k>_noisy| that fit in `max_bases`
41
+ measurement bases; the rest is returned as a classical remainder (exact under the same model).
42
+ Returns (SparsePauliOp to measure, remainder)."""
43
+ if get_bases is None:
44
+ from qiskit_addon_utils.exp_vals.measurement_bases import get_measurement_bases as get_bases
45
+ iu = np.argwhere(np.abs(np.triu(self.H, 1)) > 1e-12)
46
+ contrib = np.array([abs(self.H[a, b] * self.E_noisy[a, b]) for a, b in iu])
47
+ terms = []
48
+ for a, b in iu:
49
+ p, s = pair_pauli(self.n, int(a), int(b))
50
+ terms.append((p, self.H[a, b] * s))
51
+ order = np.argsort(contrib)[::-1]
52
+ chosen = []
53
+ for k in order:
54
+ trial = chosen + [int(k)]
55
+ op = SparsePauliOp([terms[i][0] for i in trial], [terms[i][1] for i in trial])
56
+ if len(get_bases(op)[0]) <= max_bases:
57
+ chosen = trial
58
+ rest = [i for i in range(len(terms)) if i not in set(chosen)]
59
+ remainder = float(sum(self.H[iu[i][0], iu[i][1]] * self.E_noisy[iu[i][0], iu[i][1]] for i in rest))
60
+ measured = SparsePauliOp([terms[i][0] for i in chosen], [terms[i][1] for i in chosen])
61
+ return measured, remainder
62
+
63
+
64
+ def absorb_noise(circuit: QuantumCircuit, observable, chain, refs=None, ref_qubits=None,
65
+ noise_site="after") -> FreeFermionAbsorption:
66
+ """Exact noise-absorbing observable O~ with <O~>_noisy = <O>_ideal.
67
+
68
+ circuit : boxed circuit (samplomatic, with InjectNoise annotations) or plain circuit with
69
+ `PauliLindbladError` instructions.
70
+ observable : SparsePauliOp on the chain (virtual qubit v = chain[v]); must be quadratic in Majoranas
71
+ (e.g. Z_i Z_i+1, X_i).
72
+ chain : circuit qubit indices of the 1D chain, in order.
73
+ refs, ref_qubits : learned noise per InjectNoise ref and the box qubits (sorted) of each ref.
74
+ Raises NotFreeFermionError if the circuit or observable is not free-fermion along `chain`.
75
+ """
76
+ steps, n, leftovers = build_steps(circuit, chain, refs, ref_qubits, noise_site)
77
+ obs = observable
78
+ for v, U in leftovers.items(): # final diagonal rotations act on the observable: O -> U^dag O U
79
+ phi = 2 * np.angle(U[1, 1] / U[0, 0]) / 2 if abs(U[0, 0]) > 0 else 0.0
80
+ if abs(np.sin(phi)) > 1e-12 or abs(np.cos(phi) - 1) > 1e-12:
81
+ obs = _conj_rz(obs, v, phi, n)
82
+ H0 = quadratic_from_pauli(obs, n)
83
+ E0 = zero_state_expectations(n)
84
+ # Schroedinger pass (noisy and ideal), forward
85
+ En, Ei = E0.copy(), E0.copy()
86
+ for st in steps:
87
+ if isinstance(st, Noise):
88
+ En *= np.exp(-2 * st.L)
89
+ else:
90
+ _heis(En, st, inverse=True); _heis(Ei, st, inverse=True)
91
+ # ideal Heisenberg pass back to t=0, then forward with inverse gates and inverse noise
92
+ X = H0.copy()
93
+ for st in reversed(steps):
94
+ if not isinstance(st, Noise): _heis(X, st)
95
+ for st in steps:
96
+ if isinstance(st, Noise):
97
+ X *= np.exp(2 * st.L)
98
+ else:
99
+ _heis(X, st, inverse=True)
100
+ X = 0.5 * (X - X.T)
101
+ return FreeFermionAbsorption(X, En, Ei, n, chain)
102
+
103
+
104
+ def _conj_rz(O, v, phi, n):
105
+ """U^dag O U for U = Rz(phi) = exp(-i phi Z_v / 2)."""
106
+ from qiskit.quantum_info import Pauli
107
+ lab = ["I"] * n; lab[n - 1 - v] = "Z"; P = Pauli("".join(lab))
108
+ ps, cs = [], []
109
+ for q, c in zip(O.paulis, O.coeffs):
110
+ if q.commutes(P): ps.append(q); cs.append(c)
111
+ else: ps += [q, P.dot(q)]; cs += [c * np.cos(phi), 1j * np.sin(phi) * c]
112
+ return SparsePauliOp(ps, cs).simplify(atol=1e-14)
113
+
114
+
115
+ def is_free_fermion(circuit, chain) -> bool:
116
+ try:
117
+ build_steps(circuit, chain)
118
+ return True
119
+ except NotFreeFermionError:
120
+ return False
ffmit/runtime.py ADDED
@@ -0,0 +1,242 @@
1
+ """IBM Runtime workflow helpers (optional extra: pip install ffmit[runtime]).
2
+
3
+ Pipeline used on ibm_kingston for the Qiskit Fall Fest 2026 Noise Busters challenge:
4
+ parallel copies on disjoint chains, NoiseLearnerV3, exact free-fermion noise absorption,
5
+ TREX + post-selection, mirror calibration.
6
+ """
7
+ import numpy as np
8
+ import samplomatic
9
+ from qiskit import QuantumCircuit
10
+ from qiskit.quantum_info import SparsePauliOp, Pauli
11
+ from qiskit.transpiler import PassManager, generate_preset_pass_manager
12
+ from qiskit_ibm_runtime import QuantumProgram
13
+ from samplomatic.transpiler import generate_boxing_pass_manager
14
+ from samplomatic.utils import find_unique_box_instructions, get_annotation
15
+ from samplomatic.annotations import InjectNoise
16
+ from qiskit_addon_utils.exp_vals.measurement_bases import get_measurement_bases
17
+ from qiskit_addon_utils.exp_vals.expectation_values import executor_expectation_values
18
+ from qiskit_addon_utils.noise_management import trex_factors
19
+ from qiskit_addon_utils.noise_management.post_selection import PostSelector
20
+ from qiskit_addon_utils.noise_management.post_selection.transpiler.passes import (
21
+ AddPostSelectionMeasures, AddSpectatorMeasures)
22
+
23
+ def find_disjoint_chains(backend, length, k_max, gap=1):
24
+ """Greedy: lowest-error chains of `length` qubits, pairwise separated by >= gap qubits."""
25
+ cz = backend.target["cz"]
26
+ err = {frozenset(q): (p.error if (p is not None and p.error is not None) else 1.0) for q, p in cz.items()}
27
+ g = backend.coupling_map.graph.to_undirected(multigraph=False)
28
+ nbrs = {n: list(g.neighbors(n)) for n in g.node_indices()}
29
+ def blocked_set(chain):
30
+ b = set(chain); frontier = set(chain)
31
+ for _ in range(gap):
32
+ frontier = {m for n in frontier for m in nbrs[n]} - b
33
+ b |= frontier
34
+ return b
35
+ def best_chain(forbidden):
36
+ best, best_cost = None, np.inf
37
+ for start in nbrs:
38
+ if start in forbidden: continue
39
+ path, visited = [start], {start}
40
+ def grow():
41
+ if len(path) == length: return True
42
+ for nxt in sorted(nbrs[path[-1]], key=lambda m: err.get(frozenset((path[-1], m)), 1.0)):
43
+ if nxt not in visited and nxt not in forbidden:
44
+ visited.add(nxt); path.append(nxt)
45
+ if grow(): return True
46
+ path.pop(); visited.discard(nxt)
47
+ return False
48
+ if grow():
49
+ cost = sum(err.get(frozenset((path[i], path[i + 1])), 1.0) for i in range(length - 1))
50
+ if cost < best_cost: best, best_cost = list(path), cost
51
+ return best
52
+ chains, forbidden = [], set()
53
+ while len(chains) < k_max:
54
+ ch = best_chain(forbidden)
55
+ if ch is None: break
56
+ chains.append(ch); forbidden |= blocked_set(ch)
57
+ return chains
58
+
59
+ def ising(nq, steps, angle):
60
+ qc = QuantumCircuit(nq)
61
+ for _ in range(steps):
62
+ qc.rx(angle, range(nq))
63
+ for first in (1, 2):
64
+ for idx in range(first, nq, 2):
65
+ qc.sdg([idx - 1, idx]); qc.cz(idx - 1, idx)
66
+ return qc
67
+
68
+ def mirror_of(qc):
69
+ m = QuantumCircuit(qc.num_qubits)
70
+ m.compose(qc, inplace=True); m.barrier(); m.compose(qc.inverse(), inplace=True)
71
+ return m
72
+
73
+ def replicate(qc, k):
74
+ n = qc.num_qubits
75
+ big = QuantumCircuit(n * k)
76
+ for j in range(k):
77
+ big.compose(qc, qubits=range(j * n, (j + 1) * n), inplace=True)
78
+ return big
79
+
80
+ def box(qc, backend, layout):
81
+ qm = qc.copy(); qm.measure_active()
82
+ isa = generate_preset_pass_manager(backend=backend, initial_layout=layout, optimization_level=0,
83
+ translation_method="translator").run(qm)
84
+ boxed = generate_boxing_pass_manager(
85
+ twirling_strategy="active", inject_noise_strategy="individual_modification",
86
+ inject_noise_site="after", inject_noise_targets="gates", measure_annotations="all").run(isa)
87
+ uniq = find_unique_box_instructions(boxed, normalize_annotations=None, undress_boxes=True)
88
+ return isa, boxed, uniq
89
+
90
+ def ref_qubit_map(boxed, uniq):
91
+ """InjectNoise ref -> physical qubits of the box (sorted: local index order of the learned map)."""
92
+ out = {}
93
+ for inst in uniq:
94
+ ann = get_annotation(inst.operation, InjectNoise)
95
+ if ann is not None:
96
+ out[ann.ref] = sorted(boxed.find_bit(q).index for q in inst.qubits)
97
+ return out
98
+
99
+ def layer_key(inst, bx):
100
+ return (tuple(sorted(bx.find_bit(q).index for q in inst.qubits)),
101
+ tuple(sorted((i.operation.name, tuple(bx.find_bit(q).index for q in i.qubits))
102
+ for i in inst.operation.body.data)))
103
+
104
+ def refs_for(bx, ux, learned_keys, nl_result):
105
+ """Map each InjectNoise ref of a boxed circuit to the learned layer with the same CZ structure."""
106
+ refs = {}
107
+ for inst in ux:
108
+ ann = get_annotation(inst.operation, InjectNoise)
109
+ if ann is not None:
110
+ refs[ann.ref] = nl_result[learned_keys.index(layer_key(inst, bx))].to_pauli_lindblad_map()
111
+ return refs
112
+
113
+ SYM = {0: "I", 1: "Z", 2: "X", 3: "Y"}
114
+ def _label(arr): return "".join(SYM[int(a)] for a in np.asarray(arr)[::-1])
115
+ def _permute_op(op, perm, n):
116
+ return SparsePauliOp.from_sparse_list([(s, [perm[q] for q in qs], c) for s, qs, c in op.to_sparse_list()], num_qubits=n)
117
+
118
+ def measurement_item(backend, bx, refs, layout, measured_ops, randomizations, x_pulse_type="rx"):
119
+ """measured_ops[j]: operator to measure on copy j, indexed by virtual qubit (position in `layout`)."""
120
+ nv = len(layout); p_2_v = {p: v for v, p in enumerate(layout)}
121
+ meas_box = bx.data[-1]
122
+ canon = [i for i, q in enumerate(bx.qubits) if q in meas_box.qubits]
123
+ c_2_v = {c: p_2_v[p] for c, p in enumerate(canon)}
124
+ v_2_c = {v: c for c, v in c_2_v.items()}
125
+ per = []
126
+ for ot in measured_ops:
127
+ bases_v, rev_v = get_measurement_bases(ot)
128
+ per.append(dict(bases=[np.asarray(b) for b in bases_v], terms=[rev_v[k][0] for k in rev_v]))
129
+ nb = max(len(p["bases"]) for p in per)
130
+ comb_v = []
131
+ for b in range(nb):
132
+ arr = np.zeros(nv, dtype=np.uint8)
133
+ for p in per:
134
+ bv = p["bases"][min(b, len(p["bases"]) - 1)]
135
+ arr[bv != 0] = bv[bv != 0]
136
+ comb_v.append(arr)
137
+ map_v, map_c = {}, {}
138
+ for b in range(nb):
139
+ vals = [p["terms"][b] if b < len(p["terms"]) else None for p in per]
140
+ map_v[Pauli(_label(comb_v[b]))] = vals
141
+ kc = np.zeros(nv, dtype=np.uint8)
142
+ for v in range(nv): kc[v_2_c[v]] = comb_v[b][v]
143
+ map_c[Pauli(_label(kc))] = [None if t is None else _permute_op(t, v_2_c, nv) for t in vals]
144
+ comb_c = [np.array([bv[c_2_v[c]] for c in range(nv)], dtype=np.uint8) for bv in comb_v]
145
+ template, samplex = samplomatic.build(bx)
146
+ template = PassManager([AddSpectatorMeasures(backend.coupling_map),
147
+ AddPostSelectionMeasures(x_pulse_type=x_pulse_type)]).run(template)
148
+ inp = {s.name: 0.0 for s in samplex.inputs().get_specs("noise_scales")}
149
+ inp |= {"pauli_lindblad_maps": refs}
150
+ bb = np.expand_dims(np.array(comb_c), axis=1)
151
+ inp |= {s.name: bb for s in samplex.inputs().get_specs(r"^basis_changes\.")}
152
+ args = samplex.inputs().make_broadcastable().bind(**inp)
153
+ return (template, samplex, args, nb), dict(per_copy=per, nb=nb, map_v=map_v, map_c=map_c, template=template)
154
+
155
+ def evaluate(data, info, meas_noise_map, backend, strategy="edge", use_trex=True, use_ps=True):
156
+ mask = PostSelector.from_circuit(circuit=info["template"], coupling_map=backend.coupling_map
157
+ ).compute_mask(data, strategy=strategy) if use_ps else None
158
+ out = []
159
+ for j in range(len(info["per_copy"])):
160
+ map_v = {k: [v[j]] for k, v in info["map_v"].items()}
161
+ map_c = {k: [v[j]] for k, v in info["map_c"].items()}
162
+ rescale = trex_factors(meas_noise_map, map_c) if use_trex else None
163
+ r = executor_expectation_values(
164
+ data["meas"], map_v, meas_basis_axis=0, avg_axis=1,
165
+ measurement_flips=data["measurement_flips.meas"], pauli_signs=data.get("pauli_signs", None),
166
+ postselect_mask=mask, rescale_factors=rescale, gamma_factor=1.0)
167
+ out.append((float(r[0][0]), float(np.sqrt(r[0][1]))))
168
+ return out
169
+
170
+
171
+ # ---------------------------------------------------------------- high-level pipeline
172
+ from .mitigation import absorb_noise
173
+
174
+
175
+ def _to_global(op, j, n, nv):
176
+ return SparsePauliOp.from_sparse_list([(s, [j * n + q for q in qs], c.real) for s, qs, c in op.to_sparse_list()],
177
+ num_qubits=nv)
178
+
179
+
180
+ class ParallelMirrorExperiment:
181
+ """Exact free-fermion absorption on `k` disjoint chains in parallel, with a mirror calibration per chain.
182
+
183
+ usage:
184
+ exp = ParallelMirrorExperiment(circuit, observable, backend, k=5)
185
+ nl_job = NoiseLearnerV3(mode=backend, options=...).run(exp.learning_circuits)
186
+ exp.build(nl_job.result()) # CPU: exact absorbing observables
187
+ job = Executor(backend).run(exp.program)
188
+ out = exp.evaluate(job.result()) # values per copy, mirror-corrected, combined
189
+ `observable` is a SparsePauliOp on the n logical qubits (quadratic in Majoranas, e.g. Z_i Z_i+1).
190
+ """
191
+
192
+ def __init__(self, circuit, observable, backend, k=5, gap=1, chains=None):
193
+ self.n = circuit.num_qubits; self.backend = backend; self.observable = observable
194
+ self.chains = chains or find_disjoint_chains(backend, self.n, k, gap=gap)
195
+ self.k = len(self.chains); self.layout = [q for c in self.chains for q in c]
196
+ self.circuit, self.mirror = circuit, mirror_of(circuit)
197
+ self.isa, self.boxed, self.uniq = box(replicate(self.circuit, self.k), backend, self.layout)
198
+ self.m_isa, self.m_boxed, self.m_uniq = box(replicate(self.mirror, self.k), backend, self.layout)
199
+ self.learning_circuits = self.uniq
200
+
201
+ def build(self, nl_result, max_bases=9, randomizations=256, shots=64, verbose=True):
202
+ learned = [layer_key(i, self.boxed) for i in self.uniq]
203
+ self.meas_map = nl_result[-1].to_pauli_lindblad_map()
204
+ nv = len(self.layout)
205
+ out = {}
206
+ for name, bx, ux in (("circuit", self.boxed, self.uniq), ("mirror", self.m_boxed, self.m_uniq)):
207
+ refs = refs_for(bx, ux, learned, nl_result); rq = ref_qubit_map(bx, ux)
208
+ meas, rem, absr = [], [], []
209
+ for j, ch in enumerate(self.chains):
210
+ a = absorb_noise(bx, self.observable, ch, refs, rq)
211
+ m, r = a.split_for_measurement(max_bases, get_measurement_bases)
212
+ meas.append(_to_global(m, j, self.n, nv)); rem.append(r); absr.append(a)
213
+ if verbose:
214
+ print(f"copy {j} {name}: {a.num_terms} terms, measured {len(m)}, remainder {r:+.4f}, "
215
+ f"model {a.model_value():.7f}")
216
+ item, info = measurement_item(self.backend, bx, refs, self.layout, meas, randomizations)
217
+ out[name] = dict(item=item, info=info, remainder=np.array(rem), absorptions=absr)
218
+ self.parts = out
219
+ self.program = QuantumProgram(shots=shots)
220
+ for name in ("circuit", "mirror"):
221
+ template, samplex, args, nb = out[name]["item"]
222
+ self.program.append_samplex_item(circuit=template, samplex=samplex, samplex_arguments=args,
223
+ shape=(nb, randomizations))
224
+ return self
225
+
226
+ def evaluate(self, result):
227
+ c = evaluate(result[0], self.parts["circuit"]["info"], self.meas_map, self.backend)
228
+ m = evaluate(result[1], self.parts["mirror"]["info"], self.meas_map, self.backend)
229
+ cv = np.array([v for v, _ in c]) + self.parts["circuit"]["remainder"]; ce = np.array([e for _, e in c])
230
+ mv = np.array([v for v, _ in m]) + self.parts["mirror"]["remainder"]; me = np.array([e for _, e in m])
231
+ corr = cv / np.sqrt(mv)
232
+ corr_e = np.sqrt((ce / np.sqrt(mv)) ** 2 + (cv * me / (2 * mv ** 1.5)) ** 2)
233
+ w = 1 / corr_e ** 2
234
+ return dict(circuit=cv, circuit_err=ce, mirror=mv, mirror_err=me, corrected=corr, corrected_err=corr_e,
235
+ value=float(np.sum(w * corr) / np.sum(w)), error=float(1 / np.sqrt(np.sum(w))))
236
+
237
+
238
+ def combine(evaluations):
239
+ """Inverse-variance combination of several `evaluate` outputs (independent runs)."""
240
+ v = np.concatenate([e["corrected"] for e in evaluations]); s = np.concatenate([e["corrected_err"] for e in evaluations])
241
+ w = 1 / s ** 2
242
+ return float(np.sum(w * v) / np.sum(w)), float(1 / np.sqrt(np.sum(w)))
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: ffmit
3
+ Version: 0.1.1
4
+ Summary: Exact noise absorption for free-fermion (matchgate) circuits under learned Pauli-Lindblad noise
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: qiskit>=2.2
10
+ Requires-Dist: numpy>=1.24
11
+ Provides-Extra: runtime
12
+ Requires-Dist: qiskit-ibm-runtime>=0.52; extra == "runtime"
13
+ Requires-Dist: samplomatic>=0.21; extra == "runtime"
14
+ Requires-Dist: qiskit-addon-utils>=0.4; extra == "runtime"
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest; extra == "test"
17
+ Requires-Dist: qiskit-aer>=0.17; extra == "test"
18
+ Requires-Dist: qiskit-ibm-runtime>=0.52; extra == "test"
19
+ Requires-Dist: samplomatic>=0.21; extra == "test"
20
+ Requires-Dist: qiskit-addon-utils>=0.4; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # ffmit
24
+
25
+ Exact noise absorption for **free-fermion circuits** (transverse-field Ising, XY and other matchgate circuits on a
26
+ 1D chain) under a **learned Pauli-Lindblad noise model** (e.g. from `NoiseLearnerV3`).
27
+
28
+ ## Why
29
+
30
+ Propagated noise absorption (PNA) builds a noise-mitigating observable by propagating the inverse noise through the
31
+ circuit in the Pauli basis. For a generic circuit the number of Pauli terms grows exponentially, so PNA truncates,
32
+ and the truncation leaves a bias.
33
+
34
+ For a 1D circuit made only of X-rotations and nearest-neighbour ZZ couplings, the Jordan-Wigner transformation
35
+ rewrites the n qubits as 2n Majorana operators. Every gate rotates *pairs* of Majoranas into pairs; the observable
36
+ (e.g. `Z_i Z_i+1`) is a pair; and Pauli noise only rescales each pair. The noise-mitigating observable therefore lives
37
+ in a fixed space of at most n(2n-1) terms, and the inverse noise can be absorbed **exactly, with no truncation**.
38
+
39
+ This works for **any chain length n** (tested from 2 to 200 qubits). The 15-qubit case below is the hardware
40
+ benchmark from the Qiskit Fall Fest 2026 Noise Busters challenge, not a limit.
41
+
42
+ | 15-qubit TFIM, 8 Trotter steps, ⟨Z6Z7⟩, learned ibm_kingston noise | terms | CPU time | result |
43
+ |---|---|---|---|
44
+ | PNA (`qiskit-addon-pna`), `max_terms=100000` | 100 000 (truncated) | 650 s | not converged (0.7742 and falling) |
45
+ | `ffmit` | 423 (exact) | < 1 s | 0.7480 (exact under the model) |
46
+
47
+ On hardware (ibm_kingston, 5 parallel chains, mirror calibration, 4 runs) the combined estimate was
48
+ **0.6977 ± 0.0030** against the exact 0.6953 (|error| 0.0024), versus 0.0077 for PNA + mirror at the same QPU cost.
49
+
50
+ ## Install
51
+
52
+ ```bash
53
+ pip install ffmit # core
54
+ pip install "ffmit[runtime]" # IBM Runtime pipeline
55
+ ```
56
+
57
+ ## Use
58
+
59
+ ```python
60
+ from ffmit import absorb_noise
61
+
62
+ res = absorb_noise(boxed_circuit, observable, chain, refs, ref_qubits)
63
+ res.model_value() # == ideal value: noise cancelled exactly under the model
64
+ O_tilde = res.observable() # SparsePauliOp to measure instead of `observable`
65
+ measured, remainder = res.split_for_measurement(max_bases=9) # measure the big terms, add the rest classically
66
+ ```
67
+
68
+ - `boxed_circuit`: samplomatic-boxed circuit with `InjectNoise` annotations, or a plain circuit with
69
+ `qiskit_aer.noise.PauliLindbladError` instructions.
70
+ - `chain`: circuit qubit indices of the 1D chain, in order (`find_chain_order` can detect it).
71
+ - `refs`: `{InjectNoise ref: PauliLindbladMap}` from the noise learner; `ref_qubits`: the sorted box qubits per ref.
72
+ - Raises `NotFreeFermionError` when the circuit or observable is not free-fermion along `chain` (non-neighbour
73
+ couplings, rotations that are not X-rotations up to floating Z-rotations, observables of more than two Majoranas).
74
+
75
+ Full hardware pipeline (parallel copies + mirror):
76
+
77
+ ```python
78
+ from ffmit.runtime import ParallelMirrorExperiment, combine
79
+ exp = ParallelMirrorExperiment(circuit, observable, backend, k=5)
80
+ nl_job = NoiseLearnerV3(mode=backend, options=opts).run(exp.learning_circuits)
81
+ exp.build(nl_job.result())
82
+ job = Executor(backend).run(exp.program)
83
+ out = exp.evaluate(job.result()) # out["value"], out["error"]
84
+ ```
85
+
86
+ ## Scope and limits
87
+
88
+ - Exact only for free-fermion circuits on a 1D chain: X-rotations, ZZ couplings between chain neighbours (`cz`, `rzz`),
89
+ and Z-rotations that only meet couplings or Clifford points. Generic circuits are rejected, not approximated.
90
+ - Initial state |0...0⟩.
91
+ - The noise model must be Pauli (twirled). Exactness is with respect to the learned model; model error and drift
92
+ remain, which is what the mirror calibration addresses.
93
+ - Any chain length works. The noise step is dense in 2n x 2n, so time grows with n: about 1 s at n = 50 and
94
+ 15 s at n = 200 (`tests/test_sizes.py`). On hardware, `k` parallel copies of n qubits must fit on the device.
95
+
96
+ ## Tests
97
+
98
+ `pytest tests/`: random free-fermion circuits with Pauli-Lindblad noise against an independent Aer density-matrix
99
+ simulation (exact to 1e-9), the boxed ibm_kingston structure against the Pauli-propagation reference engine used for
100
+ the hardware runs, detection of non-free-fermion circuits, the full pipeline build, and chain lengths from 2 to 200 qubits.
101
+
102
+ ## Prior work
103
+
104
+ Classical simulation of free-fermion (matchgate) circuits with Pauli noise is known (e.g. arXiv:2604.18996). The
105
+ contribution here is using that structure to replace the truncated Pauli propagation of PNA with an exact
106
+ noise-absorbing observable, integrated with NoiseLearnerV3 / samplomatic / Executor.
@@ -0,0 +1,11 @@
1
+ ffmit/__init__.py,sha256=EVWUdT_1HBrm8DQTG246kACvKE7rfTPi4YyAcXjQg_U,804
2
+ ffmit/chain.py,sha256=di1tYkI_elZg4ylIzCN8-JvlDuQSJQ9PJaIPTkPv9-8,1387
3
+ ffmit/engine.py,sha256=MuZIyATPBJIxkIf5XIYa7pNkbx30QeKSyRtU8R2Zr8k,11539
4
+ ffmit/majorana.py,sha256=jxCcjbblDdg0NWgRMU8TlwwtfhLBB7-ZGBDmOXdlOQU,4593
5
+ ffmit/mitigation.py,sha256=1ZCN87b0J-u0JdQTtW5OOXaxo7KZ2ZxV2bMnJHCa-So,5401
6
+ ffmit/runtime.py,sha256=UV0MW1PvsyCgQXD9eAsQdSKmR7TJSdRmUOskVrkoEyc,12603
7
+ ffmit-0.1.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ ffmit-0.1.1.dist-info/METADATA,sha256=-o9aXWVTmp2yky6TXi7SzNzmUT_DbdnadXd5ZPgwiiA,5347
9
+ ffmit-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ ffmit-0.1.1.dist-info/top_level.txt,sha256=K7BjqcXGQOWdthYtSer4TkSQgy-U2z8vxIrzthY8czY,6
11
+ ffmit-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ ffmit