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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,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
Expand Down
29 changes: 27 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,36 @@ 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)
```

### 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}
Comment on lines +53 to +60

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
s = """
include "qelib1.inc";
qubit q;
rz(5*pi/4) q;
"""
parser = OpenQASMParser()
parsed = parser.parse_str(s)
print(parsed.qubits) # {'q': 0}
s = """
include "qelib1.inc";
qubit q;
rz(5*pi/4) q;
cx q, $55;
bit b;
b = measure q;
"""
parser = OpenQASMParser()
parsed = parser.parse_str(s)
print(parsed.circuit.instruction) # [RZ(0, 5pi/4), CNOT(0, 1), M(0, Axis.Z)]
print(parsed.qubits) # {'q': 0}
print(parsed.physical_qubits) # {55: 1}
print(parsed.bits) # {'b': 0}

```

## Supported Specification
Expand All @@ -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`.
Expand Down
5 changes: 2 additions & 3 deletions graphix_qasm_parser/__init__.py
Original file line number Diff line number Diff line change
@@ -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
110 changes: 97 additions & 13 deletions graphix_qasm_parser/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
FileStream,
InputStream,
ParserRuleContext,
TerminalNode,
)
from graphix import ANGLE_PI, Axis, Circuit, Instruction, rad_to_angle
from graphix.instruction import InstructionVisitor
Expand All @@ -26,7 +27,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
Expand All @@ -35,13 +36,62 @@
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]


_T = TypeVar("_T")


class OpenQASMParser:
"""Graphix OpenQASM parser."""

def parse_stream(self, stream: InputStream, *, stacklevel: int = 1) -> Circuit:
def parse_stream(self, stream: InputStream, *, stacklevel: int = 1) -> ParsedCircuit:
"""
Parse the OpenQASM circuit described in the given stream.

Expand All @@ -56,7 +106,7 @@ def parse_stream(self, stream: InputStream, *, stacklevel: int = 1) -> Circuit:

Returns
-------
Circuit
ParsedCircuit
The parsed circuit.

"""
Expand All @@ -68,9 +118,24 @@ def parse_stream(self, stream: InputStream, *, stacklevel: int = 1) -> Circuit:
tree.accept(visitor)
for msg in visitor.warnings:
warn(msg, stacklevel=stacklevel + 1)
return Circuit(visitor.width, instr=visitor.block.instructions)

def parse_str(self, s: str, *, stacklevel: int = 1) -> Circuit:
circuit = Circuit(visitor.width, instr=visitor.block.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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand that here isinstance is done just to inform the typechecker that value has the attribute index, but it can also read as if we wanted to filter the _Bit instances from the value array.
I suggested the following to improve readability:

Suggested change
bits[identifier] = tuple(value.index for value in value.values if isinstance(value, _Bit))
bits[identifier] = tuple(cast(_Bit, v).index for v in value.values)

Tests and mypy pass, but needs importing from typing import cast

else:
qubits[identifier] = tuple(value.index for value in value.values if isinstance(value, _Qubit))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
qubits[identifier] = tuple(value.index for value in value.values if isinstance(value, _Qubit))
qubits[identifier] = tuple(cast(_Qubit, v).index for v in value.values)

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, *, stacklevel: int = 1) -> ParsedCircuit:
"""
Parse the OpenQASM circuit described in the given string.

Expand All @@ -85,14 +150,14 @@ def parse_str(self, s: str, *, stacklevel: int = 1) -> Circuit:

Returns
-------
Circuit
ParsedCircuit
The parsed circuit.

"""
stream = InputStream(s)
return self.parse_stream(stream, stacklevel=stacklevel + 1)

def parse_file(self, path: Path | str, *, stacklevel: int = 1) -> Circuit:
def parse_file(self, path: Path | str, *, stacklevel: int = 1) -> ParsedCircuit:
"""
Parse the OpenQASM circuit described in the given file.

Expand All @@ -107,7 +172,7 @@ def parse_file(self, path: Path | str, *, stacklevel: int = 1) -> Circuit:

Returns
-------
Circuit
ParsedCircuit
The parsed circuit.

"""
Expand Down Expand Up @@ -684,6 +749,8 @@ class _CircuitVisitor(qasm3ParserVisitor):
env: dict[str, _Value]
warnings: list[str]
user_defined_gates: dict[str, _Gate]
declared_symbols: list[str]
physical_qubits: dict[int, _Qubit]

def __init__(self, parser: OpenQASMParser) -> None:
self.parser = parser
Expand All @@ -692,6 +759,8 @@ def __init__(self, parser: OpenQASMParser) -> None:
self.env = BASE_ENV
self.warnings = []
self.user_defined_gates = {}
self.declared_symbols = []
self.physical_qubits = {}

def expect_circuit_block(self, ctx: ParserRuleContext) -> _CircuitBlock: # type: ignore[valid-type]
if not isinstance(self.block, _CircuitBlock):
Expand Down Expand Up @@ -836,7 +905,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 @@ -875,10 +944,13 @@ def add_measurement(self, ctx: ParserRuleContext, target_bit: _Value, target_qub
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(
Expand All @@ -896,13 +968,25 @@ 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)
return value.as_qubit().index

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}"
Expand Down
Loading
Loading