emlint 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.
emlint/__init__.py ADDED
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import stim
6
+
7
+ from emlint import frontends
8
+ from emlint.checks import ALL_CHECKS
9
+ from emlint.model import ErrorModel
10
+ from emlint.report import CheckFn, Report, format_json, format_text
11
+
12
+ __all__ = ["check", "ErrorModel", "Report", "CheckFn", "ALL_CHECKS", "format_text", "format_json"]
13
+
14
+
15
+ def check(
16
+ source: stim.DetectorErrorModel | str | Path,
17
+ checks: dict[str, CheckFn] | None = None,
18
+ ) -> Report:
19
+ """Run checks against *source* and return a Report.
20
+
21
+ Parameters
22
+ ----------
23
+ source:
24
+ A ``stim.DetectorErrorModel``, a ``pathlib.Path`` to a ``.dem`` file,
25
+ a string path to a ``.dem`` file, or a raw DEM string.
26
+ checks:
27
+ Dict of ``{name: check_fn}`` to run. Defaults to ``ALL_CHECKS``.
28
+
29
+ Examples
30
+ --------
31
+ ::
32
+
33
+ report = emlint.check(stim.Circuit.generated(...).detector_error_model())
34
+ print(report.all_passed())
35
+ """
36
+ if checks is None:
37
+ checks = ALL_CHECKS
38
+
39
+ if isinstance(source, stim.DetectorErrorModel):
40
+ dem = source
41
+ elif isinstance(source, Path):
42
+ text = source.read_text() # FileNotFoundError / PermissionError propagate
43
+ try:
44
+ dem = stim.DetectorErrorModel(text)
45
+ except Exception as exc:
46
+ raise ValueError(f"Failed to parse DEM: {exc}") from exc
47
+ elif isinstance(source, str):
48
+ path = Path(source)
49
+ if path.exists():
50
+ text = path.read_text() # PermissionError propagates
51
+ try:
52
+ dem = stim.DetectorErrorModel(text)
53
+ except Exception as exc:
54
+ raise ValueError(f"Failed to parse DEM: {exc}") from exc
55
+ else:
56
+ try:
57
+ dem = stim.DetectorErrorModel(source)
58
+ except Exception as exc:
59
+ raise ValueError(f"Failed to parse DEM: {exc}") from exc
60
+ else:
61
+ raise TypeError(
62
+ f"Unsupported source type {type(source).__name__}. "
63
+ "Pass a stim.DetectorErrorModel, a path to a .dem file, "
64
+ "or a raw DEM string."
65
+ )
66
+
67
+ model = frontends.from_stim_dem(dem)
68
+ results = [fn(model) for fn in checks.values()]
69
+ return Report(
70
+ results=results,
71
+ num_detectors=len(model.detectors),
72
+ num_observables=len(model.observables),
73
+ num_error_mechanisms=len(model.error_mechanisms),
74
+ )
emlint/checks.py ADDED
@@ -0,0 +1,360 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections import Counter
5
+ from emlint.model import ErrorModel
6
+ from emlint.report import CheckFn, PropertyResult
7
+
8
+ _MAX_SHOWN = 10 # max counter-examples shown in truncated lists
9
+
10
+
11
+ def _det_label(d: int, coords: dict[int, tuple[float, ...]]) -> str:
12
+ """Format a detector as 'D17@(1,0,2)' when coordinates are available, else 'D17'."""
13
+ c = coords.get(d)
14
+ if c:
15
+ coord_str = ",".join(f"{v:g}" for v in c)
16
+ return f"D{d}@({coord_str})"
17
+ return f"D{d}"
18
+
19
+
20
+ def _xor_fold(probs: list[float]) -> float:
21
+ """XOR-fold a list of probabilities: p1 ⊕ p2 ⊕ … = p1(1-p2) + p2(1-p1) iterated.
22
+
23
+ The identity element is 0.0 (no error), so an empty list returns 0.0.
24
+ """
25
+ if not probs:
26
+ return 0.0
27
+ p = probs[0]
28
+ for q in probs[1:]:
29
+ p = p * (1 - q) + q * (1 - p)
30
+ return p
31
+
32
+
33
+ def check_detectability(model: ErrorModel, max_shown: int = _MAX_SHOWN) -> PropertyResult:
34
+ """Verify every error mechanism that flips observables also triggers detectors.
35
+
36
+ This check is about *detectability*: a logical error that leaves the syndrome
37
+ trivially empty cannot be detected, and therefore not corrected, by any decoder.
38
+ It does not verify whether the syndrome uniquely identifies which observable
39
+ was flipped; that stronger guarantee is checked by check_correctability.
40
+
41
+ Property: ∀m ∈ mechanisms, obs(m) ≠ ∅ → det(m) ≠ ∅
42
+ """
43
+ violations = [
44
+ mech for mech in model.error_mechanisms
45
+ if not mech.detectors and mech.observables
46
+ ]
47
+
48
+ if violations:
49
+ lines = []
50
+ for mech in violations[:max_shown]:
51
+ obs_str = ", ".join(f"L{o}" for o in sorted(mech.observables))
52
+ lines.append(f"error({mech.probability}) flips {obs_str} but triggers 0 detectors")
53
+ counter = "; ".join(lines)
54
+ if len(violations) > max_shown:
55
+ counter += f" (and {len(violations) - max_shown} more)"
56
+ return PropertyResult(
57
+ name="detectability",
58
+ passed=False,
59
+ severity="error",
60
+ message=f"Found {len(violations)} undetectable error mechanism(s) that flip observable(s).",
61
+ counter_example=counter,
62
+ )
63
+
64
+ return PropertyResult(
65
+ name="detectability",
66
+ passed=True,
67
+ severity="error",
68
+ message="All error mechanisms that flip observables also trigger detectors.",
69
+ )
70
+
71
+
72
+ def check_sensitivity(model: ErrorModel, max_shown: int = _MAX_SHOWN) -> PropertyResult:
73
+ """Verify every declared detector is triggered by at least one error mechanism.
74
+
75
+ A detector that is never triggered by any modelled fault is either wired
76
+ incorrectly or redundant. It contributes no information to decoding and
77
+ may indicate a missing fault model.
78
+
79
+ Property: ∀d ∈ D, ∃m ∈ mechanisms, d ∈ det(m)
80
+ equivalently: D ⊆ ⋃_{m} det(m)
81
+ """
82
+ participating: set[int] = set()
83
+ for mech in model.error_mechanisms:
84
+ participating.update(mech.detectors)
85
+
86
+ dead = sorted(model.detectors - participating)
87
+
88
+ if dead:
89
+ counter = "Detector(s) not triggered by any error mechanism: " + ", ".join(
90
+ _det_label(d, model.detector_coords) for d in dead[:max_shown]
91
+ )
92
+ if len(dead) > max_shown:
93
+ counter += f" (and {len(dead) - max_shown} more)"
94
+ return PropertyResult(
95
+ name="sensitivity",
96
+ passed=False,
97
+ severity="warning",
98
+ message=f"{len(dead)} detector(s) are never triggered by any error mechanism.",
99
+ counter_example=counter,
100
+ )
101
+
102
+ return PropertyResult(
103
+ name="sensitivity",
104
+ passed=True,
105
+ severity="warning",
106
+ message="All detectors are triggered by at least one error mechanism.",
107
+ )
108
+
109
+
110
+ def check_observable_coverage(model: ErrorModel, max_shown: int = _MAX_SHOWN) -> PropertyResult:
111
+ """Verify every declared logical observable is flipped by at least one error mechanism.
112
+
113
+ An observable that never appears in any mechanism is either perfectly protected
114
+ (implausible) or the OBSERVABLE_INCLUDE instruction is not linked to any data qubits.
115
+ In both cases the decoder will always predict the trivial correction for that
116
+ observable, masking real logical errors entirely.
117
+
118
+ Property: ∀ℓ ∈ O, ∃m ∈ mechanisms, ℓ ∈ obs(m)
119
+ equivalently: O ⊆ ⋃_{m} obs(m)
120
+ """
121
+ covered: set[int] = set()
122
+ for mech in model.error_mechanisms:
123
+ covered.update(mech.observables)
124
+
125
+ uncovered = sorted(model.observables - covered)
126
+
127
+ if uncovered:
128
+ counter = "Observable(s) not flipped by any error mechanism: " + ", ".join(
129
+ f"L{o}" for o in uncovered[:max_shown]
130
+ )
131
+ if len(uncovered) > max_shown:
132
+ counter += f" (and {len(uncovered) - max_shown} more)"
133
+ return PropertyResult(
134
+ name="observable_coverage",
135
+ passed=False,
136
+ severity="error",
137
+ message=(
138
+ f"{len(uncovered)} logical observable(s) are never flipped by any "
139
+ f"error mechanism. The decoder will always predict the correct logical "
140
+ f"outcome for these observables, masking real logical errors entirely."
141
+ ),
142
+ counter_example=counter,
143
+ )
144
+
145
+ return PropertyResult(
146
+ name="observable_coverage",
147
+ passed=True,
148
+ severity="error",
149
+ message="All declared observables are flipped by at least one error mechanism.",
150
+ )
151
+
152
+
153
+ def _prob_label(p: float) -> tuple[str, str]:
154
+ """Return (summary_tag, counter_example_hint) for an out-of-range probability."""
155
+ if math.isnan(p): return "p = NaN", "NaN probability"
156
+ if not math.isfinite(p): return "p = ±inf", "infinite probability"
157
+ if p < 0.0: return "p < 0", "negative probability"
158
+ if p == 0.0: return "p = 0", "zero probability"
159
+ return "p > 0.5", "use complementary probability (p → 1−p)"
160
+
161
+
162
+ # Tags that represent unphysical probabilities; p > 0.5 is merely anomalous.
163
+ _UNPHYSICAL_TAGS = {"p = NaN", "p = ±inf", "p < 0", "p = 0"}
164
+
165
+
166
+ def check_probability_bounds(model: ErrorModel, max_shown: int = _MAX_SHOWN) -> PropertyResult:
167
+ """Verify every error mechanism has a probability in (0, 0.5].
168
+
169
+ p = 0 is a no-op that should be pruned from the DEM.
170
+ p < 0, p = NaN or p = ±inf indicates a genuine (compiler) error.
171
+ p > 0.5 is anomalous: for a physical single-fault channel the lower-probability
172
+ branch should be used instead (p → 1−p), though valid use-cases such as
173
+ conditioned or adversarial models may legitimately exceed 0.5.
174
+
175
+ Severity: "error" when any probability is unphysical (NaN, ±inf, ≤ 0);
176
+ "warning" when all violations are merely p > 0.5.
177
+
178
+ Property: ∀m ∈ mechanisms, 0 < p(m) ≤ 0.5 (and p(m) ∉ {NaN, −∞, +∞})
179
+ """
180
+ violations = [
181
+ mech for mech in model.error_mechanisms
182
+ if math.isnan(mech.probability) or not (0.0 < mech.probability <= 0.5)
183
+ ]
184
+ if violations:
185
+ lines: list[str] = []
186
+ tag_counts: Counter[str] = Counter()
187
+ has_unphysical = False
188
+ for mech in violations:
189
+ p = mech.probability
190
+ tag, hint = _prob_label(p)
191
+ tag_counts[tag] += 1
192
+ if tag in _UNPHYSICAL_TAGS:
193
+ has_unphysical = True
194
+ if len(lines) < max_shown:
195
+ target_parts = [f"D{d}" for d in sorted(mech.detectors)] + [f"L{o}" for o in sorted(mech.observables)]
196
+ targets = (" " + " ".join(target_parts)) if target_parts else ""
197
+ lines.append(f"error({p}){targets} — {hint}")
198
+ counter = "; ".join(lines)
199
+ if len(violations) > max_shown:
200
+ counter += f" (and {len(violations) - max_shown} more)"
201
+ parts = [f"{n} with {tag}" for tag, n in tag_counts.items()]
202
+ return PropertyResult(
203
+ name="probability_bounds",
204
+ passed=False,
205
+ severity="error" if has_unphysical else "warning",
206
+ message=f"Found {len(violations)} error mechanism(s) with out-of-range probability ({', '.join(parts)}).",
207
+ counter_example=counter,
208
+ )
209
+
210
+ return PropertyResult(
211
+ name="probability_bounds",
212
+ passed=True,
213
+ severity="error",
214
+ message="All error mechanism probabilities are in (0, 0.5].",
215
+ )
216
+
217
+
218
+ def check_duplicates(model: ErrorModel, max_shown: int = _MAX_SHOWN) -> PropertyResult:
219
+ """Flag error mechanisms that share the same (detectors, observables) signature.
220
+
221
+ When a DEM is assembled from sub-circuits or boundary conditions, the same
222
+ fault path can be counted twice instead of being XOR-fused. Decoders that
223
+ assume independence miscalculate likelihoods. The correct XOR-fold over n
224
+ occurrences is iterated: p_eff = p1 ⊕ p2 ⊕ … where a ⊕ b = a(1-b) + b(1-a).
225
+
226
+ Property: ∀m, m' ∈ mechanisms, m ≠ m' → (det(m), obs(m)) ≠ (det(m'), obs(m'))
227
+ i.e., the signature map m ↦ (det(m), obs(m)) is injective.
228
+ """
229
+ seen: dict[tuple[frozenset[int], frozenset[int]], list[float]] = {}
230
+ for mech in model.error_mechanisms:
231
+ key = (mech.detectors, mech.observables)
232
+ seen.setdefault(key, []).append(mech.probability)
233
+
234
+ duplicates = {k: ps for k, ps in seen.items() if len(ps) > 1}
235
+ # Injectivity is violated if two distinct mechanisms share the same signature.
236
+ if duplicates:
237
+ lines = []
238
+ for (dets, obs), probs in list(duplicates.items())[:max_shown]:
239
+ targets = " ".join(_det_label(d, model.detector_coords) for d in sorted(dets))
240
+ obs_str = (" " + " ".join(f"L{o}" for o in sorted(obs))) if obs else ""
241
+ p_fused = _xor_fold(probs)
242
+ prob_list = ", ".join(str(p) for p in probs)
243
+ lines.append(
244
+ f"error({prob_list}) share signature {targets}{obs_str}; "
245
+ f"XOR-fused probability is {p_fused:.6g}"
246
+ )
247
+ counter = "; ".join(lines)
248
+ if len(duplicates) > max_shown:
249
+ counter += f" (and {len(duplicates) - max_shown} more)"
250
+ return PropertyResult(
251
+ name="duplicates",
252
+ passed=False,
253
+ severity="warning",
254
+ message=(
255
+ f"Found {len(duplicates)} duplicate mechanism signature(s). "
256
+ f"The same fault path appears more than once in the DEM, which "
257
+ f"typically happens when sub-circuit DEMs are concatenated without "
258
+ f"merging coincident mechanisms. Duplicate probabilities should be "
259
+ f"XOR-folded as p_eff = p1*(1-p2) + p2*(1-p1) (iterated for 3+), "
260
+ f"not left as separate entries."
261
+ ),
262
+ counter_example=counter,
263
+ )
264
+
265
+ return PropertyResult(
266
+ name="duplicates",
267
+ passed=True,
268
+ severity="warning",
269
+ message="No duplicate mechanism signatures found.",
270
+ )
271
+
272
+
273
+ def check_correctability(model: ErrorModel, max_shown: int = _MAX_SHOWN) -> PropertyResult:
274
+ """Verify that no two distinct mechanisms share the same detector syndrome
275
+ but differ in the observables they flip.
276
+
277
+ A decoder that receives a syndrome must infer a unique logical correction.
278
+ If two mechanisms produce the same syndrome yet flip different observables,
279
+ any decoder is forced to guess between them and will fail on at least one
280
+ of the two faults.
281
+
282
+ Property: ∀m, m' ∈ mechanisms, det(m) = det(m') → obs(m) = obs(m')
283
+ equivalently: the map det(m) ↦ obs(m) is well-defined (functional)
284
+ on the image of the syndrome map.
285
+
286
+ Scope: this check examines each mechanism independently. It does not detect
287
+ cases where two *distinct* mechanisms, when they co-occur, produce a combined
288
+ syndrome that maps to conflicting observable corrections — that is the code
289
+ distance problem and is in general NP-hard to verify.
290
+
291
+ Known false-positive sources:
292
+ - decompose_errors=True: stim decomposes high-weight errors into pairs of
293
+ low-weight components that share a syndrome but differ in their observable
294
+ sets; these violations are artefacts of the decomposition, not genuine
295
+ decoding ambiguities.
296
+ - Intentionally degenerate codes: codes where multiple fault paths produce
297
+ the same syndrome but map to the same net logical correction (e.g. via
298
+ compensating observables) may still trigger this check because it operates
299
+ on individual mechanisms rather than equivalence classes of corrections.
300
+ """
301
+ # Map each detector frozenset to the set of observable frozensets seen with it.
302
+ syndrome_to_obs: dict[frozenset[int], set[frozenset[int]]] = {}
303
+ for mech in model.error_mechanisms:
304
+ syndrome_to_obs.setdefault(mech.detectors, set()).add(mech.observables)
305
+
306
+ conflicts: dict[frozenset[int], set[frozenset[int]]] = {
307
+ dets: obs_set
308
+ for dets, obs_set in syndrome_to_obs.items()
309
+ if len(obs_set) > 1
310
+ }
311
+ # A conflict occurs when a syndrome (detector set) maps to more than one distinct observable set,
312
+ # i.e. there exist at least two mechanisms m and m' such that det(m) = det(m') but obs(m) ≠ obs(m').
313
+ if conflicts:
314
+ lines = []
315
+ for dets, obs_set in list(conflicts.items())[:max_shown]:
316
+ det_str = " ".join(_det_label(d, model.detector_coords) for d in sorted(dets)) if dets else "(no detectors)"
317
+
318
+ obs_variants = ", ".join(
319
+ "{" + " ".join(f"L{o}" for o in sorted(obs)) + "}"
320
+ for obs in sorted(obs_set, key=lambda s: sorted(s))
321
+ )
322
+ lines.append(f"syndrome {{{det_str}}} maps to observable sets {obs_variants}")
323
+ counter = "; ".join(lines)
324
+ if len(conflicts) > max_shown:
325
+ counter += f" (and {len(conflicts) - max_shown} more)"
326
+ return PropertyResult(
327
+ name="correctability",
328
+ passed=False,
329
+ severity="warning",
330
+ message=(
331
+ f"Found {len(conflicts)} syndrome(s) that map to more than one distinct "
332
+ f"observable set. The decoder cannot determine which logical observable "
333
+ f"was flipped from the measurement outcome alone. "
334
+ f"Note: if this DEM was generated with decompose_errors=True, some "
335
+ f"violations may be artefacts of the decomposition rather than genuine "
336
+ f"ambiguities."
337
+ ),
338
+ counter_example=counter,
339
+ )
340
+
341
+ return PropertyResult(
342
+ name="correctability",
343
+ passed=True,
344
+ severity="warning",
345
+ message="Every syndrome maps to at most one distinct set of logical observables.",
346
+ )
347
+
348
+
349
+ # Check Registry
350
+ LOCAL_CHECKS: dict[str, CheckFn] = {
351
+ "detectability": check_detectability,
352
+ "sensitivity": check_sensitivity,
353
+ "observable_coverage": check_observable_coverage,
354
+ "probability_bounds": check_probability_bounds,
355
+ "duplicates": check_duplicates,
356
+ "correctability": check_correctability,
357
+ }
358
+
359
+ # ALL_CHECKS is the public registry used by emlint.check() and the CLI.
360
+ ALL_CHECKS = dict(LOCAL_CHECKS)
emlint/cli.py ADDED
@@ -0,0 +1,108 @@
1
+ """Command-line interface for emlint."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import importlib.metadata
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import emlint
10
+ from emlint.checks import ALL_CHECKS
11
+ from emlint.report import format_json, format_text
12
+
13
+ def _build_parser() -> argparse.ArgumentParser:
14
+ parser = argparse.ArgumentParser(
15
+ prog="emlint",
16
+ description="Static analysis for Detector Error Models.",
17
+ )
18
+ parser.add_argument(
19
+ "--version",
20
+ action="version",
21
+ version=f"%(prog)s {importlib.metadata.version('emlint')}",
22
+ )
23
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND")
24
+
25
+ check_cmd = sub.add_parser("check", help="Run checks against a DEM file or string.")
26
+ check_cmd.add_argument(
27
+ "source",
28
+ help="Path to a .dem file, or a raw DEM string.",
29
+ )
30
+ check_cmd.add_argument(
31
+ "--format",
32
+ choices=["text", "json"],
33
+ default="text",
34
+ help="Output format (default: text).",
35
+ )
36
+ check_cmd.add_argument(
37
+ "--check",
38
+ metavar="NAMES",
39
+ help=(
40
+ "Comma-separated list of check names to run (default: all). "
41
+ f"Available: {', '.join(ALL_CHECKS)}."
42
+ ),
43
+ )
44
+ check_cmd.add_argument(
45
+ "--severity",
46
+ choices=["error", "warning"],
47
+ default="warning",
48
+ help="Minimum severity to report (default: warning). "
49
+ "Use 'error' to suppress warnings and only surface error-severity findings.",
50
+ )
51
+ return parser
52
+
53
+
54
+ def main() -> None:
55
+ parser = _build_parser()
56
+ args = parser.parse_args()
57
+
58
+ if args.command is None:
59
+ parser.print_help()
60
+ sys.exit(0)
61
+
62
+ # Resolve check subset
63
+ checks = None
64
+ if args.check:
65
+ names = [n.strip() for n in args.check.split(",")]
66
+ unknown = [n for n in names if n not in ALL_CHECKS]
67
+ if unknown:
68
+ parser.error(
69
+ f"Unknown check(s): {', '.join(unknown)}. "
70
+ f"Available: {', '.join(ALL_CHECKS)}."
71
+ )
72
+ checks = {n: ALL_CHECKS[n] for n in names}
73
+
74
+ try:
75
+ report = emlint.check(args.source, checks=checks)
76
+ except FileNotFoundError:
77
+ parser.error(f"File not found: {args.source}")
78
+ except PermissionError:
79
+ parser.error(f"Permission denied: {args.source}")
80
+ except ValueError as exc:
81
+ parser.error(str(exc))
82
+
83
+ # Apply severity filter to the displayed output only; exit code is always
84
+ # based on the full report so that error-severity failures are never silently dropped.
85
+ if args.severity == "error":
86
+ from emlint.report import Report as _Report
87
+ display_report = _Report(
88
+ results=[r for r in report.results if r.severity == "error"],
89
+ num_detectors=report.num_detectors,
90
+ num_observables=report.num_observables,
91
+ num_error_mechanisms=report.num_error_mechanisms,
92
+ )
93
+ else:
94
+ display_report = report
95
+
96
+ formatter = format_json if args.format == "json" else format_text
97
+ print(formatter(display_report))
98
+
99
+ if report.has_errors():
100
+ sys.exit(1)
101
+ elif args.severity != "error" and report.has_warnings():
102
+ sys.exit(2)
103
+ else:
104
+ sys.exit(0)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
emlint/frontends.py ADDED
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ import stim
4
+
5
+ from emlint.model import ErrorMechanism, ErrorModel
6
+
7
+
8
+ def from_stim_dem(dem: stim.DetectorErrorModel) -> ErrorModel:
9
+ """Translate a stim.DetectorErrorModel into a frontend-agnostic ErrorModel."""
10
+ # detectors is populated from both 'detector' instructions (declared detectors)
11
+ # and 'error' instructions (detectors referenced by error mechanisms). A
12
+ # well-formed DEM declares every detector explicitly, but we accept both to
13
+ # handle partially-specified models without silent data loss.
14
+ # observables is derived from dem.num_observables so that observables declared
15
+ # in the circuit but never referenced in any error mechanism are still tracked.
16
+ detectors: set[int] = set()
17
+ error_mechanisms: list[ErrorMechanism] = []
18
+ detector_coords: dict[int, tuple[float, ...]] = {}
19
+
20
+ for instruction in dem.flattened():
21
+ if instruction.type == "error":
22
+ prob = instruction.args_copy()[0]
23
+ det_targets: list[int] = []
24
+ obs_targets: list[int] = []
25
+ for t in instruction.targets_copy():
26
+ if t.is_relative_detector_id():
27
+ det_targets.append(t.val)
28
+ detectors.add(t.val)
29
+ elif t.is_logical_observable_id():
30
+ obs_targets.append(t.val)
31
+ error_mechanisms.append(
32
+ ErrorMechanism(
33
+ probability=prob,
34
+ detectors=frozenset(det_targets),
35
+ observables=frozenset(obs_targets),
36
+ )
37
+ )
38
+ elif instruction.type == "detector":
39
+ coords = tuple(float(v) for v in instruction.args_copy())
40
+ for t in instruction.targets_copy():
41
+ if t.is_relative_detector_id():
42
+ detectors.add(t.val)
43
+ if coords:
44
+ detector_coords[t.val] = coords
45
+
46
+ return ErrorModel(
47
+ detectors=detectors,
48
+ observables=set(range(dem.num_observables)),
49
+ error_mechanisms=error_mechanisms,
50
+ detector_coords=detector_coords,
51
+ )
emlint/model.py ADDED
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class ErrorMechanism:
8
+ """A single error mechanism, e.g. "X error on qubit 3 with probability 0.01". """
9
+ probability: float
10
+ detectors: frozenset[int]
11
+ observables: frozenset[int]
12
+
13
+
14
+ @dataclass
15
+ class ErrorModel:
16
+ """Frontend-agnostic error model. All checks operate on this."""
17
+ detectors: set[int]
18
+ observables: set[int]
19
+ error_mechanisms: list[ErrorMechanism]
20
+ # Maps detector index → coordinate tuple, e.g. {17: (1.0, 0.0, 2.0)}.
21
+ # Populated when the DEM carries detector() coordinate annotations.
22
+ # Empty for DEMs that omit coordinates.
23
+ detector_coords: dict[int, tuple[float, ...]] = field(default_factory=dict)
emlint/report.py ADDED
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import json
5
+ from dataclasses import dataclass
6
+ from typing import Callable, Literal
7
+
8
+ from emlint.model import ErrorModel
9
+
10
+
11
+ @dataclass
12
+ class PropertyResult:
13
+ name: str
14
+ passed: bool
15
+ severity: Literal["error", "warning"]
16
+ message: str
17
+ counter_example: str | None = None
18
+
19
+
20
+ @dataclass
21
+ class Report:
22
+ results: list[PropertyResult]
23
+ num_detectors: int
24
+ num_observables: int
25
+ num_error_mechanisms: int
26
+
27
+ def all_passed(self) -> bool:
28
+ return all(r.passed for r in self.results)
29
+
30
+ def has_errors(self) -> bool:
31
+ return any(not r.passed and r.severity == "error" for r in self.results)
32
+
33
+ def has_warnings(self) -> bool:
34
+ return any(not r.passed and r.severity == "warning" for r in self.results)
35
+
36
+
37
+ # The canonical type for all check functions.
38
+ # Extension packages should use this to type-check their custom checks.
39
+ # Callable[..., PropertyResult] accommodates the optional max_shown parameter
40
+ # without breaking structural compatibility.
41
+ CheckFn = Callable[..., PropertyResult]
42
+
43
+
44
+ def format_text(report: Report) -> str:
45
+ lines: list[str] = [
46
+ f"Detectors: {report.num_detectors} "
47
+ f"Observables: {report.num_observables} "
48
+ f"Error mechanisms: {report.num_error_mechanisms}",
49
+ "",
50
+ ]
51
+ for r in report.results:
52
+ icon = "✓" if r.passed else "✗"
53
+ lines.append(f" {icon} {r.name}: {r.message}")
54
+ if r.counter_example:
55
+ lines.append(f" Counter-example: {r.counter_example}")
56
+ return "\n".join(lines)
57
+
58
+
59
+ def format_json(report: Report) -> str:
60
+ data = {
61
+ "num_detectors": report.num_detectors,
62
+ "num_observables": report.num_observables,
63
+ "num_error_mechanisms": report.num_error_mechanisms,
64
+ "all_passed": report.all_passed(),
65
+ "has_errors": report.has_errors(),
66
+ "results": [dataclasses.asdict(r) for r in report.results],
67
+ }
68
+ return json.dumps(data, indent=2)
@@ -0,0 +1,314 @@
1
+ Metadata-Version: 2.4
2
+ Name: emlint
3
+ Version: 0.1.0
4
+ Summary: A static analysis tool for quantum error correction
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: stim<3.0,>=1.14
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest>=7.0; extra == "dev"
11
+ Requires-Dist: hypothesis>=6.50; extra == "dev"
12
+ Provides-Extra: benchmark
13
+ Requires-Dist: pytest>=7.0; extra == "benchmark"
14
+ Requires-Dist: hypothesis>=6.50; extra == "benchmark"
15
+ Requires-Dist: qldpc; extra == "benchmark"
16
+
17
+ # emlint
18
+
19
+ [![CI](https://github.com/MathysRennela/dem-linter/actions/workflows/emlint.yml/badge.svg)](https://github.com/MathysRennela/dem-linter/actions/workflows/emlint.yml)
20
+ [![PyPI](https://img.shields.io/pypi/v/emlint)](https://pypi.org/project/emlint/)
21
+
22
+ **stim simulates. sinter samples. emlint verifies.**
23
+
24
+ emlint is a static linter for Detector Error Models (DEMs). A DEM describes
25
+ a circuit's noise as a list of *error mechanisms* — independent faults, each
26
+ with a probability and a syndrome footprint: which detectors it fires and which
27
+ logical observables it flips. It catches structural bugs in milliseconds — before
28
+ you run a single shot.
29
+
30
+ ## The problem
31
+
32
+ A `DETECTOR` instruction omitted in round 2 of a d=5 surface code leaves
33
+ detector D17 wired to nothing. The decoder silently miscorrects. The logical
34
+ error rate rises. The bug is invisible until ~10⁶ Sinter shots (≈45 minutes
35
+ on a standard laptop).
36
+
37
+ ```
38
+ $ emlint check examples/buggy.dem
39
+
40
+ Detectors: 24 Observables: 1 Error mechanisms: 35
41
+
42
+ ✓ detectability: All error mechanisms that flip observables also trigger detectors.
43
+ ✗ sensitivity: 1 detector(s) are never triggered by any error mechanism.
44
+ Counter-example: Detector(s) not triggered by any error mechanism: D17
45
+ ✓ observable_coverage: All declared observables are flipped by at least one error mechanism.
46
+ ✓ probability_bounds: All error probabilities are within (0, 0.5].
47
+ ✓ duplicates: No duplicate error mechanisms found.
48
+ ✓ correctability: All syndromes map to a unique observable set.
49
+ ```
50
+
51
+ 2ms. One line. No simulation. D17 carries coordinates `(1, 0, 2)` — round 2,
52
+ position (1, 0) — so you know exactly where in the circuit to look.
53
+
54
+ ```
55
+ $ emlint check examples/fixed.dem
56
+
57
+ ✓ detectability ✓ sensitivity ✓ observable_coverage
58
+ ✓ probability_bounds ✓ duplicates ✓ correctability
59
+ ```
60
+
61
+ ## Installation
62
+
63
+ ```
64
+ pip install emlint
65
+ ```
66
+
67
+ ## Usage
68
+
69
+ ### CLI
70
+
71
+ ```
72
+ emlint check path/to/circuit.dem
73
+ emlint check path/to/circuit.dem --format json
74
+ emlint check path/to/circuit.dem --check detectability,sensitivity
75
+ emlint check path/to/circuit.dem --severity error
76
+ ```
77
+
78
+ Exit code `0` when all checks pass. Exit code `1` when any `error`-severity
79
+ check fails. Exit code `2` when there are warnings but no errors (usable in CI
80
+ to optionally escalate warnings without breaking the build).
81
+
82
+ `--severity error` suppresses `warning`-severity findings entirely — only
83
+ `error`-severity violations appear in output and affect the exit code. Useful
84
+ in CI pipelines where warnings are acknowledged but should not break the build.
85
+
86
+ ### Python API
87
+
88
+ ```python
89
+ import stim
90
+ import emlint
91
+
92
+ circuit = stim.Circuit.generated(
93
+ "surface_code:rotated_memory_z",
94
+ rounds=3,
95
+ distance=5,
96
+ after_clifford_depolarization=0.001,
97
+ )
98
+ report = emlint.check(circuit.detector_error_model(decompose_errors=True))
99
+ print(emlint.format_text(report))
100
+ ```
101
+
102
+ `emlint.check()` also accepts a `pathlib.Path` or a raw DEM string.
103
+
104
+ ### CI integration
105
+
106
+ Add to `.github/workflows/qec.yml`:
107
+
108
+ ```yaml
109
+ - name: Lint DEM
110
+ run: pip install emlint && emlint check circuit.dem
111
+ ```
112
+
113
+ ## Checks
114
+
115
+ | Check | What it catches | Severity |
116
+ |---|---|---|
117
+ | `detectability` | Errors that flip observables but trigger no detectors (undetectable) | error |
118
+ | `sensitivity` | Detectors never triggered by any error mechanism (dead detectors) | warning |
119
+ | `observable_coverage` | Logical observables never flipped by any error mechanism | error |
120
+ | `probability_bounds` | Error probabilities outside `(0, 0.5]` | error |
121
+ | `duplicates` | Error mechanisms with identical (detector, observable) signatures | warning |
122
+ | `correctability` | Syndromes mapping to multiple distinct observable sets | warning |
123
+
124
+ All checks operate on the standalone `.dem` file — no original circuit required.
125
+ Each failing check produces a counter-example pointing to the specific mechanism
126
+ or detector at fault.
127
+
128
+ ## Connecting a failed check to the circuit bug
129
+
130
+ When a check fails, the counter-example tells you *where* in the DEM the problem
131
+ is. The table below tells you *what* circuit-level mistake most likely produced it
132
+ and where to look in your circuit source.
133
+
134
+ ### `detectability` fails
135
+
136
+ > `error(0.001) L0 — flips observable but triggers 0 detectors`
137
+
138
+ The listed mechanism flips a logical observable but no detector fires — the
139
+ decoder has no syndrome signal to correct it.
140
+
141
+ **What went wrong in the circuit:**
142
+ - A `DETECTOR` instruction was omitted from a syndrome measurement round. The
143
+ round still runs and produces data, but no detector was wired to it.
144
+ - `OBSERVABLE_INCLUDE` targets a qubit that is outside the fault support of every
145
+ modelled error (wrong qubit index, wrong basis).
146
+
147
+ **Where to look:** search your circuit for the round that *should* cover the data
148
+ qubits referenced in the failing mechanism's observable. Check that every syndrome
149
+ extraction round ends with a `DETECTOR` pointing at the right ancilla measurement.
150
+
151
+ ---
152
+
153
+ ### `sensitivity` fails
154
+
155
+ > `D17@(1,0,2) not triggered by any error mechanism`
156
+
157
+ The listed detector is declared but no error mechanism ever fires it.
158
+
159
+ **What went wrong in the circuit:**
160
+ - The ancilla qubit for this detector is measuring in the wrong Pauli basis
161
+ (`X` vs `Z` mismatch), so the errors that *should* flip it pass through silently.
162
+ - The detector's coordinates point to the wrong spatial position — the qubit index
163
+ in `DETECTOR rec[…]` is off by one.
164
+ - A syndrome round was accidentally removed from the circuit, leaving its detector
165
+ declaration orphaned.
166
+
167
+ **Where to look:** the detector's coordinates (shown as `D17@(col,row,round)`)
168
+ identify the syndrome round and stabilizer position. Verify that the corresponding
169
+ ancilla qubit is connected to data qubits via the expected CNOT schedule, and that
170
+ the noise model includes errors on those CNOTs.
171
+
172
+ ---
173
+
174
+ ### `observable_coverage` fails
175
+
176
+ > `L1 not flipped by any error mechanism`
177
+
178
+ The listed logical observable is declared but no physical error can flip it.
179
+
180
+ **What went wrong in the circuit:**
181
+ - `OBSERVABLE_INCLUDE` on the wrong qubit or at the wrong point in the circuit
182
+ (e.g. applied to an ancilla instead of a data qubit, or after a reset that
183
+ erases the correlation).
184
+ - Observable index off-by-one in a multi-observable code.
185
+
186
+ **Where to look:** the counter-example gives you the observable index (e.g.
187
+ `L1`). Search your circuit source for every `OBSERVABLE_INCLUDE` with that
188
+ index. Verify that the qubit it references is part of the logical operator's
189
+ support and that errors on that qubit survive to the measurement record.
190
+ (`emlint check --format json` outputs counter-examples as structured data,
191
+ making it easy to script a targeted search when the circuit is auto-generated.)
192
+
193
+ ---
194
+
195
+ ### `probability_bounds` fails
196
+
197
+ > `error(0.0) D0 D1 — zero probability`
198
+ > `error(nan) D3 — NaN probability`
199
+
200
+ An error mechanism has a probability of exactly 0 (a no-op), is negative, or is
201
+ NaN — all of which indicate a fault in DEM generation, not a physical noise model.
202
+
203
+ **What went wrong in the circuit / DEM generation script:**
204
+ - Numerical underflow: a product of small probabilities rounded to 0 instead of
205
+ being pruned or clamped.
206
+ - Naive addition of two complementary probabilities exceeded 1, producing a
207
+ negative remainder.
208
+ - A copy-paste error in a manual DEM left a placeholder (`nan`, `-1`, `0`)
209
+ instead of a real probability.
210
+
211
+ **Where to look:** the mechanism's detector and observable targets identify which
212
+ fault path the DEM compiler was trying to express. Trace that fault path back to
213
+ the noise model parameters in your DEM generation script.
214
+
215
+ ---
216
+
217
+ ### `duplicates` fails
218
+
219
+ > `error(0.001, 0.001) share signature D3 D7; XOR-fused probability is 0.001998`
220
+
221
+ Two or more mechanisms share the same `(detectors, observables)` signature — the
222
+ same physical fault path is counted more than once.
223
+
224
+ **What went wrong in the circuit / DEM assembly:**
225
+ - Sub-circuit DEMs were concatenated (e.g. bulk + boundary + initialisation)
226
+ without merging mechanisms that touch the same fault path. The correct operation
227
+ is XOR-fusion: `p_eff = p1(1−p2) + p2(1−p1)`.
228
+ - An X error and a Y error on the same data qubit at a repetition code boundary
229
+ each trigger the same detector set and flip the same observable (legitimate
230
+ physics; use `--severity error` in CI to suppress this warning for known-correct
231
+ code families).
232
+
233
+ **Where to look:** if the duplicate arises from concatenation, find the boundary
234
+ between the sub-circuits where the mechanism originates. If you are manually
235
+ composing DEMs with Python, apply XOR-fusion instead of list concatenation.
236
+
237
+ ---
238
+
239
+ ### `correctability` fails
240
+
241
+ > `syndrome {D3 D7} maps to observable sets {L0}, {L1}`
242
+
243
+ The same detector syndrome is produced by mechanisms that flip *different*
244
+ observables — the decoder cannot determine the correct logical correction.
245
+
246
+ **What went wrong in the circuit:**
247
+ - Two physically distinct errors (e.g. an X error on qubit A and a Z error on
248
+ qubit B) produce the same syndrome but flip different logical observables. This
249
+ is a genuine code distance problem: the code cannot distinguish them.
250
+ - The DEM was generated with `decompose_errors=True`, which breaks hyperedge
251
+ mechanisms into sub-mechanisms that can create artificial syndrome collisions
252
+ (use `--severity error` to suppress this known artefact in CI).
253
+ - A degenerate code family (colour codes) has syndromes that legitimately map to
254
+ multiple valid logical corrections — this is an expected property, not a bug.
255
+
256
+ **Where to look:** the counter-example gives you the exact syndrome (e.g.
257
+ `{D3 D7}`) and the conflicting observable sets. Search your `.dem` file for
258
+ every `error(…)` line whose detector targets match that set — those are the two
259
+ colliding mechanisms. In the original circuit, find the gate locations
260
+ corresponding to each mechanism's targets (the detector coordinates annotate
261
+ the round and spatial position). If both locations are in the *same* Pauli
262
+ basis and the same round, this is likely a genuine distance-1 path. If they
263
+ are in different bases or rounds, look for a missing stabilizer measurement
264
+ or a mis-wired CNOT that merges two logically distinct fault paths.
265
+
266
+ **Scope note:** this check examines each mechanism *individually*. It does not
267
+ detect cases where two *co-occurring* faults combine to produce a syndrome that
268
+ maps to conflicting corrections — that is the code distance problem and is not
269
+ checked here. A future version will address multi-fault correctability via
270
+ compositional reasoning (pre/post-conditions on circuit segments).
271
+
272
+ ## qLDPC & lifted-product codes
273
+
274
+ emlint accepts any DEM, including those generated from hypergraph product (HGP)
275
+ and lifted-product (Bivariate Bicycle) codes. Pass the DEM from any source:
276
+
277
+ ```python
278
+ # From a qldpc-generated code
279
+ import qldpc, stim, emlint
280
+
281
+ classical = qldpc.codes.ClassicalCode.random(7, 5, seed=0)
282
+ code = qldpc.codes.HGPCode(classical)
283
+ noise = qldpc.circuits.DepolarizingNoiseModel(0.001)
284
+ circuit = qldpc.circuits.get_memory_experiment(code, num_rounds=5, noise_model=noise)
285
+ report = emlint.check(circuit.detector_error_model(decompose_errors=False))
286
+ ```
287
+
288
+ The six structural checks apply universally — they do not assume surface code
289
+ topology and do not require knowledge of the underlying code family.
290
+
291
+ ## Known false positives
292
+
293
+ **`correctability` with `decompose_errors=True`**
294
+
295
+ When a DEM is generated with `stim`'s `decompose_errors=True`, the hyperedge
296
+ decomposition can create sub-mechanism pairs that share the same detector set
297
+ but differ in observables — a syndrome collision that does not exist in the
298
+ original hyperedge model. The check fires at `warning` severity.
299
+
300
+ *Mitigation:* use `--severity error` in CI, or pass `decompose_errors=False`
301
+ to get a clean `correctability` result with no artefacts.
302
+
303
+ **`duplicates` at boundaries in degenerate code families**
304
+
305
+ Degenerate fault paths (e.g. X and Y errors at a repetition code boundary that
306
+ produce the same syndrome and flip the same observable) are correctly flagged as
307
+ duplicates. The warning is accurate — the XOR-fused probability is shown — but
308
+ may not require user action in degenerate code families.
309
+
310
+ *Mitigation:* use `--severity error` in CI to suppress.
311
+
312
+ ## License
313
+
314
+ Apache 2.0
@@ -0,0 +1,11 @@
1
+ emlint/__init__.py,sha256=ytLtU4H-sCPF0q39siUzZJ04VQjatM56JxJ4WtXhZPE,2396
2
+ emlint/checks.py,sha256=Xs6yIL0gwFQWTslbXfh53rU1SmssX-DXbK5lQAOKOEc,15302
3
+ emlint/cli.py,sha256=zw4fLpfhEFNx__Lc6zuZv-Ty4omVQi7Cbi_D0yJ0UHY,3289
4
+ emlint/frontends.py,sha256=C52PcdoTNz3aORXtgv7ISyDQ_lpc_Qe8QjIN4hlYuSo,2131
5
+ emlint/model.py,sha256=nrqeFxmn780N5XypAW22yIswqjjqpa4539Qpq-wI8gY,761
6
+ emlint/report.py,sha256=gCIlwe_w4WiHxVnaaTzsGPOmNuvdiHou5BtjspDga_A,1997
7
+ emlint-0.1.0.dist-info/METADATA,sha256=oad1ddY4F7PsYUFGVotcsU3_rJXgFgjuN3MQY0urq1U,12762
8
+ emlint-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
9
+ emlint-0.1.0.dist-info/entry_points.txt,sha256=TSZPYYzkweb1ZRchfj2ObMi5_PUcWavBb50gQx2yuWc,43
10
+ emlint-0.1.0.dist-info/top_level.txt,sha256=sjFW2NwHHRgSG4jzomM3Qu2W_N0ttgjus5ixgxXiUvk,7
11
+ emlint-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ emlint = emlint.cli:main
@@ -0,0 +1 @@
1
+ emlint