Hello dynamic circuits

Note

Click here to view this tutorial as an interactive Jupyter notebook in IBM Quantum Lab (requires sign-in).

Join us in our Slack channel #dynamic-circuits in the Qiskit workspace.

We will be using Qiskit throughout the tutorial. This notebook will guide you through the setup process.

Preamble

import sys
import warnings

if not sys.warnoptions:
    warnings.simplefilter("ignore")

Installation

Please follow the installation guide below to get started.

IBM Quantum Services registration

If you do not already have one, sign up for an IBM Quantum account.

Notebook access

The tutorial notebooks live in IBM Quantum Lab, where you can either run them in the cloud, or download them to run on your local machine.

Local machine

Log on to IBM Quantum Lab with your IBM Quantum account credentials.

Download the Dynamic circuits notebooks, including the figs directory and the run_openqasm3.py file.

Next, install Qiskit by following these instructions.

  • Set up a Python virtual environment for the tutorial (good practice but not necessary).

  • Make sure you have have the latest Qiskit installed.
    • pip install jupyter matplotlib scipy

    • pip install qiskit --upgrade

  • Open up this notebook (Hello-Dynamic-Circuits), run to check your installation, and run your first OpenQASM 3 program on hardware.

Quantum Lab

Log on to IBM Quantum Lab with your IBM Quantum account credentials.

Please verify that your qiskit-terra version >=0.19.0.

import qiskit.tools.jupyter

%qiskit_version_table

Version Information

Qiskit SoftwareVersion
qiskit-terra0.21.0
qiskit-aer0.10.4
qiskit-ignis0.7.0
qiskit-ibmq-provider0.20.0.dev0+4f1f8c6
qiskit0.36.1
System information
Python version3.9.5
Python compilerClang 10.0.0
Python builddefault, May 18 2021 12:31:01
OSDarwin
CPUs8
Memory (Gb)32.0
Tue Jun 21 09:45:31 2022 EDT
  • Locate the Dynamic Circuits directory. Launch this tutorial notebook from Jupyter in the tutorial root folder.

  • The notebook is ready to run!

Testing OpenQASM 3 Support

Let’s test out our installation by verifying we have access to the code and hardware necessary.

First, load our backend.

Note

This can be any hub/group/project that has access to the required device and Qiskit Runtime, and has OpenQASM 3 support.

# Note: This can be any hub/group/project that has access to the required device and Qiskit Runtime.
# Verify that ``qasm3`` is present in ``backend.configuration().supported_features``.
# hub = "<hub>"
# group = "<group>"
# project = "<project>"

Next, we load our IBM Quantum account credentials.

import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq.exceptions import IBMQAccountCredentialsNotFound

# Save token if necessary
#IBMQ.save_account("<token>")
try:
    IBMQ.load_account()
except IBMQAccountCredentialsNotFound:
    print("Could not find your credentials"
          "Uncomment the lines above and insert your API token "
          "which can be found here https://quantum-computing.ibm.com/account."
          "After saving your credentials add back the comment."
         )
    raise

Next, let’s load the hub/group/project.

from qiskit.providers.ibmq.exceptions import IBMQProviderError

# load provider
try:
    provider = IBMQ.get_provider(hub=hub, group=group, project=project)
except IBMQProviderError:
    print(
        "The provider was not found. "
        "This means your IBM Quantum Services account was not yet added. "
        "Contact one of the tutorial presenters to add you."
    )
    raise

Make sure to use any OpenQASM 3 enabled backend.

supports_qasm = lambda backend: (hasattr(backend.configuration(), "supported_features") and "qasm3" in backend.configuration().supported_features)
qasm3_backends = set(backend.name() for backend in provider.backends() if supports_qasm(backend))

print(f"The following backends support dynamic circuits: {qasm3_backends}")
# Get our backend
backend = provider.get_backend(backend_name)

Now we prepare our circuit.

qubit = 0
shots = 1000
from qiskit import QuantumCircuit

h_qc = QuantumCircuit(1, 1, name="|+> Prep")
h_qc.h(0)
h_qc.measure(0, 0)
h_qc.draw(idle_wires=False)
     ┌───┐┌─┐
  q: ┤ H ├┤M├
     └───┘└╥┘
c: 1/══════╩═
           0 

Next, transpile our quantum circuit for the hardware basis gates.

from qiskit import transpile

h_qc_transpiled = transpile(h_qc, backend, initial_layout=[1])
h_qc_transpiled.draw(idle_wires=False)
global phase: π/4
         ┌─────────┐┌────┐┌─────────┐┌─┐
q_0 -> 1 ┤ Rz(π/2) ├┤ √X ├┤ Rz(π/2) ├┤M├
         └─────────┘└────┘└─────────┘└╥┘
    c: 1/═════════════════════════════╩═
                                      0 

Now we submit our circuit to the backend to verify it is working.

job = backend.run(h_qc_transpiled, shots=shots)
print(f"Your job's id: {job.job_id()}")
result = job.result()
print(f"|+> preparation results: {result.get_counts(0)}")
Your job's id: 62b1cb89440f586de5aed415
|+> preparation results: {'0': 519, '1': 481}
job.error_message()

Now, run the circuit as an OpenQASM 3 program below. Here we are using a helper method run_openqasm3 that calls the Qiskit Runtime program qasm3-runner. We will describe what is happening in the Introduction to dynamic circuits notebook.

Note

In order to import run_openqasm3, it needs to be on your $PATH, which by default includes the folder where you have launched your jupyter notebook or ipython console.

job = run_openqasm3(h_qc_transpiled, backend, shots=shots)
=======|+> Prep=======
=======OpenQASM 3======
OPENQASM 3;
bit[1] c;
rz(pi/2) $1;
sx $1;
rz(pi/2) $1;
c[0] = measure $1;

==================
global phase: π/4

ancilla_0 -> 0 ───────────────────────────────
               ┌─────────┐┌────┐┌─────────┐┌─┐
      q_0 -> 1 ┤ Rz(π/2) ├┤ √X ├┤ Rz(π/2) ├┤M├
               └─────────┘└────┘└─────────┘└╥┘
ancilla_1 -> 2 ─────────────────────────────╫─
                                            ║
ancilla_2 -> 3 ─────────────────────────────╫─
                                            ║
ancilla_3 -> 4 ─────────────────────────────╫─
                                            ║
ancilla_4 -> 5 ─────────────────────────────╫─
                                            ║
ancilla_5 -> 6 ─────────────────────────────╫─
                                            ║
          c: 1/═════════════════════════════╩═
                                            0
==================
Running: caosn6lk1m9sjqungbt0
=======|+> Prep=======
{'0': 540, '1': 460}
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright

Version Information

Qiskit SoftwareVersion
qiskit-terra0.21.0
qiskit-aer0.10.4
qiskit-ignis0.7.0
qiskit-ibmq-provider0.20.0.dev0+4f1f8c6
qiskit0.36.1
System information
Python version3.9.5
Python compilerClang 10.0.0
Python builddefault, May 18 2021 12:31:01
OSDarwin
CPUs8
Memory (Gb)32.0
Tue Jun 21 09:46:43 2022 EDT

This code is a part of Qiskit

© Copyright IBM 2017, 2022.

This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.

Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.