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_rotation 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_involutory as pow_involutory2
from pennylane.ops.op_math.pow2 import pow_rotation as pow_rotation2
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 (
    _wrap_mcx_rule_w_alloc,
    controlled_two_qubit_unitary_rule,
    ctrl_decomp_bisect_rule,
    decompose_mcx_many_workers,
    decompose_mcx_one_worker,
    decompose_mcx_two_controls_elbows,
    decompose_mcx_two_workers,
    decompose_mcx_with_no_worker,
    mcx_to_cnot_or_toffoli,
    multi_control_decomp_zyz_rule,
    single_ctrl_decomp_zyz_rule,
)
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) """ 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_resource(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_resource) # pylint: disable=too-many-arguments def _to_general_c_qu(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, ctrl_decomp_bisect_rule, single_ctrl_decomp_zyz_rule, multi_control_decomp_zyz_rule, controlled_two_qubit_unitary_rule, _to_general_c_qu, ) 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}) def _adjoint_controlled_qubit_unitary(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)
[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 """ 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) 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 """ 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_cry_s_resources(wires: AbstractWires): return {qp.CRY: 1, qp.S: 1} @register_resources(_cy_to_cry_s_resources) def _cy(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)) 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}, ) def _cy_lattice_surgery_ppm(wires: AbstractWires): _pauli_ctrl_pauli_ppm(wires, qp.Z, qp.Y) add_decomps(CY, _cy, _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 """ 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): # pylint: disable=arguments-differ,unused-argument 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): # pylint: disable=unused-argument return {qp.ControlledPhaseShift: 1} @register_resources(_cz_to_cps_resources) def _cz_to_cps(wires: WiresLike): qp.ControlledPhaseShift(np.pi, wires=wires) def _cz_to_cnot_resources(wires: AbstractWires): # pylint: disable=unused-argument return {qp.H: 2, qp.CNOT: 1} @register_resources(_cz_to_cnot_resources) 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)) def _cz_to_ppr(wires: AbstractWires): _pauli_ctrl_pauli_ppr(wires, qp.Z, qp.Z) # pylint: disable-next=unused-argument 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}) 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 """ 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_toffoli_resources(wires: WiresLike = None): return {qp.CNOT: 2, qp.Toffoli: 1} @register_resources(_cswap_to_toffoli_resources) def _cswap(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_resource(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_resource) 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, _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]]) """ 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): # pylint: disable=arguments-differ,unused-argument 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_resources(wires: AbstractWires): # pylint: disable=unused-argument return { qp.CNOT: 6, _adjoint_abstract(qp.T): 3, qp.T: 4, qp.Hadamard: 2, } @register_resources(_ccz_resources) def _ccz(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): # pylint: disable=unused-argument return {qp.Hadamard: 2, qp.Toffoli: 1} @register_resources(_ccz_to_toffoli_resources) def _ccz_to_toffoli(wires: WiresLike, **__): qp.Hadamard(wires[2]) qp.Toffoli(wires) qp.Hadamard(wires[2]) add_decomps(CCZ, _ccz, _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]]) """ 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_cz_h_resources(wires: WiresLike): return {qp.H: 2, qp.CZ: 1} @register_resources(_cnot_cz_h_resources) 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)) 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}) 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_resource(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_resource) 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]]) """ 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_resources(wires: WiresLike): return { qp.Hadamard: 2, qp.CNOT: 6, qp.T: 4, _adjoint_abstract(qp.T): 3, } @register_resources(_toffoli_resources) def _toffoli(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_resource(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_resource) 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}) 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, _toffoli_to_ppr, _toffoli_elbow) add_decomps("Adjoint(Toffoli)", self_adjoint) add_decomps("Pow(Toffoli)", pow_involutory2) def _ctrl_toffoli_resource(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_resource) 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. """ 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(decompose_mcx_many_workers)(**arguments) if len(arguments["work_wires"]) >= 2: return _to_op_list(decompose_mcx_two_workers)(**arguments) if len(arguments["work_wires"]) == 1: return _to_op_list(decompose_mcx_one_worker)(**arguments) return _to_op_list(decompose_mcx_with_no_worker)(**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, decompose_mcx_two_controls_elbows] return [ decompose_mcx_many_workers, decompose_mcx_two_workers, decompose_mcx_one_worker, decompose_mcx_with_no_worker, ] 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(decompose_mcx_two_controls_elbows, 1, "zeroed") return [mcx_to_cnot_or_toffoli, elbow_rule] capture_compatible_rules = [ _wrap_mcx_rule_w_alloc(decompose_mcx_two_workers, 2, "zeroed", "two_zeroed_workers"), _wrap_mcx_rule_w_alloc(decompose_mcx_two_workers, 2, "borrowed", "two_borrowed_workers"), _wrap_mcx_rule_w_alloc(decompose_mcx_one_worker, 1, "zeroed", "one_zeroed_worker"), _wrap_mcx_rule_w_alloc(decompose_mcx_one_worker, 1, "borrowed", "one_borrowed_worker"), decompose_mcx_with_no_worker, ] 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( decompose_mcx_many_workers, len(op.control_wires) - 2, "zeroed", "many_zeroed_workers", ), _wrap_mcx_rule_w_alloc( decompose_mcx_many_workers, len(op.control_wires) - 2, "borrowed", "many_borrowed_workers", ), ] + capture_compatible_rules add_decomps( "MultiControlledX", mcx_to_cnot_or_toffoli, decompose_mcx_two_controls_elbows, decompose_mcx_many_workers, decompose_mcx_two_workers, decompose_mcx_one_worker, decompose_mcx_with_no_worker, _wrap_mcx_rule_w_alloc(decompose_mcx_two_controls_elbows, 1, "zeroed"), _wrap_mcx_rule_w_alloc(decompose_mcx_two_workers, 2, "zeroed", "two_zeroed_workers"), _wrap_mcx_rule_w_alloc(decompose_mcx_two_workers, 2, "borrowed", "two_borrowed_workers"), _wrap_mcx_rule_w_alloc(decompose_mcx_one_worker, 1, "zeroed", "one_zeroed_worker"), _wrap_mcx_rule_w_alloc(decompose_mcx_one_worker, 1, "borrowed", "one_borrowed_worker"), # TODO: include the allocation-wrapped versions of decompose_mcx_many_workers # 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_resource(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_resource) 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 """ 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 # pylint: disable-next=unused-argument 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): # pylint: disable=unused-argument return {qp.RZ: 2, qp.RY: 2, qp.CNOT: 2} @register_resources(_crx_to_rz_ry_resources) 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): # pylint: disable=unused-argument return {qp.RX: 2, qp.CZ: 2} @register_resources(_crx_to_rx_cz_resources) 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): # pylint: disable=unused-argument return {qp.Hadamard: 2, qp.CRZ: 1} @register_resources(_crx_to_h_crz_resources) 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): # pylint: disable=unused-argument 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) 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 """ 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 # pylint: disable-next=unused-argument 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_resources(phi, wires): # pylint: disable=unused-argument return {qp.RY: 2, qp.CNOT: 2} @register_resources(_cry_resources) def _cry(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): # pylint: disable=unused-argument 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) 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, _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 """ 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 # pylint: disable=unused-argument, arguments-differ 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 # pylint: disable=unused-argument, arguments-differ 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)
# pylint: disable=unused-argument def _crz_resources(phi, wires): return {qp.RZ: 2, qp.CNOT: 2} @register_resources(_crz_resources) def _crz(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) # pylint: disable=unused-argument 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) 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, _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 """ 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 # pylint: disable-next=arguments-differ,unused-argument 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_resources(*_, **__): return {qp.RZ: 3, qp.CNOT: 2, qp.RY: 2} @register_resources(_crot_resources) def _crot(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) @register_resources({CRot: 1}) def _adjoint_crot(base): CRot(-base.omega, -base.theta, -base.phi, wires=base.wires) add_decomps("Adjoint(CRot)", _adjoint_crot)
[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:: _cphase_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:: _cphase_to_ppr :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:: _cphase_to_single_phase :image: /_static/decomposition_thumbnails/cphase_to_single_phase.svg :requires: 1 work wire :class:`~.TemporaryAND` | :math:`1` :class:`~.PhaseShift` | :math:`1` :class:`Adjoint(TemporaryAND) <.TemporaryAND>` | :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 # pylint: disable=arguments-differ,unused-argument 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 # pylint: disable=arguments-differ,unused-argument 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_rz_resource(phi, wires): # pylint: disable=unused-argument return {qp.RZ: 3, qp.CNOT: 2, qp.GlobalPhase: 1} @register_resources(_cphase_rz_resource) 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_resource(phi, wires): # pylint: disable=unused-argument 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_resource) 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): # pylint: disable=unused-argument 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}) 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