From a60d6cd428e9b8adb17f960b87be80065b58b9e2 Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Mon, 19 Oct 2026 09:34:55 +0200 Subject: [PATCH 01/10] Support for physical qubit and `ParsedCircuit` structure This commit adds support for physical qubits and changes the return types of `parse_str` and `parse_file` result to `ParsedCircuit`, which contains mappings from the symbols declared in the OpenQASM document to the indices of the corresponding qubits. --- CHANGELOG.md | 4 ++ README.md | 29 ++++++++- graphix_qasm_parser/parser.py | 117 +++++++++++++++++++++++++++++++--- tests/test_parser.py | 31 ++++++--- 4 files changed, 161 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b1a142..4e7a1d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - #18: Support for user gate definitions +- #21: + - `parse_str` and `parse_file` return `ParsedCircuit` instances containing mappings from declared identifiers to bit and qubit indices. + - Support for physical qubits. + ## [0.1.1] - 2026-02-05 - #7: Parsing of `CZ` gate diff --git a/README.md b/README.md index c760447..1dfe2c2 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ s = """ rz(5*pi/4) q; """ parser = OpenQASMParser() -circuit = parser.parse_str(s) +circuit = parser.parse_str(s).circuit pattern = circuit.transpile().pattern print(pattern) ``` @@ -36,7 +36,28 @@ print(pattern) ### Parsing a file: ```python -circuit = parser.parse_file("my_circuit.qasm") +circuit = parser.parse_file("my_circuit.qasm").circuit +``` + +### Mapping declarations + +Methods `parse_str` and `parse_file` return a `ParsedCircuit` +instance. This dataclass exposes the Graphix circuit itself through +the `circuit` attribute. The other attributes are mapping from the +symbols declared in the OpenQASM document to the indices of the +corresponding qubits in the circuit. + +```python +from graphix_qasm_parser import OpenQASMParser + +s = """ + include "qelib1.inc"; + qubit q; + rz(5*pi/4) q; +""" +parser = OpenQASMParser() +parsed = parser.parse_str(s) +print(parsed.qubits) # {'q': 0} ``` ## Supported Specification @@ -47,6 +68,10 @@ circuit = parser.parse_file("my_circuit.qasm") - Qubit register arrays: `qubit[n] q`, or the old syntax `qreg q[n]`. +### [Physical qubits](https://openqasm.com/language/types.html#physical-qubits) + +Physical (hardware) qubits `$n` are supported. + ### [Classical bits](https://openqasm.com/language/types.html#classical-bits-and-registers) - Single-bit registers: `bit b`, or the old syntax `creg b`. diff --git a/graphix_qasm_parser/parser.py b/graphix_qasm_parser/parser.py index f873c05..191cec1 100644 --- a/graphix_qasm_parser/parser.py +++ b/graphix_qasm_parser/parser.py @@ -13,6 +13,7 @@ FileStream, InputStream, ParserRuleContext, + TerminalNode, ) from graphix import ANGLE_PI, Axis, Circuit, Instruction, rad_to_angle from graphix.instruction import InstructionVisitor @@ -23,7 +24,7 @@ from typing_extensions import override if TYPE_CHECKING: - from collections.abc import Collection + from collections.abc import Collection, Mapping from pathlib import Path from antlr4.token import Token @@ -32,25 +33,102 @@ from graphix.parameters import Expression, Parameter +@dataclass(frozen=True) +class ParsedCircuit: + """ + Parsed circuit. + + Attributes: + ---------- + circuit : Circuit + The circuit. + qubits : Mapping[str, int | tuple[int, ...]] + Mapping ordered by the program declaration order, mapping + quantum register identifiers to the indices of the + corresponding qubits in ``circuit``. + physical_qubits: Mapping[int, int] + Mapping ordered by the first occurrence order, mapping + physical qubits to the indices of the corresponding qubits in + ``circuit``. + bits: Mapping[str, int | tuple[int | None, ...] | None] + Mapping ordered by the program declaration order, mapping + classical register identifiers to the indices of the last + measured qubit assigned to them in ``circuit`` if any, or + ``None`` otherwise. + + Example: + ------- + >>> from graphix_qasm_parser import OpenQASMParser + >>> s = ''' + ... qubit[2] q; + ... bit[3] b; + ... cx $1, $2; + ... qubit single_q; + ... bit single_b; + ... single_b = measure $3; + ... ''' + >>> parser = OpenQASMParser() + >>> parsed = parser.parse_str(s) + >>> assert parsed.circuit.width == 6 + >>> assert parsed.qubits == {"q": (0, 1), "single_q": 4} + >>> assert parsed.bits == {"b": (None, None, None), "single_b": 5} + >>> assert parsed.physical_qubits == {1: 2, 2: 3, 3: 5} + + """ + + circuit: Circuit + qubits: Mapping[str, int | tuple[int, ...]] + physical_qubits: Mapping[int, int] + bits: Mapping[str, int | tuple[int | None, ...] | None] + + class OpenQASMParser: """Graphix OpenQASM parser.""" - def parse_stream(self, stream: InputStream) -> Circuit: - """Parse the OpenQASM circuit described in the given stream.""" + def parse_stream(self, stream: InputStream) -> ParsedCircuit: + """ + Parse the OpenQASM circuit described in the given stream. + + Parameters + ---------- + stream : InputStream + The input stream to parse. + + Returns + ------- + ParsedCircuit + The parsed circuit. + + """ lexer = qasm3Lexer(stream) tokens = CommonTokenStream(lexer) parser = qasm3Parser(tokens) tree = parser.program() # type: ignore[no-untyped-call] visitor = _CircuitVisitor(self) tree.accept(visitor) - return Circuit(visitor.width, instr=visitor.instructions) - - def parse_str(self, s: str) -> Circuit: + circuit = Circuit(visitor.width, instr=visitor.instructions) + qubits: dict[str, int | tuple[int, ...]] = {} + bits: dict[str, int | tuple[int | None, ...] | None] = {} + for identifier in visitor.declared_symbols: + value = visitor.env[identifier] + if isinstance(value, _Array): + if isinstance(value.values[0], _Bit): + bits[identifier] = tuple(value.index for value in value.values if isinstance(value, _Bit)) + else: + qubits[identifier] = tuple(value.index for value in value.values if isinstance(value, _Qubit)) + elif isinstance(value, _Bit): + bits[identifier] = value.index + elif isinstance(value, _Qubit): + qubits[identifier] = value.index + physical_qubits = {index: qubit.index for index, qubit in visitor.physical_qubits.items()} + return ParsedCircuit(circuit, qubits, physical_qubits, bits) + + def parse_str(self, s: str) -> ParsedCircuit: """Parse the OpenQASM circuit described in the given string.""" stream = InputStream(s) return self.parse_stream(stream) - def parse_file(self, path: Path | str) -> Circuit: + def parse_file(self, path: Path | str) -> ParsedCircuit: """Parse the OpenQASM circuit described in the given file.""" stream = FileStream(str(path)) return self.parse_stream(stream) @@ -570,6 +648,8 @@ class _CircuitVisitor(qasm3ParserVisitor): env: dict[str, _Value] user_defined_gates: dict[str, _Gate] inside_gate_definition: bool + declared_symbols: list[str] + physical_qubits: dict[int, _Qubit] def __init__(self, parser: OpenQASMParser) -> None: self.parser = parser @@ -582,6 +662,8 @@ def __init__(self, parser: OpenQASMParser) -> None: } self.user_defined_gates = {} self.inside_gate_definition = False + self.declared_symbols = [] + self.physical_qubits = {} def check_not_inside_gate_definition(self, ctx: ParserRuleContext) -> None: # type: ignore[valid-type] if self.inside_gate_definition: @@ -744,10 +826,13 @@ def add_measurement(self, target_bit: _Value, target_qubit: _Value) -> None: def declare_register(self, ctx: ParserRuleContext, decl_kind: _DeclKind) -> _Value: # type: ignore[valid-type] match decl_kind: case _DeclKind.Bit: - value: _Value = _Bit(ctx) + return _Bit(ctx) case _DeclKind.Qubit: - value = _Qubit(ctx, self.width) - self.width += 1 + return self.declare_qubit(ctx) + + def declare_qubit(self, ctx: ParserRuleContext) -> _Qubit: # type: ignore[valid-type] + value = _Qubit(ctx, self.width) + self.width += 1 return value def declare_registers( @@ -765,6 +850,7 @@ def declare_registers( else: value = self.declare_register(ctx, decl_kind) self.env[identifier] = value + self.declared_symbols.append(identifier) def convert_qubit_index(self, operand: qasm3Parser.GateOperandContext) -> int: value = self.evaluate_operand(operand) @@ -772,6 +858,17 @@ def convert_qubit_index(self, operand: qasm3Parser.GateOperandContext) -> int: def evaluate_operand(self, operand: qasm3Parser.GateOperandContext) -> _Value: child = operand.getChild(0) + if isinstance(child, TerminalNode): + text = child.getText() # type: ignore[attr-defined] + if text[0] != "$": + msg = f"Physical qubit expected but {text} found" + raise ValueError(text) + index = int(text[1:]) + value = self.physical_qubits.get(index) + if value is None: + value = self.declare_qubit(child) + self.physical_qubits[index] = value + return value if child.getRuleIndex() == qasm3Parser.RULE_indexedIdentifier: return self.evaluate_indexed_identifier(child) msg = f"Unknown operand: {operand}" diff --git a/tests/test_parser.py b/tests/test_parser.py index fa8d521..d6b5003 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -16,7 +16,7 @@ def test_parse_simple_circuit() -> None: rz(5*pi/4) q; """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 1 assert len(circuit.instruction) == 1 instruction = circuit.instruction[0] @@ -33,7 +33,7 @@ def test_parse_simple_circuit_old_syntax() -> None: rz(5*pi/4) q; """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 1 assert len(circuit.instruction) == 1 instruction = circuit.instruction[0] @@ -76,7 +76,7 @@ def test_parse_all_instructions() -> None: # noqa: PLR0915 gphase(pi/3); """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 3 iterator = iter(circuit.instruction) instruction = next(iterator) @@ -220,7 +220,7 @@ def test_parse_all_expressions() -> None: rz(π) q; """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 1 iterator = iter(circuit.instruction) instruction = next(iterator) @@ -277,7 +277,7 @@ def test_const_declarations() -> None: rz(alpha) q[0]; """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 1 iterator = iter(circuit.instruction) instruction = next(iterator) @@ -304,7 +304,7 @@ def test_gate_definition() -> None: cphase(π / 2) q[0], q[1]; """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 2 assert circuit.instruction == [ Instruction.RZ(0, ANGLE_PI / 4), @@ -325,7 +325,7 @@ def test_gate_without_parameters() -> None: fancyid q; """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 1 assert circuit.instruction == [Instruction.H(0), Instruction.H(0)] @@ -367,7 +367,7 @@ def test_measurement() -> None: br2 = measure qr2; """ parser = OpenQASMParser() - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 6 assert circuit.instruction == [ Instruction.M(0, Axis.Z), @@ -377,3 +377,18 @@ def test_measurement() -> None: Instruction.M(4, Axis.Z), Instruction.M(5, Axis.Z), ] + + +def test_physical_qubit() -> None: + """Test physical qubits.""" + s = """ +OPENQASM 3.0; +include "stdgates.inc"; +cx $2, $1; +h $1; +""" + parser = OpenQASMParser() + parsed = parser.parse_str(s) + assert parsed.circuit.width == 2 + assert parsed.physical_qubits == {1: 1, 2: 0} + assert parsed.circuit.instruction == [Instruction.CNOT(control=0, target=1), Instruction.H(1)] From 536ec81ebb8e8da641cde7b6887bf13bbd7792c8 Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Mon, 19 Oct 2026 00:14:48 +0200 Subject: [PATCH 02/10] Update for Python 3.15 --- .github/workflows/ci.yml | 2 +- .github/workflows/typecheck.yml | 2 +- noxfile.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c0be3e..629d4e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: fail-fast: false matrix: os: ["ubuntu-latest", "windows-latest", "macos-latest"] - python: ["3.10", "3.11", "3.12", "3.13"] + python: ["3.11", "3.12", "3.13", "3.14", "3.15"] name: "Python ${{ matrix.python }} / ${{ matrix.os }}" runs-on: ${{ matrix.os }} diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index acd3790..7beedb0 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -12,7 +12,7 @@ concurrency: cancel-in-progress: true env: - python-version: "3.13" + python-version: "3.15" jobs: mypy-pyright: diff --git a/noxfile.py b/noxfile.py index 4f5b55a..18c85fe 100644 --- a/noxfile.py +++ b/noxfile.py @@ -11,7 +11,7 @@ def install_pytest(session: Session) -> None: session.install("pytest") -@nox.session(python=["3.9", "3.10", "3.11", "3.12", "3.13"]) +@nox.session(python=["3.11", "3.12", "3.13", "3.14", "3.15"]) def tests(session: Session) -> None: """Run the test suite with minimal dependencies.""" session.install(".") From c70275b51ab6ce6dd890c6f24067b4833b054ba6 Mon Sep 17 00:00:00 2001 From: thierry-martinez Date: Tue, 27 Oct 2026 00:59:32 +0100 Subject: [PATCH 03/10] 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 223035f4d626a3a3f27f5c99efa9b980fc4427da Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Tue, 27 Oct 2026 17:55:11 +0100 Subject: [PATCH 04/10] Export ParsedCircuit --- graphix_qasm_parser/__init__.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/graphix_qasm_parser/__init__.py b/graphix_qasm_parser/__init__.py index 9e060e2..40dcbe1 100644 --- a/graphix_qasm_parser/__init__.py +++ b/graphix_qasm_parser/__init__.py @@ -1,5 +1,4 @@ """Graphix QASM parser.""" -from graphix_qasm_parser.parser import OpenQASMParser - -__all__ = ["OpenQASMParser"] +from graphix_qasm_parser.parser import OpenQASMParser as OpenQASMParser +from graphix_qasm_parser.parser import ParsedCircuit as ParsedCircuit From c5de3cbaf27f9ceae4a855d0bfe029d1c47ecef5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 13:20:48 +0000 Subject: [PATCH 05/10] 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) From 7813464097f67a0454533685baa4e85b92c7056b Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Wed, 25 Nov 2026 20:34:09 +0100 Subject: [PATCH 06/10] Target graphix master --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fbaeafd..f7e3d7d 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 = "measure-without-discard" } +graphix = { git = "https://github.com/thierry-martinez/graphix.git" } From 64cd932996d526e3e0a642793c15dc5cddd3d470 Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Wed, 25 Nov 2026 20:49:41 +0100 Subject: [PATCH 07/10] Use TeamGraphix repo --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index f7e3d7d..3672d82 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" } +graphix = { git = "https://github.com/TeamGraphix/graphix.git" } From ca866d42fd9449fe17c664cbd7ff2dae2997c276 Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Wed, 25 Nov 2026 23:26:40 +0100 Subject: [PATCH 08/10] Add PR number --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cec9a5c..15c765f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ 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`. +- #23: 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 From b14ec9b862d4bcbdc80a90ce1e079b9d7e631acc Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Wed, 25 Nov 2026 23:38:00 +0100 Subject: [PATCH 09/10] Add missing `.circuit` in test introduced in #23 --- tests/test_parser.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_parser.py b/tests/test_parser.py index 97b98db..cc7507e 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -547,7 +547,7 @@ def test_measurement_without_discard() -> None: } """ parser = OpenQASMParser(discard_measurements=False) - circuit = parser.parse_str(s) + circuit = parser.parse_str(s).circuit assert circuit.width == 2 assert circuit.instruction == [ Instruction.M(0, Axis.Z, discard=False), From 2d67d7070098c9db8f31e6b135c63ab424a4ae81 Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Thu, 26 Nov 2026 02:51:31 +0100 Subject: [PATCH 10/10] Fixed example --- graphix_qasm_parser/parser.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphix_qasm_parser/parser.py b/graphix_qasm_parser/parser.py index 3be421c..004764e 100644 --- a/graphix_qasm_parser/parser.py +++ b/graphix_qasm_parser/parser.py @@ -74,7 +74,7 @@ class ParsedCircuit: >>> parsed = parser.parse_str(s) >>> assert parsed.circuit.width == 6 >>> assert parsed.qubits == {"q": (0, 1), "single_q": 4} - >>> assert parsed.bits == {"b": (None, None, None), "single_b": 5} + >>> assert parsed.bits == {"b": (None, None, None), "single_b": 0} >>> assert parsed.physical_qubits == {1: 2, 2: 3, 3: 5} """