Introduction to the Diagonal gate with code

Interested in learning how to program quantum computers? Then check out our Qiskit textbook Introduction to Quantum Computing with Qiskit.

Introduction

In this tutorial we will explore how to implement the diagonal gate on IBM’s Quantum Computers with Qiskit.

The diagonal gate a multi-qubit gate that operates on a qubit based upon diagonal entries in it’s matrix. The operation of the diagonal gate can be described using the following matrix:

CodeCogsEqn (1).png

Implementation

In Qiskit the diagonal gate can be implemented very easily using the following function:

Diagonal(entries)

Where entries is a list of diagonal entries

Note: For K qubits there will be 2^k entries. For example for 2 qubits there will be 4 diagonal entries eg: entries=[-1,1,1,-1]

The diagonal gate is only useful if the qubits are in superposition. In the code below you will notice the qubits have been put in to superposition using Hadamard gates. This is because the diagonal gate operates on the phase of the qubit. Another thing to point out is that the entries can only be an absolute value of 1 that is -1 or +1.

How to run the program

Copy and paste the code below in to a python file

  1. Enter your API token in the IBMQ.enable_account('Insert API token here') part

  2. Save and run

Code

from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import Diagonal

pi = np.pi

IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')

backend = provider.get_backend('ibmq_qasm_simulator')

diagonals = [-1,1,1,-1]

q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')

circuit = QuantumCircuit(q,c)

circuit.h(q[0])
circuit.h(q[1])
circuit += Diagonal(diagonals)
circuit.h(q[0])
circuit.h(q[1])

circuit.measure(q,c) # Qubit Measurment

print(circuit)

job = execute(circuit, backend, shots=8192)
    
job_monitor(job)
counts = job.result().get_counts()

print(counts)
    

Output

Output when entries are set to [-1,1,1,-1]

Output when entries are set to [-1,1,1,-1]