operator.py 6.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
# !/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 class for the special quantum operator.
"""

Q
Quleaf 已提交
20
import numpy as np
Q
Quleaf 已提交
21
import paddle
Q
Quleaf 已提交
22

Q
Quleaf 已提交
23
import warnings
Q
Quleaf 已提交
24
import paddle_quantum as pq
Q
Quleaf 已提交
25
from ..base import Operator
Q
Quleaf 已提交
26 27
from ..backend import Backend
from ..backend import state_vector, density_matrix, unitary_matrix
Q
Quleaf 已提交
28 29
from ..intrinsic import _format_qubits_idx, _get_float_dtype
from ..state import State
Q
Quleaf 已提交
30
from ..qinfo import partial_trace_discontiguous
Q
Quleaf 已提交
31
from typing import Union, Iterable
Q
Quleaf 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67


class ResetState(Operator):
    r"""The class to reset the quantum state. It will be implemented soon.
    """
    def __init__(self):
        super().__init__()

    def forward(self, *inputs, **kwargs):
        r"""The forward function.

        Returns:
            NotImplemented.
        """
        return NotImplemented


class PartialState(Operator):
    r"""The class to obtain the partial quantum state. It will be implemented soon.
    """
    def __init__(self):
        super().__init__()

    def forward(self, *inputs, **kwargs):
        r"""The forward function.

        Returns:
            NotImplemented.
        """
        return NotImplemented


class Collapse(Operator):
    r"""The class to compute the collapse of the quantum state.

    Args:
Q
Quleaf 已提交
68 69 70 71
        qubits_idx: list of qubits to be collapsed. Defaults to ``'full'``.
        num_qubits: Total number of qubits. Defaults to ``None``.
        desired_result: The desired result you want to collapse. Defaults to ``None`` meaning randomly choose one.
        if_print: whether print the information about the collapsed state. Defaults to ``False``.
Q
Quleaf 已提交
72 73 74
        measure_basis: The basis of the measurement. The quantum state will collapse to the corresponding eigenstate.

    Raises:
Q
Quleaf 已提交
75 76 77 78
        NotImplementedError: If the basis of measurement is not z. Other bases will be implemented in future.
        
    Note:
        When desired_result is `None`, Collapse does not support gradient calculation
Q
Quleaf 已提交
79
    """
Q
Quleaf 已提交
80 81 82
    def __init__(self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None,
                 desired_result: Union[int, str] = None, if_print: bool = False,
                 measure_basis: Union[Iterable[paddle.Tensor], str] = 'z'):
Q
Quleaf 已提交
83 84
        super().__init__()
        self.measure_basis = []
Q
Quleaf 已提交
85

Q
Quleaf 已提交
86 87
        # the qubit indices must be sorted
        self.qubits_idx = sorted(_format_qubits_idx(qubits_idx, num_qubits))
Q
Quleaf 已提交
88

Q
Quleaf 已提交
89 90
        self.desired_result = desired_result
        self.if_print = if_print
Q
Quleaf 已提交
91 92

        if measure_basis in ['z', 'computational_basis']:
Q
Quleaf 已提交
93
            self.measure_basis = 'z'
Q
Quleaf 已提交
94 95
        else:
            raise NotImplementedError
Q
Quleaf 已提交
96
        
Q
Quleaf 已提交
97
    def forward(self, state: State) -> State:
Q
Quleaf 已提交
98 99 100
        r"""Compute the collapse of the input state.

        Args:
Q
Quleaf 已提交
101
            state: The input state, which will be collapsed
Q
Quleaf 已提交
102 103 104 105

        Returns:
            The collapsed quantum state.
        """
Q
Quleaf 已提交
106
        complex_dtype = pq.get_dtype()
Q
Quleaf 已提交
107
        float_dtype = _get_float_dtype(complex_dtype)    
Q
Quleaf 已提交
108

Q
Quleaf 已提交
109 110 111 112 113
        backend = state.backend
        num_acted_qubits = len(self.qubits_idx)
        desired_result = self.desired_result
        desired_result = int(desired_result, 2) if isinstance(desired_result, str) else desired_result 
        
Q
Quleaf 已提交
114 115 116 117 118 119 120
        def projector_gen() -> paddle.Tensor:
            proj = paddle.zeros([2 ** num_acted_qubits, 2 ** num_acted_qubits])
            proj[desired_result, desired_result] += 1
            proj = proj.cast(complex_dtype)
            return proj
        
        num_qubits = state.num_qubits
Q
Quleaf 已提交
121 122 123 124 125 126
        # when backend is unitary
        if backend == Backend.UnitaryMatrix:
            assert isinstance(desired_result, int), "desired_result cannot be None in unitary_matrix backend"
            warnings.warn(
                "the unitary_matrix of a circuit containing Collapse operator is no longer a unitary"
            )
Q
Quleaf 已提交
127 128 129

            local_projector = projector_gen()

Q
Quleaf 已提交
130
            projected_state = unitary_matrix.unitary_transformation(state.data, local_projector, self.qubits_idx, num_qubits)
Q
Quleaf 已提交
131 132
            return State(projected_state, backend=Backend.UnitaryMatrix)

Q
Quleaf 已提交
133
        # retrieve prob_amplitude
Q
Quleaf 已提交
134
        rho = state.ket @ state.bra if backend == Backend.StateVector else state.data
Q
Quleaf 已提交
135 136
        rho = partial_trace_discontiguous(rho, self.qubits_idx)
        prob_amplitude = paddle.zeros([2 ** num_acted_qubits], dtype=float_dtype)
Q
Quleaf 已提交
137
        for idx in range(2 ** num_acted_qubits):
Q
Quleaf 已提交
138 139
            prob_amplitude[idx] += rho[idx, idx].real()
        prob_amplitude /= paddle.sum(prob_amplitude)
Q
Quleaf 已提交
140

Q
Quleaf 已提交
141 142
        if desired_result is None:
            # randomly choose desired_result
Q
Quleaf 已提交
143 144
            desired_result = np.random.choice(list(range(2**num_acted_qubits)), p=prob_amplitude)

Q
Quleaf 已提交
145
        else:
Q
Quleaf 已提交
146
            desired_result_str = bin(desired_result)[2:]
Q
Quleaf 已提交
147
            # check whether the state can collapse to desired_result
Q
Quleaf 已提交
148 149 150 151
            assert prob_amplitude[desired_result] > 1e-20, \
                f"it is infeasible for the state in qubits {self.qubits_idx} to collapse to state |{bin(desired_result)[2:]}>"


Q
Quleaf 已提交
152 153 154 155
        # retrieve the binary version of desired result
        desired_result_str = bin(desired_result)[2:]
        assert num_acted_qubits >= len(desired_result_str), "the desired_result is too large"
        for _ in range(num_acted_qubits - len(desired_result_str)):
Q
Quleaf 已提交
156 157
            desired_result_str = f'0{desired_result_str}'

Q
Quleaf 已提交
158 159 160 161 162
        # whether print the collapsed result
        if self.if_print:
            # retrieve binary representation
            prob = prob_amplitude[desired_result].item()
            print(f"qubits {self.qubits_idx} collapse to the state |{desired_result_str}> with probability {prob}")
Q
Quleaf 已提交
163 164 165

        local_projector = projector_gen()

Q
Quleaf 已提交
166 167 168 169 170
        # apply the local projector and normalize it
        if backend == Backend.StateVector:
            projected_state = state_vector.unitary_transformation(state.data, local_projector, self.qubits_idx, num_qubits)
        else:
            projected_state = density_matrix.unitary_transformation(state.data, local_projector, self.qubits_idx, num_qubits)
Q
Quleaf 已提交
171 172 173
        state = State(projected_state)
        state.normalize()
        return state