Notebook template

View on QuantumAI Run in Google Colab View source on GitHub Download notebook

Setup

try:
    import cirq
    import cirq_google
except ImportError:
    print("installing cirq...")
    !pip install --quiet cirq-google --pre
    print("installed cirq.")
    import cirq
    import cirq_google

Make a copy of this template

You will need to have access to Quantum Computing Service before running this colab.

This notebook can serve as a starter kit for you to run programs on Google's quantum hardware. You can download it using the directions below, open it in colab (or Jupyter), and modify it to begin your experiments.

How to download iPython notebooks from GitHub

You can retrieve iPython notebooks in the Cirq repository by going to the docs/ directory. For instance, this Colab template is found here. Select the file that you would like to download and then click the Raw button in the upper-right part of the window:

GitHub UI button to view raw file

This will show the entire file contents. Right-click and select Save as to save this file to your computer. Make sure to save to a file with a .ipynb extension (you may need to select All files from the format dropdown instead of text). You can also get to this Colab's raw content directly

You can also retrieve the entire Cirq repository by running the following command in a terminal that has git installed:

git checkout https://github.com/quantumlib/Cirq.git

How to open Google Colab

You can open a new Colab notebook from your Google Drive window or by visiting the Colab site. From the Colaboratory site, you can use the menu to upload an iPython notebook:

Google Colab's upload notebook entry in File menu.

This will upload the ipynb file that you downloaded before. You can now run all the commands, modify it to suit your goals, and share it with others.

Authenticate with Quantum Computing Service and install Cirq

For details of authentication and installation, please see Get started with Quantum Computing Service.

  1. Enter the Cloud project ID you'd like to use in the project_id field.
  2. Then run the cell below (and go through the auth flow for access to the project id you entered).

Quantum Engine console

# The Google Cloud Project id to use.
project_id = ''
processor_id = ""

from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook
# For real engine instances, delete 'virtual=True' below.
qcs_objects = get_qcs_objects_for_notebook(project_id, processor_id, virtual=True)
engine = qcs_objects.engine
processor_id = qcs_objects.processor_id
Available processors: ['rainbow', 'weber']
Using processor: rainbow

Create an Engine variable

The following creates an engine variable which can be used to run programs under the project ID you entered above.

from google.auth.exceptions import DefaultCredentialsError
from google.api_core.exceptions import PermissionDenied

# Create an Engine object to use, providing the project id and the args
try: 
    if qcs_objects.signed_in: # This line only needed for colab testing.
        engine = cirq_google.get_engine()
    print(f"Successful authentication using project {project_id}!")
    print('Available Processors: ')
    print(engine.list_processors())
    print(f'Using processor: {processor_id}')
    processor = engine.get_processor(processor_id)
except DefaultCredentialsError as err: 
    print("Could not authenticate to Google Quantum Computing Service.")
    print(" Tips: If you are using Colab: make sure the previous cell was executed successfully.")
    print("       If this notebook is not in Colab (e.g. Jupyter notebook), make sure gcloud is installed and `gcloud auth application-default login` was executed.")
    print()
    print("Error message:")
    print(err)
except PermissionDenied as err:
    print(f"While you are authenticated to Google Cloud it seems the project '{project_id}' does not exist or does not have the Quantum Engine API enabled.")
    print("Error message:")
    print(err)
Successful authentication using project !
Available Processors: 
[<cirq_google.engine.simulated_local_processor.SimulatedLocalProcessor object at 0x7f8587111430>, <cirq_google.engine.simulated_local_processor.SimulatedLocalProcessor object at 0x7f85870d4dc0>]
Using processor: rainbow

Example

# A simple example.
q = cirq.GridQubit(5, 2)
circuit = cirq.Circuit(cirq.X(q)**0.5, cirq.measure(q, key='m'))

job = processor.run_sweep(
    program=circuit,
    repetitions=1000)

results = [str(int(b)) for b in job.results()[0].measurements['m'][:, 0]]
print('Success!  Results:')
print(''.join(results))
Success!  Results:
1010101001011000111100010100011001111001001010100101001100011101001011011000010111011011111111000010101111110111100111110000010111010010011000010000010111000101101000010010111101001010010101000101101010001110001111101011010111110010101111011010010011100011010000010101010001111101001111111000111001101010011100110011000000001001001100111001110010010010110000111001111000101001100100110010011110110000111100100001010001001110110100011011010100001011111000100011011010010100000100101001011110010100111000001000000000000000110110010001101010100111100011101101100100011101101000101000100011000010000000011010100000011111111010110000110110111111001101010101001000010111110010010010110111001000101111001011111110010010010010011011010000000111001011100000001101100000100010101010111010110001110011101101100101011100011100111101100110000010110001010011111111100100110101001011001110001010010110010000100011111011110111011010100010100110000011101000010101101100110001110100100101111001011011111110100100111000