|
| 1 | +# Copyright 2019 The Cirq Developers |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from typing import Union |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +import sympy |
| 19 | + |
| 20 | +import cirq |
| 21 | +from cirq import value, _compat |
| 22 | +from cirq.ops import raw_types |
| 23 | + |
| 24 | + |
| 25 | +@value.value_equality |
| 26 | +class QuantumFourierTransformGate(raw_types.Gate): |
| 27 | + """Switches from the computational basis to the frequency basis.""" |
| 28 | + |
| 29 | + def __init__(self, num_qubits: int, *, without_reverse: bool = False): |
| 30 | + """ |
| 31 | + Args: |
| 32 | + num_qubits: The number of qubits the gate applies to. |
| 33 | + without_reverse: Whether or not to include the swaps at the end |
| 34 | + of the circuit decomposition that reverse the order of the |
| 35 | + qubits. These are technically necessary in order to perform the |
| 36 | + correct effect, but can almost always be optimized away by just |
| 37 | + performing later operations on different qubits. |
| 38 | + """ |
| 39 | + self._num_qubits = num_qubits |
| 40 | + self._without_reverse = without_reverse |
| 41 | + |
| 42 | + def _json_dict_(self): |
| 43 | + return { |
| 44 | + 'cirq_type': self.__class__.__name__, |
| 45 | + 'num_qubits': self._num_qubits, |
| 46 | + 'without_reverse': self._without_reverse |
| 47 | + } |
| 48 | + |
| 49 | + def _value_equality_values_(self): |
| 50 | + return self._num_qubits, self._without_reverse |
| 51 | + |
| 52 | + def num_qubits(self) -> int: |
| 53 | + return self._num_qubits |
| 54 | + |
| 55 | + def _decompose_(self, qubits): |
| 56 | + if len(qubits) == 0: |
| 57 | + return |
| 58 | + yield cirq.H(qubits[0]) |
| 59 | + for i in range(1, len(qubits)): |
| 60 | + yield PhaseGradientGate( |
| 61 | + num_qubits=i, |
| 62 | + exponent=0.5).on(*qubits[:i][::-1]).controlled_by(qubits[i]) |
| 63 | + yield cirq.H(qubits[i]) |
| 64 | + if not self._without_reverse: |
| 65 | + for i in range(len(qubits) // 2): |
| 66 | + yield cirq.SWAP(qubits[i], qubits[-i - 1]) |
| 67 | + |
| 68 | + def _has_unitary_(self): |
| 69 | + return True |
| 70 | + |
| 71 | + def __str__(self): |
| 72 | + return 'QFT[norev]' if self._without_reverse else 'QFT' |
| 73 | + |
| 74 | + def __repr__(self): |
| 75 | + return ('cirq.QuantumFourierTransformGate(num_qubits={!r}, ' |
| 76 | + 'without_reverse={!r})'.format(self._num_qubits, |
| 77 | + self._without_reverse)) |
| 78 | + |
| 79 | + def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs'): |
| 80 | + return cirq.CircuitDiagramInfo( |
| 81 | + wire_symbols=(str(self),) + |
| 82 | + tuple(f'#{k+1}' for k in range(1, self._num_qubits)), |
| 83 | + exponent_qubit_index=0) |
| 84 | + |
| 85 | + |
| 86 | +@value.value_equality |
| 87 | +class PhaseGradientGate(raw_types.Gate): |
| 88 | + """Phases each state |k⟩ out of n by e^(2*pi*i*k/n*exponent). |
| 89 | + """ |
| 90 | + |
| 91 | + def __init__(self, *, num_qubits: int, exponent: Union[float, sympy.Basic]): |
| 92 | + self._num_qubits = num_qubits |
| 93 | + self.exponent = exponent |
| 94 | + |
| 95 | + def _json_dict_(self): |
| 96 | + return { |
| 97 | + 'cirq_type': self.__class__.__name__, |
| 98 | + 'num_qubits': self._num_qubits, |
| 99 | + 'exponent': self.exponent |
| 100 | + } |
| 101 | + |
| 102 | + def _value_equality_values_(self): |
| 103 | + return self._num_qubits, self.exponent |
| 104 | + |
| 105 | + def num_qubits(self) -> int: |
| 106 | + return self._num_qubits |
| 107 | + |
| 108 | + def _decompose_(self, qubits): |
| 109 | + for i, q in enumerate(qubits): |
| 110 | + yield cirq.Z(q)**(self.exponent / 2**i) |
| 111 | + |
| 112 | + def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs'): |
| 113 | + if isinstance(self.exponent, sympy.Basic): |
| 114 | + return NotImplemented |
| 115 | + |
| 116 | + n = int(np.product([args.target_tensor.shape[k] for k in args.axes])) |
| 117 | + for i in range(n): |
| 118 | + p = 1j**(4 * i / n * self.exponent) |
| 119 | + args.target_tensor[args.subspace_index(big_endian_bits_int=i)] *= p |
| 120 | + |
| 121 | + return args.target_tensor |
| 122 | + |
| 123 | + def __pow__(self, power): |
| 124 | + new_exponent = cirq.mul(self.exponent, power, NotImplemented) |
| 125 | + if new_exponent is NotImplemented: |
| 126 | + # coverage: ignore |
| 127 | + return NotImplemented |
| 128 | + return PhaseGradientGate(num_qubits=self._num_qubits, |
| 129 | + exponent=new_exponent) |
| 130 | + |
| 131 | + def _unitary_(self): |
| 132 | + if isinstance(self.exponent, sympy.Basic): |
| 133 | + return NotImplemented |
| 134 | + |
| 135 | + size = 1 << self._num_qubits |
| 136 | + return np.diag( |
| 137 | + [1j**(4 * i / size * self.exponent) for i in range(size)]) |
| 138 | + |
| 139 | + def _has_unitary_(self): |
| 140 | + return not isinstance(self.exponent, sympy.Basic) |
| 141 | + |
| 142 | + def _is_parameterized_(self): |
| 143 | + return isinstance(self.exponent, sympy.Basic) |
| 144 | + |
| 145 | + def _resolve_parameters_(self, resolver): |
| 146 | + new_exponent = cirq.resolve_parameters(self.exponent, resolver) |
| 147 | + if new_exponent is self.exponent: |
| 148 | + return self |
| 149 | + return PhaseGradientGate(num_qubits=self._num_qubits, |
| 150 | + exponent=new_exponent) |
| 151 | + |
| 152 | + def __str__(self): |
| 153 | + return f'Grad[{self._num_qubits}]' + (f'^{self.exponent}' |
| 154 | + if self.exponent != 1 else '') |
| 155 | + |
| 156 | + def __repr__(self): |
| 157 | + return 'cirq.PhaseGradientGate(num_qubits={!r}, exponent={})'.format( |
| 158 | + self._num_qubits, _compat.proper_repr(self.exponent)) |
| 159 | + |
| 160 | + def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs'): |
| 161 | + return cirq.CircuitDiagramInfo( |
| 162 | + wire_symbols=('Grad',) + |
| 163 | + tuple(f'#{k+1}' for k in range(1, self._num_qubits)), |
| 164 | + exponent=self.exponent, |
| 165 | + exponent_qubit_index=0) |
| 166 | + |
| 167 | + |
| 168 | +def QFT(*qubits: 'cirq.Qid', |
| 169 | + without_reverse: bool = False, |
| 170 | + inverse: bool = False) -> 'cirq.Operation': |
| 171 | + """The quantum Fourier transform. |
| 172 | +
|
| 173 | + Transforms a qubit register from the computational basis to the frequency |
| 174 | + basis. |
| 175 | +
|
| 176 | + The inverse quantum Fourier transform is `cirq.QFT(*qubits)**-1` or |
| 177 | + equivalently `cirq.inverse(cirq.QFT(*qubits))`. |
| 178 | +
|
| 179 | + Args: |
| 180 | + qubits: The qubits to apply the QFT to. |
| 181 | + without_reverse: When set, swap gates at the end of the QFT are omitted. |
| 182 | + This reverses the qubit order relative to the standard QFT effect, |
| 183 | + but makes the gate cheaper to apply. |
| 184 | + inverse: If set, the inverse QFT is performed instead of the QFT. |
| 185 | + Equivalent to calling `cirq.inverse` on the result, or raising it |
| 186 | + to the -1. |
| 187 | +
|
| 188 | + Returns: |
| 189 | + A `cirq.Operation` applying the QFT to the given qubits. |
| 190 | + """ |
| 191 | + result = QuantumFourierTransformGate( |
| 192 | + len(qubits), without_reverse=without_reverse).on(*qubits) |
| 193 | + if inverse: |
| 194 | + result = cirq.inverse(result) |
| 195 | + return result |
0 commit comments