diff --git a/.github/qasm-parser-requirements.txt b/.github/qasm-parser-requirements.txt index 05f0904cf..a3ea41ca1 100644 --- a/.github/qasm-parser-requirements.txt +++ b/.github/qasm-parser-requirements.txt @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 286e3b8df..4203455dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. @@ -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 @@ -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 diff --git a/graphix/instruction.py b/graphix/instruction.py index 1b360434c..4b7491070 100644 --- a/graphix/instruction.py +++ b/graphix/instruction.py @@ -686,10 +686,27 @@ 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 @@ -697,7 +714,7 @@ 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 @@ -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`. """ diff --git a/graphix/pattern.py b/graphix/pattern.py index 4088bc4b8..9eec173c0 100644 --- a/graphix/pattern.py +++ b/graphix/pattern.py @@ -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)] @@ -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: @@ -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: @@ -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: @@ -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 diff --git a/graphix/qasm3_exporter.py b/graphix/qasm3_exporter.py index 9d24d75d4..7c2c5e30d 100644 --- a/graphix/qasm3_exporter.py +++ b/graphix/qasm3_exporter.py @@ -3,6 +3,7 @@ from __future__ import annotations import warnings +from dataclasses import dataclass from typing import TYPE_CHECKING, assert_never from graphix._version import version @@ -81,10 +82,11 @@ def circuit_to_qasm3_lines(circuit: Circuit, *, transpile: bool = True, stacklev yield "OPENQASM 3;" yield 'include "stdgates.inc";' yield f"qubit[{circuit.nqubit}] q;" - if any(instr.kind == InstructionKind.M for instr in circuit.instruction): - yield f"bit[{circuit.nqubit}] b;" + if circuit.measurement_count: + yield f"bit[{circuit.measurement_count}] b;" + converter = ToQASM3() for instr in circuit.instruction: - yield from instruction_to_qasm3(instr) + yield from converter.instruction_to_qasm3(instr) def qasm3_qubit(index: int) -> str: @@ -108,119 +110,138 @@ def angle_to_qasm3(angle: ParameterizedAngle) -> str: return angle_to_str(angle, output=OutputFormat.ASCII, multiplication_sign=True) -def instruction_to_qasm3(instruction: InstructionType) -> Iterable[str]: - """Get the OpenQASM3 representation of a single circuit instruction. +@dataclass +class ToQASM3: + """Converter of circuit instructions to OpenQASM 3.0. - Parameters - ---------- - instruction : Instruction - The instruction to convert. + The converter keeps track of the classical bits: the outcome of the + ``i``-th converted measurement is written to the bit ``b[i]``. + """ - Returns - ------- - str - The OpenQASM3 representation of the instruction. + measurement_count: int = 0 + """Number of measurements converted so far. - Raises - ------ - ValueError - If the instruction is not supported by OpenQASM3. + It is also the index of the classical bit written by the next + measurement, since the ``i``-th measurement writes the bit ``b[i]``. """ - match instruction.kind: - case InstructionKind.M: - if instruction.axis != Axis.Z: + + def instruction_to_qasm3(self, instruction: InstructionType) -> Iterator[str]: + """Get the OpenQASM3 representation of a single circuit instruction. + + If the instruction is a measurement, its outcome is written to the + classical bit ``self.measurement_count``, and ``self.measurement_count`` is incremented. + + Parameters + ---------- + instruction : Instruction + The instruction to convert. + + Returns + ------- + Iterator[str] + The OpenQASM3 lines that represent the instruction. + + Raises + ------ + ValueError + If the instruction is not supported by OpenQASM3. + """ + match instruction.kind: + case InstructionKind.M: + if instruction.axis != Axis.Z: + raise ValueError( + "OpenQASM3 only supports measurements on Z axis. Use `Circuit.transpile_measurements_to_z_axis` to rewrite measurements on X and Y axes, or setting `transpile=True`." + ) + yield f"b[{self.measurement_count}] = measure q[{instruction.target}];" + self.measurement_count += 1 + case InstructionKind.RX | InstructionKind.RY | InstructionKind.RZ | InstructionKind.P: + angle = angle_to_qasm3(instruction.angle) + yield qasm3_gate_call( + instruction.kind.name.lower(), args=[angle], operands=[qasm3_qubit(instruction.target)] + ) + case InstructionKind.CRX | InstructionKind.CRY | InstructionKind.CRZ | InstructionKind.CP: + angle = angle_to_qasm3(instruction.angle) + yield qasm3_gate_call( + instruction.kind.name.lower(), + args=[angle], + operands=[qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)], + ) + case InstructionKind.J: raise ValueError( - "OpenQASM3 only supports measurements on Z axis. Use `Circuit.transpile_measurements_to_z_axis` to rewrite measurements on X and Y axes, or setting `transpile=True`." + "J gates must be decomposed before QASM3 export using `Circuit.transpile_j_to_rzh`, or setting `transpile=True`." ) - yield f"b[{instruction.target}] = measure q[{instruction.target}]" - case InstructionKind.RX | InstructionKind.RY | InstructionKind.RZ | InstructionKind.P: - angle = angle_to_qasm3(instruction.angle) - yield qasm3_gate_call( - instruction.kind.name.lower(), args=[angle], operands=[qasm3_qubit(instruction.target)] - ) - case InstructionKind.CRX | InstructionKind.CRY | InstructionKind.CRZ | InstructionKind.CP: - angle = angle_to_qasm3(instruction.angle) - yield qasm3_gate_call( - instruction.kind.name.lower(), - args=[angle], - operands=[qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)], - ) - case InstructionKind.J: - raise ValueError( - "J gates must be decomposed before QASM3 export using `Circuit.transpile_j_to_rzh`, or setting `transpile=True`." - ) - case InstructionKind.CJ: - raise ValueError( - "CJ gates must be decomposed before QASM3 export using `Circuit.transpile_cj`, or setting `transpile=True`." - ) - case ( - InstructionKind.H - | InstructionKind.S - | InstructionKind.SDG - | InstructionKind.T - | InstructionKind.TDG - | InstructionKind.SX - | InstructionKind.SXDG - | InstructionKind.X - | InstructionKind.Y - | InstructionKind.Z - ): - yield qasm3_gate_call(instruction.kind.name.lower(), [qasm3_qubit(instruction.target)]) - case InstructionKind.I: - yield qasm3_gate_call("id", [qasm3_qubit(instruction.target)]) - case InstructionKind.CNOT: - yield qasm3_gate_call("cx", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) - case InstructionKind.CY: - yield qasm3_gate_call("cy", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) - case InstructionKind.CH: - yield qasm3_gate_call("ch", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) - case InstructionKind.SWAP: - yield qasm3_gate_call("swap", [qasm3_qubit(instruction.targets[i]) for i in (0, 1)]) - case InstructionKind.CSWAP: - yield qasm3_gate_call( - "cswap", - [qasm3_qubit(qubit) for qubit in [instruction.control, *[instruction.targets[i] for i in (0, 1)]]], - ) - case InstructionKind.CZ: - yield qasm3_gate_call("cz", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) - case InstructionKind.RZZ: - raise ValueError( - "RZZ gates must be decomposed before QASM3 export using `Circuit.transpile_rzz`, or setting `transpile=True`." - ) - case InstructionKind.CCX: - yield qasm3_gate_call( - "ccx", - [ - qasm3_qubit(instruction.controls[0]), - qasm3_qubit(instruction.controls[1]), - qasm3_qubit(instruction.target), - ], - ) - case InstructionKind.U: - theta = angle_to_qasm3(instruction.theta) - phi = angle_to_qasm3(instruction.phi) - lambda_ = angle_to_qasm3(instruction.lambda_) - yield qasm3_gate_call("U", args=[theta, phi, lambda_], operands=[qasm3_qubit(instruction.target)]) - case InstructionKind.CU: - theta = angle_to_qasm3(instruction.theta) - phi = angle_to_qasm3(instruction.phi) - lambda_ = angle_to_qasm3(instruction.lambda_) - gamma = angle_to_qasm3(instruction.gamma) - yield qasm3_gate_call( - "cu", - args=[theta, phi, lambda_, gamma], - operands=[qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)], - ) - case InstructionKind.GPHASE: - yield qasm3_gate_call("gphase", operands=[], args=[angle_to_qasm3(instruction.angle)]) - case InstructionKind.CONDINSTR: - yield from domain_to_qasm3_lines( - instruction.domain, - (line for instr in instruction.instructions for line in instruction_to_qasm3(instr)), - _circuit_bit_to_qasm3, - ) - case _: - assert_never(instruction.kind) + case InstructionKind.CJ: + raise ValueError( + "CJ gates must be decomposed before QASM3 export using `Circuit.transpile_cj`, or setting `transpile=True`." + ) + case ( + InstructionKind.H + | InstructionKind.S + | InstructionKind.SDG + | InstructionKind.T + | InstructionKind.TDG + | InstructionKind.SX + | InstructionKind.SXDG + | InstructionKind.X + | InstructionKind.Y + | InstructionKind.Z + ): + yield qasm3_gate_call(instruction.kind.name.lower(), [qasm3_qubit(instruction.target)]) + case InstructionKind.I: + yield qasm3_gate_call("id", [qasm3_qubit(instruction.target)]) + case InstructionKind.CNOT: + yield qasm3_gate_call("cx", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) + case InstructionKind.CY: + yield qasm3_gate_call("cy", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) + case InstructionKind.CH: + yield qasm3_gate_call("ch", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) + case InstructionKind.SWAP: + yield qasm3_gate_call("swap", [qasm3_qubit(instruction.targets[i]) for i in (0, 1)]) + case InstructionKind.CSWAP: + yield qasm3_gate_call( + "cswap", + [qasm3_qubit(qubit) for qubit in [instruction.control, *[instruction.targets[i] for i in (0, 1)]]], + ) + case InstructionKind.CZ: + yield qasm3_gate_call("cz", [qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)]) + case InstructionKind.RZZ: + raise ValueError( + "RZZ gates must be decomposed before QASM3 export using `Circuit.transpile_rzz`, or setting `transpile=True`." + ) + case InstructionKind.CCX: + yield qasm3_gate_call( + "ccx", + [ + qasm3_qubit(instruction.controls[0]), + qasm3_qubit(instruction.controls[1]), + qasm3_qubit(instruction.target), + ], + ) + case InstructionKind.U: + theta = angle_to_qasm3(instruction.theta) + phi = angle_to_qasm3(instruction.phi) + lambda_ = angle_to_qasm3(instruction.lambda_) + yield qasm3_gate_call("U", args=[theta, phi, lambda_], operands=[qasm3_qubit(instruction.target)]) + case InstructionKind.CU: + theta = angle_to_qasm3(instruction.theta) + phi = angle_to_qasm3(instruction.phi) + lambda_ = angle_to_qasm3(instruction.lambda_) + gamma = angle_to_qasm3(instruction.gamma) + yield qasm3_gate_call( + "cu", + args=[theta, phi, lambda_, gamma], + operands=[qasm3_qubit(instruction.control), qasm3_qubit(instruction.target)], + ) + case InstructionKind.GPHASE: + yield qasm3_gate_call("gphase", operands=[], args=[angle_to_qasm3(instruction.angle)]) + case InstructionKind.CONDINSTR: + yield from domain_to_qasm3_lines( + instruction.domain, + (line for instr in instruction.instructions for line in self.instruction_to_qasm3(instr)), + _circuit_bit_to_qasm3, + ) + case _: + assert_never(instruction.kind) def pattern_to_qasm3(pattern: Pattern, input_state: dict[int, State] | State = BasicStates.PLUS) -> str: @@ -365,5 +386,5 @@ def _pattern_node_to_qasm3(node: int) -> str: return f"c{node}" -def _circuit_bit_to_qasm3(node: int) -> str: - return f"b[{node}]" +def _circuit_bit_to_qasm3(bit: int) -> str: + return f"b[{bit}]" diff --git a/graphix/repr_mixins.py b/graphix/repr_mixins.py index 33bf88943..8e9a2052a 100644 --- a/graphix/repr_mixins.py +++ b/graphix/repr_mixins.py @@ -38,7 +38,7 @@ def __repr__(self: DataclassInstance) -> str: continue custom_repr = field.metadata.get("repr") value_str = custom_repr(value) if custom_repr else repr(value) - if saw_omitted: + if saw_omitted or field.kw_only is True: arguments.append(f"{field.name}={value_str}") else: arguments.append(value_str) diff --git a/graphix/transpiler.py b/graphix/transpiler.py index c33b2946b..e28ace656 100644 --- a/graphix/transpiler.py +++ b/graphix/transpiler.py @@ -27,7 +27,8 @@ from graphix.ops import Ops from graphix.parameter import InplaceParameterizable from graphix.pattern import Pattern -from graphix.sim.base_backend import DenseStateBackend +from graphix.pauli import Pauli +from graphix.sim.base_backend import DenseStateBackend, NodeIndex from graphix.sim.density_matrix import DensityMatrixBackend from graphix.sim.statevec import Statevector, StatevectorBackend from graphix.states import BasicStates @@ -110,9 +111,12 @@ class _InstructionValidatorVisitor(InstructionVisitor): """Instruction visitor that validates operations on active qubits.""" output_kind: dict[int, OutputKind] + measurement_count: int + """Number of measurements so far: the next measurement writes the bit of this index.""" def __init__(self, nqubit: int) -> None: self.output_kind = dict.fromkeys(range(nqubit), OutputKind.Qubit) + self.measurement_count = 0 @override def visit_qubit(self, qubit: int) -> int: @@ -123,8 +127,8 @@ def visit_qubit(self, qubit: int) -> int: @override def visit_domain(self, domain: set[int]) -> set[int]: for bit in domain: - if self.output_kind.get(bit) is not OutputKind.Bit: - raise ValueError(f"Qubit {bit} is not a measured qubit.") + if not 0 <= bit < self.measurement_count: + raise ValueError(f"Bit {bit} has not been measured.") return domain @@ -135,6 +139,11 @@ class Circuit(InplaceParameterizable): measurement-based quantum computing (MBQC) measurement patterns and state vector simulation. + Each measurement writes its outcome to a classical bit: the outcome + of the first measurement of the circuit is bit 0, the outcome of the + second measurement is bit 1, etc. The domains of conditional + instructions refer to these bits. + Attributes ---------- width : int @@ -200,11 +209,18 @@ def nqubit(self) -> int: """ return self.width + self.ancillas + @property + def measurement_count(self) -> int: + """Number of measurements in the circuit, that is to say, the number of classical bits.""" + return self._visitor.measurement_count + def add(self, instr: InstructionType) -> Self: """Add an instruction to the circuit.""" self.instruction.append(instr.visit(self._visitor)) if instr.kind == InstructionKind.M: - self._visitor.output_kind[instr.target] = OutputKind.Bit + self._visitor.measurement_count += 1 + if instr.discard: + self._visitor.output_kind[instr.target] = OutputKind.Bit return self def extend(self, instrs: Iterable[InstructionType]) -> Self: @@ -466,10 +482,11 @@ def i(self, target: int) -> Self: """ return self.add(Instruction.I(target=target)) - def m(self, target: int, axis: Axis) -> Self: + def m(self, target: int, axis: Axis, *, discard: bool = True) -> Self: """Measure a quantum qubit. - The measured qubit cannot be used afterwards. + If ``discard`` is ``True`` (the default), the measured qubit cannot be used afterwards. + The outcome is written to the next classical bit (see :class:`Circuit`). See :class:`~graphix.instruction.M` for more information. @@ -479,8 +496,10 @@ def m(self, target: int, axis: Axis) -> Self: target qubit axis : Axis measurement basis + discard : bool, optional + If ``False``, the qubit remains active after the measurement, in the eigenstate corresponding to the outcome. """ - return self.add(Instruction.M(target=target, axis=axis)) + return self.add(Instruction.M(target=target, axis=axis, discard=discard)) def sdg(self, target: int) -> Self: """Apply an SDG gate. @@ -782,13 +801,14 @@ def condinstr(self, domain: AbstractSet[int], instrs: Iterable[InstructionTypeWi Parameters ---------- domain : AbstractSet[int] - Indices of measured qubits whose outcomes determine the condition. + Indices of the classical bits whose values determine the condition + (the bit ``i`` is the outcome of the ``i``-th measurement of the circuit). instrs : Iterable[InstructionTypeWithoutM] Sequence of instructions to apply conditionally. Notes ----- - .. The instruction sequence is applied when the XOR of the measurement outcomes of the qubits in ``domain`` evaluates to ``1``. + .. The instruction sequence is applied when the XOR of the bits in ``domain`` evaluates to ``1``. .. Conditional measurements are not well defined since they would result in circuits with an indeterminate number of qubits. Therefore, the parameter ``instrs`` cannot contain instances of `Instruction.M`. This is statically ensured by the type checker. """ @@ -804,7 +824,18 @@ def transpile_to_causalflow(self) -> TranspiledFlow: Returns ------- the result of the transpilation: a causal flow and classical outputs. + + Raises + ------ + NotImplementedError + If the circuit contains measurements without discard. These + measurements can be removed with :meth:`transpile_discard`, which + :meth:`transpile` calls automatically. """ + if _has_measurements_without_discard(self): + raise NotImplementedError( + "Direct transpilation of measurements without discard is not supported. First remove them with `transpile_discard`." + ) n_nodes = self.nqubit indices: list[int | None] = list(range(n_nodes)) measurements: dict[int, BlochMeasurement] = {} @@ -813,11 +844,7 @@ def transpile_to_causalflow(self) -> TranspiledFlow: graph: nx.Graph[int] = nx.empty_graph(n_nodes) x_corrections: dict[int, set[int]] = {} - circuit = ( - self.transpile_ancilla_state(BasicStates.PLUS) - if self.ancillas and self.ancilla_state is not BasicStates.PLUS - else self - ) + circuit = self.transpile_ancilla_state(BasicStates.PLUS) if self.ancillas else self circuit = ( circuit.transpile_condinstr() @@ -893,6 +920,8 @@ def transpile(self, *, transpile_swaps: bool = True) -> TranspiledPattern: TranspiledPattern The result of the transpilation: a pattern and classical outputs. """ + if _has_measurements_without_discard(self): + return self.transpile_discard().transpile(transpile_swaps=transpile_swaps) if not transpile_swaps: return self.transpile_to_causalflow().to_pattern() swap = _transpile_swaps(self, copy=True) @@ -975,10 +1004,17 @@ def simulate( _backend.add_nodes(range(self.width, self.nqubit), self.ancilla_state) classical_measures: list[Outcome] = [] - results: dict[int, Outcome] = {} # Mimics `DefaultMeasureMethod.results` - # Modifies in place `_backend`, `results`, `classical_measures` - simulate_instructions(self.instruction, _backend, rng, results, classical_measures, stacklevel=stacklevel + 1) + # Modifies in place `_backend` and `classical_measures` + simulate_instructions(self.instruction, _backend, rng, classical_measures, stacklevel=stacklevel + 1) + # `backend.measure` removes the measured node from `node_index`, and a qubit + # measured without discard is then re-added by `add_nodes` at the *end* of + # `node_index`. The state is therefore no longer ordered by qubit index: + # permute it back so that the returned state is ordered as if the qubit had + # never been measured. This is a no-op for circuits that only discard. + output_nodes = sorted(_backend.node_index) + if list(_backend.node_index) != output_nodes: + _backend.finalize(output_nodes) return SimulateResult(_backend.state, tuple(classical_measures)) def visit(self, visitor: InstructionVisitor, *, copy: bool = False) -> Circuit: @@ -1001,8 +1037,7 @@ def visit(self, visitor: InstructionVisitor, *, copy: bool = False) -> Circuit: """ if copy: result = Circuit(width=self.width, ancillas=self.ancillas, ancilla_state=self.ancilla_state) - for instr in self.instruction: - result.instruction.append(instr.visit(visitor, copy=True)) + result.extend(instr.visit(visitor, copy=True) for instr in self.instruction) return result for instr in self.instruction: instr.visit(visitor, copy=False) @@ -1078,10 +1113,14 @@ def transpile_to_qasm_gates(self) -> Circuit: match instr.axis: case Axis.X: new_circuit.h(instr.target) - new_circuit.m(instr.target, Axis.Z) + new_circuit.m(instr.target, Axis.Z, discard=instr.discard) + if not instr.discard: + new_circuit.h(instr.target) case Axis.Y: new_circuit.rx(instr.target, ANGLE_PI / 2) - new_circuit.m(instr.target, Axis.Z) + new_circuit.m(instr.target, Axis.Z, discard=instr.discard) + if not instr.discard: + new_circuit.rx(instr.target, -ANGLE_PI / 2) case Axis.Z: new_circuit.add(instr) case _: @@ -1102,12 +1141,15 @@ def transpile_ancilla_state(self, target_state: PlanarState = BasicStates.PLUS) ------- Circuit Equivalent circuit with the required initialization gates prepended. + If `target_state` equals `self.ancilla_state`, then `self` is returned unchanged. Raises ------ NotImplementedError If ``target_state`` is not supported. """ + if self.ancilla_state == target_state: + return self new_circuit = Circuit(self.width, ancillas=self.ancillas, ancilla_state=target_state) match target_state: case BasicStates.PLUS: @@ -1122,7 +1164,7 @@ def transpile_ancilla_state(self, target_state: PlanarState = BasicStates.PLUS) for qubit in range(self.width, self.nqubit): for instr in initialization: new_circuit.add(instr(qubit)) - new_circuit.instruction += self.instruction + new_circuit.extend(self.instruction) return new_circuit def transpile_condinstr(self) -> Circuit: @@ -1138,8 +1180,8 @@ def transpile_condinstr(self) -> Circuit: Notes ----- - For each qubit that appears in the domain of a conditional instruction, - its measurement is transpiled to a :math:`Z`-axis measurement. If the original + For each bit that appears in the domain of a conditional instruction, + the measurement of the corresponding qubit is transpiled to a :math:`Z`-axis measurement. If the original measurement is in the :math:`X` or :math:`Y` basis, the corresponding basis rotation is inserted before the controlled instruction: .. :math:`X`-axis measurements are preceded by a Hadamard gate. @@ -1151,25 +1193,31 @@ def transpile_condinstr(self) -> Circuit: Non-conditional instructions are preserved unchanged. All measurements are deferred to the end of the circuit, even if they do not appear in any - conditional instruction. + conditional instruction. Therefore, measurements without discard are not supported: they can + be removed first with :meth:`transpile_discard`. """ + if _has_measurements_without_discard(self): + raise NotImplementedError( + "Transpilation of conditional instructions with measurements without discard is not supported. First remove them with `transpile_discard`." + ) circuit = Circuit(width=self.width, ancillas=self.ancillas, ancilla_state=self.ancilla_state) - measurements: dict[int, Instruction.M] = {} + # Indexed by classical bit. Measurements are deferred in the same order, so bits are preserved. + measurements: list[Instruction.M] = [] for instr in self.instruction: match instr.kind: case InstructionKind.M: - measurements[instr.target] = instr + measurements.append(instr) case InstructionKind.CONDINSTR: if instr.domain: - domain_list = list(instr.domain) - for cbit in domain_list: + # Every qubit is measured at most once, since measurements discard qubits. + domain_list = [measurements[cbit].target for cbit in instr.domain] + for cbit in instr.domain: meas_instr = measurements[cbit] - assert cbit == meas_instr.target if meas_instr.axis == Axis.X: - circuit.h(cbit) + circuit.h(meas_instr.target) elif meas_instr.axis == Axis.Y: - circuit.rx(cbit, ANGLE_PI / 2) - measurements[cbit] = Instruction.M(cbit, Axis.Z) # Record updated measurement + circuit.rx(meas_instr.target, ANGLE_PI / 2) + measurements[cbit] = Instruction.M(meas_instr.target, Axis.Z) # Record updated measurement cnot_instr = [ Instruction.CNOT(control=control, target=target) for control, target in itertools.pairwise(domain_list) @@ -1180,11 +1228,102 @@ def transpile_condinstr(self) -> Circuit: case _: circuit.add(instr) - for instr in measurements.values(): - circuit.add(instr) + circuit.extend(measurements) return circuit + def transpile_discard(self) -> Circuit: + r"""Return an equivalent circuit where all measurements discard the measured qubit. + + Each measurement without discard of a qubit :math:`q` along an axis is + replaced by the following sequence: :math:`q` is measured along the + axis and discarded, then a new ancilla :math:`a` is prepared, with + conditional instructions, in the eigenstate of the axis that + corresponds to the outcome, and :math:`a` replaces :math:`q` in the + tail of the circuit. The measurements keep their order, so the + classical bits, and therefore the domains of conditional instructions, + are unchanged. Finally, SWAP gates are appended (with + :meth:`reorder_active_qubits_with_swaps`) so that the output qubits + are in the same order as in the original circuit: the returned + circuit has the same semantics as the original one. + + The new ancillas are initialized in :math:`|+\rangle`: if the ancillas + of the original circuit are initialized in another state, they are + transpiled to :math:`|+\rangle` first, with :meth:`transpile_ancilla_state`. + + The original circuit remains unchanged. + + Returns + ------- + Circuit + The transpiled circuit. + + Raises + ------ + NotImplementedError + If the circuit contains measurements without discard and its ancillas + are not initialized in a basic state. + """ + nmeasurements = sum(1 for instr in self.instruction if instr.kind == InstructionKind.M and not instr.discard) + visitor = _TranspileDiscardVisitor(self.nqubit) + if nmeasurements == 0: + return self.visit(visitor, copy=True) + source = self.transpile_ancilla_state(BasicStates.PLUS) if self.ancillas else self + new_circuit = Circuit(self.width, ancillas=self.ancillas + nmeasurements, ancilla_state=BasicStates.PLUS) + ancilla = self.nqubit + measurement_count = 0 + for instr in source.instruction: + if instr.kind == InstructionKind.M: + new_circuit.m(visitor.visit_qubit(instr.target), instr.axis) + if not instr.discard: + new_circuit.extend(_prepare_eigenstate(ancilla, instr.axis, measurement_count)) + visitor.qubits[instr.target] = ancilla + ancilla += 1 + measurement_count += 1 + else: + new_circuit.add(instr.visit(visitor, copy=True)) + new_circuit.reorder_active_qubits_with_swaps([visitor.qubits[qubit] for qubit in self._active_qubits()]) + return new_circuit + + def _active_qubits(self) -> list[int]: + """Return the qubits that have not been discarded by a measurement, in increasing order.""" + return [qubit for qubit in range(self.nqubit) if self._visitor.output_kind[qubit] == OutputKind.Qubit] + + def reorder_active_qubits_with_swaps(self, qubits: Sequence[int]) -> Circuit: + """Append SWAP gates to reorder the active qubits. + + After the SWAP gates, for every index ``i``, the ``i``-th active + qubit (that is, the ``i``-th qubit, in increasing order, that has + not been discarded by a measurement) holds the state that the qubit + ``qubits[i]`` holds before the SWAP gates. + + Parameters + ---------- + qubits : Sequence[int] + A permutation of the active qubits. + + Returns + ------- + Circuit + The circuit itself, with the SWAP gates appended. + + Raises + ------ + ValueError + If ``qubits`` is not a permutation of the active qubits. + """ + active_qubits = self._active_qubits() + if sorted(qubits) != active_qubits: + raise ValueError(f"{list(qubits)} is not a permutation of the active qubits {active_qubits}.") + sorted_idx = NodeIndex() + sorted_idx.extend(qubits) + for active_qubit_idx, qubit in enumerate(active_qubits): + idx = sorted_idx.index(qubit) + if active_qubit_idx != idx: + self.swap(qubit, sorted_idx[active_qubit_idx]) + sorted_idx.swap(active_qubit_idx, idx) + return self + def decompose_rzz(instr: Instruction.RZZ) -> Iterator[Instruction.CNOT | Instruction.RZ]: """Yield a decomposition of RZZ(α) gate as CNOT(control, target)·Rz(target, α)·CNOT(control, target). @@ -1867,13 +2006,16 @@ def transpile_swaps(circuit: Circuit, *, copy: bool = False) -> TranspileSwapsRe visitor.outputs[u], visitor.outputs[v] = visitor.outputs[v], visitor.outputs[u] elif instr.kind == InstructionKind.M: old_target = instr.target + discard = instr.discard new_circuit.add(instr.visit(visitor, copy=copy)) - visitor.outputs[old_target] = OutputIndex(OutputKind.Bit, measurement_index) + if discard: + visitor.outputs[old_target] = OutputIndex(OutputKind.Bit, measurement_index) measurement_index += 1 else: new_circuit.add(instr.visit(visitor, copy=copy)) if not copy: circuit.instruction = new_circuit.instruction + circuit._visitor = new_circuit._visitor new_circuit = circuit return TranspileSwapsResult(new_circuit, tuple(visitor.outputs)) @@ -1883,6 +2025,39 @@ def transpile_swaps(circuit: Circuit, *, copy: bool = False) -> TranspileSwapsRe _transpile_swaps = transpile_swaps +class _TranspileDiscardVisitor(InstructionVisitor): + """Renumber the qubits of the tail of a circuit.""" + + qubits: list[int] + """Index of the qubit that currently holds each qubit of the original circuit.""" + + def __init__(self, nqubit: int) -> None: + self.qubits = list(range(nqubit)) + + @override + def visit_qubit(self, qubit: int) -> int: + return self.qubits[qubit] + + +def _has_measurements_without_discard(circuit: Circuit) -> bool: + return any(instr.kind == InstructionKind.M and not instr.discard for instr in circuit.instruction) + + +def _prepare_eigenstate(qubit: int, axis: Axis, bit: int) -> Iterator[InstructionType]: + r"""Yield instructions that prepare ``qubit``, initially in :math:`|+\rangle`, in the eigenstate of ``axis`` for the outcome ``bit``.""" + match axis: + case Axis.X: + yield Instruction.CONDINSTR({bit}, (Instruction.Z(qubit),)) + case Axis.Y: + yield Instruction.S(qubit) + yield Instruction.CONDINSTR({bit}, (Instruction.Z(qubit),)) + case Axis.Z: + yield Instruction.H(qubit) + yield Instruction.CONDINSTR({bit}, (Instruction.X(qubit),)) + case _: + assert_never(axis) + + @overload def _initialize_backend( backend: StatevectorBackend | Literal["statevector"], @@ -1950,7 +2125,6 @@ def simulate_instructions( instructions: Iterable[InstructionType], backend: _BuiltinDenseStateBackend | DenseStateBackend[_DenseStateT], rng: Generator | None, - results: dict[int, Outcome], classical_outputs: list[Outcome], *, stacklevel: int = 1, @@ -1965,10 +2139,8 @@ def simulate_instructions( Backend containing the quantum state. rng : Generator or None Random number generator used for stochastic measurements. If ``None``, the backend's default random number generation behavior is used. - results : dict[int, Outcome] - Mapping from measured qubit indices to their measurement outcomes. This mapping is updated in place as measurement instructions are simulated. classical_outputs : list[Outcome] - List of measurement outcomes. This list is updated in place and retained for backwards compatibility. + List of measurement outcomes, indexed by classical bit. This list is updated in place as measurement instructions are simulated. stacklevel : int, default=1 Stack level used when reporting warnings generated during measurement. """ @@ -1981,7 +2153,7 @@ def evolve(op: Matrix, qargs: Iterable[int]) -> None: # Mimics `MeasureMethod.check_domain` def check_domain(domain: set[int]) -> bool: - return sum(results[j] for j in domain) % 2 == 1 + return sum(classical_outputs[j] for j in domain) % 2 == 1 for instr in instructions: match instr.kind: @@ -2052,16 +2224,17 @@ def check_domain(domain: set[int]) -> bool: evolve(Ops.CSWAP, [instr.control, instr.targets[0], instr.targets[1]]) case InstructionKind.M: result = backend.measure(instr.target, PauliMeasurement(instr.axis), rng=rng, stacklevel=stacklevel + 1) - # We keep `classical_outputs` for backwards compatibility but ``results`` contains the same information classical_outputs.append(result) - results[instr.target] = result + if not instr.discard: + # The measured qubit is re-added in the post-measurement state. + backend.add_nodes([instr.target], Pauli.from_axis(instr.axis).eigenstate(result)) case InstructionKind.GPHASE: # Global phase is currently ignored pass case InstructionKind.CONDINSTR: if check_domain(instr.domain): simulate_instructions( - instr.instructions, backend, rng, results, classical_outputs, stacklevel=stacklevel + 1 + instr.instructions, backend, rng, classical_outputs, stacklevel=stacklevel + 1 ) case _: assert_never(instr.kind) diff --git a/noxfile.py b/noxfile.py index 7c60227e5..4af856b72 100644 --- a/noxfile.py +++ b/noxfile.py @@ -97,8 +97,8 @@ class ReverseDependency: "graphix-stim-backend": ReverseDependency("https://github.com/TeamGraphix/graphix-stim-backend"), "graphix-qasm-parser": ReverseDependency( # Keep in sync with .github/qasm-parser-requirements.txt - "https://github.com/TeamGraphix/graphix-qasm-parser", - branch="refs/pull/22/head", + "https://github.com/thierry-martinez/graphix-qasm-parser", + branch="measure-without-discard", ), "graphix-ibmq": ReverseDependency( "https://github.com/TeamGraphix/graphix-ibmq", diff --git a/tests/test_qasm3_exporter_to_graphix_parser.py b/tests/test_qasm3_exporter_to_graphix_parser.py index 1e4033310..64a81dd44 100644 --- a/tests/test_qasm3_exporter_to_graphix_parser.py +++ b/tests/test_qasm3_exporter_to_graphix_parser.py @@ -125,11 +125,11 @@ def test_condinstr_to_qasm3() -> None: 3, instr=[ Instruction.M(2, Axis.Z), - Instruction.CONDINSTR({2}, (Instruction.X(0),)), + Instruction.CONDINSTR({0}, (Instruction.X(0),)), Instruction.M(0, Axis.Z), Instruction.M(3, Axis.X), Instruction.CONDINSTR( - {0, 2, 3}, + {0, 1, 2}, ( Instruction.X(1), Instruction.Z(1), @@ -141,6 +141,16 @@ def test_condinstr_to_qasm3() -> None: check_round_trip(circuit) +def test_measurement_without_discard_to_qasm3() -> None: + circuit = Circuit(2) + circuit.m(0, Axis.Z, discard=False).x(0).m(0, Axis.Z, discard=False) + circuit.condinstr({0, 1}, [Instruction.X(1)]) + qasm = circuit_to_qasm3(circuit) + parser = OpenQASMParser(discard_measurements=False) + parsed_circuit = parser.parse_str(qasm) + assert parsed_circuit.instruction == circuit.instruction + + @pytest.mark.parametrize( "ancilla_state", [ diff --git a/tests/test_transpiler.py b/tests/test_transpiler.py index 8c4473117..6d7a3d954 100644 --- a/tests/test_transpiler.py +++ b/tests/test_transpiler.py @@ -10,8 +10,9 @@ from graphix import Instruction, instruction from graphix.branch_selector import ConstBranchSelector, FixedBranchSelector from graphix.fundamentals import ANGLE_PI, Axis, Plane, Sign -from graphix.instruction import I, InstructionKind +from graphix.instruction import I, InstructionKind, InstructionVisitor from graphix.ops import Ops, controlled +from graphix.pauli import Pauli from graphix.random_objects import rand_circuit, rand_gate, rand_state_vector from graphix.sim.density_matrix import DensityMatrix from graphix.sim.statevec import Statevector, StatevectorBackend @@ -84,9 +85,9 @@ def test_condinstr_rnd(self, fx_rng: Generator, axis: Axis, outcome: Outcome) -> instr: list[InstructionType] = [ Instruction.M(3, axis), - Instruction.CONDINSTR({3}, instr_1), + Instruction.CONDINSTR({0}, instr_1), Instruction.M(4, axis), - Instruction.CONDINSTR({3, 4}, instr_2), + Instruction.CONDINSTR({0, 1}, instr_2), ] circuit_ref = Circuit(5, instr) @@ -486,8 +487,8 @@ def test_add_extend(self) -> None: instruction.CONDINSTR({0}, (instruction.H(1), instruction.X(2), instruction.SWAP((1, 4)))), r"Qubit 4 is not an active qubit.", ), - (instruction.CONDINSTR({0, 1}, (instruction.RX(2, 0.2),)), r"Qubit 1 is not a measured qubit."), - (instruction.CONDINSTR({0, 4}, (instruction.J(1, 0.2),)), r"Qubit 4 is not a measured qubit."), + (instruction.CONDINSTR({0, 1}, (instruction.RX(2, 0.2),)), r"Bit 1 has not been measured."), + (instruction.CONDINSTR({0, 4}, (instruction.J(1, 0.2),)), r"Bit 4 has not been measured."), ], ) def test_wrong_qubits(self, instruction: InstructionType, msg: str) -> None: @@ -655,7 +656,7 @@ def test_transpile_condinstr( instr: list[InstructionType] = [ Instruction.M(3, axis), - Instruction.CONDINSTR({3}, (test_case.instruction(fx_rng),)), + Instruction.CONDINSTR({0}, (test_case.instruction(fx_rng),)), ] circuit_ref = Circuit(4, instr) @@ -690,9 +691,9 @@ def test_transpile_condinstr_rnd(self, fx_rng: Generator, axis: Axis, outcome: O instr: list[InstructionType] = [ Instruction.M(3, axis), - Instruction.CONDINSTR({3}, instr_1), + Instruction.CONDINSTR({0}, instr_1), Instruction.M(4, axis), - Instruction.CONDINSTR({3, 4}, instr_2), + Instruction.CONDINSTR({0, 1}, instr_2), ] circuit_ref = Circuit(5, instr) @@ -755,7 +756,7 @@ def test_chained_instructions(self) -> None: .cswap(0, 1, 2) .gphase(angle) .m(3, axis) - .condinstr({3}, [Instruction.H(0), Instruction.X(0)]) + .condinstr({0}, [Instruction.H(0), Instruction.X(0)]) ) qc_ref = Circuit(3, ancillas=1, ancilla_state=BasicStates.MINUS) qc_ref.extend( @@ -795,7 +796,7 @@ def test_chained_instructions(self) -> None: Instruction.CSWAP(control=0, targets=(1, 2)), Instruction.GPHASE(angle), Instruction.M(3, axis), - Instruction.CONDINSTR({3}, (Instruction.H(0), Instruction.X(0))), + Instruction.CONDINSTR({0}, (Instruction.H(0), Instruction.X(0))), ] ) assert qc_ref == qc_test @@ -970,7 +971,7 @@ def test_insert_control_condinstr( ) -> None: meas = Instruction.M(3, axis) - instr = [Instruction.CONDINSTR({3}, (test_case.instruction(fx_rng),))] + instr = [Instruction.CONDINSTR({0}, (test_case.instruction(fx_rng),))] instr_ref: list[Instruction.M | Instruction.CONDINSTR] = ( [meas, *instr] if ancilla_state == BasicStates.ONE else [meas] @@ -1113,3 +1114,203 @@ def _without_m(instrs: Iterable[InstructionType]) -> Iterator[InstructionTypeWit for instr in instrs: assert instr.kind != InstructionKind.M yield instr + + +def circuit_with_measurements_without_discard(axis: Axis, ancilla_state: State = BasicStates.PLUS) -> Circuit: + circuit = Circuit(3, ancillas=1, ancilla_state=ancilla_state) + circuit.h(0).cnot(0, 1).ry(2, 0.3).cnot(3, 2) + circuit.m(1, axis, discard=False) + circuit.cnot(1, 2).rx(1, 0.4).swap(0, 1) + circuit.condinstr({0}, [Instruction.X(2)]) + # With the swap, qubit 0 holds the former qubit 1, which is measured again. + circuit.m(0, axis, discard=False) + circuit.condinstr({1}, [Instruction.Z(3)]) + circuit.rz(0, 0.7).m(2, Axis.Z) + return circuit + + +@pytest.mark.parametrize("axis", [Axis.X, Axis.Y, Axis.Z]) +@pytest.mark.parametrize("outcome", [0, 1]) +def test_measure_without_discard(fx_rng: Generator, axis: Axis, outcome: Outcome) -> None: + circuit = Circuit(1).m(0, axis, discard=False) + result = circuit.simulate( + input_state=rand_state_vector(1, rng=fx_rng), branch_selector=ConstBranchSelector(outcome), rng=fx_rng + ) + assert result.classical_measures == (outcome,) + eigenstate = Statevector(data=Pauli.from_axis(axis).eigenstate(outcome)) + assert result.state.isclose(eigenstate) + + +def test_measure_without_discard_validation() -> None: + circuit = Circuit(2).m(0, Axis.Z, discard=False) + # The measured qubit can still be used, and its outcome can be used in domains. + circuit.h(0).condinstr({0}, [Instruction.X(1)]) + circuit.m(0, Axis.Z) + with pytest.raises(ValueError, match=r"Qubit 0 is not an active qubit."): + circuit.h(0) + assert repr(Instruction.M(0, Axis.X)) == "M(0, Axis.X)" + assert repr(Instruction.M(0, Axis.X, discard=False)) == "M(0, Axis.X, discard=False)" + + +@pytest.mark.parametrize(("domain", "output"), [({0}, BasicStates.ZERO), ({1}, BasicStates.ONE)]) +def test_domain_of_qubit_measured_twice(fx_rng: Generator, domain: set[int], output: State) -> None: + # The two outcomes are 0 and 1: the domain tells them apart. + circuit = Circuit(2).m(0, Axis.Z, discard=False).x(0).m(0, Axis.Z) + circuit.condinstr(domain, [Instruction.X(1)]) + assert circuit.measurement_count == 2 + result = circuit.simulate(input_state=BasicStates.ZERO, rng=fx_rng) + assert result.classical_measures == (0, 1) + assert result.state.isclose(Statevector(data=output)) + + +@pytest.mark.parametrize("axis", [Axis.X, Axis.Y, Axis.Z]) +@pytest.mark.parametrize("outcome", [0, 1]) +@pytest.mark.parametrize( + "ancilla_state", + [ + BasicStates.PLUS, + BasicStates.MINUS, + BasicStates.ZERO, + BasicStates.ONE, + BasicStates.PLUS_I, + BasicStates.MINUS_I, + ], +) +def test_transpile_discard(fx_rng: Generator, axis: Axis, outcome: Outcome, ancilla_state: State) -> None: + circuit = circuit_with_measurements_without_discard(axis, ancilla_state) + instructions = list(circuit.instruction) + transpiled = circuit.transpile_discard() + assert circuit.instruction == instructions + assert all(instr.discard for instr in transpiled.instruction if instr.kind == InstructionKind.M) + # Qubit 0 ends on the second new ancilla (5), qubit 1 on the first one (4), and qubit 3 stays in place: + # a final swap restores the order of the output qubits. + assert transpiled.instruction[-2:] == [Instruction.M(2, Axis.Z), Instruction.SWAP((3, 5))] + + input_state = rand_state_vector(3, rng=fx_rng) + simulation = circuit.simulate(input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng) + simulation_test = transpiled.simulate( + input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng + ) + assert simulation_test.classical_measures == simulation.classical_measures + assert simulation_test.state.isclose(simulation.state) + + +def test_transpile_discard_reorders_outputs(fx_rng: Generator) -> None: + # Example from https://github.com/TeamGraphix/graphix/pull/644#discussion_r4482277320 + input_state = rand_state_vector(3, rng=fx_rng) + circuit = Circuit(3).m(0, Axis.Z, discard=False).m(2, Axis.Z, discard=False).m(0, Axis.Z, discard=False) + for outcome in (0, 1): + branch_selector = ConstBranchSelector(outcome) + state = circuit.simulate(input_state=input_state, branch_selector=branch_selector, rng=fx_rng).state + state_transpiled = ( + circuit.transpile_discard() + .simulate(input_state=input_state, branch_selector=branch_selector, rng=fx_rng) + .state + ) + assert state_transpiled.isclose(state) + + +@pytest.mark.parametrize("axis", [Axis.X, Axis.Y, Axis.Z]) +@pytest.mark.parametrize("outcome", [0, 1]) +@pytest.mark.parametrize("transpile_swaps", [True, False]) +def test_transpile_pattern_without_discard( + fx_rng: Generator, axis: Axis, outcome: Outcome, transpile_swaps: bool +) -> None: + circuit = circuit_with_measurements_without_discard(axis) + pattern = circuit.transpile(transpile_swaps=transpile_swaps).pattern + input_state = rand_state_vector(3, rng=fx_rng) + state = circuit.simulate(input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng).state + state_mbqc = pattern.simulate( + input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng, optimized=False + ) + assert state_mbqc.isclose(state) + + +def test_transpile_discard_without_measurements_without_discard(fx_rng: Generator) -> None: + circuit = rand_circuit(3, 3, fx_rng) + circuit.m(1, Axis.X) + transpiled = circuit.transpile_discard() + assert transpiled is not circuit + assert transpiled.instruction == circuit.instruction + # The copy has its own validator state. + transpiled.h(0) + assert len(transpiled.instruction) == len(circuit.instruction) + 1 + with pytest.raises(ValueError, match=r"Qubit 1 is not an active qubit."): + transpiled.h(1) + + +def test_reorder_active_qubits_with_swaps() -> None: + circuit = Circuit(4).m(1, Axis.Z) + input_state = [BasicStates.ZERO, BasicStates.PLUS, BasicStates.ONE, BasicStates.PLUS_I] + reordered = circuit.visit(InstructionVisitor(), copy=True).reorder_active_qubits_with_swaps([3, 0, 2]) + state = reordered.simulate(input_state=input_state, branch_selector=ConstBranchSelector(0)).state + # The active qubits are 0, 2, 3: after the swaps, they hold the former qubits 3, 0, 2. + assert state.isclose(Statevector(data=[BasicStates.PLUS_I, BasicStates.ZERO, BasicStates.ONE])) + with pytest.raises(ValueError, match="not a permutation of the active qubits"): + circuit.reorder_active_qubits_with_swaps([0, 1, 2]) + + +def test_measure_without_discard_unsupported() -> None: + circuit = Circuit(2).m(0, Axis.Z, discard=False) + with pytest.raises(NotImplementedError, match="transpile_discard"): + circuit.transpile_to_causalflow() + with pytest.raises(NotImplementedError, match="transpile_discard"): + circuit.transpile_condinstr() + with pytest.raises(NotImplementedError): + Circuit(1, ancillas=1, ancilla_state=PlanarState(Plane.XY, 0.3)).m(0, Axis.Z, discard=False).transpile_discard() + + +@pytest.mark.parametrize("axis", [Axis.X, Axis.Y, Axis.Z]) +@pytest.mark.parametrize("outcome", [0, 1]) +def test_transpile_to_qasm_gates_without_discard(fx_rng: Generator, axis: Axis, outcome: Outcome) -> None: + circuit = Circuit(2).ry(0, 0.3).cnot(0, 1).m(0, axis, discard=False).rx(0, 0.4) + input_state = rand_state_vector(2, rng=fx_rng) + state = circuit.simulate(input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng).state + state_test = ( + circuit.transpile_to_qasm_gates() + .simulate(input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng) + .state + ) + assert state_test.isclose(state) + + +def test_measurement_count_after_transformations() -> None: + circuit = Circuit(2, ancillas=1, ancilla_state=BasicStates.ZERO) + circuit.m(0, Axis.Z, discard=False).swap(0, 1).m(1, Axis.X).cnot(0, 2) + assert circuit.measurement_count == 2 + assert circuit.visit(InstructionVisitor(), copy=True).measurement_count == 2 + assert circuit.transpile_ancilla_state(BasicStates.PLUS).measurement_count == 2 + swapped = transpile_swaps(circuit.transpile_ancilla_state(BasicStates.PLUS), copy=False).circuit + assert swapped.measurement_count == 2 + # The swap has been transpiled: the qubit measured with discard is now qubit 0. + with pytest.raises(ValueError, match=r"Qubit 0 is not an active qubit."): + swapped.h(0) + + +@pytest.mark.parametrize("outcome", [0, 1]) +@pytest.mark.parametrize("transpile_swaps", [True, False]) +def test_condinstr_after_swap(fx_rng: Generator, outcome: Outcome, transpile_swaps: bool) -> None: + # Regression test for https://github.com/TeamGraphix/graphix/issues/640 + circuit = Circuit(2).swap(0, 1).m(0, Axis.Z).condinstr({0}, [Instruction.X(1)]) + pattern = circuit.transpile(transpile_swaps=transpile_swaps).pattern + input_state = rand_state_vector(2, rng=fx_rng) + state = circuit.simulate(input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng).state + state_mbqc = pattern.simulate( + input_state=input_state, branch_selector=ConstBranchSelector(outcome), rng=fx_rng, optimized=False + ) + assert state_mbqc.isclose(state) + + +@pytest.mark.parametrize("transpile_swaps", [True, False]) +def test_condinstr_after_swap_reads_right_outcome(fx_rng: Generator, transpile_swaps: bool) -> None: + # Regression test for https://github.com/TeamGraphix/graphix/issues/640: when both + # qubits are measured, the domain must still refer to the first measurement + # (outcome 1), not to the measurement of the qubit that had index 0 before the swap. + circuit = Circuit(3).swap(0, 1).m(0, Axis.Z).m(1, Axis.Z).condinstr({0}, [Instruction.X(2)]) + input_state = [BasicStates.ZERO, BasicStates.ONE, BasicStates.ZERO] + result = circuit.simulate(input_state=input_state, rng=fx_rng) + assert result.classical_measures == (1, 0) + assert result.state.isclose(Statevector(data=BasicStates.ONE)) + pattern = circuit.transpile(transpile_swaps=transpile_swaps).pattern + state_mbqc = pattern.simulate(input_state=input_state, rng=fx_rng, optimized=False) + assert state_mbqc.isclose(result.state)