Quantum Computing in Practice with Qiskit® and IBM Quantum Experience®

By Hassi Norlen
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Chapter 1: Preparing Your Environment

About this book

IBM Quantum Experience® is a leading platform for programming quantum computers and implementing quantum solutions directly on the cloud. This book will help you get up to speed with programming quantum computers and provide solutions to the most common problems and challenges.

You’ll start with a high-level overview of IBM Quantum Experience® and Qiskit®, where you will perform the installation while writing some basic quantum programs. This introduction puts less emphasis on the theoretical framework and more emphasis on recent developments such as Shor’s algorithm and Grover’s algorithm. Next, you’ll delve into Qiskit®, a quantum information science toolkit, and its constituent packages such as Terra, Aer, Ignis, and Aqua. You’ll cover these packages in detail, exploring their benefits and use cases. Later, you’ll discover various quantum gates that Qiskit® offers and even deconstruct a quantum program with their help, before going on to compare Noisy Intermediate-Scale Quantum (NISQ) and Universal Fault-Tolerant quantum computing using simulators and actual hardware. Finally, you’ll explore quantum algorithms and understand how they differ from classical algorithms, along with learning how to use pre-packaged algorithms in Qiskit® Aqua.

By the end of this quantum computing book, you’ll be able to build and execute your own quantum programs using IBM Quantum Experience® and Qiskit® with Python.

Publication date:
November 2020
Publisher
Packt
Pages
408
ISBN
9781838828448

 

Chapter 1: Preparing Your Environment

Before you can start working on your quantum programs, you must have a Python environment to execute your code. The examples in this book can be run both on your local machine by using the Qiskit® developer environment provided by IBM Quantum® and in an online environment on IBM Quantum Experience®.

In this chapter, we will take a look at both environments, get you a login account on IBM Quantum Experience®, and install a local version of Qiskit®. We will also discuss the fast-moving environment that is open source Qiskit®, and how to keep your local environment up to date.

We will cover the following recipes:

  • Creating your IBM Quantum Experience® account
  • Installing Qiskit®
  • Downloading the code samples
  • Installing your API key and accessing your provider
  • Keeping your Qiskit® environment up to date

So, let's get started. This chapter, and its contents, is pretty important as it provides you with the foundation on which you can start building your Qiskit® future. Do spend a moment or two setting this up, and then get going with the recipes in this book to get started with quantum programming on Qiskit®. To get you started quickly, you can also grab and run the sample recipe code that is provided with this book.

 

Technical requirements

The recipes that we will discuss in this chapter can be found here: https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience/tree/master/Chapter01.

You can run the recipes in this book in your local Qiskit® environment that you set up as a part of this chapter. You can also run most of them in the Quantum Lab environment of the online IBM Quantum Experience®. This is also true for the c1_r1_version.py recipe in this chapter, which lists the installed version of Qiskit® in the environment in which you run the recipe.

For information about how to download the recipes, see Downloading the code samples.

The local environment in which you choose to install Qiskit® must have Python 3.5 or higher installed (as of this book's writing). For detailed information about the most current requirements for Qiskit® installation, see the Qiskit® requirements page at https://qiskit.org/documentation/install.html.

IBM Quantum® recommends using the Anaconda distribution of Python (https://www.anaconda.com/distribution/), and to use virtual environments to keep your Qiskit® installation isolated from your usual Python environment.

New to virtual environments?

Virtual environments provide isolated Python environments that you can modify separately from each other. For example, you can create an isolated environment for your Qiskit® installation. You will then install Qiskit® only in that environment, and not touch the Python framework in the base environment which will then contain an untarnished version of Python.

As Qiskit® releases new versions of their packages, there is technically nothing stopping you from creating a new isolated environment for each updated version of Qiskit® to retain your old and stable version for your Qiskit® quantum programming, and a new environment where you can test updated versions of Qiskit®. You will find more on this in the Keeping your Qiskit® environment up to date recipe.

 

Creating your IBM Quantum Experience® account

Your key to exploring quantum computer programming with IBM is your IBM Quantum Experience® account. This free account gives you access to the online IBM Quantum Experience® interface, and the programming tools that are available there. An IBM Quantum Experience® account is not technically required to test out IBM Quantum Experience® or to install Qiskit® but is required to run your programs on the freely available IBM quantum computers, which are, after all, probably why you are reading this book in the first place.

Getting ready

To set up your IBM Quantum Experience® account, you can log in with an IBMid, or with one of the following:

  • A Google account
  • A GitHub account
  • A LinkedIn account
  • A Twitter account
  • An email address

How to do it...

  1. In your browser (Google Chrome seems to work best), go to this link: https://quantum-computing.ibm.com/login.
  2. Enter your IBMid credentials or select another login method.

    You can also skip the sign-in, which will give you access to IBM Quantum Experience® but with a limit of 3 qubits for your quantum circuits, and with simulator backends only.

  3. Once you have logged in, you now have an activated IBM Quantum Experience® account, and will find yourself at the main dashboard:
    Figure 1.1 – The IBM Quantum Experience® home page

    Figure 1.1 – The IBM Quantum Experience® home page

  4. From here, you have a couple of paths:

    Go to a composer to start building your quantum programs in a graphical user interface. Click the Circuit composer left-menu icon () and then go to Chapter 3, IBM Quantum Experience® – Quantum Drag and Drop.

    If you want to start writing your quantum programs in Python without first installing a local Qiskit® instance, you can go to the Qiskit® notebooks to start working on your quantum programs in a Jupyter Notebook Python environment. Click on the Quantum Lab left-menu icon (A picture containing drawing

Description automatically generated), click New Notebook, and then go to Chapter 4, Starting at the Ground Level with Terra.

    If you want to continue down the Qiskit® path for which this book was written, you can now log out of IBM Quantum Experience®, and continue with installing Qiskit® on your local machine.

See also

 

Installing Qiskit®

With your Python environment prepared and ready to go, and your IBM Quantum Experience® account set up, you can now use pip to install the Qiskit® Python extension. The process should take about 10 minutes or so, after which you can use your Python command line, or your favorite Anaconda Python interpreter to start writing your quantum programs.

Getting ready

This recipe provides information about the generic way to install Qiskit® and does not go into any detail regarding operating system differences or general installation troubleshooting.

For detailed information about the most current requirements for Qiskit® installation, see the Qiskit® requirements page at https://qiskit.org/documentation/install.html.

How to do it...

  1. Create your Anaconda virtual environment:
    $ conda create -n environment_name python=3

    This will install a set of environment-specific packages.

  2. Activate your virtual environment:
    $ conda activate environment_name
  3. Verify that you are in your virtual environment.

    Your Command Prompt should now include the name of your environment; I used something like this for my own environment with the name packt_qiskit:

    (packt_qiskit) Hassis-Mac:~ hassi$

    Nomenclature

    In this chapter, I will print out the full prompt like this (environment_name) … $ to remind you that you must execute the commands in the correct environment. In the rest of the book, I will assume that you are indeed in your Qiskit-enabled environment and just show the generic prompt: $.

  4. If needed, do a pip update.

    To install Qiskit®, you must use pip as Qiskit® is not distributed as conda packages. The latest Qiskit® requires pip 19 or newer.

    If you have an older version of pip, you must upgrade using the following command:

    (environment_name) … $  pip  install  -U  pip
  5. Install Qiskit®.

    So, with everything set up and prepared, we can now get on to the main course, installing the Qiskit® code in your environment. Here we go!

    (environment_name) … $  pip install qiskit

    Failed wheel build

    As part of the installation, you might see errors that the wheel failed to build. This error can be ignored.

  6. Use Python to Verify that Qiskit® installed successfully.

    Open Python:

    (environment_name) … $  python3

    Import Qiskit®:

    >>> import qiskit

    This is a little bit exciting; we are going to use Qiskit® code for the first time. Granted, not exactly for programming a quantum computer, but at least to make sure that we are now ready to start programming your quantum programs.

    List the version details:

    >>> qiskit.__qiskit_version__

    This should display the versions of the installed Qiskit® components:

    {'qiskit-terra': '0.15.2', 'qiskit-aer': '0.6.1', 'qiskit-ignis': '0.4.0', 'qiskit-ibmq-provider': '0.9.0', 'qiskit-aqua': '0.7.5', 'qiskit': '0.21.0'}

Congratulations, your Qiskit® installation is complete; you are ready to go!

By using pip install from your virtual environment, you can install Qiskit® in just that environment, which will then stay isolated from the rest of your Python environment.

There's more…

Qiskit® also comes with some optional visualization dependencies to use visualizations across the Qiskit® components. You can install these with the following command:

(environment_name) … $ pip install qiskit[visualization]

Note

If you are using the zsh shell you must enclose the component in quotes:pip install 'qiskit[visualization]'

See also

For a quick introduction to Anaconda environments, see Managing environments in the Anaconda docs: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html.

This book does not, in any way, act as a Qiskit® installation troubleshooting guide, and you might conceivably run into issues when installing it, depending on your local OS, versions, and more.

But fear not, help is on the way. Here are a couple of good and friendly channels on which to reach out for help:

 

Downloading the code samples

The recipes in this book include short, and some not so short, sample programs that will lead you through your first steps in programming quantum computers. You can type in these programs directly from the instructions in the book if you want, but for convenience, you can also grab the sample code directly from the Packt Cookbook GitHub organization.

The Python samples are written for Python 3.5+ and the Qiskit® extension that you installed in your Python environment. The Python samples all have the extension: .py.

Getting ready

While you can type the recipes directly into your Python environment, or into Jupyter Notebooks on IBM Quantum Experience® or on your local Anaconda environment, it is somewhat more efficient to download or use Git to clone the sample code to your local environment. The advantage of cloning is that you can later refresh your local files from the remote repository if any updates are made.

If you do not plan to use Git, but instead to download the recipes as a compressed file, continue on with How to do it.

To use Git to clone the sample code, you must first do the following:

  1. Get a GitHub account. These are free and you can sign up for one at https://github.com.
  2. Install Git in your local environment. For more information, see https://git-scm.com/book/en/v2/Getting-Started-Installing-Git.
  3. If you are a user interface person, you might also want to install GitHub Desktop, available here: https://desktop.github.com/.

How to do it...

You have several different options to download the sample recipes to your local machine.

For each, start by opening your web browser and then go to the Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience GitHub repository at https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience.

Downloading the repository as a compressed file

The easiest way to get the recipes is to just grab the sample files as a compressed directory and decompress it on your local machine:

  1. At the preceding URL, click the Clone or download button and select Download zip.
  2. Download the compressed file and select a location.
  3. Decompress the file.

Cloning the repository using git

  1. Click the Clone or download button and copy the URL.
  2. Open your command line and navigate to the location where you want to clone the directory.
  3. Enter the following command:
    $ git clone https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience.git

    The command should result in something like the following:

    Cloning into 'Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience'...
    remote: Enumerating objects: 250, done.
    remote: Counting objects: 100% (250/250), done.
    remote: Compressing objects: 100% (195/195), done.
    remote: Total 365 (delta 106), reused 183 (delta 54), pack-reused 115
    Receiving objects: 100% (365/365), 52.70 MiB | 5.42 MiB/s, done.
    Resolving deltas: 100% (153/153), done.

Cloning the repository using GitHub Desktop

  1. Click the Clone or download button and select Open in desktop.
  2. In the GitHub Desktop dialog, select a directory to clone the repository to and click OK.

You can now browse the recipes in this cookbook. Each chapter includes one or more recipes. If you want, you can copy and paste the recipes directly into your Python environment, or into Jupyter Notebooks on IBM Quantum Experience® or on your local Anaconda environment.

Opening a recipe file

So far, you have done everything with the command line. So how about you grab the following Python program and run it from your favorite Python interpreters, such as Anaconda Spyder or Jupyter Notebooks?

If you have downloaded the sample files, the recipe file is available in the following local directory:

<The folder where you downloaded the files>/https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience/blob/master/Chapter01/ch1_r1_version.py

The ch1_r1_version.py code sample lists the version numbers of the Qiskit® components that we just installed:

# Import Qiskit
import qiskit
# Set versions variable to the current Qiskit versions
versions=qiskit.__qiskit_version__
# Print the version number for the Qiskit components
print("Qiskit components and versions:")
print("===============================")
 
for i in versions:
    print (i, versions[i]) 

When run, the preceding code should give an output similar to the following:

Figure 1.2 – A list of the Qiskit® components and versions

Figure 1.2 – A list of the Qiskit® components and versions

The following sections cover how to run the script in the environments that we have available.

Python scripts in Spyder

In your local environment, you can now open the Python scripts in the Python interpreter of your choice; for example, Spyder, which is included with Anaconda:

Important

Be sure that you run your interpreter in the virtual environment in which you installed Qiskit®. Otherwise, it will not be able to find Qiskit®, and the program will not run correctly.

  1. Open your Anaconda user interface.
  2. Select your virtual environment.
  3. Click the Spyder tile. If Spyder is not yet installed for your virtual environment, it will now install. This might take a while. Be patient!
  4. In Spyder, open the Python script that is included with this chapter:
    <The folder where you downloaded the files>/https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience/blob/master/Chapter01/ch1_r1_version.py
  5. Click Run. The script will now pull out the version numbers of the installed Qiskit® components. You can also open the Python scripts in a Jupyter notebook, for example, in the online IBM Quantum Experience® environment, but this takes a little extra work.

Jupyter Notebooks in Anaconda

  1. Open your Anaconda user interface.
  2. Select your virtual environment.
  3. Click the Jupyter Notebooks tile. If Jupyter Notebooks is not yet installed for your virtual environment, it will now install.
  4. Your default web browser opens at your root directory. Browse to and open the following:
    <The folder where you downloaded the files>/https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience/blob/master/Chapter01/ch1_r1_version.py
  5. The sample script opens in a Jupyter text editor. You can now see the code but not run it.
  6. Go back to the Jupyter browser and click New | Notebook.
  7. Copy and paste the Python script code into the new notebook. You can now click Run and see the code execute.

Jupyter Notebooks in IBM Quantum Experience®

  1. To run the Python scripts in the online IBM Quantum Experience® notebooks, log in to IBM Quantum Experience® at https://quantum-computing.ibm.com/login.
  2. On the main dashboard, click on the Quantum Lab left-menu icon (A picture containing drawing

Description automatically generated), then click New Notebook and follow the process we discussed in the Jupyter Notebooks in Anaconda section.:
Figure 1.3 – Running your Qiskit® code on IBM Quantum Experience®

Figure 1.3 – Running your Qiskit® code on IBM Quantum Experience®

How it works...

The Qiskit®-based Python code that we will be going through in the chapters that follow can be run in any Python environment that meets the Qiskit® requirements, so you have free reins to pick the environment that suits you. And with that environment, you can also freely pick your favorite tools to run the programs.

For this book, I have tested running the code in both the Spyder editor that comes as standard with Anaconda and with the Jupyter Notebook environments on both IBM Quantum Experience® and Anaconda.

 

Installing your API key and accessing your provider

Now that you have installed Qiskit®, you can immediately start creating your quantum programs and run these on local simulators. If, however, at some point, you want to run your quantum code on actual IBM Quantum® hardware, you must install your own unique API key locally.

API keys on IBM Quantum Experience®

If you are running your Qiskit® programs in the IBM Quantum Experience® notebook environment, your API key is automatically registered.

Getting ready

Before you can install your API key, you must first have an IBM Quantum Experience® account. If you have not yet created one, go back and do it (see the Creating your IBM Quantum Experience® account section).

How to do it...

Let's take a look at how to install the API key locally:

  1. Log in to IBM Quantum Experience® at https://quantum-computing.ibm.com/login.
  2. On the IBM Quantum Experience® dashboard, find your user icon in the upper-right corner, click it, and select My account.
  3. On the account page, find the Qiskit in local environment section, and click Copy token.
  4. You can now paste your token in a temporary location or keep it in the clipboard.
  5. On your local machine, access your Qiskit® environment. We have done this one, but here's a repeat of the process if you are using Anaconda.
  6. Activate your virtual environment:
    $ conda activate environment_name
  7. Open Python:
    $(environment_name) … $  python3

    Verify that the Python header displays and that you are running the correct version of Python:

    Python 3.7.6 (default, Jan  8 2020, 13:42:34) 
    [Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
  8. Get the required IBMQ class:
    >>> from qiskit import IBMQ		
  9. Install your API token locally:
    >>> IBMQ.save_account('MY_API_TOKEN')

    Here, instead of MY_API_TOKEN, paste in the API token that you just copied from IBM Quantum Experience®: Keep the single quotes as they are required for the command.

  10. Load your account.

    Now that the token is in place, let's verify that all is in order and that your account has the correct privileges:

    >>> IBMQ.load_account()

    This should display the following output:

    <AccountProvider for IBMQ(hub='ibm-q', group='open', project='main')>

    This is the provider information for your account, with hub, group, and project.

How it works...

The main class that you import for this exercise is IBMQ, which is a toolbox for working with the quantum hardware and software that is provided by IBM in the cloud.

In this chapter, we used save.account() to store your account locally. As we go forward, in the recipes where we will access the IBM Quantum® machines, we will use the IBMQ.load_account() and IBMQ.get_provider() classes in your quantum programs to make sure that you have the correct access.

Updating your API key

If for some reason, you need to create a new API token on IBM Quantum Experience® and update your locally saved token, you can use the following command:

>>> IBMQ.save_account('NEW_API_TOKEN', overwrite=True)

There's more…

In the code that follows in the recipes in this cookbook, we will set a provider variable to hold the provider information for your account by using the following command:

>>> provider = IBMQ.get_provider()

We can then use the provider information when selecting the IBM Quantum® computer, or backend, to run your quantum programs on. In the following example, we select a quantum computer that is called IBM Q 5 Yorktown (ibmqx2) as our backend. The internal reference for this machine is ibmqx2:

>>> backend = provider.get_backend('ibmqx2')
 

Keeping your Qiskit® environment up to date

Qiskit® is an open source programming environment that is in continuous flux. Over the course of writing this book, I have passed through many minor and major version updates of the software.

It is generally a good idea to stay updated with the latest version, but with some updates, components of the code might change behavior. It is always a good idea to have a good look at the release notes for each new version. Sometimes changes are introduced that will change the way your code behaves. In those cases, you might want to hold off on upgrading until you have verified that your code still works as expected.

If you are using Anaconda environments, then you can maintain more than one environment at different Qiskit® levels, to have a fallback environment in case an upgraded Qiskit® version breaks your code.

Qiskit® moves fast

The IBM Quantum Experience® Notebook environment always runs the latest version of Qiskit®, and it might be a good idea to test drive your code in that environment before you upgrade your local environment.

You can also subscribe to notification updates, to find out when a new release has been offered:

  1. Log in to IBM Quantum Experience® at https://quantum-computing.ibm.com/login.
  2. On the IBM Quantum Experience® dashboard, find your user icon in the upper-right corner, click it, and select My account.
  3. On the account page, under Notification settings, set Updates and new feature announcements to On.

Getting ready

Before you begin, verify which version of Qiskit® you are running for each of your environments (if you have more than one).

For each environment, launch Python, either from the command line, from an IDE such as Spyder, or as a Jupyter notebook, then execute the following code:

>>> import qiskit
>>> qiskit.__qiskit_version__

If you have an old version of Qiskit® installed, the preceding code might result in the following output:

{'qiskit-terra': '0.9.0', 'qiskit-aer': '0.3.0', 'qiskit-ibmq-provider': '0.3.0', 'qiskit-aqua': '0.6.0', 'qiskit': '0.12.0'}

You can then go to the Qiskit® release notes to find out if there is a more up-to-date version available: https://qiskit.org/documentation/release_notes.html

This is a lot of steps just to make sure. The whole process is automated in Python. To go down that path, go to the next section.

How to do it...

  1. Activate your virtual environment:
    $ conda activate environment_name
  2. Run the following command to check for outdated pip packages for your virtual environment:
    (environment_name) … $  pip list --outdated
  3. This will return a list of all your pip packages that are currently outdated and list the available versions:
    Example:Package                  Version  Latest   Type 
    ------------------------ -------- -------- -----
    
    qiskit                   0.19.6   0.21.0   sdist
    qiskit-aer               0.5.2    0.6.1    wheel
    qiskit-aqua              0.7.3    0.7.5    wheel
    qiskit-ibmq-provider     0.7.2    0.9.0    wheel
    qiskit-ignis             0.3.3    0.4.0    wheel
    qiskit-terra             0.14.2   0.15.1   wheel 
    
  4. It is then a breeze to update Qiskit® using pip:
    (environment_name) … $  pip install qiskit --upgrade
  5. From the command line, verify that Qiskit® is installed:
    (environment_name)… $ pip show qiskit

    This will result in an output similar to the following:

    Name: qiskit
    Version: 0.21.0
    Summary: Software for developing quantum computing programs
    Home-page: https://github.com/Qiskit/qiskit
    Author: Qiskit Development Team
    Author-email: [email protected]
    License: Apache 2.0
    Location: /Users/hassi/opt/anaconda3/envs/packt_qiskit/lib/python3.7/site-packages
    Requires: qiskit-aer, qiskit-terra, qiskit-aqua, qiskit-ignis, qiskit-ibmq-provider
    Required-by: 
    
  6. Verify that Qiskit® is integrated with Python in your isolated environment.

    Open Python:

    (environment_name)… $ python3

    Import Qiskit®:

    >>> import qiskit

    List the version details:

    >>> qiskit.__qiskit_version__

    This should display the versions of the installed Qiskit® components:

    {'qiskit-terra': '0.15.2', 'qiskit-aer': '0.6.1', 'qiskit-ignis': '0.4.0', 'qiskit-ibmq-provider': '0.9.0', 'qiskit-aqua': '0.7.5', 'qiskit': '0.21.0'} 

Congratulations, your Qiskit® upgrade worked; you are now running the latest code!

How it works...

Depending on how you consume this book, you might be looking over this process as part of your first read-through, and no upgrades were available. If so, go ahead and bookmark this recipe, and come back to it at a later time when there has been a Qiskit® upgrade.

The pip tool will manage your upgrade for you for each virtual environment. As I mentioned before, it might be a good idea to do a staged upgrade of your environments if you have more than one.

For example, you can upgrade one environment and test run your quantum programs in that environment to make sure that the new version did not break anything in your code.

OK, with this you should be reasonably set with one or more Qiskit® environments on which to run your quantum programs. If you feel ready for it, you can now take the plunge and go directly to Chapter 4, Starting at the Ground Level with Terra, to start writing quantum programs in Python using Qiskit®. If you are up for some prep work to get a feel for what programming a quantum computer is all about, start with Chapter 2, Quantum Computing and Qubits with Python, to get an introduction to qubits and gates, or Chapter 3, IBM Quantum Experience® – Quantum Drag and Drop, to get a visual feel for quantum programs by using the IBM Quantum Experience® drag-and-drop programming interface.

No matter which path you take, don't worry, we'll let Python do the hard work. Again, have fun!

About the Author

  • Hassi Norlen

    Hassi Norlen is a Physicist and science educator who works as an IBM Quantum Ambassador and Content Design lead with IBM Watson IoT Solutions. Before joining the IBM Watson IoT Solutions team, Hassi worked with information design across several IBM divisions, notably IBM BigInsights in the field of Big Data, InfoSphere Optim database management software with products such as IBM InfoSphere Workload Replay (ID lead) and IBM Data Server Manager, and Enterprise Content Management (ECM) with products such as IBM FileNet and IBM Web Content Manager.

    Browse publications by this author
Book Title
Unlock this book and the full library for only $5/m
Access now