# Code your first quantum circuit¶

Learn to code your first quantum circuit without downloading anything to your computer, by using Qiskit Notebooks embedded within IBM Quantum Experience. While you can benefit from having some familiarity with Python and quantum computing, you can get a sense of the big picture without those prerequisites.

## Overview¶

To code any quantum circuit with Qiskit, you follow three high-level steps:

• Build: Design a quantum circuit that represents the problem you are considering.

• Execute: Run experiments on different backends, either systems or simulators.

• Analyze: Calculate summary statistics and visualize the results of experiments.

The following instructions guide you through building a circuit with example code in a Qiskit Notebook, executing your program, and analyzing the results. You will then learn in greater detail how each component of the program functions.

## Run code in a Qiskit Notebook¶

1. Go to IBM Quantum Experience.

Open Qiskit Notebooks

1. To open Qiskit Notebooks, select Qiskit Notebooks in the navigation bar.

2. Click on New Notebook +. The first cell in your new notebook imports Qiskit into your Jupyter Notebook environment.

Enter code into a notebook

1. Copy Code Snippet 1 (below) and paste it in an empty code block cell in your new Qiskit Notebook.

2. Click the Run button.

Code Snippet 1

# Build
#------

# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)

# Add a H gate on qubit 0
circuit.h(0)

# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)

# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])

# Execute
#--------

# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')

# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)

# Grab results from the job
result = job.result()

# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)

# Analyze
#--------

# Draw the circuit
circuit.draw()


Total count for 00 and 11 are: {'00': 524, '11': 476}

     ┌───┐     ┌─┐
q_0: ┤ H ├──■──┤M├───
└───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c_0: ═══════════╩══╬═
║
c_1: ══════════════╩═


Plot a histogram

1. To see a visualization of the results, copy and paste Code Snippet 2 (below) into the next empty cell in your notebook.

2. Run the cell by holding the Shift key and then pressing the Enter/Return key on your keyboard.

Code Snippet 2

# Analyze
#--------

# Plot a histogram
plot_histogram(counts)


## Explanation: components of the program¶

The program contains six actions. The comments above each line of code indicate which of the six actions it is performing. Explore the details of each in the following sections.

• Build

• Execute

• Analyze

### Import packages¶

The import lines import the basic elements (packages and functions) needed for your program. The following imports are the default imports for any new Qiskit Notebook in IBM Quantum Experience, so they do no appear in the code snippet.

%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *


The imports used in the rest of the code example are

• QuantumCircuit: Holds all your quantum operations; the instructions for the quantum system

• execute: Runs your circuit

• Aer: Handles simulator backends

• qiskit.visualization: Enables data visualization, such as plot_histogram

### Initialize variables¶

In the next line of code, you initialize two qubits in the zero state, and two classical bits in the zero state, in the quantum circuit called circuit.

circuit = QuantumCircuit(2, 2)


The next three lines of code, beginning with circuit., add gates that manipulate the qubits in your circuit.

circuit.h(0)
circuit.cx(0, 1)
circuit.measure([0,1], [0,1])


The code above applies the following gates:

• QuantumCircuit.h(0): A Hadamard gate on qubit 0, which puts it into a superposition state

• QuantumCircuit.cx(0, 1): A controlled-NOT operation () on control qubit 0 and target qubit 1, putting the qubits in an entangled state

• QuantumCircuit.measure([0,1], [0,1]): The first argument indexes the qubits, the second argument indexes the classical bits. The nth qubit’s measurement result will be stored in the nth classical bit.

This particular trio of gates added one-by-one to the circuit forms the Bell state,

In this state, there is a 50 percent chance of finding both qubits to have the value zero and a 50 percent chance of finding both qubits to have the value one.

### Simulate the experiment¶

The next line of code calls a specific simulator framework – in this case, it calls Qiskit Aer, which is a high-performance simulator that provides several backends to achieve different simulation goals.

In this program, you use the qasm_simulator. Each run of this circuit will yield either the bit string '00' or '11'.

simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1000)
result = job.result()
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)


Total count for 00 and 11 are: {'00': 498, '11': 502}


The program specifies the number of times to run the circuit in the shots argument of the execute method (job = execute(circuit, simulator, shots=1000)). The number of shots of the simulation is set to 1000 (the default is 1024).

Once you have a result object, you can access the counts via the method get_counts(circuit). This gives you the aggregate outcomes of your experiment.

As expected, the output bit string is '00' approximately 50 percent of the time. This simulator does not model noise. Any deviation from 50 percent is due to the small sample size.

### Visualize the circuit¶

QuantumCircuit.draw() (called by circuit.draw() in the code) displays your circuit in one of the various styles used in textbooks and research articles.

circuit.draw()

     ┌───┐     ┌─┐
q_0: ┤ H ├──■──┤M├───
└───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c_0: ═══════════╩══╬═
║
c_1: ══════════════╩═


In this circuit, the qubits are ordered with qubit zero at the top and qubit one below it. The circuit is read from left to right, representing the passage of time.

### Visualize the results¶

Qiskit provides many visualizations, including the function plot_histogram, to view your results.

plot_histogram(counts)


The probabilities (relative frequencies) of observing the and states are computed by taking the respective counts and dividing by the total number of shots.

## Notices¶

### Version Information

Qiskit SoftwareVersion
Qiskit0.19.6
Terra0.14.2
Aer0.5.2
Ignis0.3.3
Aqua0.7.3
IBM Q Provider0.7.2
System information
Python3.7.6 (default, Feb 26 2020, 15:34:58) [GCC 8.3.0]
OSLinux
CPUs1
Memory (Gb)29.93264389038086
Fri Jun 26 10:06:06 2020 UTC