# Copyright 2018-2023 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.
"""
This submodule contains the template for AQFT.
"""
import warnings
import numpy as np
from pennylane import capture, compiler, math
from pennylane.capture import hint
from pennylane.control_flow import for_loop
from pennylane.core.operator import Operator2
from pennylane.decomposition import add_decomps, register_resources
from pennylane.ops import SWAP, ControlledPhaseShift, Hadamard
from pennylane.typing import Wire
from pennylane.wires import Wires, WiresLike
[docs]
class AQFT(Operator2):
r"""AQFT(order, wires)
Apply an approximate quantum Fourier transform (AQFT).
The `AQFT <https://arxiv.org/abs/1803.04933>`_ method helps to reduce the number of ``ControlledPhaseShift`` operations required
for QFT by only using a maximum of ``order`` number of ``ControlledPhaseShift`` gates per qubit.
.. seealso:: :class:`~.QFT`
Args:
order (int): the order of approximation
wires (int or Iterable[Number, str]]): the wire(s) the operation acts on
**Example**
The approximate quantum Fourier transform is applied by specifying the corresponding wires and
the order of approximation:
.. code-block:: python
wires = 3
dev = qp.device('default.qubit', wires=wires)
@qp.qnode(dev)
def circuit_aqft():
qp.X(0)
qp.Hadamard(1)
qp.AQFT(order=1,wires=range(wires))
return qp.state()
>>> np.round(circuit_aqft(), 8)
array([ 0.5 +0.j , -0.25-0.25j, 0. +0.j , -0.25+0.25j, 0.5 +0.j ,
-0.25-0.25j, 0. +0.j , -0.25+0.25j])
.. details::
:title: Available decompositions
.. decomposition-table:: qp.AQFT
:stacked:
:symbols: :math:`n` wires and order :math:`m \leq n-1`
:example: :math:`n=4`, :math:`m=1`
.. decomposition-rule:: _AQFT_decomposition
:image: /_static/decomposition_thumbnails/aqft_cphase_swap.svg
:class:`~.Hadamard` | :math:`n` | 4
:class:`~.ControlledPhaseShift` | :math:`m(2n-m-1)/2` | 3
:class:`~.SWAP` | :math:`\lfloor n/2 \rfloor` | 2
.. details::
:title: Usage Details
**Order**
The order of approximation should be a whole number less than :math:`n`
where :math:`n` is the number of wires the operation is being applied on.
This creates three cases for different ``order`` values:
* ``order`` :math:`< 0`
This will raise a ``ValueError``
* :math:`0 \leq` ``order`` :math:`< n`
This is the intended AQFT use case.
.. code-block:: python
@qp.qnode(qp.device('default.qubit'))
def circ():
qp.AQFT(order=2, wires=range(4))
return qp.probs()
The resulting circuit is:
>>> print(qp.draw(circ, level='device')())
0: ──H─╭Rϕ(1.57)─╭Rϕ(0.79)────────────────────────────────────────╭SWAP───────┤ ╭Probs
1: ────╰●────────│──────────H─╭Rϕ(1.57)─╭Rϕ(0.79)─────────────────│─────╭SWAP─┤ ├Probs
2: ──────────────╰●───────────╰●────────│──────────H─╭Rϕ(1.57)────│─────╰SWAP─┤ ├Probs
3: ─────────────────────────────────────╰●───────────╰●─────────H─╰SWAP───────┤ ╰Probs
For ``order`` :math:`= n-1`, the AQFT is equivalent to a standard :class:`~.QFT`.
* ``order`` :math:`\geq n`
The AQFT is equivalent to a standard QFT, and to AQFT with ``order`` :math:`= n-1`,
so the ``order`` is capped at :math:`n-1`.
"""
compilable_argnames = ("order",)
arg_specs = {"wires": Wire[-1]}
wire_sizes = (None,)
def __init__(self, order: int, wires: WiresLike) -> None:
wires = Wires(wires)
num_wires = len(wires)
if num_wires == 0:
raise ValueError("AQFT on empty wires is not supported.")
if order < 0:
raise ValueError("Order can not be less than 0")
if not isinstance(order, int):
raise ValueError("The order must be an integer. Got {order} of type {type(order)}.")
if order >= num_wires:
warnings.warn(
f"The order ({order}) in AQFT is larger than or equal to the number of wires "
f"({num_wires}). Using order = {num_wires - 1} instead. Pass an order of "
f"{num_wires - 1} or less to silence this warning."
)
order = num_wires - 1
super().__init__(order, wires)
def _AQFT_resources(order, wires):
num_wires = len(wires)
num_ctrl_ps = sum(min(num_wires - 1 - i, order) for i in range(num_wires))
return {
Hadamard: num_wires,
ControlledPhaseShift: num_ctrl_ps,
SWAP: num_wires // 2,
}
@register_resources(_AQFT_resources)
def _AQFT_decomposition(wires, order):
num_wires = len(wires)
shifts = [2 * np.pi / (2**i) for i in range(2, num_wires + 1)]
if compiler.active() or capture.enabled():
shifts = math.array(shifts, like="jax")
wires = math.array(wires, like="jax")
total_inner_iters = sum(min(num_wires - 1 - i, order) for i in range(num_wires))
average_inner_iters = total_inner_iters / num_wires
@for_loop(num_wires)
def wire_loop(i):
wire = wires[i]
Hadamard(wire)
@hint({"num-iters": average_inner_iters})
@for_loop(math.min(math.array([num_wires - 1 - i, order], like=math.get_interface(i))))
def cphase_loop(j):
shift = shifts[j]
control_wire = wires[i + 1 + j]
ControlledPhaseShift(shift, wires=[control_wire, wire])
cphase_loop() # pylint: disable=no-value-for-parameter
wire_loop() # pylint: disable=no-value-for-parameter
@for_loop(num_wires // 2)
def half_wire_loop(k):
wire1 = wires[k]
wire2 = wires[-k - 1]
SWAP(wires=[wire1, wire2])
half_wire_loop() # pylint: disable=no-value-for-parameter
add_decomps(AQFT, _AQFT_decomposition)