Source code for pennylane.ops.functions.is_commuting

# Copyright 2018-2021 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.
"""
Defines `is_commuting`, an function for determining if two functions commute.
"""

import numpy as np

import pennylane as qp
from pennylane.core.pauli import PauliSentence
from pennylane.exceptions import QuantumFunctionError
from pennylane.ops.op_math import Controlled, Prod, SProd, Sum
from pennylane.wires import Wires

SPECIAL_UTILITIES = {
    "Barrier",
    "Snapshot",
}
# Ops that don't commute with anything
IDENTITIES = {"Identity", "GlobalPhase"}
# Ops that commute with everything other than special utilities
SELF_COMMUTE = {"Hadamard"}
# Ops that only commute with themselves and identities

PAULIZ_GROUP = {
    "PauliZ",
    "ctrl",
    "S",
    "T",
    "RZ",
    "PhaseShift",
    "MultiRZ",
    "U1",
    "IsingZZ",
}
# Set[str]: names of operations that commute with PauliZ

SWAP_GROUP = {
    "SWAP",
    "ISWAP",
    "SISWAP",
    "Permute",
}
# Set[str]: names of operations that commute with SWAP

PAULIX_GROUP = {"PauliX", "SX", "RX", "Identity", "IsingXX", "BasisState"}
# Set[str]: names of operations that commute with X

PAULIY_GROUP = {"PauliY", "RY", "Identity", "IsingYY"}
# Set[str]: names of operations that commute with Y


def _pword_is_commuting(pauli_word_1, pauli_word_2):
    r"""Checks if two Pauli words commute.

    Args:
        pauli_word_1 (Operator): first Pauli word in commutator.
        pauli_word_2 (Operator): second Pauli word in commutator.

    Returns:
        bool: returns True if the input Pauli commute, False otherwise.

    **Example**

    >>> pauli_word_1 = qp.prod(qp.X("a"), qp.Y("b"))
    >>> pauli_word_2 = qp.prod(qp.Z("a"), qp.Z("c"))
    >>> _pword_is_commuting(pauli_word_1, pauli_word_2)
    False

    >>> pauli_word_1 = qp.sum(qp.X('a') , qp.Y('b'))
    >>> pauli_word_2 = qp.sum(qp.Z('c') , qp.X('a'))
    >>> _pword_is_commuting(pauli_word_1, pauli_word_2)
    True
    """

    pr1 = pauli_word_1.pauli_rep
    pr2 = pauli_word_2.pauli_rep

    comm = pr1.commutator(pr2)
    comm.prune()
    return comm == PauliSentence({})


def _get_target_name(op):
    """Get the name for the target operation. If the operation is not controlled, this is
    simplify the operation's name.
    """
    if isinstance(op, qp.ops.op_math.SymbolicOp):
        return _get_target_name(op.base)
    return op.name


def _check_mat_commutation(op1, op2):
    """Uses matrices and matrix multiplication to determine whether op1 and op2 commute.

    ``op1`` and ``op2`` must be on the same wires.
    """
    op1_mat = op1.matrix()
    op2_mat = op2.matrix()

    mat_12 = np.matmul(op1_mat, op2_mat)
    mat_21 = np.matmul(op2_mat, op1_mat)

    return qp.math.allclose(mat_12, mat_21)


def _create_commute_function():
    """This function constructs the ``_commutes`` helper utility function while using closure
    to hide the ``commutation_map`` data away from the global scope of the file.
    This function only needs to be called a single time.
    Returns:
        function
    """

    commutation_map = {}
    for group in [PAULIX_GROUP, PAULIY_GROUP, PAULIZ_GROUP, SWAP_GROUP, SELF_COMMUTE]:
        for op in group:
            commutation_map[op] = group

    def commutes_inner(op_name1, op_name2):
        """Determine whether or not two operations commute.

        Relies on ``commutation_map`` from the enclosing namespace of ``_create_commute_function``.

        Args:
            op_name1 (str): name of one operation.
            op_name2 (str): name of the second operation.

        Returns:
            bool: True if the operations commute, False otherwise.

        """
        if op_name1 in SPECIAL_UTILITIES or op_name2 in SPECIAL_UTILITIES:
            return False
        if op_name1 in IDENTITIES or op_name2 in IDENTITIES:
            return True
        # assume non commuting if not in commutation map
        return op_name1 in commutation_map.get(op_name2, {})

    return commutes_inner


_commutes = _create_commute_function()


def _check_opmath_operations(operation1, operation2):
    """Check that `SProd`, `Prod`, and `Sum` instances only contain Pauli words."""

    for op in [operation1, operation2]:

        if op.pauli_rep is not None:
            continue

        if isinstance(op, (SProd, Prod, Sum)):
            raise QuantumFunctionError(
                f"Operation {op} currently not supported. Prod, Sprod, and Sum instances must have a valid Pauli representation."
            )


def intersection(wires1, wires2):
    r"""Check if two sets of wires intersect.

    Args:
        wires1 (pennylane.wires.Wires): First set of wires.
        wires2 (pennylane.wires.Wires: Second set of wires.

    Returns:
        bool: True if the two sets of wires are not disjoint and False if disjoint.
    """
    return len(qp.wires.Wires.shared_wires([wires1, wires2])) != 0


def _is_single_controlled_rot(op):
    """Recognize both named and symbolic Rot operators with one control wire."""
    return isinstance(op, Controlled) and isinstance(op.base, qp.Rot) and len(op.control_wires) == 1


def check_commutation_two_non_simplified_crot(operation1, operation2):
    r"""Check commutation for two CRot that were not simplified.

    Args:
        operation1 (pennylane.Operation): First operation.
        operation2 (pennylane.Operation): Second operation.

    Returns:
        bool: True if commutation, False otherwise.
    """
    # Two non simplified CRot
    target_wires_1 = Wires([w for w in operation1.wires if w not in operation1.control_wires])
    target_wires_2 = Wires([w for w in operation2.wires if w not in operation2.control_wires])

    control_control = intersection(operation1.control_wires, operation2.control_wires)
    target_target = intersection(target_wires_1, target_wires_2)

    if control_control:
        if target_target:
            return _check_mat_commutation(operation1, operation2)
        # control_control and not target_target
        return True

    if target_target:
        return _check_mat_commutation(
            qp.Rot(*operation1.data, wires=operation1.wires[1]),
            qp.Rot(*operation2.data, wires=operation2.wires[1]),
        )
    return False


def check_commutation_two_non_simplified_rotations(operation1, operation2):
    r"""Check that the operations are two non simplified operations. If it is the case, then it checks commutation
    for two rotations that were not simplified.

    Only allowed ops are `U2`, `U3`, `Rot`, `CRot`.

    Args:
        operation1 (pennylane.Operation): First operation.
        operation2 (pennylane.Operation): Second operation.

    Returns:
        bool: True if commutation, False otherwise, None if not two rotations.
    """

    op1_ctrl_wires = operation1.control_wires if isinstance(operation1, Controlled) else Wires([])
    target_wires_1 = qp.wires.Wires([w for w in operation1.wires if w not in op1_ctrl_wires])
    op2_ctrl_wires = operation2.control_wires if isinstance(operation2, Controlled) else Wires([])
    target_wires_2 = qp.wires.Wires([w for w in operation2.wires if w not in op2_ctrl_wires])

    if _is_single_controlled_rot(operation1):
        if intersection(target_wires_1, operation2.wires):
            op1_rot = qp.Rot(*operation1.data, wires=target_wires_1)
            return _check_mat_commutation(op1_rot, operation2)
        return _commutes(operation2.name, "ctrl")

    if _is_single_controlled_rot(operation2):
        if intersection(target_wires_2, operation1.wires):
            op2_rot = qp.Rot(*operation2.data, wires=target_wires_2)
            return _check_mat_commutation(op2_rot, operation1)
        return _commutes(operation1.name, "ctrl")

    return _check_mat_commutation(operation1, operation2)


unsupported_operations = [
    "PauliRot",
    "QubitDensityMatrix",
    "ApproxTimeEvolution",
    "ArbitraryUnitary",
    "CommutingEvolution",
    "Exp",
]


[docs] def is_commuting(operation1, operation2): # pylint: disable=too-many-return-statements r"""Check if two operations are commuting using a lookup table. A lookup table is used to check the commutation between the controlled, targeted part of operation 1 with the controlled, targeted part of operation 2. .. note:: Most PennyLane operations are supported. Unsupported operations include: :class:`~.PauliRot`, :class:`~.QubitDensityMatrix`, :class:`~.ApproxTimeEvolution`, :class:`~.ArbitraryUnitary`, :class:`~.CommutingEvolution`, :class:`~.Exp` Args: operation1 (.Operation): A first quantum operation. operation2 (.Operation): A second quantum operation. Returns: bool: True if the operations commute, False otherwise. **Example** >>> qp.is_commuting(qp.X(0), qp.Z(0)) False """ # operations are disjoints if not intersection(operation1.wires, operation2.wires): return True if operation1.name in unsupported_operations or isinstance(operation1, qp.operation.Channel): raise QuantumFunctionError(f"Operation {operation1.name} not supported.") if operation2.name in unsupported_operations or isinstance(operation2, qp.operation.Channel): raise QuantumFunctionError(f"Operation {operation2.name} not supported.") if operation1.pauli_rep is not None and operation2.pauli_rep is not None: return _pword_is_commuting(operation1, operation2) # Simplify the rotations if possible with qp.QueuingManager.stop_recording(): operation1 = qp.simplify(operation1) operation2 = qp.simplify(operation2) # Arithmetic non-disjoint operations only contain Pauli words _check_opmath_operations(operation1, operation2) # Two single-controlled Rot operators that cannot be simplified is_crot_1 = _is_single_controlled_rot(operation1) is_crot_2 = _is_single_controlled_rot(operation2) if is_crot_1 and is_crot_2: return check_commutation_two_non_simplified_crot(operation1, operation2) # Check if operations are non simplified rotations and return commutation if it is the case. op_set = {"U2", "U3", "Rot", "CRot"} def _is_non_simplified_rot(op): return op.name in op_set or _is_single_controlled_rot(op) if _is_non_simplified_rot(operation1) and _is_non_simplified_rot(operation2): return check_commutation_two_non_simplified_rotations(operation1, operation2) ctrl_base_1 = _get_target_name(operation1) ctrl_base_2 = _get_target_name(operation2) op1_control_wires = getattr(operation1, "control_wires", qp.wires.Wires({})) op2_control_wires = getattr(operation2, "control_wires", qp.wires.Wires({})) target_wires_1 = qp.wires.Wires([w for w in operation1.wires if w not in op1_control_wires]) target_wires_2 = qp.wires.Wires([w for w in operation2.wires if w not in op2_control_wires]) if intersection(target_wires_1, target_wires_2) and not _commutes(ctrl_base_1, ctrl_base_2): return False if intersection(target_wires_1, op2_control_wires) and not _commutes("ctrl", ctrl_base_1): return False if intersection(target_wires_2, op1_control_wires) and not _commutes("ctrl", ctrl_base_2): return False return True