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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 0 additions & 9 deletions src/pyqasm/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
157 changes: 52 additions & 105 deletions src/pyqasm/maps/gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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

Expand Down Expand Up @@ -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 = {
Expand Down
39 changes: 14 additions & 25 deletions src/pyqasm/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
ClbitDepthNode,
Context,
Frame,
InversionOp,
QubitDepthNode,
Variable,
Waveform,
Expand Down Expand Up @@ -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,
Expand All @@ -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 = []

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