<commit_before># Copyright 2021 The Cirq Developers
#
# 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
#
#     https://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.
"""Tools for analyzing and manipulating quantum channels."""
from typing import Sequence

import numpy as np

from cirq import protocols


def kraus_to_choi(kraus_operators: Sequence[np.ndarray]) -> np.ndarray:
    r"""Returns the unique Choi matrix corresponding to a Kraus representation of a channel.

    Quantum channel E: L(H1) -> L(H2) may be described by a collection of operators A_i, called
    Kraus operators, such that

        $$
        E(\rho) = \sum_i A_i \rho A_i^\dagger.
        $$

    Kraus representation is not unique. Alternatively, E may be specified by its Choi matrix J(E)
    defined as

        $$
        J(E) = (E \otimes I)(|\phi\rangle\langle\phi|)
        $$

    where $|\phi\rangle = \sum_i|i\rangle|i\rangle$ is the unnormalized maximally entangled state
    and I: L(H1) -> L(H1) is the identity map. Choi matrix is unique for a given channel.

    The computation of the Choi matrix from a Kraus representation is essentially a reconstruction
    of a matrix from its eigendecomposition. It has the cost of O(kd**4) where k is the number of
    Kraus operators and d is the dimension of the input and output Hilbert space.

    Args:
        kraus_operators: Sequence of Kraus operators specifying a quantum channel.

    Returns:
        Choi matrix of the channel specified by kraus_operators.
    """
    d = np.prod(kraus_operators[0].shape, dtype=np.int64)
    c = np.zeros((d, d), dtype=np.complex128)
    for k in kraus_operators:
        v = np.reshape(k, d)
        c += np.outer(v, v.conj())
    return c


def choi_to_kraus(choi: np.ndarray, atol: float = 1e-10) -> Sequence[np.ndarray]:
    r"""Returns a Kraus representation of a channel with given Choi matrix.

    Quantum channel E: L(H1) -> L(H2) may be described by a collection of operators A_i, called
    Kraus operators, such that

        $$
        E(\rho) = \sum_i A_i \rho A_i^\dagger.
        $$

    Kraus representation is not unique. Alternatively, E may be specified by its Choi matrix J(E)
    defined as

        $$
        J(E) = (E \otimes I)(|\phi\rangle\langle\phi|)
        $$

    where $|\phi\rangle = \sum_i|i\rangle|i\rangle$ is the unnormalized maximally entangled state
    and I: L(H1) -> L(H1) is the identity map. Choi matrix is unique for a given channel.

    The most expensive step in the computation of a Kraus representation from a Choi matrix is
    the eigendecomposition of the Choi. Therefore, the cost of the conversion is O(d**6) where
    d is the dimension of the input and output Hilbert space.

    Args:
        choi: Choi matrix of the channel.
        atol: Tolerance used in checking if choi is positive and in deciding which Kraus
            operators to omit.

    Returns:
        Approximate Kraus representation of the quantum channel specified via a Choi matrix.
        Kraus operators with Frobenius norm smaller than atol are omitted.

    Raises:
        ValueError: when choi is not a positive square matrix.
    """
    d = int(np.round(np.sqrt(choi.shape[0])))
    if choi.shape != (d * d, d * d):
        raise ValueError(f"Invalid Choi matrix shape, expected {(d * d, d * d)}, got {choi.shape}")
    if not np.allclose(choi, choi.T.conj(), atol=atol):
        raise ValueError("Choi matrix must be Hermitian")

    w, v = np.linalg.eigh(choi)
    if np.any(w < -atol):
        raise ValueError(f"Choi matrix must be positive, got one with eigenvalues {w}")

    w = np.maximum(w, 0)
    u = np.sqrt(w) * v
    return [k.reshape(d, d) for k in u.T if np.linalg.norm(k) > atol]


def kraus_to_superoperator(kraus_operators: Sequence[np.ndarray]) -> np.ndarray:
    r"""Returns the matrix representation of the linear map with given Kraus operators.

    Quantum channel E: L(H1) -> L(H2) may be described by a collection of operators A_i, called
    Kraus operators, such that

        $$
        E(\rho) = \sum_i A_i \rho A_i^\dagger.
        $$

    Kraus representation is not unique. Alternatively, E may be specified by its superoperator
    matrix K(E) defined so that

        $$
        K(E) vec(\rho) = vec(E(\rho))
        $$

    where the vectorization map $vec$ rearranges d-by-d matrices into d**2-dimensional vectors.
    Superoperator matrix is unique for a given channel. It is also called the natural
    representation of a quantum channel.

    The computation of the superoperator matrix from a Kraus representation involves the sum of
    Kronecker products of all Kraus operators. This has the cost of O(kd**4) where k is the number
    of Kraus operators and d is the dimension of the input and output Hilbert space.

    Args:
        kraus_operators: Sequence of Kraus operators specifying a quantum channel.

    Returns:
        Superoperator matrix of the channel specified by kraus_operators.
    """
    d_out, d_in = kraus_operators[0].shape
    m = np.zeros((d_out * d_out, d_in * d_in), dtype=np.complex128)
    for k in kraus_operators:
        m += np.kron(k, k.conj())
    return m


def superoperator_to_kraus(superoperator: np.ndarray, atol: float = 1e-10) -> Sequence[np.ndarray]:
    r"""Returns a Kraus representation of a channel specified via the superoperator matrix.<commit_msg>Replace pure python loops with numpy where possible in channels.py. (#5839)<commit_after># Copyright 2021 The Cirq Developers
#
# 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
#
#     https://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.
"""Tools for analyzing and manipulating quantum channels."""
from typing import Sequence

import numpy as np

from cirq import protocols


def kraus_to_choi(kraus_operators: Sequence[np.ndarray]) -> np.ndarray:
    r"""Returns the unique Choi matrix corresponding to a Kraus representation of a channel.

    Quantum channel E: L(H1) -> L(H2) may be described by a collection of operators A_i, called
    Kraus operators, such that

        $$
        E(\rho) = \sum_i A_i \rho A_i^\dagger.
        $$

    Kraus representation is not unique. Alternatively, E may be specified by its Choi matrix J(E)
    defined as

        $$
        J(E) = (E \otimes I)(|\phi\rangle\langle\phi|)
        $$

    where $|\phi\rangle = \sum_i|i\rangle|i\rangle$ is the unnormalized maximally entangled state
    and I: L(H1) -> L(H1) is the identity map. Choi matrix is unique for a given channel.

    The computation of the Choi matrix from a Kraus representation is essentially a reconstruction
    of a matrix from its eigendecomposition. It has the cost of O(kd**4) where k is the number of
    Kraus operators and d is the dimension of the input and output Hilbert space.

    Args:
        kraus_operators: Sequence of Kraus operators specifying a quantum channel.

    Returns:
        Choi matrix of the channel specified by kraus_operators.
    """
    d = np.prod(kraus_operators[0].shape, dtype=np.int64)
    choi_rank = len(kraus_operators)
    k = np.reshape(kraus_operators, (choi_rank, d))
    return np.einsum('bi,bj->ij', k, k.conj())


def choi_to_kraus(choi: np.ndarray, atol: float = 1e-10) -> Sequence[np.ndarray]:
    r"""Returns a Kraus representation of a channel with given Choi matrix.

    Quantum channel E: L(H1) -> L(H2) may be described by a collection of operators A_i, called
    Kraus operators, such that

        $$
        E(\rho) = \sum_i A_i \rho A_i^\dagger.
        $$

    Kraus representation is not unique. Alternatively, E may be specified by its Choi matrix J(E)
    defined as

        $$
        J(E) = (E \otimes I)(|\phi\rangle\langle\phi|)
        $$

    where $|\phi\rangle = \sum_i|i\rangle|i\rangle$ is the unnormalized maximally entangled state
    and I: L(H1) -> L(H1) is the identity map. Choi matrix is unique for a given channel.

    The most expensive step in the computation of a Kraus representation from a Choi matrix is
    the eigendecomposition of the Choi. Therefore, the cost of the conversion is O(d**6) where
    d is the dimension of the input and output Hilbert space.

    Args:
        choi: Choi matrix of the channel.
        atol: Tolerance used in checking if choi is positive and in deciding which Kraus
            operators to omit.

    Returns:
        Approximate Kraus representation of the quantum channel specified via a Choi matrix.
        Kraus operators with Frobenius norm smaller than atol are omitted.

    Raises:
        ValueError: when choi is not a positive square matrix.
    """
    d = int(np.round(np.sqrt(choi.shape[0])))
    if choi.shape != (d * d, d * d):
        raise ValueError(f"Invalid Choi matrix shape, expected {(d * d, d * d)}, got {choi.shape}")
    if not np.allclose(choi, choi.T.conj(), atol=atol):
        raise ValueError("Choi matrix must be Hermitian")

    w, v = np.linalg.eigh(choi)
    if np.any(w < -atol):
        raise ValueError(f"Choi matrix must be positive, got one with eigenvalues {w}")

    w = np.maximum(w, 0)
    u = np.sqrt(w) * v
    keep = np.linalg.norm(u.T, axis=-1) > atol
    return [k.reshape(d, d) for k, keep_i in zip(u.T, keep) if keep_i]


def kraus_to_superoperator(kraus_operators: Sequence[np.ndarray]) -> np.ndarray:
    r"""Returns the matrix representation of the linear map with given Kraus operators.

    Quantum channel E: L(H1) -> L(H2) may be described by a collection of operators A_i, called
    Kraus operators, such that

        $$
        E(\rho) = \sum_i A_i \rho A_i^\dagger.
        $$

    Kraus representation is not unique. Alternatively, E may be specified by its superoperator
    matrix K(E) defined so that

        $$
        K(E) vec(\rho) = vec(E(\rho))
        $$

    where the vectorization map $vec$ rearranges d-by-d matrices into d**2-dimensional vectors.
    Superoperator matrix is unique for a given channel. It is also called the natural
    representation of a quantum channel.

    The computation of the superoperator matrix from a Kraus representation involves the sum of
    Kronecker products of all Kraus operators. This has the cost of O(kd**4) where k is the number
    of Kraus operators and d is the dimension of the input and output Hilbert space.

    Args:
        kraus_operators: Sequence of Kraus operators specifying a quantum channel.

    Returns:
        Superoperator matrix of the channel specified by kraus_operators.
    """
    d_out, d_in = kraus_operators[0].shape
    ops_arr = np.asarray(kraus_operators)
    m = np.einsum('bij,bkl->ikjl', ops_arr, ops_arr.conj())
    return m.reshape((d_out * d_out, d_in * d_in))


def superoperator_to_kraus(superoperator: np.ndarray, atol: float = 1e-10) -> Sequence[np.ndarray]:
    r"""Returns a Kraus representation of a channel specified via the superoperator matrix.
{'fraction_non_alphanumeric': 0.08597827016853452, 'fraction_numerical': 0.006758490888869878, 'mean_word_length': 3.006168608636052, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 25, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '219387', 'n_tokens_mistral': 3669, 'n_tokens_neox': 3494, 'n_words': 1438}