Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 23 additions & 4 deletions graphix_qasm_parser/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -836,7 +854,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.")
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "measure-without-discard" }
50 changes: 47 additions & 3 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -454,14 +457,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({0}, (Instruction.X(0),)),
Instruction.M(0, Axis.Z),
Instruction.CONDINSTR(
{0, 1},
(
Instruction.X(1),
Instruction.Z(1),
),
{0, 2},
),
]

Expand All @@ -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((Instruction.X(1),), {0}),
Instruction.CONDINSTR({1}, (Instruction.X(1),)),
]


Expand Down Expand Up @@ -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)
Loading