custom.py 4.6 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# !/usr/bin/env python3
# Copyright (c) 2022 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
#
# 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.

r"""
The source file of the oracle class and the control oracle class.
"""

import math
Q
Quleaf 已提交
21
import matplotlib
Q
Quleaf 已提交
22
import paddle
Q
Quleaf 已提交
23 24 25

import warnings
import paddle_quantum as pq
Q
Quleaf 已提交
26 27
from . import functional
from .base import Gate
Q
Quleaf 已提交
28
from ..intrinsic import _format_qubits_idx
Q
Quleaf 已提交
29
from typing import Union, Iterable
Q
Quleaf 已提交
30
from .functional.visual import _c_oracle_like_display, _oracle_like_display
Q
Quleaf 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43


class Oracle(Gate):
    """An oracle as a gate.

    Args:
        oracle: Unitary oracle to be implemented.
        qubits_idx: Indices of the qubits on which the gates are applied.
        num_qubits: Total number of qubits. Defaults to ``None``.
        depth: Number of layers. Defaults to ``1``.
    """
    def __init__(
            self, oracle: paddle.Tensor, qubits_idx: Union[Iterable[Iterable[int]], Iterable[int], int],
Q
Quleaf 已提交
44
            num_qubits: int = None, depth: int = 1, gate_info: dict = None
Q
Quleaf 已提交
45 46
    ):
        super().__init__(depth)
Q
Quleaf 已提交
47 48 49 50 51 52 53 54 55 56 57
        complex_dtype = pq.get_dtype()
        oracle = oracle.cast(complex_dtype)

        dimension = oracle.shape[0]
        err = paddle.norm(paddle.abs(oracle @ paddle.conj(oracle.T) - paddle.cast(paddle.eye(dimension), complex_dtype))).item()
        if err > min(1e-6 * dimension, 0.01):
            warnings.warn(
                f"\nThe input oracle may not be a unitary: norm(U * U^d - I) = {err}.", UserWarning)

        num_acted_qubits = int(math.log2(dimension))
        self.oracle = oracle
Q
Quleaf 已提交
58
        self.qubits_idx = _format_qubits_idx(qubits_idx, num_qubits, num_acted_qubits)
Q
Quleaf 已提交
59

Q
Quleaf 已提交
60 61 62 63 64 65 66 67 68 69
        self.gate_info = {
            'gatename': 'O',
            'texname': r'$O$',
            'plot_width': 0.6,
        }
        if gate_info:
            self.gate_info.update(gate_info)

    def forward(self, state: pq.State) -> pq.State:
        for _ in range(self.depth):
Q
Quleaf 已提交
70 71 72
            for qubits_idx in self.qubits_idx:
                state = functional.oracle(state, self.oracle, qubits_idx, self.backend)
        return state
Q
Quleaf 已提交
73 74 75
    
    def display_in_circuit(self, ax: matplotlib.axes.Axes, x: float,) -> float:
        return _oracle_like_display(self, ax, x)
Q
Quleaf 已提交
76 77 78 79 80 81 82 83 84 85 86 87


class ControlOracle(Gate):
    """A controlled oracle as a gate.

    Args:
        oracle: Unitary oracle to be implemented.
        qubits_idx: Indices of the qubits on which the gates are applied.
        num_qubits: Total number of qubits. Defaults to ``None``.
        depth: Number of layers. Defaults to ``1``.
    """
    def __init__(
Q
Quleaf 已提交
88
            self, oracle: paddle.Tensor, qubits_idx: Union[Iterable[Iterable[int]], Iterable[int]],
Q
Quleaf 已提交
89
            num_qubits: int = None, depth: int = 1, gate_info: dict = None
Q
Quleaf 已提交
90
    ) -> None:
Q
Quleaf 已提交
91
        super().__init__(depth)
Q
Quleaf 已提交
92
        complex_dtype = pq.get_dtype()
Q
Quleaf 已提交
93
        oracle = oracle.cast(complex_dtype)
Q
Quleaf 已提交
94
        
Q
Quleaf 已提交
95 96 97 98 99 100 101
        dimension = oracle.shape[0]
        err = paddle.norm(paddle.abs(oracle @ paddle.conj(oracle.T) - paddle.cast(paddle.eye(dimension), complex_dtype))).item()
        if  err > min(1e-6 * dimension, 0.01):
            warnings.warn(
                f"\nThe input oracle may not be a unitary: norm(U * U^d - I) = {err}.", UserWarning)

        num_acted_qubits = int(math.log2(dimension))
Q
Quleaf 已提交
102
        oracle = (
Q
Quleaf 已提交
103 104
            paddle.kron(paddle.to_tensor([[1.0, 0], [0, 0]], dtype=complex_dtype), paddle.eye(2 ** num_acted_qubits)) +
            paddle.kron(paddle.to_tensor([[0.0, 0], [0, 1]], dtype=complex_dtype), oracle)
Q
Quleaf 已提交
105
        )
Q
Quleaf 已提交
106
        num_acted_qubits += 1
Q
Quleaf 已提交
107 108
        self.oracle = oracle
        self.qubits_idx = _format_qubits_idx(qubits_idx, num_qubits, num_acted_qubits)
Q
Quleaf 已提交
109

Q
Quleaf 已提交
110 111 112 113 114 115 116 117 118 119
        self.gate_info = {
            'gatename': 'cO',
            'texname': r'$O$',
            'plot_width': 0.6,
        }
        if gate_info:
            self.gate_info.update(gate_info)

    def forward(self, state: pq.State) -> pq.State:
        for _ in range(self.depth):
Q
Quleaf 已提交
120 121 122
            for qubits_idx in self.qubits_idx:
                state = functional.oracle(state, self.oracle, qubits_idx, self.backend)
        return state
Q
Quleaf 已提交
123 124 125

    def display_in_circuit(self, ax: matplotlib.axes.Axes, x: float,) -> float:
        return _c_oracle_like_display(self, ax, x)