Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds the quantum fourier transform and controlled phase operations #1064

Merged
merged 25 commits into from
Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

<h3>New features since last release</h3>

- Added the `ControlledPhaseShift` gate as well as the `QFT` operation for applying quantum Fourier
transforms.
[(#1064)](https://github.com/PennyLaneAI/pennylane/pull/1064)
trbromley marked this conversation as resolved.
Show resolved Hide resolved

<h3>Improvements</h3>

<h3>Breaking changes</h3>
Expand All @@ -14,7 +18,7 @@

This release contains contributions from (in alphabetical order):


Thomas Bromley

# Release 0.14.0 (current release)

Expand Down
2 changes: 2 additions & 0 deletions doc/introduction/operations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Qubit gates
~pennylane.MultiRZ
~pennylane.PauliRot
~pennylane.PhaseShift
~pennylane.ControlledPhaseShift
~pennylane.CNOT
~pennylane.CZ
~pennylane.CY
Expand All @@ -81,6 +82,7 @@ Qubit gates
~pennylane.CSWAP
~pennylane.QubitUnitary
~pennylane.DiagonalQubitUnitary
~pennylane.QFT

:html:`</div>`

Expand Down
12 changes: 12 additions & 0 deletions pennylane/devices/autograd_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ def PhaseShift(phi):
return np.array([1.0, np.exp(1j * phi)])


def ControlledPhaseShift(phi):
r"""Two-qubit controlled phase shift.

Args:
phi (float): phase shift angle

Returns:
array[complex]: diagonal part of the controlled phase shift matrix
"""
return np.array([1.0, 1.0, 1.0, np.exp(1j * phi)])


def RX(theta):
r"""One-qubit rotation about the x axis.

Expand Down
2 changes: 2 additions & 0 deletions pennylane/devices/default_mixed.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ class DefaultMixed(QubitDevice):
"Toffoli",
"CZ",
"PhaseShift",
"ControlledPhaseShift",
"RX",
"RY",
"RZ",
Expand All @@ -92,6 +93,7 @@ class DefaultMixed(QubitDevice):
"BitFlip",
"PhaseFlip",
"QubitChannel",
"QFT",
}

def __init__(self, wires, *, shots=1000, analytic=True, cache=0):
Expand Down
2 changes: 2 additions & 0 deletions pennylane/devices/default_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ class DefaultQubit(QubitDevice):
"CY",
"CZ",
"PhaseShift",
"ControlledPhaseShift",
"RX",
"RY",
"RZ",
Expand All @@ -121,6 +122,7 @@ class DefaultQubit(QubitDevice):
"CRY",
"CRZ",
"CRot",
"QFT",
}

observables = {"PauliX", "PauliY", "PauliZ", "Hadamard", "Hermitian", "Identity"}
Expand Down
1 change: 1 addition & 0 deletions pennylane/devices/default_qubit_autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ class DefaultQubitAutograd(DefaultQubit):

parametric_ops = {
"PhaseShift": autograd_ops.PhaseShift,
"ControlledPhaseShift": autograd_ops.ControlledPhaseShift,
"RX": autograd_ops.RX,
"RY": autograd_ops.RY,
"RZ": autograd_ops.RZ,
Expand Down
1 change: 1 addition & 0 deletions pennylane/devices/default_qubit_jax.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ def circuit():

parametric_ops = {
"PhaseShift": jax_ops.PhaseShift,
"ControlledPhaseShift": jax_ops.ControlledPhaseShift,
"RX": jax_ops.RX,
"RY": jax_ops.RY,
"RZ": jax_ops.RZ,
Expand Down
1 change: 1 addition & 0 deletions pennylane/devices/default_qubit_tf.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ class DefaultQubitTF(DefaultQubit):

parametric_ops = {
"PhaseShift": tf_ops.PhaseShift,
"ControlledPhaseShift": tf_ops.ControlledPhaseShift,
"RX": tf_ops.RX,
"RY": tf_ops.RY,
"RZ": tf_ops.RZ,
Expand Down
12 changes: 12 additions & 0 deletions pennylane/devices/jax_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ def PhaseShift(phi):
return jnp.array([1.0, jnp.exp(1j * phi)])


def ControlledPhaseShift(phi):
r"""Two-qubit controlled phase shift.

Args:
phi (float): phase shift angle

Returns:
array[complex]: diagonal part of the controlled phase shift matrix
"""
return jnp.array([1.0, 1.0, 1.0, jnp.exp(1j * phi)])


def RX(theta):
r"""One-qubit rotation about the x axis.

Expand Down
2 changes: 2 additions & 0 deletions pennylane/devices/tests/test_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"PauliY": qml.PauliY(wires=[0]),
"PauliZ": qml.PauliZ(wires=[0]),
"PhaseShift": qml.PhaseShift(0, wires=[0]),
"ControlledPhaseShift": qml.ControlledPhaseShift(0, wires=[0, 1]),
"QubitStateVector": qml.QubitStateVector(np.array([1.0, 0.0]), wires=[0]),
"QubitUnitary": qml.QubitUnitary(np.eye(2), wires=[0]),
"RX": qml.RX(0, wires=[0]),
Expand All @@ -64,6 +65,7 @@
"T": qml.T(wires=[0]),
"SX": qml.SX(wires=[0]),
"Toffoli": qml.Toffoli(wires=[0, 1, 2]),
"QFT": qml.QFT(wires=[0, 1, 2]),
}

all_ops = ops.keys()
Expand Down
13 changes: 13 additions & 0 deletions pennylane/devices/tf_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ def PhaseShift(phi):
return tf.convert_to_tensor([1.0, tf.exp(1j * phi)])


def ControlledPhaseShift(phi):
r"""Two-qubit controlled phase shift.

Args:
phi (float): phase shift angle

Returns:
tf.Tensor[complex]: diagonal part of the controlled phase shift matrix
"""
phi = tf.cast(phi, dtype=C_DTYPE)
return tf.convert_to_tensor([1.0, 1.0, 1.0, tf.exp(1j * phi)])


def RX(theta):
r"""One-qubit rotation about the x axis.

Expand Down
156 changes: 150 additions & 6 deletions pennylane/ops/qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,19 @@
This module contains the available built-in discrete-variable
quantum operations supported by PennyLane, as well as their conventions.
"""
# pylint:disable=abstract-method,arguments-differ,protected-access
import math
import cmath
import functools

# pylint:disable=abstract-method,arguments-differ,protected-access
import math

import numpy as np

import pennylane as qml
from pennylane.operation import AnyWires, DiagonalOperation, Observable, Operation
from pennylane.templates import template
from pennylane.operation import AnyWires, Observable, Operation, DiagonalOperation
from pennylane.templates.state_preparations import BasisStatePreparation, MottonenStatePreparation
from pennylane.utils import pauli_eigs, expand
import pennylane as qml
from pennylane.utils import expand, pauli_eigs

INV_SQRT2 = 1 / math.sqrt(2)

Expand Down Expand Up @@ -722,6 +724,58 @@ def decomposition(phi, wires):
return decomp_ops


class ControlledPhaseShift(DiagonalOperation):
r"""ControlledPhaseShift(phi, wires)
A qubit controlled phase shift.

.. math:: CR_\phi(\phi) = \begin{bmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & e^{i\phi}
\end{bmatrix}.

.. note:: The first wire provided corresponds to the **control qubit**.

**Details:**

* Number of wires: 2
* Number of parameters: 1
* Gradient recipe: :math:`\frac{d}{d\phi}f(CR_\phi(\phi)) = \frac{1}{2}\left[f(CR_\phi(\phi+\pi/2)) - f(CR_\phi(\phi-\pi/2))\right]`
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did check this and can confirm that it's unlike the other CRX, CRY, CRZ gates because the 2-parameter shift works:

import pennylane as qml
from pennylane import numpy as np

wires = 2
dev = qml.device("default.qubit", wires=range(wires))

w1 = np.random.random((4, 2, 3))
w2 = np.random.random((4, 2, 3))

@qml.qnode(dev)
def f(x):
    qml.templates.StronglyEntanglingLayers(w1, wires=range(wires))
#     qml.CRX(x, wires=[0, 1])
    qml.ControlledPhaseShift(x, wires=[0, 1])
    qml.templates.StronglyEntanglingLayers(w2, wires=range(wires))
    return qml.expval(qml.PauliZ(0))

x = 0.3
g1 = qml.grad(f)(x)
g2 = (f(x + np.pi / 2) - f(x - np.pi / 2)) / 2

np.allclose(g1, g2)

where :math:`f` is an expectation value depending on :math:`CR_{\phi}(\phi)`.

Args:
phi (float): rotation angle :math:`\phi`
wires (Sequence[int] or int): the wire the operation acts on
"""
num_params = 1
num_wires = 2
par_domain = "R"
grad_method = "A"
generator = [np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]), 1]

@classmethod
def _matrix(cls, *params):
phi = params[0]
return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, cmath.exp(1j * phi)]])

@classmethod
def _eigvals(cls, *params):
phi = params[0]
return np.array([1, 1, 1, cmath.exp(1j * phi)])

@staticmethod
def decomposition(phi, wires):
decomp_ops = [
qml.PhaseShift(phi / 2, wires=wires[0]),
qml.CNOT(wires=[0, 1]),
qml.PhaseShift(-phi / 2, wires=wires[1]),
qml.CNOT(wires=[0, 1]),
qml.PhaseShift(phi / 2, wires=wires[1]),
trbromley marked this conversation as resolved.
Show resolved Hide resolved
]
return decomp_ops


class Rot(Operation):
r"""Rot(phi, theta, omega, wires)
Arbitrary single qubit rotation
Expand Down Expand Up @@ -905,7 +959,7 @@ class PauliRot(Operation):
}

def __init__(self, *params, wires=None, do_queue=True):
super().__init__(*params, wires=wires, do_queue=True)
super().__init__(*params, wires=wires, do_queue=do_queue)

pauli_word = params[1]

Expand Down Expand Up @@ -1580,6 +1634,94 @@ def decomposition(D, wires):
return [QubitUnitary(np.diag(D), wires=wires)]


class QFT(Operation):
r"""QFT(wires)
Apply a quantum Fourier transform (QFT).

For the :math:`N`-qubit computational basis state :math:`|m\rangle`, the QFT performs the
transformation

.. math::

|m\rangle \rightarrow \frac{1}{\sqrt{2^{N}}}\sum_{n=0}^{2^{N} - 1}\omega_{N}^{mn} |n\rangle,

where :math:`\omega_{N} = e^{\frac{2 \pi i}{2^{N}}}` is the :math:`2^{N}`-th root of unity.

**Details:**

* Number of wires: Any (the operation can act on any number of wires)
* Number of parameters: 0
* Gradient recipe: None
trbromley marked this conversation as resolved.
Show resolved Hide resolved

Args:
wires (int or Iterable[Number, str]]): the wire(s) the operation acts on

**Example**

The quantum Fourier transform is applied by specifying the corresponding wires:

.. code-block::

wires = 3

@qml.qnode(dev)
def circuit_qft(basis_state):
qml.BasisState(basis_state, wires=range(wires))
qml.QFT(wires=range(wires))
return qml.state()

The inverse quantum Fourier transform is accessed using ``qml.QFT(wires).inv()``.
"""
num_params = 0
num_wires = AnyWires
par_domain = None
grad_method = None

@property
def matrix(self):
# Redefine the property here to allow for a custom _matrix signature
mat = self._matrix(len(self.wires))
if self.inverse:
mat = mat.conj()
return mat

@classmethod
@functools.lru_cache()
def _matrix(cls, num_wires):
dimension = 2 ** num_wires

mat = np.zeros((dimension, dimension), dtype=np.complex128)
omega = np.exp(2 * np.pi * 1j / dimension)

for m in range(dimension):
for n in range(dimension):
mat[m, n] = omega ** (m * n)

return mat / np.sqrt(dimension)

@staticmethod
def decomposition(wires):
num_wires = len(wires)
Comment on lines +1703 to +1704
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When running the QFT, is there a way to make it print out the full decomposition when using draw? Currently it draws this:

 0: ──╭QFT──╭┤ State 
 1: ──├QFT──├┤ State 
 2: ──╰QFT──╰┤ State 

but for the sake of testing it'd be convenient to see the innards.

Copy link
Member

@josh146 josh146 Feb 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be the moment that our new qml.draw() shines!

Since it is not dependent on the QNode state (unlike qnode.draw()), we can add some logic to qml.draw() to always decompose the QFT operation (or maybe any operation that has a draw_decomp flag or something).

Copy link
Contributor

@glassnotes glassnotes Feb 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It'd be great to have it at the level of the draw function itself -

qml.draw(circuit, draw_decomp=True)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or even

qml.draw(qnode, decompose=[“QFT”, “Rot”])(params)

shifts = [2 * np.pi * 2 ** -i for i in range(2, num_wires + 1)]

decomp_ops = []
for i, wire in enumerate(wires):
decomp_ops.append(qml.Hadamard(wire))

for shift, control_wire in zip(shifts[: len(shifts) - i], wires[i + 1 :]):
op = qml.ControlledPhaseShift(shift, wires=[control_wire, wire])
decomp_ops.append(op)

first_half_wires = wires[: num_wires // 2]
last_half_wires = wires[-(num_wires // 2) :]

for wire1, wire2 in zip(first_half_wires, reversed(last_half_wires)):
swap = qml.SWAP(wires=[wire1, wire2])
decomp_ops.append(swap)

return decomp_ops


# =============================================================================
# State preparation
# =============================================================================
Expand Down Expand Up @@ -1760,6 +1902,7 @@ def diagonalizing_gates(self):
"RY",
"RZ",
"PhaseShift",
"ControlledPhaseShift",
"Rot",
"CRX",
"CRY",
Expand All @@ -1772,6 +1915,7 @@ def diagonalizing_gates(self):
"QubitStateVector",
"QubitUnitary",
"DiagonalQubitUnitary",
"QFT",
}


Expand Down
Loading