Q-CTRL logo

Jupyter Get the notebook

How to run a Qiskit program using Fire Opal

An example of how to integrate Fire Opal with IBM hardware to run quantum phase estimation

You can use Fire Opal to quickly improve the results of circuits created using Qiskit. In this user guide we demonstrate how to add Fire Opal to your Qiskit experiment pipeline to improve the probablity of achieving successful results.

Example: Running quantum phase estimation with Fire Opal

1. Import libraries

The first step is to get your environment set up and download dependencies. To learn more visit how to set up your environment and install Fire Opal.

For this guide, you will need the following dependencies, which can be done by running the following command in your terminal:

pip install fire-opal qiskit matplotlib qctrl-visualizer
import fireopal
import math
import qiskit
import qctrlvisualizer
import matplotlib.pyplot as plt

2. Set up quantum circuit

The creation of the circuit below is a minimal code version gathered from the Qiskit Quantum Phase Estimation tutorial.

The quantum phase estimation algorithm estimates the phase $\theta$ of the eigenvalue for a unitary operator $U$ applied to a quantum state $|\psi\rangle$, such that $U|\psi\rangle = \exp(2\pi i \theta)|\psi\rangle$. $n$ qubits are used to estimate $\theta$ to $n$ bits of precision. In this example, the state $|\psi\rangle = |1\rangle$, and the unitary operator rotates the state by an angle $\pi/4$, so $\theta = 1/8$.

def inverse_qft(qc, n):
    """Apply inverse quantum Fourier transform to the first n qubits in the circuit."""
    for qubit in range(n // 2):
        qc.swap(qubit, n - qubit - 1)
    for j in range(n):
        for m in range(j):
            qc.cp(-math.pi / float(2 ** (j - m)), m, j)

qpe = qiskit.QuantumCircuit(4, 3)
for qubit in range(3):

repetitions = 1
for counting_qubit in range(3):
    for i in range(repetitions):
        qpe.cp(math.pi / 4, counting_qubit, 3)
    repetitions *= 2

inverse_qft(qpe, 3)  # Apply inverse QFT.
for n in range(3):
    qpe.measure(n, n)

     ┌───┐                                                                ░    »
q_0: ┤ H ├─■──────────────────────────────────────────────────────────────░──X─»
     ├───┤ │                                                              ░  │ »
q_1: ┤ H ├─┼────────■────────■────────────────────────────────────────────░──┼─»
     ├───┤ │        │        │                                            ░  │ »
q_2: ┤ H ├─┼────────┼────────┼────────■────────■────────■────────■────────░──X─»
     ├───┤ │P(π/4)  │P(π/4)  │P(π/4)  │P(π/4)  │P(π/4)  │P(π/4)  │P(π/4)  ░    »
q_3: ┤ X ├─■────────■────────■────────■────────■────────■────────■────────░────»
     └───┘                                                                ░    »
c: 3/══════════════════════════════════════════════════════════════════════════»
«     ┌───┐                                         ░ ┌─┐      
«q_0: ┤ H ├─■──────────────■────────────────────────░─┤M├──────
«     └───┘ │P(-π/2) ┌───┐ │                        ░ └╥┘┌─┐   
«q_1: ──────■────────┤ H ├─┼─────────■──────────────░──╫─┤M├───
«                    └───┘ │P(-π/4)  │P(-π/2) ┌───┐ ░  ║ └╥┘┌─┐
«q_2: ─────────────────────■─────────■────────┤ H ├─░──╫──╫─┤M├
«                                             └───┘ ░  ║  ║ └╥┘
«q_3: ──────────────────────────────────────────────░──╫──╫──╫─
«                                                   ░  ║  ║  ║ 
«c: 3/═════════════════════════════════════════════════╩══╩══╩═
«                                                      0  1  2 

3. Define function for plotting results


def plot_histogram(counts, shot_count):
    """Plot a count histogram."""
    bitstrings = sorted(counts.keys())
    probabilities = [counts[bitstring] / shot_count for bitstring in bitstrings]
    plt.figure(figsize=(15, 5))
    bars = plt.bar(bitstrings, probabilities)
    plt.ylim([0, 1])

4. Provide your device information and credentials

Next, we’ll provide device information for the real hardware backend. Fire Opal will execute the circuit on the backend on your behalf, and it is designed to work seamlessly across multiple backend providers.

For this example, we’ll use an IBM Quantum API token. Visit IBM Quantum to sign up for an account and learn how to access systems with your account.

Use the obtained credentials to replace "your_IBMQ_token".

# Enter your IBM token here.
token = "your_IBMQ_token"

# These are the properties for the publicly available provider for IBM backends.
# If you have access to a private provider and wish to use it, replace these values.
hub = "ibm-q"
group = "open"
project = "main"

credentials = {"token": token, "hub": hub, "group": group, "project": project}

# Replace "desired_backend" with a device name
# Run fireopal.showSupportedBackends() to get a list of suppported backend names
backend_name = "desired_backend"

5. Validate the circuit and backend

Now that we have defined our credentials and are able to select a device we wish to use, we can validate that Fire Opal can compile our circuit, and that it’s compatible with the indicated backend.

Note that you may be prompted to authenticate your account with Fire Opal in a web browser.

validate_results = fireopal.validate(
    circuits=[qpe.qasm()], credentials=credentials, backend=backend_name

if validate_results["results"] == []:
    print("No errors found.")
    print("The following errors were found:")
    for error in validate_results["results"]:

In this previous example, the output should be an empty list since there are no errors in the circuit, i.e. validate_results["results"] == []. Note that the length of the validate_results list is the total number of errors present across all circuits in a batch. Since our circuit is error free, we can execute our circuit on real hardware.

6 . Run experiment using Fire Opal

The execute function from Fire Opal accepts an OpenQASM representation of the quantum circuit, which is generated with the .qasm() method of Qiskit’s QuantumCircuit class.

For more details, read the Fire Opal Get started guide.

shot_count = 2048

real_hardware_results = fireopal.execute(
bitstring_counts = real_hardware_results["results"]

7. Show Fire Opal results

The execute function returns a list containing the results of each circuits that we ran. Since we only ran one circuit, its result is the first element of this list.

def plot_histogram(counts, shot_count):
    """Plot a count histogram."""
    bitstrings = sorted(counts.keys())
    probabilities = [counts[bitstring] / shot_count for bitstring in bitstrings]
    plt.figure(figsize=(15, 5))
    bars = plt.bar(bitstrings, probabilities)
    plt.ylim([0, 1])

counts = bitstring_counts[0]

plot_histogram(counts=counts, shot_count=shot_count)


From the above plot, we observe that the bitstring with the highest probability is 001, which corresponds to

\[\theta = \frac{(001)_2}{2^3} = \frac 18,\]

since our phase estimation circuit has $n = 3$ bits of precision. This is the result we expected. We can also compute the probability of getting the correct result.

    "Success probability = {:.2f}%".format(100.0 * counts["001"] / sum(counts.values()))
Success probability = 91.65%

7. Compare results to running without Fire Opal

To get a true comparison, let’s run the same circuit without Fire Opal. We’ll run the circuit using Qiskit on the same IBM backend as used previously to get a one-to-one comparison.


provider = qiskit.IBMQ.get_provider(
    hub=credentials["hub"], group=credentials["group"], project=credentials["project"]
backend = provider.get_backend(backend_name)

ibm_result = qiskit.execute(qpe, backend=backend, shots=shot_count).result()
ibm_counts = ibm_result.get_counts()
    "Success probability = {:.2f}%".format(
        100.0 * ibm_counts["001"] / sum(ibm_counts.values())
plot_histogram(counts=ibm_counts, shot_count=shot_count)
Success probability = 26.56%


Congratulations! You’ve run a Qiskit program with Fire Opal and demonstrated the improvement it yielded on the quantum phase estimation algorithm.

Next up: Try out our tutorial on Creating and running circuits to run Fire Opal on Simon’s Algorithm.