diff --git a/CHANGELOG.md b/CHANGELOG.md index b9c7fbd6..e36f2855 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ Types of changes: ### Removed ### Fixed +- `inv @` and `pow(-n) @` now unroll to the exact inverse of every standard gate. Before, they gave a wrong circuit for `cp00`, `cp01`, `cp10` and their `cphaseshift` aliases, `iswap`, `ms`, `pswap`, `ryy`, `yy`, `xy` and `xx_plus_yy`, and raised on `sx`, `sxdg`, `p`, `u`, `prx`, `gpi`, `gpi2`, `not`, `si`, `ti`, `v`, `vi`, `u1`, `phaseshift`, `rxx`, `rzz`, `xx`, `zz`, `inv @ ctrl @ gphase(...)` and a `gphase` inside an inverted controlled custom gate. `inv @` on `ecr`, `cswap`, `c3x`, `c4x` and `rccx` now emits the reversed decomposition, which is still exact, but its text and its depth next to other gates can differ ([#492](https://github.com/qBraid/pyqasm/pull/492), [#473](https://github.com/qBraid/pyqasm/issues/473), [#476](https://github.com/qBraid/pyqasm/issues/476)). - `publish-lab-env.yml` files a publish request before it approves the environment. Since qBraid/qbraid-api#1334 the server approves only an environment with an open request, so every run failed at approve with `Environment must have status REQUESTED or PENDING to publish`. The request counts toward the API key owner's publish quota and notifies the platform admins ([#491](https://github.com/qBraid/pyqasm/pull/491), [#490](https://github.com/qBraid/pyqasm/issues/490)). ### Dependencies diff --git a/src/pyqasm/elements.py b/src/pyqasm/elements.py index 3950da36..1593c492 100644 --- a/src/pyqasm/elements.py +++ b/src/pyqasm/elements.py @@ -67,15 +67,6 @@ def is_physical_qubit(qubit_name: str) -> bool: return qubit_name.startswith(PHYSICAL_QUBIT_PREFIX) and qubit_name[1:].isdigit() -class InversionOp(Enum): - """ - Enum for specifying the inversion action of a gate. - """ - - NO_OP = 1 - INVERT_ROTATION = 2 - - class Context(Enum): """ Enum for the different contexts in Qasm. diff --git a/src/pyqasm/maps/gates.py b/src/pyqasm/maps/gates.py index d6d5edbb..fa0cb2cc 100644 --- a/src/pyqasm/maps/gates.py +++ b/src/pyqasm/maps/gates.py @@ -20,10 +20,11 @@ """ from copy import deepcopy -from typing import Callable +from typing import Callable, TypeVar import numpy as np from openqasm3.ast import ( + Expression, FloatLiteral, Identifier, IndexedIdentifier, @@ -32,12 +33,13 @@ QuantumPhase, ) -from pyqasm.elements import BasisSet, InversionOp +from pyqasm.elements import BasisSet from pyqasm.exceptions import ValidationError, raise_qasm3_error from pyqasm.linalg import kak_decomposition_angles from pyqasm.maps.expressions import CONSTANTS_MAP QubitOperand = IndexedIdentifier | Identifier +EmittedGate = TypeVar("EmittedGate", bound=QuantumGate | QuantumPhase) def _copy_qubit(qubit: QubitOperand) -> QubitOperand: @@ -115,25 +117,6 @@ def u3_gate( # global phase - e^(i*(phi+lambda)/2) is missing in the above implementation -def u3_inv_gate( - theta: int | float, - phi: int | float, - lam: int | float, - qubits, -) -> list[QuantumGate]: - """ - Implements the inverse of the U3 gate using the decomposition present in - the u3_gate function. - """ - result: list[QuantumGate] = [] - result.extend(one_qubit_rotation_op("rz", -1.0 * (phi + CONSTANTS_MAP["pi"]), qubits)) - result.extend(one_qubit_rotation_op("rx", -1.0 * (CONSTANTS_MAP["pi"] / 2), qubits)) - result.extend(one_qubit_rotation_op("rz", -1.0 * (theta + CONSTANTS_MAP["pi"]), qubits)) - result.extend(one_qubit_rotation_op("rx", -1.0 * (CONSTANTS_MAP["pi"] / 2), qubits)) - result.extend(one_qubit_rotation_op("rz", -1.0 * lam, qubits)) - return result - - def u2_gate(phi, lam, qubits) -> list[QuantumGate]: """ Implements the U2 gate using the following decomposition: @@ -142,14 +125,6 @@ def u2_gate(phi, lam, qubits) -> list[QuantumGate]: return u3_gate(CONSTANTS_MAP["pi"] / 2, phi, lam, qubits) -def u2_inv_gate(phi, lam, qubits) -> list[QuantumGate]: - """ - Implements the inverse of the U2 gate using the decomposition present in - the u2_gate function. - """ - return u3_inv_gate(CONSTANTS_MAP["pi"] / 2, phi, lam, qubits) - - def global_phase_gate(theta: float, qubit_list: list[IndexedIdentifier]) -> list[QuantumPhase]: """ Builds a global phase gate with the given theta and qubit list. @@ -883,35 +858,6 @@ def rc3x_gate( return result -def _rc3x_dg_gate( - qubit0: IndexedIdentifier, - qubit1: IndexedIdentifier, - qubit2: IndexedIdentifier, - qubit3: IndexedIdentifier, -) -> list[QuantumGate]: - """Inverse of :func:`rc3x_gate`, used in the c4x decomposition.""" - result: list[QuantumGate] = [] - result.extend(one_qubit_gate_op("h", qubit3)) - result.extend(one_qubit_gate_op("t", qubit3)) - result.extend(two_qubit_gate_op("cx", qubit2, qubit3)) - result.extend(one_qubit_gate_op("tdg", qubit3)) - result.extend(one_qubit_gate_op("h", qubit3)) - result.extend(one_qubit_gate_op("t", qubit3)) - result.extend(two_qubit_gate_op("cx", qubit1, qubit3)) - result.extend(one_qubit_gate_op("tdg", qubit3)) - result.extend(two_qubit_gate_op("cx", qubit0, qubit3)) - result.extend(one_qubit_gate_op("t", qubit3)) - result.extend(two_qubit_gate_op("cx", qubit1, qubit3)) - result.extend(one_qubit_gate_op("tdg", qubit3)) - result.extend(two_qubit_gate_op("cx", qubit0, qubit3)) - result.extend(one_qubit_gate_op("h", qubit3)) - result.extend(one_qubit_gate_op("t", qubit3)) - result.extend(two_qubit_gate_op("cx", qubit2, qubit3)) - result.extend(one_qubit_gate_op("tdg", qubit3)) - result.extend(one_qubit_gate_op("h", qubit3)) - return result - - def c4x_gate( qubit0: IndexedIdentifier, qubit1: IndexedIdentifier, @@ -929,7 +875,7 @@ def c4x_gate( result.extend(one_qubit_gate_op("h", qubit4)) result.extend(cphaseshift_gate(-pi / 2, qubit3, qubit4)) result.extend(one_qubit_gate_op("h", qubit4)) - result.extend(_rc3x_dg_gate(qubit0, qubit1, qubit2, qubit3)) + result.extend(inverse_gate_list(rc3x_gate(qubit0, qubit1, qubit2, qubit3))) result.extend(c3sx_gate(qubit0, qubit1, qubit2, qubit4)) return result @@ -1212,60 +1158,61 @@ def map_qasm_op_to_callable(op_node: QuantumGate) -> tuple[Callable, int]: # ty "tdg": "t", } ROTATION_INVERSION_ONE_QUBIT_OP_MAP = {"rx", "ry", "rz"} -U_INV_ROTATION_MAP = { - "U": u3_inv_gate, - "u3": u3_inv_gate, - "U3": u3_inv_gate, - "U2": u2_inv_gate, - "u2": u2_inv_gate, -} -# Inverses for the multi-controlled-X family. ``c3x`` / ``c4x`` are -# self-inverse (the inverse of a multi-controlled X is the same gate), while -# ``rc3x`` / ``rcccx`` are relative-phase Toffolis whose inverse is the -# dedicated :func:`_rc3x_dg_gate` decomposition. -MULTI_CONTROLLED_X_INV_MAP = { - "c3x": (c3x_gate, 4), - "c4x": (c4x_gate, 5), - "rc3x": (_rc3x_dg_gate, 4), - "rcccx": (_rc3x_dg_gate, 4), -} +# Inverses of the gates that decompositions emit. The three sets above also steer +# ``map_qasm_inv_ctrl_op_to_callable``, so these extend them instead of changing them. +_SELF_INVERSE_GATE_SET = SELF_INVERTING_ONE_QUBIT_OP_SET | {"nop", "cx", "cz", "swap", "ccx"} +_DAGGER_GATE_MAP = {**ST_GATE_INV_MAP, "sx": "sxdg", "sxdg": "sx"} +_NEGATED_ANGLE_GATE_SET = ROTATION_INVERSION_ONE_QUBIT_OP_MAP | {"p"} + +def _negated(argument: Expression) -> FloatLiteral: + if not isinstance(argument, (FloatLiteral, IntegerLiteral)): + raise ValidationError(f"Cannot negate non-literal gate argument {argument}") + return FloatLiteral(value=float(-argument.value)) + + +def inverse_gate_list(gates: list[EmittedGate]) -> list[EmittedGate]: + """Invert a decomposition in place: reverse it and replace each gate by its inverse. + + Args: + gates: The gates a decomposition emitted. They are modified and returned. -def map_qasm_inv_op_to_callable(op_name: str): + Raises: + ValidationError: If a gate is not one the decompositions emit. """ - Map a QASM operation to a callable. + for gate in gates: + if isinstance(gate, QuantumPhase): + gate.argument = _negated(gate.argument) + continue + name = gate.name.name + if name in _DAGGER_GATE_MAP: + gate.name = Identifier(name=_DAGGER_GATE_MAP[name]) + elif name in _NEGATED_ANGLE_GATE_SET: + gate.arguments = [_negated(argument) for argument in gate.arguments] + elif name not in _SELF_INVERSE_GATE_SET: + raise ValidationError(f"Cannot invert gate '{name}' in a decomposition") + gates.reverse() + return gates + + +def map_qasm_inv_op_to_callable(op_node: QuantumGate) -> tuple[Callable, int]: + """ + Map ``inv @`` on a QASM operation to a callable. + + The callable builds the operation's decomposition reversed, with every gate inverted. Args: - op_name (str): The QASM operation name. + op_node (QuantumGate): The QASM operation. Returns: - tuple: A tuple containing the callable, the number of qubits the operation acts on, - and what is to be done with the basic gate which we are trying to invert. - """ - if op_name in SELF_INVERTING_ONE_QUBIT_OP_SET or op_name in ST_GATE_INV_MAP: - # Self-inverting gates map to themselves; S/T map to their dagger and - # vice versa. Either way the result is a single-qubit gate applied as-is. - inv_gate_name = ST_GATE_INV_MAP.get(op_name, op_name) - return ONE_QUBIT_OP_MAP[inv_gate_name], 1, InversionOp.NO_OP - if op_name in TWO_QUBIT_OP_MAP: - return TWO_QUBIT_OP_MAP[op_name], 2, InversionOp.NO_OP - if op_name in THREE_QUBIT_OP_MAP: - return THREE_QUBIT_OP_MAP[op_name], 3, InversionOp.NO_OP - if op_name in MULTI_CONTROLLED_X_INV_MAP: - inv_func, num_qubits = MULTI_CONTROLLED_X_INV_MAP[op_name] - return inv_func, num_qubits, InversionOp.NO_OP - if op_name in U_INV_ROTATION_MAP: - # Special handling for U gate as it is composed of multiple - # basic gates and we need to invert each of them - return U_INV_ROTATION_MAP[op_name], 1, InversionOp.NO_OP - if op_name in ROTATION_INVERSION_ONE_QUBIT_OP_MAP: - return ( - ONE_QUBIT_ROTATION_MAP[op_name], - 1, - InversionOp.INVERT_ROTATION, - ) - raise ValidationError(f"Unsupported / undeclared QASM operation: {op_name}") + tuple: A tuple containing the callable and the number of qubits the operation acts on. + + Raises: + ValidationError: If the QASM operation is unsupported or undeclared. + """ + forward, num_qubits = map_qasm_op_to_callable(op_node) + return (lambda *args: inverse_gate_list(forward(*args))), num_qubits REV_CTRL_GATE_MAP = { diff --git a/src/pyqasm/visitor.py b/src/pyqasm/visitor.py index cd51f311..1147485f 100644 --- a/src/pyqasm/visitor.py +++ b/src/pyqasm/visitor.py @@ -41,7 +41,6 @@ ClbitDepthNode, Context, Frame, - InversionOp, QubitDepthNode, Variable, Waveform, @@ -1227,11 +1226,9 @@ def _visit_basic_gate_operation( Args: operation (QuantumGate): The gate operation to visit. inverse (bool): Whether the operation is an inverse operation. Defaults to False. - If inverse is True, we apply check for different cases in the - map_qasm_inv_op_to_callable method. - Only rotation and S / T gates are affected by this inversion. For S/T - gates we map them to Sdg / Tdg and vice versa. - For rotation gates, we map to the same gates but invert the rotation angles. + If True, the gate's decomposition is emitted reversed with each + gate inverted, unless ``map_qasm_inv_ctrl_op_to_callable`` builds + the inverse exactly from the gate's U-form. Returns: list[QuantumGate]: The list of gates after unrolling, @@ -1242,7 +1239,6 @@ def _visit_basic_gate_operation( """ logger.debug("Visiting basic gate operation '%s'", str(operation)) - inverse_action = None if ctrls is None: ctrls = [] @@ -1262,17 +1258,12 @@ def _visit_basic_gate_operation( else: qasm_func, op_qubit_count = map_qasm_op_to_callable(operation) else: - # in basic gates, inverse action only affects the rotation gates - qasm_func, op_qubit_count, inverse_action = map_qasm_inv_op_to_callable( - operation.name.name - ) + qasm_func, op_qubit_count = map_qasm_inv_op_to_callable(operation) op_parameters = [] actual_num_params = map_qasm_op_num_params(operation.name.name) if len(operation.arguments) > 0: # parametric gate op_parameters = self._get_op_parameters(operation) - if inverse_action == InversionOp.INVERT_ROTATION: - op_parameters = [-1 * param for param in op_parameters] if len(op_parameters) != actual_num_params: raise_qasm3_error( @@ -1282,22 +1273,20 @@ def _visit_basic_gate_operation( span=operation.span, ) - result = [] + result: list[qasm3_ast.QuantumGate] = [] unrolled_targets = self._unroll_multiple_target_qubits(operation, op_qubit_count) unrolled_gate_function = partial(qasm_func, *op_parameters) if inverse: - # for convenience, we recur and handle the ctrl @'s to the unrolled no inverse case - # instead of trying to map the inverted callable to a ctrl'd version - result.extend( - [ - g2 - for g in self._broadcast_gate_operation( - unrolled_gate_function, unrolled_targets, None - ) - for g2 in self._visit_basic_gate_operation(g, False, ctrls) - ] - ) + # the pieces are already inverted; re-visit each so the ctrl @'s apply to it + for piece in self._broadcast_gate_operation( + unrolled_gate_function, unrolled_targets, None + ): + if isinstance(piece, qasm3_ast.QuantumPhase): + # only gates without ctrl @'s emit gphase here; the result type omits it + result.append(piece) # type: ignore[arg-type] + else: + result.extend(self._visit_basic_gate_operation(piece, False, ctrls)) else: result.extend( self._broadcast_gate_operation(unrolled_gate_function, unrolled_targets, ctrls) diff --git a/tests/qasm3/test_gates.py b/tests/qasm3/test_gates.py index e2ee1576..5051e469 100644 --- a/tests/qasm3/test_gates.py +++ b/tests/qasm3/test_gates.py @@ -20,11 +20,22 @@ """ import numpy as np +import openqasm3 import openqasm3.ast as qasm3_ast import pytest from pyqasm.entrypoint import dumps, loads from pyqasm.exceptions import ValidationError +from pyqasm.maps.gates import ( + FIVE_QUBIT_OP_MAP, + FOUR_QUBIT_OP_MAP, + ONE_QUBIT_OP_MAP, + ONE_QUBIT_ROTATION_MAP, + THREE_QUBIT_OP_MAP, + TWO_QUBIT_OP_MAP, + inverse_gate_list, + map_qasm_op_num_params, +) from tests.qasm3.resources.gates import ( CUSTOM_GATE_INCORRECT_TESTS, PHYSICAL_QUBIT_VALID_TESTS, @@ -1084,3 +1095,132 @@ def test_csx_and_rccx_decomposition_unitary(body, num_qubits, expected_num_gates ] assert "h" not in gate_names assert len(gate_names) == expected_num_gates + + +# Angles that are not multiples of pi/4, so a sign or ordering error cannot hide behind symmetry. +_INVERSE_TEST_ANGLES = (0.37, 0.81, 1.29, 1.73) + + +def _standard_gate_statements(): + """Every standard gate pyqasm unrolls, called once with distinct angles and operands.""" + op_maps = [ + (1, ONE_QUBIT_OP_MAP), + (1, ONE_QUBIT_ROTATION_MAP), + (2, TWO_QUBIT_OP_MAP), + (3, THREE_QUBIT_OP_MAP), + (4, FOUR_QUBIT_OP_MAP), + (5, FIVE_QUBIT_OP_MAP), + ] + for num_qubits, op_map in op_maps: + for name in op_map: + if name == "nop": # a keyword, so `inv @ nop` does not parse + continue + params = _INVERSE_TEST_ANGLES[: map_qasm_op_num_params(name)] + call = f"{name}({', '.join(map(str, params))})" if params else name + operands = ", ".join(f"q[{i}]" for i in range(num_qubits)) + yield pytest.param(f"{call} {operands};", num_qubits, id=call) + + +@pytest.mark.parametrize("statement, num_qubits", _standard_gate_statements()) +def test_inverse_modifier_is_adjoint_of_every_standard_gate(statement, num_qubits): + """inv @ g unrolls to the adjoint of g for every standard gate (issues #473, #476).""" + forward = _unrolled_unitary(statement, num_qubits) + assert_unitary_equal(_unrolled_unitary(f"inv @ {statement}", num_qubits), forward.conj().T) + + +@pytest.mark.parametrize("statement, num_qubits", _standard_gate_statements()) +def test_double_inverse_and_negative_power_of_every_standard_gate(statement, num_qubits): + """inv @ inv @ g round-trips to g, and pow(-1) @ g is the adjoint.""" + forward = _unrolled_unitary(statement, num_qubits) + assert_unitary_equal(_unrolled_unitary(f"inv @ inv @ {statement}", num_qubits), forward) + assert_unitary_equal(_unrolled_unitary(f"pow(-1) @ {statement}", num_qubits), forward.conj().T) + + +_SXDG = np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]], dtype=complex) / 2 +_CV_INVERSE = np.eye(4, dtype=complex) +_CV_INVERSE[np.ix_([1, 3], [1, 3])] = _SXDG # SX^dagger on q[1] where q[0] (the low bit) is 1 +_PSWAP_INVERSE = np.array( + [ + [1, 0, 0, 0], + [0, 0, np.exp(-0.5j), 0], + [0, np.exp(-0.5j), 0, 0], + [0, 0, 0, 1], + ], + dtype=complex, +) + + +@pytest.mark.parametrize( + "body, num_qubits, expected", + [ + # issue #473 repros that #459 already fixed; they guard that fix + ("inv @ cphaseshift(0.5) q[0], q[1];", 2, np.diag([1, 1, 1, np.exp(-0.5j)])), + ("inv @ cv q[0], q[1];", 2, _CV_INVERSE), + # issue #473: inv @ pswap re-emitted the forward gate + ("inv @ pswap(0.5) q[0], q[1];", 2, _PSWAP_INVERSE), + # issue #476: inv @ raised on single-qubit gates outside the small inverse tables + ("inv @ sx q[0];", 1, _SXDG), + ], +) +def test_inverse_modifier_issue_repros(body, num_qubits, expected): + """The exact programs from issues #473 and #476 unroll to the textbook adjoint.""" + assert_unitary_equal(_unrolled_unitary(body, num_qubits), expected) + + +def test_inverse_modifier_on_custom_gate_using_decomposed_gates(): + """inv @ on a custom gate inverts a body that mixes decomposed, basis and nop gates.""" + definition = "gate mixed(t) a, b { pswap(t) a, b; sx a; rxx(t) a, b; nop b; }\n" + forward = _unrolled_unitary(definition + "mixed(0.37) q[0], q[1];", 2) + actual = _unrolled_unitary(definition + "inv @ mixed(0.37) q[0], q[1];", 2) + assert_unitary_equal(actual, forward.conj().T) + + +def test_inverse_modifier_prints_negated_integer_angles_as_floats(): + """inv @ u2(1, 2) prints its negated integer angle as rz(-2.0), as before #473.""" + header = 'OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[1] q;\n' + module = loads(header + "inv @ u2(1, 2) q[0];") + module.unroll() + expected = [ + "rz(-4.141592653589793) q[0];", + "rx(-1.5707963267948966) q[0];", + "rz(-4.71238898038469) q[0];", + "rx(-1.5707963267948966) q[0];", + "rz(-2.0) q[0];", + ] + check_unrolled_qasm(dumps(module), header + "\n".join(expected)) + + +def _qubit(index): + return qasm3_ast.IndexedIdentifier( + name=qasm3_ast.Identifier("q"), indices=[[qasm3_ast.IntegerLiteral(index)]] + ) + + +def test_inverse_gate_list_reverses_and_inverts_each_gate(): + """inverse_gate_list reverses the gates, daggers sx, and negates the p and gphase angles.""" + gates = [ + qasm3_ast.QuantumPhase(modifiers=[], argument=qasm3_ast.IntegerLiteral(2), qubits=[]), + qasm3_ast.QuantumGate( + modifiers=[], + name=qasm3_ast.Identifier("p"), + arguments=[qasm3_ast.FloatLiteral(0.37)], + qubits=[_qubit(0)], + ), + qasm3_ast.QuantumGate( + modifiers=[], name=qasm3_ast.Identifier("sx"), arguments=[], qubits=[_qubit(1)] + ), + ] + inverted = [openqasm3.dumps(gate).strip() for gate in inverse_gate_list(gates)] + assert inverted == ["sxdg q[1];", "p(-0.37) q[0];", "gphase(-2.0);"] + + +def test_inverse_gate_list_rejects_a_gate_decompositions_do_not_emit(): + """A gate outside the decomposition basis has no known inverse, so it raises.""" + gate = qasm3_ast.QuantumGate( + modifiers=[], + name=qasm3_ast.Identifier("cp"), + arguments=[qasm3_ast.FloatLiteral(0.37)], + qubits=[_qubit(0), _qubit(1)], + ) + with pytest.raises(ValidationError, match=r"Cannot invert gate 'cp' in a decomposition"): + inverse_gate_list([gate]) diff --git a/tests/utils.py b/tests/utils.py index 82004011..bf52d6b5 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -75,7 +75,10 @@ def _ry(theta): "t": _phase(np.pi / 4), "tdg": _phase(-np.pi / 4), "sx": np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]], dtype=complex) / 2, + "sxdg": np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]], dtype=complex) / 2, + "nop": _I2, } +_SWAP = np.eye(4, dtype=complex)[[0, 2, 1, 3]] _PARAM_ONE_QUBIT = {"p": _phase, "phaseshift": _phase, "rz": _rz, "rx": _rx, "ry": _ry} _PARAM_TWO_QUBIT = {"cp": _phase, "cphaseshift": _phase, "crz": _rz, "crx": _rx, "cry": _ry} _FIXED_TWO_QUBIT_TARGET = {"cx": _X, "cy": _Y, "cz": _Z} @@ -115,6 +118,19 @@ def _embed_controlled(matrix, control, target, num_qubits): return op0 + op1 +def _embed_two_qubit(matrix, first, second, num_qubits): + """Embed a 2-qubit matrix whose little-endian factors are ``first`` then ``second``.""" + dim = 2**num_qubits + operator = np.zeros((dim, dim), dtype=complex) + for basis in range(dim): + local_in = ((basis >> first) & 1) | (((basis >> second) & 1) << 1) + rest = basis & ~(1 << first) & ~(1 << second) + for local_out in range(4): + dest = rest | ((local_out & 1) << first) | (((local_out >> 1) & 1) << second) + operator[dest, basis] = matrix[local_out, local_in] + return operator + + def unitary_from_unrolled_ast(unrolled_ast, num_qubits): """Build the full operator of an unrolled circuit over basis/controlled gates. @@ -142,6 +158,8 @@ def unitary_from_unrolled_ast(unrolled_ast, num_qubits): ) elif name == "ccx": gate = mcx_unitary(num_qubits, target=qubits[2], controls=qubits[:2]) + elif name == "swap": + gate = _embed_two_qubit(_SWAP, qubits[0], qubits[1], num_qubits) elif name in _PARAM_TWO_QUBIT: gate = _embed_controlled( _PARAM_TWO_QUBIT[name](args[0]), qubits[0], qubits[1], num_qubits