From c70275b51ab6ce6dd890c6f24067b4833b054ba6 Mon Sep 17 00:00:00 2001 From: thierry-martinez Date: Tue, 27 Oct 2026 00:59:32 +0100 Subject: [PATCH 1/2] Fix for TeamGraphix/graphix#635: Mandatory domain for CONDINSTR `CONDINSTR` now takes its `domain` as first argument, before the instructions. The uv source for graphix temporarily points to the PR branch. Co-Authored-By: Claude Opus 5.5 --- graphix_qasm_parser/parser.py | 2 +- pyproject.toml | 2 +- tests/test_parser.py | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/graphix_qasm_parser/parser.py b/graphix_qasm_parser/parser.py index 74ff7d9..c00c0a0 100644 --- a/graphix_qasm_parser/parser.py +++ b/graphix_qasm_parser/parser.py @@ -814,7 +814,7 @@ def visitIfStatement(self, ctx: qasm3Parser.IfStatementContext) -> None: body = conditional_block.instructions self.block = parent_block if domain: - instruction = Instruction.CONDINSTR(tuple(body), domain) + instruction = Instruction.CONDINSTR(domain, tuple(body)) parent_block.instructions.append(instruction) else: self.warnings.append("Conditional instruction with empty condition dropped.") diff --git a/pyproject.toml b/pyproject.toml index 3672d82..8fb909a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -86,4 +86,4 @@ reportUnknownLambdaType = "information" # reportUnknownVariableType = "information" [tool.uv.sources] -graphix = { git = "https://github.com/TeamGraphix/graphix.git" } +graphix = { git = "https://github.com/thierry-martinez/graphix.git", branch = "fix-626" } diff --git a/tests/test_parser.py b/tests/test_parser.py index a0f389d..8151324 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -403,14 +403,14 @@ def test_if_statements() -> None: assert circuit.width == 3 assert circuit.instruction == [ Instruction.M(2, Axis.Z), - Instruction.CONDINSTR((Instruction.X(0),), {2}), + Instruction.CONDINSTR({2}, (Instruction.X(0),)), Instruction.M(0, Axis.Z), Instruction.CONDINSTR( + {0, 2}, ( Instruction.X(1), Instruction.Z(1), ), - {0, 2}, ), ] @@ -434,7 +434,7 @@ def test_redundant_if_statements() -> None: assert circuit.instruction == [ Instruction.M(2, Axis.Z), Instruction.M(0, Axis.Z), - Instruction.CONDINSTR((Instruction.X(1),), {0}), + Instruction.CONDINSTR({0}, (Instruction.X(1),)), ] From c5de3cbaf27f9ceae4a855d0bfe029d1c47ecef5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 13:20:48 +0000 Subject: [PATCH 2/2] Add discard option to OpenQASMParser and index bits by measurement Measurement outcomes are now referred to in domains by the index of the measurement, following Graphix's convention for CONDINSTR in TeamGraphix/graphix#644. The new option `discard_measurements` (default `True`) controls whether measured qubits are discarded; with `discard_measurements=False`, qubits remain active after measurement, as in OpenQASM. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ README.md | 6 +++++ graphix_qasm_parser/parser.py | 25 +++++++++++++++--- pyproject.toml | 2 +- tests/test_parser.py | 50 ++++++++++++++++++++++++++++++++--- 5 files changed, 78 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c771fc..cec9a5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - #18: Support for user gate definitions +- Support for measurements without discard with the `discard_measurements` option of `OpenQASMParser`. The domains of `if`-statements now refer to the indices of measurements rather than to the indices of measured qubits, following Graphix's new convention for `CONDINSTR`. + ## [0.1.1] - 2026-02-05 - #7: Parsing of `CZ` gate diff --git a/README.md b/README.md index 638e662..9cbb422 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,12 @@ Measurements of the form `bit = measure qubit;`, or the old syntax Both arguments must be registers of the same size, or both must be bit/qubit types. +By default, measured qubits are discarded, as in Graphix circuits: a +measured qubit cannot be used afterwards. In OpenQASM, measured qubits +remain available, in the post-measurement state: this behavior is +obtained with `OpenQASMParser(discard_measurements=False)`, which produces +measurements without discard (`Instruction.M(..., discard=False)`). + ### [If](https://openqasm.com/language/classical.html#if-else-statements) statements Statements of the form `if (domain) { ... }` are supported when diff --git a/graphix_qasm_parser/parser.py b/graphix_qasm_parser/parser.py index 52ca8df..943ef32 100644 --- a/graphix_qasm_parser/parser.py +++ b/graphix_qasm_parser/parser.py @@ -38,8 +38,23 @@ _T = TypeVar("_T") +@dataclass(kw_only=True) class OpenQASMParser: - """Graphix OpenQASM parser.""" + """ + Graphix OpenQASM parser. + + Attributes + ---------- + discard_measurements : bool, optional + If ``True`` (the default), measured qubits are discarded, as in + Graphix circuits by default: a measured qubit cannot be used + afterwards. If ``False``, measured qubits remain active after + the measurement, in the post-measurement state, as specified by + OpenQASM. See :class:`graphix.instruction.M`. + + """ + + discard_measurements: bool = True def parse_stream(self, stream: InputStream, *, stacklevel: int = 1) -> Circuit: """ @@ -684,6 +699,8 @@ class _CircuitVisitor(qasm3ParserVisitor): env: dict[str, _Value] warnings: list[str] user_defined_gates: dict[str, _Gate] + measurement_count: int + """Number of measurements so far: the next measurement writes the bit of this index.""" def __init__(self, parser: OpenQASMParser) -> None: self.parser = parser @@ -692,6 +709,7 @@ def __init__(self, parser: OpenQASMParser) -> None: self.env = BASE_ENV self.warnings = [] self.user_defined_gates = {} + self.measurement_count = 0 def expect_circuit_block(self, ctx: ParserRuleContext) -> _CircuitBlock: # type: ignore[valid-type] if not isinstance(self.block, _CircuitBlock): @@ -868,9 +886,10 @@ def add_measurement(self, ctx: ParserRuleContext, target_bit: _Value, target_qub msg = f"Only assignment to bit is supported: {target_bit} unexpected." raise NotImplementedError(msg) qubit_index = target_qubit.as_qubit().index - instruction = Instruction.M(qubit_index, Axis.Z) + instruction = Instruction.M(qubit_index, Axis.Z, discard=self.parser.discard_measurements) block.instructions.append(instruction) - target_bit.index = qubit_index + target_bit.index = self.measurement_count + self.measurement_count += 1 def declare_register(self, ctx: ParserRuleContext, decl_kind: _DeclKind) -> _Value: # type: ignore[valid-type] match decl_kind: diff --git a/pyproject.toml b/pyproject.toml index 8fb909a..fbaeafd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -86,4 +86,4 @@ reportUnknownLambdaType = "information" # reportUnknownVariableType = "information" [tool.uv.sources] -graphix = { git = "https://github.com/thierry-martinez/graphix.git", branch = "fix-626" } +graphix = { git = "https://github.com/thierry-martinez/graphix.git", branch = "measure-without-discard" } diff --git a/tests/test_parser.py b/tests/test_parser.py index d5a5d6b..2006842 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -4,8 +4,11 @@ import math +import numpy as np import pytest from graphix import ANGLE_PI, Axis, Instruction, rad_to_angle +from graphix.sim.statevec import Statevector +from graphix.states import BasicStates from graphix_qasm_parser import OpenQASMParser @@ -454,10 +457,10 @@ def test_if_statements() -> None: assert circuit.width == 3 assert circuit.instruction == [ Instruction.M(2, Axis.Z), - Instruction.CONDINSTR({2}, (Instruction.X(0),)), + Instruction.CONDINSTR({0}, (Instruction.X(0),)), Instruction.M(0, Axis.Z), Instruction.CONDINSTR( - {0, 2}, + {0, 1}, ( Instruction.X(1), Instruction.Z(1), @@ -485,7 +488,7 @@ def test_redundant_if_statements() -> None: assert circuit.instruction == [ Instruction.M(2, Axis.Z), Instruction.M(0, Axis.Z), - Instruction.CONDINSTR({0}, (Instruction.X(1),)), + Instruction.CONDINSTR({1}, (Instruction.X(1),)), ] @@ -513,3 +516,44 @@ def test_void_if_statements() -> None: Instruction.M(0, Axis.Z), Instruction.Z(1), ] + + +def test_measurement_without_discard() -> None: + """Test measurements without discard.""" + s = """ +include "stdgates.inc"; +qubit[2] q; +bit[2] b; +b[0] = measure q[0]; +x q[0]; +b[1] = measure q[0]; +if (b[1]) { + x q[1]; +} +""" + parser = OpenQASMParser(discard_measurements=False) + circuit = parser.parse_str(s) + assert circuit.width == 2 + assert circuit.instruction == [ + Instruction.M(0, Axis.Z, discard=False), + Instruction.X(0), + Instruction.M(0, Axis.Z, discard=False), + Instruction.CONDINSTR({1}, (Instruction.X(1),)), + ] + result = circuit.simulate(input_state=[BasicStates.ZERO, BasicStates.ZERO], rng=np.random.default_rng(42)) + assert result.classical_measures == (0, 1) + assert result.state.isclose(Statevector(data=[BasicStates.ONE, BasicStates.ONE])) + + +def test_measured_qubit_discarded() -> None: + """Test that measured qubits cannot be used afterwards by default.""" + s = """ +include "stdgates.inc"; +qubit q; +bit b; +b = measure q; +x q; +""" + parser = OpenQASMParser() + with pytest.raises(ValueError, match=r"Qubit 0 is not an active qubit."): + parser.parse_str(s)