Source code for pennylane.ops.op_math.controlled_ops

# Copyright 2018-2024 Xanadu Quantum Technologies Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
This submodule contains controlled operators based on the ControlledOp class.
"""

# pylint: disable=unused-argument,arguments-differ,arguments-renamed


from collections import defaultdict
from collections.abc import Iterable, Sequence
from functools import partial
from typing import Literal, override

import numpy as np
from scipy import sparse
from scipy.linalg import block_diag

import pennylane as qp
from pennylane import math
from pennylane.allocation import allocate
from pennylane.core.operator import Operator, abstractify
from pennylane.decomposition import add_decomps, register_resources
from pennylane.decomposition.decomposition_rule import (
    DecompCollection,
    _list_decomps,
    get_fixed_decomp,
)
from pennylane.decomposition.resources import resolve_work_wire_type
from pennylane.decomposition.symbolic_decomposition import self_adjoint
from pennylane.ops.identity import GlobalPhase
from pennylane.ops.mid_measure.pauli_measure import PauliMeasure, pauli_measure
from pennylane.ops.op_math.adjoint2 import _adjoint_abstract
from pennylane.ops.op_math.adjoint2 import _adjoint_negate_angle as adjoint_rotation2
from pennylane.ops.op_math.change_op_basis2 import _change_op_basis_abstract
from pennylane.ops.op_math.controlled2 import (
    Controlled2,
    ControlledOp2,
    _setup_control_values,
    _validate_work_wire_type,
)
from pennylane.ops.op_math.pow2 import _pow_scale_angle as pow_rotation2
from pennylane.ops.op_math.pow2 import pow_involutory as pow_involutory2
from pennylane.ops.qubit import X, Y, Z
from pennylane.typing import AbstractArray, AbstractWires, Bool, Complex, Float, TensorLike, Wire
from pennylane.wires import Wires, WiresLike, concatenate_wires, validate_no_wire_overlaps

from .adjoint2 import _adjoint_abstract
from .controlled import Controlled2, _resolve_ctrl_values
from .decompositions.controlled_decompositions import (
    _controlled_unitary_bisect,
    _controlled_unitary_multi_control_zyz,
    _controlled_unitary_single_control_zyz,
    _controlled_unitary_two_qubit,
    _mcx_many_work_wires,
    _mcx_no_work_wires,
    _mcx_one_work_wire,
    _mcx_to_cnot_or_toffoli,
    _mcx_two_controls_elbows,
    _mcx_two_work_wires,
    _wrap_mcx_rule_w_alloc,
)
from .pow2 import pow_involutory as pow_involutory2

__all__ = [
    "ControlledQubitUnitary",
    "CH",
    "CY",
    "CZ",
    "CSWAP",
    "CCZ",
    "CNOT",
    "Toffoli",
    "MultiControlledX",
    "CRX",
    "CRY",
    "CRZ",
    "CRot",
    "ControlledPhaseShift",
]

INV_SQRT2 = 1 / math.sqrt(2)

stack_last = partial(math.stack, axis=-1)


[docs] class ControlledQubitUnitary(Controlled2): r"""ControlledQubitUnitary(U, wires) Apply an arbitrary fixed unitary matrix ``U`` to ``wires``. If ``n = len(wires) `` and ``U`` has ``k`` wires, then the first ``n - k`` from ``wires`` serve as control, and ``U`` lives on the last ``k`` wires. In addition to default ``Operation`` instance attributes, the following are available for ``ControlledQubitUnitary``: * ``wires``: wires of the final controlled unitary, consisting of control wires following by target wires * ``control_values``: the state on which to apply the controlled operation (see below) * ``work_wires``: wires made use of during the decomposition of the operation into native operations **Details:** * Number of wires: Any (the operation can act on any number of wires) * Number of parameters: 1 * Number of dimensions per parameter: (2,) * Gradient recipe: None Args: U (array[complex]): a square unitary matrix that will be used to construct a QubitUnitary operator, used as the base operator. wires (Union[Wires, Sequence[int], or int]): the wires the full controlled unitary acts on, composed of the controlled wires followed by the target wire. control_values (List[int or bool]): a list providing the state of the control qubits to control on (default is the all 1s state). unitary_check (bool): whether to check whether an array U is unitary when creating the operator (default False). work_wires (Union[Wires, Sequence[int], or int]): auxiliary wire(s) that may be utilized during the decomposition of the operator into native operations. **Example** The following shows how a single-qubit unitary can be applied to wire ``2`` with control on both wires ``0`` and ``1``: >>> U = np.array([[ 0.94877869, 0.31594146], [-0.31594146, 0.94877869]]) >>> qp.ControlledQubitUnitary(U, wires=[0, 1, 2]) ControlledQubitUnitary(U=[[ 0.94877869 0.31594146] [-0.31594146 0.94877869]], wires=[0, 1, 2], control_values=[ True True], work_wires=[], work_wire_type=borrowed, unitary_check=False) Typically, controlled operations apply a desired gate if the control qubits are all in the state :math:`\vert 1\rangle`. However, there are some situations where it is necessary to apply a gate conditioned on all qubits being in the :math:`\vert 0\rangle` state, or a mix of the two. The state on which to control can be changed by passing a string of bits to `control_values`. For example, if we want to apply a single-qubit unitary to wire ``3`` conditioned on three wires where the first is in state ``0``, the second is in state ``1``, and the third in state ``1``, we can write: >>> qp.ControlledQubitUnitary(U, wires=[0, 1, 2, 3], control_values=[0, 1, 1]) ControlledQubitUnitary(U=[[ 0.94877869 0.31594146] [-0.31594146 0.94877869]], wires=[0, 1, 2, 3], control_values=[False True True], work_wires=[], work_wire_type=borrowed, unitary_check=False) or >>> qp.ControlledQubitUnitary(U, wires=[0, 1, 2, 3], control_values=[False, True, True]) ControlledQubitUnitary(U=[[ 0.94877869 0.31594146] [-0.31594146 0.94877869]], wires=[0, 1, 2, 3], control_values=[False True True], work_wires=[], work_wire_type=borrowed, unitary_check=False) .. details:: :title: Available decompositions .. decomposition-table:: qp.ControlledQubitUnitary :stacked: :symbols: :math:`n` target wires and :math:`c` control wires .. decomposition-rule:: bisect :image: /_static/decomposition_thumbnails/controlled_qubit_unitary_bisect.svg :where: :math:`n = 1` and :math:`c \geq 2`, the circuit shows :math:`c = 3`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.QubitUnitary` | :math:`4` :class:`Adjoint(QubitUnitary) <.QubitUnitary>` | :math:`4` :class:`~.Hadamard` | :math:`2` :class:`~.PhaseShift` with :math:`c - 1` controls | :math:`1` :class:`~.MultiControlledX` with :math:`c/2` controls (even :math:`c`) | :math:`6` :class:`~.MultiControlledX` with :math:`\lceil c/2 \rceil` controls (odd :math:`c`) | :math:`2` :class:`~.MultiControlledX` with :math:`\lfloor c/2 \rfloor` controls (odd :math:`c`) | :math:`4` .. decomposition-rule:: single_control_zyz :image: /_static/decomposition_thumbnails/controlled_qubit_unitary_single_ctrl_zyz.svg :where: :math:`n = 1` and :math:`c = 1`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.RZ` | :math:`3` :class:`~.RY` | :math:`2` :class:`~.CNOT` | :math:`2` :class:`~.PhaseShift` | :math:`1` .. decomposition-rule:: multi_control_zyz :image: /_static/decomposition_thumbnails/controlled_qubit_unitary_multi_ctrl_zyz.svg :where: :math:`n = 1` and :math:`c \geq 2`, the circuit shows :math:`c = 3`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.CRZ` | :math:`3` :class:`~.CRY` | :math:`2` :class:`~.MultiControlledX` with :math:`c - 1` controls | :math:`2` :class:`~.PhaseShift` with :math:`c - 1` controls | :math:`1` .. decomposition-rule:: two_qubit :image: /_static/decomposition_thumbnails/controlled_qubit_unitary_two_qubit.svg :where: :math:`n = 2`, the circuit shows :math:`c = 1`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.ControlledQubitUnitary` on :math:`1` target wire with :math:`c` controls | :math:`4` :class:`~.MultiControlledX` with :math:`c + 1` controls | :math:`3` :class:`Controlled(RZ) <.RZ>` with :math:`c` controls | :math:`1` :class:`Controlled(RY) <.RY>` with :math:`c` controls | :math:`2` :class:`~.PhaseShift` with :math:`c - 1` controls | :math:`1` .. decomposition-rule:: to_controlled_qubit_unitary :image: /_static/decomposition_thumbnails/controlled_qubit_unitary_to_general.svg :where: :math:`n \geq 3`, and the circuit shows :math:`c = 1` :class:`Controlled(QubitUnitary) <.QubitUnitary>` with :math:`c` controls | :math:`1` .. decomposition-rule:: conjugate_transpose :image: /_static/decomposition_thumbnails/controlled_qubit_unitary_adjoint.svg :region: adjoint :where: the adjoint of the input unitary matrix is used :class:`~.ControlledQubitUnitary` | :math:`1` """ dynamic_argnames = ("U", "control_values") wire_argnames = ("wires", "work_wires") compilable_argnames = ("unitary_check", "work_wire_type") arg_specs = { "U": Complex[-1, -1], "wires": Wire[-1], "control_values": Bool[-1], "work_wires": Wire[-1], } def __init__( # pylint: disable=too-many-arguments self, U: TensorLike, wires: WiresLike, control_values=None, work_wires: WiresLike = (), *, work_wire_type: str | None = "borrowed", unitary_check=False, ): if wires is None: raise TypeError("Must specify a set of wires. None is not a valid `wires` label.") if not isinstance(U, (Iterable, AbstractArray)): raise ValueError("U must be a matrix.") work_wires = Wires(() if work_wires is None else work_wires) num_base_wires = int(math.log2(qp.math.shape(U)[-1])) target_wires = wires[-num_base_wires:] control_wires = wires[:-num_base_wires] super().__init__( qp.QubitUnitary(U, wires=target_wires, unitary_check=unitary_check), control_wires, control_values=control_values, work_wires=work_wires, work_wire_type=work_wire_type, ) @property def has_decomposition(self) -> bool: # pylint: disable=invalid-overridden-method # A controlled *sparse* multi-qubit unitary has no decomposition, because the underlying # ``QubitUnitary`` base cannot be decomposed (mirrors ``QubitUnitary.has_decomposition``). return self.base.has_decomposition and super().has_decomposition
[docs] def decomposition(self) -> list[Operator]: # Guard against decomposition rules (selected purely by wire counts) being run on a sparse # base matrix they cannot handle, e.g. a controlled two-qubit sparse ``QubitUnitary``. if not self.has_decomposition: raise qp.operation.DecompositionUndefinedError( "The decomposition of a controlled sparse multi-qubit QubitUnitary is undefined." ) return super().decomposition()
def _to_general_c_qu_standard_resources(U, wires, control_values, work_wires, work_wire_type, **_): num_target_wires = int(math.log2(qp.math.shape(U)[-1])) num_control_wires = len(wires) - num_target_wires num_work_wires = len(work_wires) u_size = 2**num_target_wires return { ControlledOp2( qp.QubitUnitary(Complex[u_size, u_size], wires=Wire[num_target_wires]), control_wires=Wire[num_control_wires], control_values=Bool[num_control_wires], work_wires=Wire[num_work_wires], work_wire_type=work_wire_type, ): 1 } @qp.register_condition(lambda U, *_, **__: math.ceil_log2(qp.math.shape(U)[0]) > 2) @qp.register_resources(_to_general_c_qu_standard_resources, name="to_controlled_qubit_unitary") def _to_general_c_qu_standard(U, wires, control_values, work_wires, work_wire_type, **_): """Convert a ControlledQubitUnitary to a general Controlled(QubitUnitary) so that the graph finds the general decomposition rule of applying control to the decomposition of the base QubitUnitary.""" num_target_wires = len(wires) - len(control_values) ControlledOp2( qp.QubitUnitary(U, wires=wires[-num_target_wires:]), control_wires=wires[:-num_target_wires], control_values=control_values, work_wires=work_wires, work_wire_type=work_wire_type, ) add_decomps( ControlledQubitUnitary, _controlled_unitary_bisect, _controlled_unitary_single_control_zyz, _controlled_unitary_multi_control_zyz, _controlled_unitary_two_qubit, _to_general_c_qu_standard, ) def _conj_transpose(U): return U.conjugate().transpose() if sparse.issparse(U) else math.moveaxis(math.conj(U), -2, -1) @register_resources(lambda base: {abstractify(base): 1}, name="conjugate_transpose") def _adjoint_controlled_qubit_unitary_standard(base): ControlledQubitUnitary( _conj_transpose(base.U), wires=base.wires, control_values=base.control_values, work_wires=base.work_wires, work_wire_type=base.work_wire_type, ) add_decomps("Adjoint(ControlledQubitUnitary)", _adjoint_controlled_qubit_unitary_standard)
[docs] class CH(Controlled2): r"""CH(wires) The controlled-Hadamard operator .. math:: CH = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\ 0 & 0 & \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} \end{bmatrix}. .. note:: The first wire provided corresponds to the **control qubit**. **Details:** * Number of wires: 2 * Number of parameters: 0 Args: wires (Sequence[int]): the wires the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CH .. decomposition-rule:: to_ry_cz_ry :image: /_static/decomposition_thumbnails/ch_to_ry_cz_ry.svg :class:`~.RY` | :math:`2` :class:`~.CZ` | :math:`1` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/ch_adjoint.svg :region: adjoint :where: :class:`~.CH` is self-adjoint :class:`~.CH` | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/ch_pow_period.svg :region: pow :where: :class:`~.CH` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.CH` (odd :math:`z`) | :math:`1` :class:`Pow(CH) <.CH>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ wire_argnames = ("wires",) arg_specs = {"wires": Wire[2]} wire_sizes = (2,) num_wires = 2 """int: Number of wires that the operation acts on.""" num_params = 0 """int: Number of trainable parameters that the operator depends on.""" ndim_params = () """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" name = "CH" def __init__(self, wires: WiresLike): super().__init__(qp.H(wires[1:]), wires[:1])
[docs] @override def adjoint(self): return CH(self.wires)
[docs] @staticmethod def compute_matrix(wires: WiresLike = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CH.matrix` Args: wires (Iterable, Wires): optional wires that the operator acts on Returns: ndarray: matrix **Example** >>> print(qp.CH.compute_matrix()) [[ 1. 0. 0. 0. ] [ 0. 1. 0. 0. ] [ 0. 0. 0.707... 0.707...] [ 0. 0. 0.707... -0.707...]] """ return np.array( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, INV_SQRT2, INV_SQRT2], [0, 0, INV_SQRT2, -INV_SQRT2], ] )
def _ch_to_ry_cz_ry_resources(wires: WiresLike = None): return {qp.RY: 2, qp.CZ: 1} @register_resources(_ch_to_ry_cz_ry_resources, name="to_ry_cz_ry") def _ch_to_ry_cz_ry(wires: WiresLike, **__): qp.RY(-np.pi / 4, wires=wires[1]) qp.CZ(wires=wires) qp.RY(+np.pi / 4, wires=wires[1]) add_decomps(CH, _ch_to_ry_cz_ry) add_decomps("Adjoint(CH)", self_adjoint) add_decomps("Pow(CH)", pow_involutory2)
[docs] class CY(Controlled2): r"""CY(wires) The controlled-Y operator .. math:: CY = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0\\ 0 & 0 & 0 & -i\\ 0 & 0 & i & 0 \end{bmatrix}. .. note:: The first wire provided corresponds to the **control qubit**. **Details:** * Number of wires: 2 * Number of parameters: 0 Args: wires (Sequence[int]): the wires the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CY .. decomposition-rule:: to_ry_cnot :image: /_static/decomposition_thumbnails/cy_decomp.svg :class:`~.CRY` | :math:`1` :class:`~.S` | :math:`1` .. decomposition-rule:: to_ppr :image: /_static/decomposition_thumbnails/cy_to_ppr.svg :class:`PPR_4(-1, "Z") <.PPR_4>` | :math:`1` :class:`PPR_4(-1, "Y") <.PPR_4>` | :math:`1` :class:`PPR_4(1, "ZY") <.PPR_4>` | :math:`1` :class:`~.GlobalPhase` | :math:`1` .. decomposition-rule:: lattice_surgery_ppm :image: /_static/decomposition_thumbnails/cy_lattice_surgery_ppm.svg :requires: 1 work wire (not restored) :func:`PauliMeasure("ZX") <.pauli_measure>` | :math:`1` :func:`PauliMeasure("ZY") <.pauli_measure>` | :math:`1` :func:`PauliMeasure("X") <.pauli_measure>` | :math:`1` :class:`~.PauliZ` (conditional) | :math:`2` :class:`~.PauliY` (conditional) | :math:`1` :class:`~.GlobalPhase` (conditional) | :math:`1` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/cy_adjoint.svg :region: adjoint :where: :class:`~.CY` is self-adjoint :class:`~.CY` | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/cy_pow_period.svg :region: pow :where: :class:`~.CY` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.CY` (odd :math:`z`) | :math:`1` :class:`Pow(CY) <.CY>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ arg_specs = {"wires": Wire[2]} num_wires = 2 """int: Number of wires that the operator acts on.""" num_params = 0 """int: Number of trainable parameters that the operator depends on.""" ndim_params = () """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" def __init__(self, wires: WiresLike): super().__init__(qp.Y(wires[1:]), wires[:1])
[docs] def adjoint(self): return CY(self.wires)
[docs] @staticmethod @override def compute_matrix(wires: WiresLike | None = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CY.matrix` Returns: ndarray: matrix **Example** >>> print(qp.CY.compute_matrix()) [[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j] [ 0.+0.j 1.+0.j 0.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j -0.-1.j] [ 0.+0.j 0.+0.j 0.+1.j 0.+0.j]] """ return np.array( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, -1j], [0, 0, 1j, 0], ] )
def _cy_to_ry_cnot_resources(wires: AbstractWires): return {qp.CRY: 1, qp.S: 1} @register_resources(_cy_to_ry_cnot_resources, name="to_ry_cnot") def _cy_to_ry_cnot(wires: WiresLike, **__): qp.CRY(np.pi, wires=wires) qp.S(wires=wires[0]) def _pauli_ctrl_pauli_ppr_resources(wires: AbstractWires, pauli0, pauli1): """Resources for _pauli_ctrl_pauli_ppr.""" resources = defaultdict(int) p0, p1 = pauli0.__name__[-1], pauli1.__name__[-1] resources[qp.PPR_4(-1, pauli_word=p0, wires=Wire[len(p0)])] += 1 resources[qp.PPR_4(-1, pauli_word=p1, wires=Wire[len(p1)])] += 1 resources[qp.PPR_4(1, pauli_word=p0 + p1, wires=Wire[len(p0 + p1)])] += 1 resources[qp.GlobalPhase] += 1 return dict(resources) def _pauli_ctrl_pauli_ppr(wires: AbstractWires, pauli0, pauli1): """Generalized two-qubit Pauli-controlled Pauli gate decomposition to PPRs.""" p0, p1 = pauli0.__name__[-1], pauli1.__name__[-1] qp.PPR_4(-1, p0, wires=wires[0]) qp.PPR_4(-1, p1, wires=wires[1]) qp.PPR_4(1, p0 + p1, wires=wires) qp.GlobalPhase(np.pi / 4) @register_resources(partial(_pauli_ctrl_pauli_ppr_resources, pauli0=Z, pauli1=Y), name="to_ppr") def _cy_to_ppr(wires: AbstractWires): _pauli_ctrl_pauli_ppr(wires, qp.Z, qp.Y) def _pauli_ctrl_pauli_ppm(wires, pauli0, pauli1): """Generalized two-qubit Pauli-controlled Pauli gate decomposition to PPMs.""" with qp.allocate(1, state="zero", restored=False) as work_wires: m0 = pauli_measure(pauli0.__name__[-1] + "X", [wires[0], work_wires[0]]) m1 = pauli_measure("Z" + pauli1.__name__[-1], [work_wires[0], wires[1]]) m2 = pauli_measure("X", work_wires) qp.cond(m1, pauli0)(wires[0]) qp.cond(m0 != m2, pauli1)(wires[1]) qp.cond(m1 & (m0 != m2), qp.GlobalPhase)(np.pi) qp.cond(m2, qp.Z)(work_wires[0]) # Reset work wire (to |+>), achieving pure state @qp.register_resources( { PauliMeasure("ZX", wires=Wire[2]): 1, PauliMeasure("ZY", wires=Wire[2]): 1, PauliMeasure("X", wires=Wire[1]): 1, Z: 2, Y: 1, GlobalPhase: 1, }, work_wires={"burnable": 1}, name="lattice_surgery_ppm", ) def _cy_lattice_surgery_ppm(wires: AbstractWires): _pauli_ctrl_pauli_ppm(wires, qp.Z, qp.Y) add_decomps(CY, _cy_to_ry_cnot, _cy_to_ppr, _cy_lattice_surgery_ppm) add_decomps("Adjoint(CY)", self_adjoint) add_decomps("Pow(CY)", pow_involutory2)
[docs] class CZ(Controlled2): r"""CZ(wires) The controlled-Z operator .. math:: CZ = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & -1 \end{bmatrix}. .. note:: The first wire provided corresponds to the **control qubit**. **Details:** * Number of wires: 2 * Number of parameters: 0 Args: wires (Sequence[int]): the wires the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CZ .. decomposition-rule:: to_cps :image: /_static/decomposition_thumbnails/cz_to_cps.svg :class:`~.ControlledPhaseShift` | :math:`1` .. decomposition-rule:: to_cnot :image: /_static/decomposition_thumbnails/cz_to_cnot.svg :class:`~.Hadamard` | :math:`2` :class:`~.CNOT` | :math:`1` .. decomposition-rule:: to_ppr :image: /_static/decomposition_thumbnails/cz_to_ppr.svg :class:`PPR_4(-1, "Z") <.PPR_4>` | :math:`2` :class:`PPR_4(1, "ZZ") <.PPR_4>` | :math:`1` :class:`~.GlobalPhase` | :math:`1` .. decomposition-rule:: lattice_surgery_ppm :image: /_static/decomposition_thumbnails/cz_lattice_surgery_ppm.svg :requires: 1 work wire (not restored) :func:`PauliMeasure("ZX") <.pauli_measure>` | :math:`1` :func:`PauliMeasure("ZZ") <.pauli_measure>` | :math:`1` :func:`PauliMeasure("X") <.pauli_measure>` | :math:`1` :class:`~.PauliZ` (conditional) | :math:`3` :class:`~.GlobalPhase` (conditional) | :math:`1` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/cz_adjoint.svg :region: adjoint :where: :class:`~.CZ` is self-adjoint :class:`~.CZ` | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/cz_pow_period.svg :region: pow :where: :class:`~.CZ` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.CZ` (odd :math:`z`) | :math:`1` :class:`Pow(CZ) <.CZ>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ arg_specs = {"wires": Wire[2]} name = "CZ" num_wires = 2 """int: Number of wires that the operator acts on.""" num_params = 0 """int: Number of trainable parameters that the operator depends on.""" ndim_params = () """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" def __init__(self, wires: WiresLike): super().__init__(qp.Z(wires[1:]), wires[:1]) def __repr__(self): return f"CZ(wires={self.wires})"
[docs] def adjoint(self): return CZ(self.wires)
[docs] @staticmethod def compute_matrix(wires: WiresLike = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CZ.matrix` Returns: ndarray: matrix **Example** >>> print(qp.CZ.compute_matrix()) [[ 1 0 0 0] [ 0 1 0 0] [ 0 0 1 0] [ 0 0 0 -1]] """ return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])
def _cz_to_cps_resources(wires: AbstractWires): return {qp.ControlledPhaseShift: 1} @register_resources(_cz_to_cps_resources, name="to_cps") def _cz_to_cps(wires: WiresLike): qp.ControlledPhaseShift(np.pi, wires=wires) def _cz_to_cnot_resources(wires: AbstractWires): return {qp.H: 2, qp.CNOT: 1} @register_resources(_cz_to_cnot_resources, name="to_cnot") def _cz_to_cnot(wires: WiresLike): qp.H(wires=wires[1]) qp.CNOT(wires=wires) qp.H(wires=wires[1]) @register_resources(partial(_pauli_ctrl_pauli_ppr_resources, pauli0=Z, pauli1=Z), name="to_ppr") def _cz_to_ppr(wires: AbstractWires): _pauli_ctrl_pauli_ppr(wires, qp.Z, qp.Z) def _cz_lattice_surgery_ppm_resources(wires: AbstractWires): return { PauliMeasure("ZX", wires=Wire[2]): 1, PauliMeasure("ZZ", wires=Wire[2]): 1, PauliMeasure("X", wires=Wire[1]): 1, qp.Z: 3, qp.GlobalPhase: 1, } @qp.register_resources( _cz_lattice_surgery_ppm_resources, work_wires={"burnable": 1}, name="lattice_surgery_ppm" ) def _cz_lattice_surgery_ppm(wires: WiresLike): _pauli_ctrl_pauli_ppm(wires, qp.Z, qp.Z) add_decomps(CZ, _cz_to_cps, _cz_to_cnot, _cz_to_ppr, _cz_lattice_surgery_ppm) add_decomps("Adjoint(CZ)", self_adjoint) add_decomps("Pow(CZ)", pow_involutory2)
[docs] class CSWAP(Controlled2): r"""CSWAP(wires) The controlled-swap operator .. math:: CSWAP = \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \end{bmatrix}. .. note:: The first wire provided corresponds to the **control qubit**. **Details:** * Number of wires: 3 * Number of parameters: 0 Args: wires (Sequence[int]): the wires the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CSWAP .. decomposition-rule:: to_cnot_toffoli :image: /_static/decomposition_thumbnails/cswap_decomp.svg :class:`~.CNOT` | :math:`2` :class:`~.Toffoli` | :math:`1` .. decomposition-rule:: to_ppr :image: /_static/decomposition_thumbnails/cswap_to_ppr.svg :class:`PPR_8(-1, "ZZZ") <.PPR_8>` | :math:`1` :class:`PPR_8(-1, "ZYY") <.PPR_8>` | :math:`1` :class:`PPR_8(-1, "ZXX") <.PPR_8>` | :math:`1` :class:`PPR_8(1, "ZZ") <.PPR_8>` | :math:`1` :class:`PPR_8(1, "YY") <.PPR_8>` | :math:`1` :class:`PPR_8(1, "XX") <.PPR_8>` | :math:`1` :class:`PPR_8(1, "Z") <.PPR_8>` | :math:`1` :class:`~.GlobalPhase` | :math:`1` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/cswap_adjoint.svg :region: adjoint :where: :class:`~.CSWAP` is self-adjoint :class:`~.CSWAP` | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/cswap_pow_period.svg :region: pow :where: :class:`~.CSWAP` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.CSWAP` (odd :math:`z`) | :math:`1` :class:`Pow(CSWAP) <.CSWAP>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ wire_argnames = ("wires",) arg_specs = {"wires": Wire[3]} wire_sizes = (3,) num_wires = 3 """int : Number of wires that the operation acts on.""" num_params = 0 """int: Number of trainable parameters that the operator depends on.""" ndim_params = () """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" def __init__(self, wires: WiresLike): super().__init__(qp.SWAP(wires[1:]), wires[:1])
[docs] @override def adjoint(self): return CSWAP(self.wires)
[docs] @staticmethod def compute_matrix(wires: WiresLike = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CSWAP.matrix` Args: wires (Iterable, Wires): optional wires that the operator acts on Returns: ndarray: matrix **Example** >>> print(qp.CSWAP.compute_matrix()) [[1 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0] [0 0 1 0 0 0 0 0] [0 0 0 1 0 0 0 0] [0 0 0 0 1 0 0 0] [0 0 0 0 0 0 1 0] [0 0 0 0 0 1 0 0] [0 0 0 0 0 0 0 1]] """ return np.array( [ [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], ] )
def _cswap_to_cnot_toffoli_resources(wires: WiresLike = None): return {qp.CNOT: 2, qp.Toffoli: 1} @register_resources(_cswap_to_cnot_toffoli_resources, name="to_cnot_toffoli") def _cswap_to_cnot_toffoli(wires: WiresLike, **__): qp.CNOT([wires[2], wires[1]]) qp.Toffoli(wires=[wires[0], wires[1], wires[2]]) qp.CNOT([wires[2], wires[1]]) def _cswap_to_ppr_resources(wires: WiresLike = None): return { qp.PPR_8(-1, pauli_word="ZZZ", wires=Wire[3]): 1, qp.PPR_8(-1, pauli_word="ZYY", wires=Wire[3]): 1, qp.PPR_8(-1, pauli_word="ZXX", wires=Wire[3]): 1, qp.PPR_8(1, pauli_word="ZZ", wires=Wire[2]): 1, qp.PPR_8(1, pauli_word="YY", wires=Wire[2]): 1, qp.PPR_8(1, pauli_word="XX", wires=Wire[2]): 1, qp.PPR_8(1, pauli_word="Z", wires=Wire[1]): 1, qp.GlobalPhase: 1, } @register_resources(_cswap_to_ppr_resources, name="to_ppr") def _cswap_to_ppr(wires: WiresLike, **_): qp.PPR_8(-1, "ZZZ", wires=wires) qp.PPR_8(-1, "ZYY", wires=wires) qp.PPR_8(-1, "ZXX", wires=wires) qp.PPR_8(1, "ZZ", wires=wires[1:]) qp.PPR_8(1, "YY", wires=wires[1:]) qp.PPR_8(1, "XX", wires=wires[1:]) qp.PPR_8(1, "Z", wires=wires[0]) qp.GlobalPhase(-np.pi / 8) add_decomps(CSWAP, _cswap_to_cnot_toffoli, _cswap_to_ppr) add_decomps("Adjoint(CSWAP)", self_adjoint) add_decomps("Pow(CSWAP)", pow_involutory2)
[docs] class CCZ(Controlled2): r"""CCZ(wires) CCZ (controlled-controlled-Z) gate. .. math:: CCZ = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \end{pmatrix} .. note:: The first two wires provided correspond to the **control wires**. The third wire is the **target wire**. **Details:** * Number of wires: 3 * Number of parameters: 0 Args: wires (Sequence[int]): the subsystem the gate acts on **Example** .. code-block:: python import pennylane as qp dev = qp.device("lightning.qubit") @qp.set_shots(1) @qp.qnode(dev) def circuit(): qp.X(0) qp.X(1) qp.H(2) qp.CCZ([0,1,2]) qp.H(2) return qp.sample(wires=[0,1,2]) >>> print(qp.draw(circuit)()) 0: ──X─╭●────┤ ╭Sample 1: ──X─├●────┤ ├Sample 2: ──H─╰Z──H─┤ ╰Sample >>> circuit() array([[1, 1, 1]]) .. details:: :title: Available decompositions .. decomposition-table:: qp.CCZ :stacked: .. decomposition-rule:: to_clifford_t :image: /_static/decomposition_thumbnails/ccz_decomp.svg :class:`~.Hadamard` | :math:`2` :class:`~.CNOT` | :math:`6` :class:`~.T` | :math:`4` :class:`Adjoint(T) <.T>` | :math:`3` .. decomposition-rule:: to_toffoli :image: /_static/decomposition_thumbnails/ccz_to_toffoli.svg :class:`~.Hadamard` | :math:`2` :class:`~.Toffoli` | :math:`1` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/ccz_adjoint.svg :region: adjoint :where: :class:`~.CCZ` is self-adjoint :class:`~.CCZ` | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/ccz_pow_period.svg :region: pow :where: :class:`~.CCZ` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.CCZ` (odd :math:`z`) | :math:`1` :class:`Pow(CCZ) <.CCZ>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ arg_specs = {"wires": Wire[3]} num_wires = 3 """int: Number of wires that the operator acts on.""" num_params = 0 """int: Number of trainable parameters that the operator depends on.""" ndim_params = () """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" def __init__(self, wires: WiresLike): super().__init__(qp.Z(wires[2:]), wires[:2]) def __repr__(self): return f"CCZ(wires={self.wires})"
[docs] def adjoint(self): return CCZ(self.wires)
[docs] @staticmethod def compute_matrix(wires: WiresLike = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CCZ.matrix` Returns: ndarray: matrix **Example** >>> print(qp.CCZ.compute_matrix()) [[ 1 0 0 0 0 0 0 0] [ 0 1 0 0 0 0 0 0] [ 0 0 1 0 0 0 0 0] [ 0 0 0 1 0 0 0 0] [ 0 0 0 0 1 0 0 0] [ 0 0 0 0 0 1 0 0] [ 0 0 0 0 0 0 1 0] [ 0 0 0 0 0 0 0 -1]] """ return np.array( [ [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, -1], ] )
def _ccz_to_clifford_t_resources(wires: AbstractWires): return { qp.CNOT: 6, _adjoint_abstract(qp.T): 3, qp.T: 4, qp.Hadamard: 2, } @register_resources(_ccz_to_clifford_t_resources, name="to_clifford_t") def _ccz_to_clifford_t(wires: WiresLike, **__): qp.CNOT(wires=[wires[1], wires[2]]) qp.adjoint(qp.T(wires=wires[2])) qp.CNOT(wires=[wires[0], wires[2]]) qp.T(wires=wires[2]) qp.CNOT(wires=[wires[1], wires[2]]) qp.adjoint(qp.T(wires=wires[2])) qp.CNOT(wires=[wires[0], wires[2]]) qp.T(wires=wires[2]) qp.T(wires=wires[1]) qp.CNOT(wires=[wires[0], wires[1]]) qp.Hadamard(wires=wires[2]) qp.T(wires=wires[0]) qp.adjoint(qp.T(wires=wires[1])) qp.CNOT(wires=[wires[0], wires[1]]) qp.Hadamard(wires=wires[2]) def _ccz_to_toffoli_resources(wires: AbstractWires): return {qp.Hadamard: 2, qp.Toffoli: 1} @register_resources(_ccz_to_toffoli_resources, name="to_toffoli") def _ccz_to_toffoli(wires: WiresLike, **__): qp.Hadamard(wires[2]) qp.Toffoli(wires) qp.Hadamard(wires[2]) add_decomps(CCZ, _ccz_to_clifford_t, _ccz_to_toffoli) add_decomps("Adjoint(CCZ)", self_adjoint) add_decomps("Pow(CCZ)", pow_involutory2)
[docs] class CNOT(Controlled2): r"""CNOT(wires) The controlled-NOT operator .. math:: CNOT = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 & 1 & 0 \end{bmatrix}. .. note:: The first wire provided corresponds to the **control wire**. The second wire is the **target wire**. **Details:** * Number of wires: 2 * Number of parameters: 0 Args: wires (Sequence[int]): the wires the operation acts on **Example** .. code-block:: python import pennylane as qp dev = qp.device("lightning.qubit") @qp.set_shots(1) @qp.qnode(dev) def circuit(): qp.X(0) qp.CNOT([0,1]) return qp.sample(wires=[0,1]) >>> print(qp.draw(circuit)()) 0: ──X─╭●─┤ ╭Sample 1: ────╰X─┤ ╰Sample >>> circuit() array([[1, 1]]) .. details:: :title: Available decompositions .. decomposition-table:: qp.CNOT .. decomposition-rule:: to_cz_h :image: /_static/decomposition_thumbnails/cnot_to_cz_h.svg :class:`~.Hadamard` | :math:`2` :class:`~.CZ` | :math:`1` .. decomposition-rule:: to_ppr :image: /_static/decomposition_thumbnails/cnot_to_ppr.svg :class:`PPR_4(-1, "Z") <.PPR_4>` | :math:`1` :class:`PPR_4(-1, "X") <.PPR_4>` | :math:`1` :class:`PPR_4(1, "ZX") <.PPR_4>` | :math:`1` :class:`~.GlobalPhase` | :math:`1` .. decomposition-rule:: lattice_surgery_ppm :image: /_static/decomposition_thumbnails/cnot_lattice_surgery_ppm.svg :requires: 1 work wire (not restored) :func:`PauliMeasure("ZX") <.pauli_measure>` | :math:`2` :func:`PauliMeasure("X") <.pauli_measure>` | :math:`1` :class:`~.PauliZ` (conditional) | :math:`2` :class:`~.PauliX` (conditional) | :math:`1` :class:`~.GlobalPhase` (conditional) | :math:`1` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/cnot_adjoint.svg :region: adjoint :where: :class:`~.CNOT` is self-adjoint :class:`~.CNOT` | :math:`1` .. decomposition-rule:: to_mcx :image: /_static/decomposition_thumbnails/cnot_controlled.svg :region: controlled :where: :math:`c` is the number of added control wires, and the circuit shows :math:`c = 2` :class:`~.MultiControlledX` with :math:`c + 1` controls | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/cnot_pow_period.svg :region: pow :where: :class:`~.CNOT` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.CNOT` (odd :math:`z`) | :math:`1` :class:`Pow(CNOT) <.CNOT>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ wire_argnames = ("wires",) arg_specs = {"wires": Wire[2]} wire_sizes = (2,) num_wires = 2 """int: Number of wires that the operator acts on.""" num_params = 0 """int: Number of trainable parameters that the operator depends on.""" ndim_params = () """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" def __init__(self, wires: WiresLike): super().__init__(qp.X(wires[1]), control_wires=wires[:1])
[docs] @override def adjoint(self): return CNOT(self.wires)
[docs] @staticmethod @override def compute_matrix(wires: WiresLike = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CNOT.matrix` Returns: ndarray: matrix **Example** >>> print(qp.CNOT.compute_matrix()) [[1 0 0 0] [0 1 0 0] [0 0 0 1] [0 0 1 0]] """ return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
def _cnot_to_cz_h_resources(wires: WiresLike): return {qp.H: 2, qp.CZ: 1} @register_resources(_cnot_to_cz_h_resources, name="to_cz_h") def _cnot_to_cz_h(wires: WiresLike): qp.H(wires[1]) qp.CZ(wires=wires) qp.H(wires[1]) @register_resources(partial(_pauli_ctrl_pauli_ppr_resources, pauli0=Z, pauli1=X), name="to_ppr") def _cnot_to_ppr(wires: AbstractWires): _pauli_ctrl_pauli_ppr(wires, qp.Z, qp.X) def _cnot_lattice_surgery_ppm_resources(wires: WiresLike): return { PauliMeasure("ZX", wires=Wire[2]): 2, PauliMeasure("X", wires=Wire[1]): 1, qp.Z: 2, qp.X: 1, qp.GlobalPhase: 1, } @qp.register_resources( _cnot_lattice_surgery_ppm_resources, work_wires={"burnable": 1}, name="lattice_surgery_ppm" ) def _cnot_lattice_surgery_ppm(wires: WiresLike): _pauli_ctrl_pauli_ppm(wires, qp.Z, qp.X) add_decomps(CNOT, _cnot_to_cz_h, _cnot_to_ppr, _cnot_lattice_surgery_ppm) add_decomps("Adjoint(CNOT)", self_adjoint) add_decomps("Pow(CNOT)", pow_involutory2) def _ctrl_cnot_to_mcx_resources(base, control_wires, control_values, work_wires, work_wire_type): ctrl_values = _resolve_ctrl_values(control_values, [True], len(control_wires)) return { qp.MultiControlledX( Wire[len(control_wires) + 2], control_values=ctrl_values, work_wires=work_wires, work_wire_type=work_wire_type, ): 1 } @qp.register_resources(_ctrl_cnot_to_mcx_resources, name="to_mcx") def _ctrl_cnot_to_mcx(base, control_wires, control_values, work_wires, work_wire_type): ctrl_values = _resolve_ctrl_values(control_values, [True], len(control_wires)) qp.MultiControlledX( concatenate_wires(control_wires, base.wires), control_values=ctrl_values, work_wires=work_wires, work_wire_type=work_wire_type, ) add_decomps("C(CNOT)", _ctrl_cnot_to_mcx)
[docs] class Toffoli(Controlled2): r"""Toffoli(wires) Toffoli (controlled-controlled-X) gate. .. math:: Toffoli = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \end{pmatrix} .. note:: The first two wires provided correspond to the **control wires**. The third wire is the **target wire**. **Details:** * Number of wires: 3 * Number of parameters: 0 Args: wires (Sequence[int]): the subsystem the gate acts on **Example** .. code-block:: python import pennylane as qp dev = qp.device("lightning.qubit") @qp.set_shots(1) @qp.qnode(dev) def circuit(): qp.X(0) qp.X(1) qp.Toffoli([0,1,2]) return qp.sample(wires=[0,1,2]) >>> print(qp.draw(circuit)()) 0: ──X─╭●─┤ ╭Sample 1: ──X─├●─┤ ├Sample 2: ────╰X─┤ ╰Sample >>> circuit() array([[1, 1, 1]]) .. details:: :title: Available decompositions .. decomposition-table:: qp.Toffoli :stacked: .. decomposition-rule:: to_clifford_t :image: /_static/decomposition_thumbnails/toffoli_decomp.svg :class:`~.Hadamard` | :math:`2` :class:`~.CNOT` | :math:`6` :class:`~.T` | :math:`4` :class:`Adjoint(T) <.T>` | :math:`3` .. decomposition-rule:: to_ppr :image: /_static/decomposition_thumbnails/toffoli_to_ppr.svg :class:`PPR_8(-1, "ZZ") <.PPR_8>` | :math:`1` :class:`PPR_8(-1, "ZX") <.PPR_8>` | :math:`2` :class:`PPR_8(1, "ZZX") <.PPR_8>` | :math:`1` :class:`PPR_8(1, "X") <.PPR_8>` | :math:`1` :class:`PPR_8(1, "Z") <.PPR_8>` | :math:`2` :class:`~.GlobalPhase` | :math:`1` .. decomposition-rule:: elbow :image: /_static/decomposition_thumbnails/toffoli_elbow.svg :requires: 1 zeroed work wire :class:`~.TemporaryAND` | :math:`1` :class:`~.CNOT` | :math:`1` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`1` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/toffoli_adjoint.svg :region: adjoint :where: :class:`~.Toffoli` is self-adjoint :class:`~.Toffoli` | :math:`1` .. decomposition-rule:: to_mcx :image: /_static/decomposition_thumbnails/toffoli_controlled.svg :region: controlled :where: :math:`c` is the number of added control wires, and the circuit shows :math:`c = 2` :class:`~.MultiControlledX` with :math:`c + 2` controls | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/toffoli_pow_period.svg :region: pow :where: :class:`~.Toffoli` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.Toffoli` (odd :math:`z`) | :math:`1` :class:`Pow(Toffoli) <.Toffoli>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ wire_argnames = ("wires",) arg_specs = {"wires": Wire[3]} wire_sizes = (3,) num_wires = 3 """int: Number of wires that the operator acts on.""" num_params = 0 """int: Number of trainable parameters that the operator depends on.""" ndim_params = () """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" def __init__(self, wires): super().__init__(qp.X(wires[2]), wires[:2])
[docs] @override def adjoint(self): return Toffoli(self.wires)
[docs] @staticmethod @override def compute_matrix(wires: WiresLike = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.Toffoli.matrix` Returns: ndarray: matrix **Example** >>> print(qp.Toffoli.compute_matrix()) [[1 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0] [0 0 1 0 0 0 0 0] [0 0 0 1 0 0 0 0] [0 0 0 0 1 0 0 0] [0 0 0 0 0 1 0 0] [0 0 0 0 0 0 0 1] [0 0 0 0 0 0 1 0]] """ return np.array( [ [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], ] )
def _toffoli_to_clifford_t_resources(wires: WiresLike): return { qp.Hadamard: 2, qp.CNOT: 6, qp.T: 4, _adjoint_abstract(qp.T): 3, } @register_resources(_toffoli_to_clifford_t_resources, name="to_clifford_t") def _toffoli_to_clifford_t(wires: WiresLike): qp.Hadamard(wires=wires[2]) CNOT(wires=[wires[1], wires[2]]) qp.adjoint(qp.T(wires=wires[2])) CNOT(wires=[wires[0], wires[2]]) qp.T(wires=wires[2]) CNOT(wires=[wires[1], wires[2]]) qp.adjoint(qp.T(wires=wires[2])) CNOT(wires=[wires[0], wires[2]]) qp.T(wires=wires[2]) qp.T(wires=wires[1]) CNOT(wires=[wires[0], wires[1]]) qp.Hadamard(wires=wires[2]) qp.T(wires=wires[0]) qp.adjoint(qp.T(wires=wires[1])) CNOT(wires=[wires[0], wires[1]]) def _toffoli_to_ppr_resources(wires: WiresLike): return { qp.PPR_8(-1, pauli_word="ZZ", wires=Wire[2]): 1, qp.PPR_8(-1, pauli_word="ZX", wires=Wire[2]): 2, qp.PPR_8(1, pauli_word="ZZX", wires=Wire[3]): 1, qp.PPR_8(1, pauli_word="X", wires=Wire[1]): 1, qp.PPR_8(1, pauli_word="Z", wires=Wire[1]): 2, qp.GlobalPhase: 1, } @register_resources(_toffoli_to_ppr_resources, name="to_ppr") def _toffoli_to_ppr(wires: WiresLike): qp.PPR_8(-1, "ZZ", wires=wires[:2]) qp.PPR_8(-1, "ZX", wires=[wires[0], wires[2]]) qp.PPR_8(-1, "ZX", wires=wires[1:]) qp.PPR_8(1, "ZZX", wires=wires) qp.PPR_8(1, "X", wires=wires[2]) qp.PPR_8(1, "Z", wires=wires[1]) qp.PPR_8(1, "Z", wires=wires[0]) qp.GlobalPhase(-np.pi / 8) def _toffoli_elbow_resources(*_, **__): return {_change_op_basis_abstract(qp.Elbow, qp.CNOT, qp.adjoint(qp.Elbow(Wire[3]))): 1} @register_resources(_toffoli_elbow_resources, work_wires={"zeroed": 1}, name="elbow") def _toffoli_elbow(wires: WiresLike): with allocate(1, qp.allocation.AllocateState.ZERO, restored=True) as work_wires: qp.change_op_basis( qp.Elbow([wires[0], wires[1], work_wires[0]]), qp.CNOT([work_wires[0], wires[2]]), ) add_decomps(Toffoli, _toffoli_to_clifford_t, _toffoli_to_ppr, _toffoli_elbow) add_decomps("Adjoint(Toffoli)", self_adjoint) add_decomps("Pow(Toffoli)", pow_involutory2) def _ctrl_toffoli_to_mcx_resources(base, control_wires, control_values, work_wires, work_wire_type): ctrl_values = _resolve_ctrl_values(control_values, [True, True], len(control_wires)) return { qp.MultiControlledX( Wire[len(control_wires) + 3], control_values=ctrl_values, work_wires=work_wires, work_wire_type=work_wire_type, ): 1 } @qp.register_resources(_ctrl_toffoli_to_mcx_resources, name="to_mcx") def _ctrl_toffoli_to_mcx(base, control_wires, control_values, work_wires, work_wire_type): ctrl_values = _resolve_ctrl_values(control_values, [True, True], len(control_wires)) qp.MultiControlledX( concatenate_wires(control_wires, base.wires), control_values=ctrl_values, work_wires=work_wires, work_wire_type=work_wire_type, ) add_decomps("C(Toffoli)", _ctrl_toffoli_to_mcx)
[docs] class MultiControlledX(Controlled2): r"""Apply a :class:`~.PauliX` gate controlled on an arbitrary computational basis state. **Details:** * Number of wires: Any (the operation can act on any number of wires) * Number of parameters: 1 (the non-differentiable ``control_values``) * Gradient recipe: None Args: wires (WiresLike): control wire(s) followed by a single target wire (the last entry of ``wires``) where the operation acts on control_values (Union[bool, list[bool], int, list[int]]): The value(s) the control wire(s) should take. Integers other than 0 or 1 will be treated as :code:`int(bool(x))`. work_wires (WiresLike): optional work wires used to decompose the operation into a series of :class:`~.Toffoli` gates work_wire_type (str): whether the work wires are ``"zeroed"`` or ``"borrowed"``. ``"zeroed"`` indicates that the work wires are in the state :math:`|0\rangle`, while ``"borrowed"`` indicates that the work wires are in an arbitrary state. Defaults to ``"borrowed"``. .. note:: If :class:`~.MultiControlledX` is not supported on the targeted device, PennyLane will decompose the operation into :class:`~.Toffoli` and/or :class:`~.CNOT` gates. When controlling on three or more wires, the Toffoli-based decompositions described in Lemmas 7.2 of `Barenco et al. <https://arxiv.org/abs/quant-ph/9503016>`__ and Sec 5 of `Khattar and Gidney <https://arxiv.org/abs/2407.17966>`__ will be used. These methods require at least one work wire. The number of work wires provided determines the decomposition method used and the resulting number of Toffoli gates required. When :class:`~.MultiControlledX` is controlling on :math:`n` wires: #. If at least :math:`n - 2` work wires are provided, the decomposition in Lemma 7.2 will be applied using the first :math:`n - 2` work wires. #. If at least :math:`2` work wires are provided, Sec. 5.2 and 5.4 of Khattar and Gidney will be used depending on whether the ``work_wire_type`` is ``"zeroed"`` or ``"borrowed"``. #. If at least :math:`1` work wire is provided, Sec. 5.1 and 5.3 of Khattar and Gidney will be used depending on whether the ``work_wire_type`` is ``"zeroed"`` or ``"borrowed"``. These methods present a tradeoff between qubit number and depth. The method in point 1 requires fewer Toffoli gates but a greater number of qubits. Note that the state of the work wires before and after the decomposition takes place is unchanged. .. details:: :title: Available decompositions .. decomposition-table:: qp.MultiControlledX :stacked: :symbols: :math:`c` control wires and :math:`w` work wires .. decomposition-rule:: to_cnot_or_toffoli :image: /_static/decomposition_thumbnails/mcx_to_cnot_or_toffoli.svg :where: :math:`c \leq 2`, the circuit shows :math:`c = 2`, and a control value of :math:`0` adds :class:`~.PauliX` gates, not included in the counts: one on the target if :math:`c = 1`, and two per such control wire if :math:`c = 2` :class:`~.CNOT` (:math:`c = 1`) | :math:`1` :class:`~.Toffoli` (:math:`c = 2`) | :math:`1` .. decomposition-rule:: two_controls_elbows :image: /_static/decomposition_thumbnails/mcx_two_controls_elbows.svg :requires: :math:`w \geq 1` zeroed work wire :where: :math:`c = 2`, the circuit shows :math:`c = 2`, with 1 zeroed work wire, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.TemporaryAND` | :math:`1` :class:`~.CNOT` | :math:`1` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`1` .. decomposition-rule:: many_work_wires :image: /_static/decomposition_thumbnails/mcx_many_workers.svg :requires: :math:`w \geq c - 2` work wires :where: :math:`c \geq 3`, :math:`s = [w > c - 2]` is 1 if :math:`w > c - 2` and 0 otherwise, counts are for zeroed / borrowed work wires, the circuit shows :math:`c = 4`, with 2 zeroed work wires, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.TemporaryAND` | :math:`c - 2` / :math:`0` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`c - 2` / :math:`0` :class:`~.Toffoli` | :math:`1 - s` / :math:`4(c - 2) - s` :class:`~.MultiControlledX` with :math:`2` controls | :math:`s` / :math:`s` .. decomposition-rule:: two_work_wires :image: /_static/decomposition_thumbnails/mcx_two_workers.svg :requires: :math:`w \geq 2` work wires, or :math:`w = 1` if :math:`c < 6` :where: :math:`c \geq 3`, :math:`s = [c < 6]` is 1 if :math:`c < 6` and 0 otherwise, counts are for zeroed / borrowed work wires, the circuit shows :math:`c = 4`, with 2 zeroed work wires, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.Toffoli` | :math:`c - 3 + s` / :math:`2c - 2s` :class:`Adjoint(Toffoli) <.Toffoli>` | :math:`c - 4 + s` / :math:`2(c - 4 + s)` :class:`~.PauliX` | :math:`c - 4 + s` / :math:`2(c - 4 + s)` :class:`Adjoint(PauliX) <.PauliX>` | :math:`c - 4 + s` / :math:`2(c - 4 + s)` :class:`~.TemporaryAND` | :math:`2 - s` / :math:`0` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`2 - s` / :math:`0` .. decomposition-rule:: one_work_wire :image: /_static/decomposition_thumbnails/mcx_one_worker.svg :requires: :math:`w = 1` work wire :where: :math:`c \geq 3`, counts are for zeroed / borrowed work wires, the circuit shows :math:`c = 4`, with 1 zeroed work wire, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.Toffoli` | :math:`c - 2` / :math:`2c - 2` :class:`Adjoint(Toffoli) <.Toffoli>` | :math:`c - 3` / :math:`2(c - 3)` :class:`~.PauliX` | :math:`c - 3` / :math:`2(c - 3)` :class:`Adjoint(PauliX) <.PauliX>` | :math:`c - 3` / :math:`2(c - 3)` :class:`~.TemporaryAND` | :math:`1` / :math:`0` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`1` / :math:`0` .. decomposition-rule:: no_work_wires :image: /_static/decomposition_thumbnails/mcx_no_worker.svg :where: :math:`c \geq 3` and :math:`w = 0`, the circuit shows :math:`c = 4`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.Hadamard` | :math:`2` :class:`~.QubitUnitary` | :math:`2` :class:`Adjoint(QubitUnitary) <.QubitUnitary>` | :math:`2` :class:`~.PhaseShift` with :math:`c - 1` controls | :math:`1` :class:`~.MultiControlledX` with :math:`\lceil c/2 \rceil` controls | :math:`2` :class:`~.MultiControlledX` with :math:`\lfloor c/2 \rfloor` controls | :math:`2` .. decomposition-rule:: two_controls_elbows_allocated :image: /_static/decomposition_thumbnails/mcx_alloc_two_controls_elbows.svg :requires: 1 zeroed work wire, allocated by the rule :where: :math:`c = 2` and :math:`w = 0`, the circuit shows :math:`c = 2`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.TemporaryAND` | :math:`1` :class:`~.CNOT` | :math:`1` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`1` .. decomposition-rule:: two_zeroed_work_wires :image: /_static/decomposition_thumbnails/mcx_alloc_two_zeroed_work_wires.svg :requires: 2 zeroed work wires, allocated by the rule :where: :math:`c \geq 3` and :math:`w = 0`, :math:`s = [c < 6]` is 1 if :math:`c < 6` and 0 otherwise, the circuit shows :math:`c = 4`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.Toffoli` | :math:`c - 3 + s` :class:`Adjoint(Toffoli) <.Toffoli>` | :math:`c - 4 + s` :class:`~.PauliX` | :math:`c - 4 + s` :class:`Adjoint(PauliX) <.PauliX>` | :math:`c - 4 + s` :class:`~.TemporaryAND` | :math:`2 - s` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`2 - s` .. decomposition-rule:: two_borrowed_work_wires :image: /_static/decomposition_thumbnails/mcx_alloc_two_borrowed_work_wires.svg :requires: 2 borrowed work wires, allocated by the rule :where: :math:`c \geq 3` and :math:`w = 0`, :math:`s = [c < 6]` is 1 if :math:`c < 6` and 0 otherwise, the circuit shows :math:`c = 4`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.Toffoli` | :math:`2c - 2s` :class:`Adjoint(Toffoli) <.Toffoli>` | :math:`2(c - 4 + s)` :class:`~.PauliX` | :math:`2(c - 4 + s)` :class:`Adjoint(PauliX) <.PauliX>` | :math:`2(c - 4 + s)` .. decomposition-rule:: one_zeroed_work_wire :image: /_static/decomposition_thumbnails/mcx_alloc_one_zeroed_work_wire.svg :requires: 1 zeroed work wire, allocated by the rule :where: :math:`c \geq 3` and :math:`w = 0`, the circuit shows :math:`c = 4`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.Toffoli` | :math:`c - 2` :class:`Adjoint(Toffoli) <.Toffoli>` | :math:`c - 3` :class:`~.PauliX` | :math:`c - 3` :class:`Adjoint(PauliX) <.PauliX>` | :math:`c - 3` :class:`~.TemporaryAND` | :math:`1` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`1` .. decomposition-rule:: one_borrowed_work_wire :image: /_static/decomposition_thumbnails/mcx_alloc_one_borrowed_work_wire.svg :requires: 1 borrowed work wire, allocated by the rule :where: :math:`c \geq 3` and :math:`w = 0`, the circuit shows :math:`c = 4`, and each control wire with control value :math:`0` adds two :class:`~.PauliX` gates, not included in the counts :class:`~.Toffoli` | :math:`2c - 2` :class:`Adjoint(Toffoli) <.Toffoli>` | :math:`2(c - 3)` :class:`~.PauliX` | :math:`2(c - 3)` :class:`Adjoint(PauliX) <.PauliX>` | :math:`2(c - 3)` .. decomposition-rule:: to_base :image: /_static/decomposition_thumbnails/mcx_adjoint.svg :region: adjoint :where: :class:`~.MultiControlledX` is self-adjoint :class:`~.MultiControlledX` | :math:`1` .. decomposition-rule:: to_mcx :image: /_static/decomposition_thumbnails/mcx_controlled.svg :region: controlled :where: :math:`c'` is the number of added control wires, and the circuit shows :math:`c' = 2` :class:`~.MultiControlledX` with :math:`c + c'` controls | :math:`1` .. decomposition-rule:: reduce_period :image: /_static/decomposition_thumbnails/mcx_pow_period.svg :region: pow :where: :class:`~.MultiControlledX` is its own inverse, so only :math:`z \bmod 2` matters, the rule applies if :math:`z \geq 2` or :math:`z < 0`, and the circuit shows :math:`z = 3` :class:`~.MultiControlledX` (odd :math:`z`) | :math:`1` :class:`Pow(MultiControlledX) <.MultiControlledX>` with power :math:`z \bmod 2` (non-integer :math:`z`) | :math:`1` """ num_params = 1 """int: Number of dynamic parameters that the operator depends on.""" ndim_params = (1,) """tuple[int]: Number of dimensions per dynamic parameter that the operator depends on.""" dynamic_argnames = ("control_values",) wire_argnames = ("wires", "work_wires") compilable_argnames = ("work_wire_type",) arg_specs = {"control_values": Bool[-1], "wires": Wire[-1], "work_wires": Wire[-1]} def __init__( self, wires: WiresLike, control_values: int | bool | Sequence[int | bool] | None = None, work_wires: WiresLike | None = None, work_wire_type: Literal["zeroed", "borrowed"] = "borrowed", ): arguments = _setup_inputs_mcx(wires, control_values, work_wires, work_wire_type) super().__init__( base=qp.X(arguments["wires"][-1]), control_wires=arguments["wires"][:-1], control_values=arguments["control_values"], work_wires=arguments["work_wires"], work_wire_type=arguments["work_wire_type"], ) def __repr__(self): params = [f"wires={self.wires}"] ctrl_values = self.control_values # Same convention as ``Controlled2.__repr__``: trivial (all-``True``) control values and # the absence of work wires are not shown. if isinstance(ctrl_values, AbstractArray) or math.is_tracer(ctrl_values): params.append(f"control_values={ctrl_values}") elif not all(ctrl_values): params.append(f"control_values={ctrl_values.tolist()}") if self.work_wires: params.append(f"work_wires={self.work_wires}") params.append(f"work_wire_type={self.work_wire_type}") return f"MultiControlledX({", ".join(params)})"
[docs] @override def adjoint(self): return MultiControlledX( wires=self.wires, control_values=self.control_values, work_wires=self.work_wires, work_wire_type=self.work_wire_type, )
[docs] @staticmethod @override def compute_matrix( wires: WiresLike, control_values: int | bool | Sequence[int | bool] | None = None, work_wires: WiresLike | None = None, work_wire_type: Literal["zeroed", "borrowed"] = "borrowed", ): arguments = _setup_inputs_mcx(wires, control_values, work_wires, work_wire_type) control_wires = arguments["wires"][:-1] ctrl_vals = arguments["control_values"] padding_left = sum(2**i * int(v) for i, v in enumerate(reversed(ctrl_vals))) * 2 padding_right = 2 ** (len(control_wires) + 1) - 2 - padding_left return block_diag(np.eye(padding_left), qp.X.compute_matrix(), np.eye(padding_right))
[docs] @classmethod @override def compute_decomposition( cls, wires: WiresLike, control_values: int | bool | Sequence[int | bool] | None = None, work_wires: WiresLike | None = None, work_wire_type: Literal["zeroed", "borrowed"] = "borrowed", ): """Chooses the best decomposition rule for MCX.""" arguments = _setup_inputs_mcx(wires, control_values, work_wires, work_wire_type) if len(arguments["wires"]) <= 3: return _to_op_list(_mcx_to_cnot_or_toffoli)(**arguments) n_ctrl_wires = len(arguments["wires"]) - 1 if len(arguments["work_wires"]) >= n_ctrl_wires - 2: return _to_op_list(_mcx_many_work_wires)(**arguments) if len(arguments["work_wires"]) >= 2: return _to_op_list(_mcx_two_work_wires)(**arguments) if len(arguments["work_wires"]) == 1: return _to_op_list(_mcx_one_work_wire)(**arguments) return _to_op_list(_mcx_no_work_wires)(**arguments)
def _setup_inputs_mcx( wires: WiresLike, control_values: int | bool | Sequence[int | bool] | None = None, work_wires: WiresLike | None = None, work_wire_type: Literal["zeroed", "borrowed"] = "borrowed", ): # Validate and canonicalize wire args wires = Wires(wires) if len(wires) < 2: raise ValueError(f"MultiControlledX acts on at least 2 wires, {len(wires)} given.") work_wires = Wires([] if work_wires is None else work_wires) wire_args = {"wires": wires, "work_wires": work_wires} validate_no_wire_overlaps(wire_args) # Validate and canonicalize control values control_values = _setup_control_values(control_values, len(wires) - 1) # Validate work_wire_type _validate_work_wire_type(work_wire_type) # Return processed inputs return { "wires": wires, "control_values": control_values, "work_wires": work_wires, "work_wire_type": work_wire_type, } def _to_op_list(rule): def _inner(*args, **kwargs): with qp.queuing.AnnotatedQueue() as q: rule(*args, **kwargs) if qp.queuing.QueuingManager.recording(): for op in q.queue: qp.apply(op) return q.queue return _inner @_list_decomps.register def _list_mcx_decomps(op: MultiControlledX): # fixed_decomps should override everything if fixed_rule := get_fixed_decomp(op): return DecompCollection([fixed_rule]) if not op.work_wires: return DecompCollection(_list_mcx_no_work_wire_decomps(op)) if len(op.wires) == 2: return [_mcx_to_cnot_or_toffoli] if len(op.wires) == 3: return [_mcx_to_cnot_or_toffoli, _mcx_two_controls_elbows] return [ _mcx_many_work_wires, _mcx_two_work_wires, _mcx_one_work_wire, _mcx_no_work_wires, ] def _list_mcx_no_work_wire_decomps(op: MultiControlledX): if len(op.wires) == 2: return [_mcx_to_cnot_or_toffoli] if len(op.wires) == 3: elbow_rule = _wrap_mcx_rule_w_alloc( _mcx_two_controls_elbows, 1, "zeroed", name="two_controls_elbows_allocated" ) return [_mcx_to_cnot_or_toffoli, elbow_rule] capture_compatible_rules = [ _wrap_mcx_rule_w_alloc(_mcx_two_work_wires, 2, "zeroed", "two_zeroed_work_wires"), _wrap_mcx_rule_w_alloc(_mcx_two_work_wires, 2, "borrowed", "two_borrowed_work_wires"), _wrap_mcx_rule_w_alloc(_mcx_one_work_wire, 1, "zeroed", "one_zeroed_work_wire"), _wrap_mcx_rule_w_alloc(_mcx_one_work_wire, 1, "borrowed", "one_borrowed_work_wire"), _mcx_no_work_wires, ] if qp.capture.enabled(): return capture_compatible_rules # TODO: the following decomposition rules are not capture compatible [sc-129521] return [ _wrap_mcx_rule_w_alloc( _mcx_many_work_wires, len(op.control_wires) - 2, "zeroed", "many_zeroed_work_wires", ), _wrap_mcx_rule_w_alloc( _mcx_many_work_wires, len(op.control_wires) - 2, "borrowed", "many_borrowed_work_wires", ), ] + capture_compatible_rules add_decomps( "MultiControlledX", _mcx_to_cnot_or_toffoli, _mcx_two_controls_elbows, _mcx_many_work_wires, _mcx_two_work_wires, _mcx_one_work_wire, _mcx_no_work_wires, _wrap_mcx_rule_w_alloc( _mcx_two_controls_elbows, 1, "zeroed", name="two_controls_elbows_allocated" ), _wrap_mcx_rule_w_alloc(_mcx_two_work_wires, 2, "zeroed", "two_zeroed_work_wires"), _wrap_mcx_rule_w_alloc(_mcx_two_work_wires, 2, "borrowed", "two_borrowed_work_wires"), _wrap_mcx_rule_w_alloc(_mcx_one_work_wire, 1, "zeroed", "one_zeroed_work_wire"), _wrap_mcx_rule_w_alloc(_mcx_one_work_wire, 1, "borrowed", "one_borrowed_work_wire"), # TODO: include the allocation-wrapped versions of _mcx_many_work_wires # after we support tracer indexing into allocated wires. [sc-129521] ) add_decomps("Adjoint(MultiControlledX)", self_adjoint) add_decomps("Pow(MultiControlledX)", pow_involutory2) def _ctrl_mcx_to_mcx_resources(base, control_wires, control_values, work_wires, work_wire_type): work_wire_type = resolve_work_wire_type( base.work_wires, base.work_wire_type, work_wires, work_wire_type, ) return { qp.MultiControlledX( control_wires + base.wires, control_values=Bool[len(control_values) + len(base.control_values)], work_wires=work_wires + base.work_wires, work_wire_type=work_wire_type, ): 1 } @qp.register_resources(_ctrl_mcx_to_mcx_resources, name="to_mcx") def _ctrl_mcx_to_mcx(base, control_wires, control_values, work_wires, work_wire_type): n_ctrl_wires = len(control_wires) work_wire_type = resolve_work_wire_type( base.work_wires, base.work_wire_type, work_wires, work_wire_type, ) qp.MultiControlledX( concatenate_wires(control_wires, base.wires), control_values=_resolve_ctrl_values(control_values, base.control_values, n_ctrl_wires), work_wires=concatenate_wires(work_wires, base.work_wires), work_wire_type=work_wire_type, ) add_decomps("C(MultiControlledX)", _ctrl_mcx_to_mcx)
[docs] class CRX(Controlled2): r"""The controlled-RX operator .. math:: \begin{align} CR_x(\phi) &= \begin{bmatrix} & 1 & 0 & 0 & 0 \\ & 0 & 1 & 0 & 0\\ & 0 & 0 & \cos(\phi/2) & -i\sin(\phi/2)\\ & 0 & 0 & -i\sin(\phi/2) & \cos(\phi/2) \end{bmatrix}. \end{align} **Details:** * Number of wires: 2 * Number of parameters: 1 * Number of dimensions per parameter: (0,) * Gradient recipe: The controlled-RX operator satisfies a four-term parameter-shift rule (see Appendix F, https://doi.org/10.1088/1367-2630/ac2cb3): .. math:: \frac{d}{d\phi}f(CR_x(\phi)) = c_+ \left[f(CR_x(\phi+a)) - f(CR_x(\phi-a))\right] - c_- \left[f(CR_x(\phi+b)) - f(CR_x(\phi-b))\right] where :math:`f` is an expectation value depending on :math:`CR_x(\phi)`, and - :math:`a = \pi/2` - :math:`b = 3\pi/2` - :math:`c_{\pm} = (\sqrt{2} \pm 1)/{4\sqrt{2}}` Args: phi (float): rotation angle :math:`\phi` wires (Sequence[int]): the wire the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CRX .. decomposition-rule:: to_rx_cz :image: /_static/decomposition_thumbnails/crx_to_rx_cz.svg :class:`~.RX` | :math:`2` :class:`~.CZ` | :math:`2` .. decomposition-rule:: to_rz_ry :image: /_static/decomposition_thumbnails/crx_to_rz_ry.svg :class:`~.RZ` | :math:`2` :class:`~.RY` | :math:`2` :class:`~.CNOT` | :math:`2` .. decomposition-rule:: to_h_crz :image: /_static/decomposition_thumbnails/crx_to_h_crz.svg :class:`~.Hadamard` | :math:`2` :class:`~.CRZ` | :math:`1` .. decomposition-rule:: to_paulirot :image: /_static/decomposition_thumbnails/crx_to_ppr.svg :class:`PauliRot("ZX") <.PauliRot>` | :math:`1` :class:`PauliRot("X") <.PauliRot>` | :math:`1` .. decomposition-rule:: negate_angle :image: /_static/decomposition_thumbnails/crx_adjoint.svg :region: adjoint :where: ``phi`` changes sign :class:`~.CRX` | :math:`1` .. decomposition-rule:: scale_angle :image: /_static/decomposition_thumbnails/crx_pow.svg :region: pow :where: ``phi`` is multiplied by the power :math:`z` :class:`~.CRX` | :math:`1` """ num_wires = 2 """int: Number of wires that the operation acts on.""" num_params = 1 """int: Number of trainable parameters that the operator depends on.""" ndim_params = (0,) """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" dynamic_argnames = ("phi",) arg_specs = {"phi": Float, "wires": Wire[2]} def __init__(self, phi, wires: WiresLike): super().__init__(qp.RX(phi, wires=wires[-1]), control_wires=wires[:-1])
[docs] @override def adjoint(self): return CRX(-self.phi, wires=self.wires)
[docs] @staticmethod @override def compute_matrix(phi, wires: WiresLike | None = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CRX.matrix` Args: phi (tensor_like or float): rotation angle Returns: tensor_like: canonical matrix **Example** >>> qp.CRX.compute_matrix(torch.tensor(0.5)) tensor([[1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [0.0000+0.0000j, 1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [0.0000+0.0000j, 0.0000+0.0000j, 0.9689+0.0000j, 0.0000-0.2474j], [0.0000+0.0000j, 0.0000+0.0000j, 0.0000-0.2474j, 0.9689+0.0000j]]) """ c = qp.math.cos(phi / 2) s = qp.math.sin(phi / 2) # The following avoids casting an imaginary quantity to reals when back propagating c = (1 + 0j) * c js = -1j * s ones = math.ones_like(js) zeros = math.zeros_like(js) matrix = [ [ones, zeros, zeros, zeros], [zeros, ones, zeros, zeros], [zeros, zeros, c, js], [zeros, zeros, js, c], ] return math.stack([stack_last(row) for row in matrix], axis=-2)
def _crx_to_rz_ry_resources(phi, wires): return {qp.RZ: 2, qp.RY: 2, qp.CNOT: 2} @register_resources(_crx_to_rz_ry_resources, name="to_rz_ry") def _crx_to_rz_ry(phi: TensorLike, wires: WiresLike): qp.RZ(np.pi / 2, wires=wires[1]) qp.RY(phi / 2, wires=wires[1]) qp.CNOT(wires=wires) qp.RY(-phi / 2, wires=wires[1]) qp.CNOT(wires=wires) qp.RZ(-np.pi / 2, wires=wires[1]) def _crx_to_rx_cz_resources(phi, wires): return {qp.RX: 2, qp.CZ: 2} @register_resources(_crx_to_rx_cz_resources, name="to_rx_cz") def _crx_to_rx_cz(phi: TensorLike, wires: WiresLike): qp.RX(phi / 2, wires=wires[1]) qp.CZ(wires=wires) qp.RX(-phi / 2, wires=wires[1]) qp.CZ(wires=wires) def _crx_to_h_crz_resources(phi, wires): return {qp.Hadamard: 2, qp.CRZ: 1} @register_resources(_crx_to_h_crz_resources, name="to_h_crz") def _crx_to_h_crz(phi: TensorLike, wires: WiresLike): qp.Hadamard(wires=wires[1]) qp.CRZ(phi, wires=wires) qp.Hadamard(wires=wires[1]) def _crx_to_ppr_resources(phi, wires): return { qp.PauliRot(Float, pauli_word="ZX", wires=Wire[2]): 1, qp.PauliRot(Float, pauli_word="X", wires=Wire[1]): 1, } @register_resources(_crx_to_ppr_resources, name="to_paulirot") def _crx_to_ppr(phi: TensorLike, wires: WiresLike): qp.PauliRot(phi / 2, "X", wires=wires[1]) qp.PauliRot(-phi / 2, "ZX", wires=wires) add_decomps(CRX, _crx_to_rx_cz, _crx_to_rz_ry, _crx_to_h_crz, _crx_to_ppr) add_decomps("Adjoint(CRX)", adjoint_rotation2) add_decomps("Pow(CRX)", pow_rotation2)
[docs] class CRY(Controlled2): r"""The controlled-RY operator .. math:: \begin{align} CR_y(\phi) &= \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0\\ 0 & 0 & \cos(\phi/2) & -\sin(\phi/2)\\ 0 & 0 & \sin(\phi/2) & \cos(\phi/2) \end{bmatrix}. \end{align} **Details:** * Number of wires: 2 * Number of parameters: 1 * Number of dimensions per parameter: (0,) * Gradient recipe: The controlled-RY operator satisfies a four-term parameter-shift rule (see Appendix F, https://doi.org/10.1088/1367-2630/ac2cb3): .. math:: \frac{d}{d\phi}f(CR_y(\phi)) = c_+ \left[f(CR_y(\phi+a)) - f(CR_y(\phi-a))\right] - c_- \left[f(CR_y(\phi+b)) - f(CR_y(\phi-b))\right] where :math:`f` is an expectation value depending on :math:`CR_y(\phi)`, and - :math:`a = \pi/2` - :math:`b = 3\pi/2` - :math:`c_{\pm} = (\sqrt{2} \pm 1)/{4\sqrt{2}}` Args: phi (float): rotation angle :math:`\phi` wires (Sequence[int]): the wire the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CRY .. decomposition-rule:: to_ry_cnot :image: /_static/decomposition_thumbnails/cry_decomp.svg :class:`~.RY` | :math:`2` :class:`~.CNOT` | :math:`2` .. decomposition-rule:: to_paulirot :image: /_static/decomposition_thumbnails/cry_to_ppr.svg :class:`PauliRot("ZY") <.PauliRot>` | :math:`1` :class:`PauliRot("Y") <.PauliRot>` | :math:`1` .. decomposition-rule:: negate_angle :image: /_static/decomposition_thumbnails/cry_adjoint.svg :region: adjoint :where: ``phi`` changes sign :class:`~.CRY` | :math:`1` .. decomposition-rule:: scale_angle :image: /_static/decomposition_thumbnails/cry_pow.svg :region: pow :where: ``phi`` is multiplied by the power :math:`z` :class:`~.CRY` | :math:`1` """ num_wires = 2 """int: Number of wires that the operation acts on.""" num_params = 1 """int: Number of trainable parameters that the operator depends on.""" ndim_params = (0,) """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" dynamic_argnames = ("phi",) arg_specs = {"phi": Float, "wires": Wire[2]} def __init__(self, phi, wires: WiresLike): super().__init__(qp.RY(phi, wires=wires[-1]), control_wires=wires[:-1])
[docs] @override def adjoint(self): return CRY(-self.phi, wires=self.wires)
[docs] @staticmethod @override def compute_matrix(phi, wires: WiresLike | None = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CRY.matrix` Args: phi (tensor_like or float): rotation angle Returns: tensor_like: canonical matrix **Example** >>> qp.CRY.compute_matrix(torch.tensor(0.5)) tensor([[ 1.0000+0.j, 0.0000+0.j, 0.0000+0.j, 0.0000+0.j], [ 0.0000+0.j, 1.0000+0.j, 0.0000+0.j, 0.0000+0.j], [ 0.0000+0.j, 0.0000+0.j, 0.9689+0.j, -0.2474-0.j], [ 0.0000+0.j, 0.0000+0.j, 0.2474+0.j, 0.9689+0.j]]) """ c = qp.math.cos(phi / 2) s = qp.math.sin(phi / 2) # The following avoids casting an imaginary quantity to reals when back propagating c = (1 + 0j) * c s = (1 + 0j) * s ones = math.ones_like(s) zeros = math.zeros_like(s) matrix = [ [ones, zeros, zeros, zeros], [zeros, ones, zeros, zeros], [zeros, zeros, c, -s], [zeros, zeros, s, c], ] return math.stack([stack_last(row) for row in matrix], axis=-2)
def _cry_to_ry_cnot_resources(phi, wires): return {qp.RY: 2, qp.CNOT: 2} @register_resources(_cry_to_ry_cnot_resources, name="to_ry_cnot") def _cry_to_ry_cnot(phi: TensorLike, wires: WiresLike): qp.RY(phi / 2, wires=wires[1]) qp.CNOT(wires=wires) qp.RY(-phi / 2, wires=wires[1]) qp.CNOT(wires=wires) def _cry_to_ppr_resources(phi, wires): return { qp.PauliRot(Float, pauli_word="ZY", wires=Wire[2]): 1, qp.PauliRot(Float, pauli_word="Y", wires=Wire[1]): 1, } @register_resources(_cry_to_ppr_resources, name="to_paulirot") def _cry_to_ppr(phi: TensorLike, wires: WiresLike): qp.PauliRot(phi / 2, "Y", wires=wires[1]) qp.PauliRot(-phi / 2, "ZY", wires=wires) add_decomps(CRY, _cry_to_ry_cnot, _cry_to_ppr) add_decomps("Adjoint(CRY)", adjoint_rotation2) add_decomps("Pow(CRY)", pow_rotation2)
[docs] class CRZ(Controlled2): r"""The controlled-RZ operator .. math:: \begin{align} CR_z(\phi) &= \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0\\ 0 & 0 & e^{-i\phi/2} & 0\\ 0 & 0 & 0 & e^{i\phi/2} \end{bmatrix}. \end{align} .. note:: The subscripts of the operations in the formula refer to the wires they act on, e.g. 1 corresponds to the first element in ``wires`` that is the **control qubit**. **Details:** * Number of wires: 2 * Number of parameters: 1 * Number of dimensions per parameter: (0,) * Gradient recipe: The controlled-RZ operator satisfies a four-term parameter-shift rule (see Appendix F, https://doi.org/10.1088/1367-2630/ac2cb3): .. math:: \frac{d}{d\phi}f(CR_z(\phi)) = c_+ \left[f(CR_z(\phi+a)) - f(CR_z(\phi-a))\right] - c_- \left[f(CR_z(\phi+b)) - f(CR_z(\phi-b))\right] where :math:`f` is an expectation value depending on :math:`CR_z(\phi)`, and - :math:`a = \pi/2` - :math:`b = 3\pi/2` - :math:`c_{\pm} = (\sqrt{2} \pm 1)/{4\sqrt{2}}` Args: phi (float): rotation angle :math:`\phi` wires (Sequence[int]): the wire the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CRZ .. decomposition-rule:: to_rz_cnot :image: /_static/decomposition_thumbnails/crz_decomp.svg :class:`~.RZ` | :math:`2` :class:`~.CNOT` | :math:`2` .. decomposition-rule:: to_paulirot :image: /_static/decomposition_thumbnails/crz_to_ppr.svg :class:`PauliRot("ZZ") <.PauliRot>` | :math:`1` :class:`PauliRot("Z") <.PauliRot>` | :math:`1` .. decomposition-rule:: negate_angle :image: /_static/decomposition_thumbnails/crz_adjoint.svg :region: adjoint :where: ``phi`` changes sign :class:`~.CRZ` | :math:`1` .. decomposition-rule:: scale_angle :image: /_static/decomposition_thumbnails/crz_pow.svg :region: pow :where: ``phi`` is multiplied by the power :math:`z` :class:`~.CRZ` | :math:`1` """ num_wires = 2 """int: Number of wires that the operation acts on.""" num_params = 1 """int: Number of trainable parameters that the operator depends on.""" ndim_params = (0,) """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" name = "CRZ" wire_sizes = (2,) dynamic_argnames = ("phi",) arg_specs = {"phi": Float, "wires": Wire[2]} def __init__(self, phi, wires): super().__init__(qp.RZ(phi, wires[1:]), control_wires=wires[:1])
[docs] def adjoint(self): return CRZ(-self.phi, wires=self.wires)
[docs] @staticmethod def compute_matrix(phi, wires=None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CRZ.matrix` Args: phi (TensorLike): rotation angle Returns: tensor_like: canonical matrix **Example** >>> qp.CRZ.compute_matrix(torch.tensor(0.5)) tensor([[1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [0.0000+0.0000j, 1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [0.0000+0.0000j, 0.0000+0.0000j, 0.9689-0.2474j, 0.0000+0.0000j], [0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j, 0.9689+0.2474j]]) """ signs = qp.math.array([0, 0, 1, -1], like=phi) arg = -0.5j * phi if math.ndim(arg) == 0: return math.diag(qp.math.exp(arg * signs)) diags = math.exp(qp.math.outer(arg, signs)) return diags[:, :, np.newaxis] * math.cast_like(qp.math.eye(4, like=diags), diags)
[docs] @staticmethod def compute_eigvals(phi, wires=None): r"""Eigenvalues of the operator in the computational basis (static method). If :attr:`diagonalizing_gates` are specified and implement a unitary :math:`U^{\dagger}`, the operator can be reconstructed as .. math:: O = U \Sigma U^{\dagger}, where :math:`\Sigma` is the diagonal matrix containing the eigenvalues. Otherwise, no particular order for the eigenvalues is guaranteed. .. seealso:: :meth:`~.CRZ.eigvals` Args: phi (tensor_like or float): rotation angle Returns: tensor_like: eigenvalues **Example** >>> qp.CRZ.compute_eigvals(torch.tensor(0.5)) tensor([1.0000+0.0000j, 1.0000+0.0000j, 0.9689-0.2474j, 0.9689+0.2474j]) """ prefactors = qp.math.array([0, 0, -0.5j, 0.5j], like=phi) if qp.math.ndim(phi) == 0: product = phi * prefactors else: product = math.outer(phi, prefactors) return math.exp(product)
[docs] def eigvals(self): return self.compute_eigvals(*self.parameters)
def _crz_to_rz_cnot_resources(phi, wires): return {qp.RZ: 2, qp.CNOT: 2} @register_resources(_crz_to_rz_cnot_resources, name="to_rz_cnot") def _crz_to_rz_cnot(phi: TensorLike, wires: WiresLike): qp.RZ(phi / 2, wires=wires[1]) qp.CNOT(wires=wires) qp.RZ(-phi / 2, wires=wires[1]) qp.CNOT(wires=wires) def _crz_to_ppr_resources(phi, wires): return { qp.PauliRot(Float, pauli_word="ZZ", wires=Wire[2]): 1, qp.PauliRot(Float, pauli_word="Z", wires=Wire[1]): 1, } @register_resources(_crz_to_ppr_resources, name="to_paulirot") def _crz_to_ppr(phi: TensorLike, wires: WiresLike): qp.PauliRot(phi / 2, "Z", wires=wires[1]) qp.PauliRot(-phi / 2, "ZZ", wires=wires) add_decomps(CRZ, _crz_to_rz_cnot, _crz_to_ppr) add_decomps("Adjoint(CRZ)", adjoint_rotation2) add_decomps("Pow(CRZ)", pow_rotation2)
[docs] class CRot(Controlled2): r"""The controlled-Rot operator .. math:: CR(\phi, \theta, \omega) = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0\\ 0 & 0 & e^{-i(\phi+\omega)/2}\cos(\theta/2) & -e^{i(\phi-\omega)/2}\sin(\theta/2)\\ 0 & 0 & e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) \end{bmatrix}. .. note:: The first wire provided corresponds to the **control qubit**. **Details:** * Number of wires: 2 * Number of parameters: 3 * Number of dimensions per parameter: (0, 0, 0) * Gradient recipe: The controlled-Rot operator satisfies a four-term parameter-shift rule (see Appendix F, https://doi.org/10.1088/1367-2630/ac2cb3): .. math:: \frac{d}{d\mathbf{x}_i}f(CR(\mathbf{x}_i)) = c_+ \left[f(CR(\mathbf{x}_i+a)) - f(CR(\mathbf{x}_i-a))\right] - c_- \left[f(CR(\mathbf{x}_i+b)) - f(CR(\mathbf{x}_i-b))\right] where :math:`f` is an expectation value depending on :math:`CR(\mathbf{x}_i)`, and - :math:`\mathbf{x} = (\phi, \theta, \omega)` and `i` is an index to :math:`\mathbf{x}` - :math:`a = \pi/2` - :math:`b = 3\pi/2` - :math:`c_{\pm} = (\sqrt{2} \pm 1)/{4\sqrt{2}}` Args: phi (float): rotation angle :math:`\phi` theta (float): rotation angle :math:`\theta` omega (float): rotation angle :math:`\omega` wires (Sequence[int]): the wire the operation acts on .. details:: :title: Available decompositions .. decomposition-table:: qp.CRot .. decomposition-rule:: to_rot_cnot :image: /_static/decomposition_thumbnails/crot_decomp.svg :class:`~.RZ` | :math:`3` :class:`~.RY` | :math:`2` :class:`~.CNOT` | :math:`2` .. decomposition-rule:: reverse_angles :image: /_static/decomposition_thumbnails/crot_adjoint.svg :region: adjoint :where: ``phi`` and ``omega`` swap, and all three angles change sign :class:`~.CRot` | :math:`1` """ num_wires = 2 ndim_params = (0, 0, 0) num_params = 3 dynamic_argnames = ("phi", "theta", "omega") arg_specs = {"phi": Float, "theta": Float, "omega": Float, "wires": Wire[2]} def __init__(self, phi, theta, omega, wires): super().__init__(qp.Rot(phi, theta, omega, wires[1]), control_wires=wires[:1])
[docs] @override def adjoint(self): return CRot(-self.omega, -self.theta, -self.phi, wires=self.wires)
[docs] @staticmethod @override def compute_matrix(phi, theta, omega, wires: WiresLike | None = None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.CRot.matrix` Args: phi(tensor_like or float): first rotation angle theta (tensor_like or float): second rotation angle omega (tensor_like or float): third rotation angle Returns: tensor_like: canonical matrix **Example** >>> qp.CRot.compute_matrix(torch.tensor(0.1), torch.tensor(0.2), torch.tensor(0.3)) tensor([[ 1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [ 0.0000+0.0000j, 1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [ 0.0000+0.0000j, 0.0000+0.0000j, 0.9752-0.1977j, -0.0993+0.0100j], [ 0.0000+0.0000j, 0.0000+0.0000j, 0.0993+0.0100j, 0.9752+0.1977j]]) """ c = qp.math.cos(theta / 2) s = qp.math.sin(theta / 2) # The following variable is used to assert the all terms to be stacked have same shape one = math.ones_like(phi) * qp.math.ones_like(omega) c = c * one s = s * one o = math.ones_like(c) z = math.zeros_like(c) mat = [ [o, z, z, z], [z, o, z, z], [ z, z, math.exp(-0.5j * (phi + omega)) * c, -math.exp(0.5j * (phi - omega)) * s, ], [ z, z, math.exp(-0.5j * (phi - omega)) * s, math.exp(0.5j * (phi + omega)) * c, ], ] return math.stack([stack_last(row) for row in mat], axis=-2)
def _crot_to_rot_cnot_resources(*_, **__): return {qp.RZ: 3, qp.CNOT: 2, qp.RY: 2} @register_resources(_crot_to_rot_cnot_resources, name="to_rot_cnot") def _crot_to_rot_cnot(phi: TensorLike, theta: TensorLike, omega: TensorLike, wires: WiresLike): qp.RZ((phi - omega) / 2, wires=wires[1]) qp.CNOT(wires=wires) qp.RZ(-(phi + omega) / 2, wires=wires[1]) qp.RY(-theta / 2, wires=wires[1]) qp.CNOT(wires=wires) qp.RY(theta / 2, wires=wires[1]) qp.RZ(omega, wires=wires[1]) add_decomps(CRot, _crot_to_rot_cnot) @register_resources({CRot: 1}, name="reverse_angles") def _adjoint_crot_standard(base): CRot(-base.omega, -base.theta, -base.phi, wires=base.wires) add_decomps("Adjoint(CRot)", _adjoint_crot_standard)
[docs] class ControlledPhaseShift(Controlled2): r"""A qubit controlled phase shift. Also accessible as :class:`~.CPhase`. .. math:: CR_\phi(\phi) = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & e^{i\phi} \end{bmatrix}. .. note:: The first wire provided corresponds to the **control qubit**. **Details:** * Number of wires: 2 * Number of parameters: 1 * Number of dimensions per parameter: (0,) * Gradient recipe: :math:`\frac{d}{d\phi}f(CR_\phi(\phi)) = \frac{1}{2}\left[f(CR_\phi(\phi+\pi/2)) - f(CR_\phi(\phi-\pi/2))\right]` where :math:`f` is an expectation value depending on :math:`CR_{\phi}(\phi)`. Args: phi (float): rotation angle :math:`\phi` wires (Sequence[int]): the wire the operation acts on .. seealso:: ``ControlledPhaseShift`` is also available as :class:`~.CPhase`. .. details:: :title: Available decompositions .. decomposition-table:: qp.ControlledPhaseShift .. decomposition-rule:: to_rz_cnot :image: /_static/decomposition_thumbnails/cphase_to_rz_cnot.svg :class:`~.RZ` | :math:`3` :class:`~.CNOT` | :math:`2` :class:`~.GlobalPhase` | :math:`1` .. decomposition-rule:: to_paulirot :image: /_static/decomposition_thumbnails/cphase_to_ppr.svg :class:`PauliRot("ZZ") <.PauliRot>` | :math:`1` :class:`PauliRot("Z") <.PauliRot>` | :math:`2` :class:`~.GlobalPhase` | :math:`1` .. decomposition-rule:: to_single_phase :image: /_static/decomposition_thumbnails/cphase_to_single_phase.svg :requires: 1 zeroed work wire :class:`~.TemporaryAND` | :math:`1` :class:`~.PhaseShift` | :math:`1` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :math:`1` .. decomposition-rule:: negate_angle :image: /_static/decomposition_thumbnails/cphase_adjoint.svg :region: adjoint :where: ``phi`` changes sign :class:`~.ControlledPhaseShift` | :math:`1` .. decomposition-rule:: scale_angle :image: /_static/decomposition_thumbnails/cphase_pow.svg :region: pow :where: ``phi`` is multiplied by the power :math:`z` :class:`~.ControlledPhaseShift` | :math:`1` """ wire_sizes = (2,) dynamic_argnames = ("phi",) arg_specs = {"phi": Float, "wires": Wire[2]} num_wires = 2 """int: Number of wires the operator acts on.""" num_params = 1 """int: Number of trainable parameters that the operator depends on.""" ndim_params = (0,) """tuple[int]: Number of dimensions per trainable parameter that the operator depends on.""" name = "ControlledPhaseShift" def __init__(self, phi, wires): super().__init__(qp.PhaseShift(phi, wires[1:]), wires[:1])
[docs] @override def adjoint(self): return ControlledPhaseShift(-self.phi, wires=self.wires)
[docs] @staticmethod def compute_matrix(phi, wires=None): r"""Representation of the operator as a canonical matrix in the computational basis (static method). The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order. .. seealso:: :meth:`~.ControlledPhaseShift.matrix` Args: phi (tensor_like or float): phase shift Returns: tensor_like: canonical matrix **Example** >>> qp.ControlledPhaseShift.compute_matrix(torch.tensor(0.5)) tensor([[1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [0.0000+0.0000j, 1.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j], [0.0000+0.0000j, 0.0000+0.0000j, 1.0000+0.0000j, 0.0000+0.0000j], [0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j, 0.8776+0.4794j]]) """ signs = qp.math.array([0, 0, 0, 1], like=phi) arg = 1j * phi if math.ndim(arg) == 0: return math.diag(qp.math.exp(arg * signs)) diags = math.exp(qp.math.outer(arg, signs)) return diags[:, :, np.newaxis] * math.cast_like(qp.math.eye(4, like=diags), diags)
[docs] @staticmethod def compute_eigvals(phi, wires=None): r"""Eigenvalues of the operator in the computational basis (static method). If :attr:`diagonalizing_gates` are specified and implement a unitary :math:`U^{\dagger}`, the operator can be reconstructed as .. math:: O = U \Sigma U^{\dagger}, where :math:`\Sigma` is the diagonal matrix containing the eigenvalues. Otherwise, no particular order for the eigenvalues is guaranteed. .. seealso:: :meth:`~.ControlledPhaseShift.eigvals` Args: phi (tensor_like or float): phase shift Returns: tensor_like: eigenvalues **Example** >>> qp.ControlledPhaseShift.compute_eigvals(torch.tensor(0.5)) tensor([1.0000+0.0000j, 1.0000+0.0000j, 1.0000+0.0000j, 0.8776+0.4794j]) """ prefactors = qp.math.array([0, 0, 0, 1j], like=phi) if qp.math.ndim(phi) == 0: product = phi * prefactors else: product = math.outer(phi, prefactors) return math.exp(product)
def _cphase_to_rz_cnot_resources(phi, wires): return {qp.RZ: 3, qp.CNOT: 2, qp.GlobalPhase: 1} @register_resources(_cphase_to_rz_cnot_resources, name="to_rz_cnot") def _cphase_to_rz_cnot(phi: TensorLike, wires: WiresLike, **__): qp.RZ(phi / 2, wires=wires[0]) qp.CNOT(wires=wires) qp.RZ(-phi / 2, wires=wires[1]) qp.CNOT(wires=wires) qp.RZ(phi / 2, wires=wires[1]) qp.GlobalPhase(-phi / 4) def _cphase_to_ppr_resources(phi, wires): return { qp.GlobalPhase: 1, qp.PauliRot(Float, pauli_word="Z", wires=Wire[1]): 2, qp.PauliRot(Float, pauli_word="ZZ", wires=Wire[2]): 1, } @register_resources(_cphase_to_ppr_resources, name="to_paulirot") def _cphase_to_ppr(phi: TensorLike, wires: WiresLike, **__): qp.PauliRot(-phi / 2, pauli_word="ZZ", wires=wires) qp.PauliRot(phi / 2, pauli_word="Z", wires=wires[1]) qp.PauliRot(phi / 2, pauli_word="Z", wires=wires[0]) qp.GlobalPhase(-phi / 4) def _cphase_to_single_phase_resources(phi, wires): elbow = qp.TemporaryAND(wires=Wire[3]) return {_change_op_basis_abstract(elbow, qp.PhaseShift, qp.adjoint(elbow)): 1} @register_resources( _cphase_to_single_phase_resources, work_wires={"zeroed": 1}, name="to_single_phase" ) def _cphase_to_single_phase(phi: TensorLike, wires: WiresLike, **__): with qp.allocate(1, state="zero", restored=True) as work_wire: elbow = qp.TemporaryAND([wires[0], wires[1], work_wire[0]]) qp.change_op_basis(elbow, qp.PhaseShift(phi, work_wire)) add_decomps(ControlledPhaseShift, _cphase_to_rz_cnot, _cphase_to_ppr, _cphase_to_single_phase) add_decomps("Adjoint(ControlledPhaseShift)", adjoint_rotation2) add_decomps("Pow(ControlledPhaseShift)", pow_rotation2) CPhase = ControlledPhaseShift