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: 1 addition & 1 deletion .github/qasm-parser-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# Keep in sync with noxfile.py
graphix-qasm-parser @ git+https://github.com/TeamGraphix/graphix-qasm-parser@refs/pull/22/head
graphix-qasm-parser @ git+https://github.com/thierry-martinez/graphix-qasm-parser@measure-without-discard
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- #474, #564: Added `FocusedPauliFlow` and `FocusedGFlow` classes to encapsulate operations specific to focused flows. Flow-finding algorithms return focused flows by construction. Having dedicated classes removes the need to dynamically recheck that a flow is focused during circuit extraction.

- #644:
- Added measurements without discard: `Circuit.m(target, axis, discard=False)` (and the new attribute `discard` of `Instruction.M`) measures a qubit and leaves it active, in the eigenstate corresponding to the outcome. The new method `Circuit.transpile_discard` returns an equivalent circuit where these measurements are rewritten into measurements with discard followed by the preparation of a fresh ancilla, and where SWAP gates restore the order of the output qubits; `Circuit.transpile` applies it automatically.
- The new method `Circuit.reorder_active_qubits_with_swaps` appends the SWAP gates that permute the active qubits.

### Fixed

- Fixed incorrect Clifford signs during circuit extraction for input vertices measured in negative Pauli X or Y bases.
Expand All @@ -36,6 +40,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- #637, #643: Decompositions no longer drop global phases, which made controlled gates produced by `insert_control` wrong. `instruction_to_jcz` now keeps the global phase of `S`, `SDG`, `T`, `TDG`, `SX`, `SXDG`, `X`, `Y` and `Z`, and `decompose_ccx` now uses `T`, `TDG` and `S` gates as in Nielsen & Chuang instead of `RZ` rotations.

- #640, #644: `transpile_swaps` no longer breaks conditional instructions whose domain refers to a qubit measured after a `SWAP`, since domains now refer to classical bits, which do not depend on qubit indices. The OpenQASM 3 exporter now terminates measurement statements with a semicolon.

- #645: Fix negative sign in circuit extraction strings

### Changed
Expand All @@ -46,6 +52,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- #626, #635: The `domain` argument of the `X` and `Z` commands is now mandatory. Previously, it defaulted to the empty set, so that `X(1)` silently had no effect; write `X(1, set())` to state this explicitly.

- #644: The domains of conditional instructions (`CONDINSTR`) now refer to classical bits instead of measured qubits: the bit `i` is the outcome of the `i`-th measurement of the circuit (see the new property `Circuit.measurement_count`). Accordingly, `simulate_instructions` no longer takes a `results` argument, and the function `instruction_to_qasm3` is replaced by the method `ToQASM3.instruction_to_qasm3`, where `ToQASM3` keeps track of the classical bit written by the next measurement.

## [0.4.1] - 2026-10-13

### Added
Expand Down
24 changes: 22 additions & 2 deletions graphix/instruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,18 +686,35 @@ class I(_KindChecker, SingleTargetInstruction):

@dataclass(repr=False)
class M(_KindChecker, BaseInstruction):
"""M circuit instruction."""
"""M circuit instruction.

Attributes
----------
target : int
Index of the measured qubit.
axis : Axis
Measurement basis.
discard : bool, optional
Keyword-only. If ``True`` (the default), the measured qubit is discarded and
cannot be used afterwards. If ``False``, the qubit remains active,
in the eigenstate corresponding to the measurement outcome.
In both cases, the outcome is written to a new classical bit,
which can be used in the domain of a subsequent conditional
instruction: the outcome of the ``i``-th measurement of a circuit
is the bit ``i``.
"""

target: int
axis: Axis
discard: bool = field(default=True, kw_only=True)
kind: ClassVar[Literal[InstructionKind.M]] = field(default=InstructionKind.M, init=False)

@override
def visit(self, visitor: InstructionVisitor, *, copy: bool = False) -> M:
target = visitor.visit_qubit(self.target)
axis = visitor.visit_axis(self.axis)
if copy:
return M(target, axis)
return M(target, axis, discard=self.discard)
self.target = target
self.axis = axis
return self
Expand Down Expand Up @@ -1198,6 +1215,9 @@ def visit(self, visitor: InstructionVisitor, *, copy: bool = False) -> GPHASE:
class CONDINSTR(_KindChecker, BaseInstruction):
"""Base class for conditional circuit instructions.

The instructions are applied when the XOR of the classical bits in ``domain`` is ``1``.
The bit ``i`` is the outcome of the ``i``-th measurement of the circuit.

Conditional measurements are not well defined since they would result in circuits with an indeterminate number of qubits. Therefore, the attribute ``instructions`` cannot contain instances of `Instruction.M`.
"""

Expand Down
29 changes: 10 additions & 19 deletions graphix/pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -1515,7 +1515,6 @@ def to_circuit(self) -> Circuit:
To extract a unitary circuit from a pattern, see :meth:`OpenGraph.to_circuit`.
"""
from graphix import Circuit # noqa: PLC0415 # Avoid circular imports
from graphix.transpiler import OutputKind # noqa: PLC0415 # Avoid circular imports

width = len(self.input_nodes)
all_nodes = [*self.input_nodes, *(cmd.node for cmd in self.__seq if cmd.kind == CommandKind.N)]
Expand All @@ -1524,6 +1523,10 @@ def to_circuit(self) -> Circuit:
node_idx.extend(all_nodes)
circuit = Circuit(width, ancillas=ancillas)
ancilla_state: State | None = None
node_bit: dict[int, int] = {} # Mapping measured nodes to classical bits

def domain_bits(domain: Iterable[int]) -> set[int]:
return {node_bit[node] for node in domain}

for cmd in self.__seq:
match cmd.kind:
Expand All @@ -1541,9 +1544,10 @@ def to_circuit(self) -> Circuit:
case CommandKind.M:
qubit = node_idx.index(cmd.node)
if cmd.s_domain:
circuit.condinstr({node_idx.index(node) for node in cmd.s_domain}, (Instruction.X(qubit),))
circuit.condinstr(domain_bits(cmd.s_domain), (Instruction.X(qubit),))
if cmd.t_domain:
circuit.condinstr({node_idx.index(node) for node in cmd.t_domain}, (Instruction.Z(qubit),))
circuit.condinstr(domain_bits(cmd.t_domain), (Instruction.Z(qubit),))
node_bit[cmd.node] = len(node_bit)

meas = cmd.measurement.to_pauli_or_none()
if meas is not None and meas.sign == Sign.PLUS:
Expand All @@ -1555,7 +1559,7 @@ def to_circuit(self) -> Circuit:
circuit.m(qubit, bloch.plane.cos)
case CommandKind.X | CommandKind.Z:
qubit = node_idx.index(cmd.node)
domain = {node_idx.index(node) for node in cmd.domain}
domain = domain_bits(cmd.domain)
if cmd.kind == CommandKind.X:
circuit.condinstr(domain, (Instruction.X(qubit),))
else:
Expand All @@ -1581,21 +1585,8 @@ def to_circuit(self) -> Circuit:
case _:
raise RuntimeError("Invalid Clifford decomposition.")

# The following code adds SWAP gates so that qubits are in the same
# order as the output nodes.

sorted_qubits = (node_idx.index(node) for node in self.output_nodes)
sorted_idx = NodeIndex()
sorted_idx.extend(sorted_qubits)

active_qubit_idx = 0
for qubit in range(circuit.nqubit):
if circuit._visitor.output_kind[qubit] == OutputKind.Qubit:
idx = sorted_idx.index(qubit)
if active_qubit_idx != idx:
circuit.swap(qubit, sorted_idx[active_qubit_idx])
sorted_idx.swap(active_qubit_idx, idx)
active_qubit_idx += 1
# Add SWAP gates so that qubits are in the same order as the output nodes.
circuit.reorder_active_qubits_with_swaps([node_idx.index(node) for node in self.output_nodes])

if ancilla_state is not None:
circuit.ancilla_state = ancilla_state
Expand Down
Loading
Loading