10 - Introduction to OpenQAOA: An example workflow

This section provides a walkthrough of a simple example workflow, and is intended as a quick introduction to the functionalities of the OpenQAOA library. More focused examples are provided in other sections of the documentation.

The QAOA workflow can be divided in four simple steps: - Problem definition: Define your optimization problem here, either by: - using pre-defined problem classes or, - supplying your own QUBO - Model building: - Build the QAOA circuit with the available configurations - Choose the backend (device) to run the circuit - Choose the properties of the classical optimizer - Compile model and optimize: - Compile the model by passing the problem defined in step-1 - Execute model.optimize() to run the optimization process - Extract results - Run model.results to obtain information on the optimization run

Begin by importing necessary modules

[1]:
#some regular python libraries
import networkx as nx
import numpy as np
from pprint import pprint
import matplotlib.pyplot as plt

#import problem classes from OQ for easy problem creation
from openqaoa.problems import MaximumCut, NumberPartition

#import the QAOA workflow model
from openqaoa import QAOA

#import method to specify the device
from openqaoa.backends import create_device

Step 1: Create a problem instance

We begin by creating a problem instance for a simple MaximumCut problem for a random graph created using the python networkx module. MaximumCut is a go-to problem to demonstrate QAOA in action.

For this, we first: - create a random graph using the networkx module - using the MaximumCut problem class, we translate into the QUBO formalism to optimize with QAOA

[2]:
nodes = 6
edge_probability = 0.6
g = nx.generators.fast_gnp_random_graph(n=nodes,p=edge_probability, seed=45)

# import graph plotter from openqaoa
from openqaoa.utilities import plot_graph
plot_graph(g)
../_images/notebooks_10_workflows_on_Amazon_braket_4_0.png
[3]:
# Use the MaximumCut class to instantiate the problem.
maxcut_prob = MaximumCut(g)

# The property `qubo` translates the problem into a binary Qubo problem.
# The binary values can be access via the `asdict()` method.
maxcut_qubo = maxcut_prob.qubo
[4]:
pprint(maxcut_qubo.asdict())
{'constant': 0,
 'metadata': {},
 'n': 6,
 'problem_instance': {'G': {'directed': False,
                            'graph': {},
                            'links': [{'source': 0, 'target': 1},
                                      {'source': 0, 'target': 2},
                                      {'source': 0, 'target': 3},
                                      {'source': 0, 'target': 4},
                                      {'source': 0, 'target': 5},
                                      {'source': 1, 'target': 2},
                                      {'source': 1, 'target': 3},
                                      {'source': 1, 'target': 4},
                                      {'source': 1, 'target': 5},
                                      {'source': 2, 'target': 3},
                                      {'source': 2, 'target': 4},
                                      {'source': 3, 'target': 5},
                                      {'source': 4, 'target': 5}],
                            'multigraph': False,
                            'nodes': [{'id': 0},
                                      {'id': 1},
                                      {'id': 2},
                                      {'id': 3},
                                      {'id': 4},
                                      {'id': 5}]},
                      'problem_type': 'maximum_cut'},
 'terms': [[0, 1],
           [0, 2],
           [0, 3],
           [0, 4],
           [0, 5],
           [1, 2],
           [1, 3],
           [1, 4],
           [1, 5],
           [2, 3],
           [2, 4],
           [3, 5],
           [4, 5]],
 'weights': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}

Extract the exact solution for a small enough problem

[5]:
hamiltonian = maxcut_qubo.hamiltonian

# import the brute-force solver to obtain exact solution
from openqaoa.utilities import ground_state_hamiltonian
energy, configuration = ground_state_hamiltonian(hamiltonian)
print(f"Ground State energy: {energy}, Solution: {configuration}")
Ground State energy: -5.0, Solution: ['100110', '010110', '101001', '011001']
[6]:
#plot the solution on graph
g_sol = np.copy(g)
pos =  nx.spring_layout(g)
nx.draw_networkx_nodes(g, pos, nodelist=[idx for idx,bit in enumerate(configuration[0]) if bit == '1'], node_color="tab:red")
nx.draw_networkx_nodes(g, pos, nodelist=[idx for idx,bit in enumerate(configuration[0]) if bit == '0'], node_color="tab:blue")
nx.draw_networkx_edges(g, pos)
[6]:
<matplotlib.collections.LineCollection at 0x7f7b4ae5e3e0>
../_images/notebooks_10_workflows_on_Amazon_braket_9_1.png

Step 2: Build the QAOA model

  • Initialize the model (with default parameters)

  • Optionally set the following properties for the model

    • model.set_device(...): Set the device

      • The device properties include the location of the device [local, qcs, ibmq] and the device name. Full list of devices available at openqaoa.workflows.parameters.qaoa_parameters.ALLOWED_DEVICES

    • model.set_circuit_properties(...): Sets the circuit properties. Mainly used for:

      • p: the number of layers

      • param_type: the desired parameterisation to be chosen between ['standard', 'extended', 'fourier', annealing]

      • init_type: the initialisation strategy for param_type. To be chosen between ['ramp', 'random', 'custom']

    • model.set_backend_properties(...)

    • model.set_classical_optimizer(...)

For more details on the configurable properties, please refer to the documentation

[7]:
# initialize model with default configurations
q = QAOA()

You will need to be authenticated through the AWS CLI to use Braket Backends.

[8]:
# optionally configure the following properties of the model
# device

device_name = 'arn:aws:braket:::device/quantum-simulator/amazon/sv1'
braket_device = create_device(location='aws', name=device_name)
q.set_device(braket_device)

# circuit properties
q.set_circuit_properties(p=2, param_type='standard', init_type='rand', mixer_hamiltonian='x')

# backend properties (already set by default)
q.set_backend_properties(prepend_state=None, append_state=None)

# classical optimizer properties
q.set_classical_optimizer(method='cobyla', maxiter=10,
                          optimization_progress=True, cost_progress=True, parameter_log=True)

Step 3: Compile and Optimize

  • Once the QAOA model is configured, we need to compile it. Compilation is necessary because the QAOA solver has to interact with the problem in to be able to create the underlying QAOA circuit.

  • The problem is ready to be optimized now. The user can call model.optimize() to initiate the optimization loop.

[9]:
q.compile(maxcut_qubo)

Note that the optimise cell may take a few minutes to terminate!

[10]:
q.optimize()

Step 4: Accessing the results

[11]:
opt_results = q.result
[12]:
# print the cost history
fig, ax = opt_results.plot_cost()
../_images/notebooks_10_workflows_on_Amazon_braket_20_0.png
[13]:
# prints a large output (commented by default)
# pprint(opt_results.intermediate)
[14]:
pprint(opt_results.optimized)
{'angles': [1.730159433583, 0.4062112821, 1.073457082124, 2.933876052955],
 'cost': -1.4,
 'eval_number': 7,
 'job_id': 'arn:aws:braket:eu-west-2:733853225053:quantum-task/90c19780-90ff-4c7b-884c-d2977f980095',
 'measurement_outcomes': {'000011': 3,
                          '000101': 3,
                          '000110': 1,
                          '000111': 2,
                          '001011': 2,
                          '001100': 5,
                          '001101': 4,
                          '001110': 1,
                          '001111': 5,
                          '010000': 2,
                          '010011': 1,
                          '010101': 3,
                          '010110': 7,
                          '011001': 2,
                          '011010': 2,
                          '011100': 1,
                          '011111': 7,
                          '100000': 1,
                          '100011': 3,
                          '100101': 1,
                          '100110': 2,
                          '101001': 4,
                          '101010': 3,
                          '101111': 1,
                          '110000': 9,
                          '110001': 5,
                          '110010': 4,
                          '110011': 3,
                          '110100': 3,
                          '110101': 1,
                          '110110': 2,
                          '111000': 1,
                          '111001': 1,
                          '111010': 2,
                          '111100': 1,
                          '111110': 1,
                          '111111': 1}}
[15]:
variational_params = q.optimizer.variational_params
[16]:
#create the optimized QAOA circuit for qiskit backend
optimized_angles = opt_results.optimized['angles']
variational_params.update_from_raw(optimized_angles)
optimized_circuit = q.backend.qaoa_circuit(variational_params)

#print the optimized QAOA circuit for qiskit backend
print(optimized_circuit)
T  : |0|1|   2    |3|4|   5    |6| 7 |   8    | 9 |10 |   11   |12 | 13  |   14   | 15  |    16     |   17   |18 |   19    |   20   |   21   |   22    |   23   |   24   |   25    |26 |   27   |28 |29 |   30   |31 | 32  |   33   | 34  |    35     |   36   |37 |   38    |   39   |40|   41    |   42   |43|   44    |Result Types|

q0 : -H-C----------C-C----------C-C------------C---C------------C---C--------------C-----Rx(-3.46)--------------------------C-----------------C---------C-----------------C---------C------------C---C------------C---C--------------C-----Rx(-0.81)----------------------------------------------------------------------Probability--
        |          | |          | |            |   |            |   |              |                                        |                 |         |                 |         |            |   |            |   |              |                                                                                    |
q1 : -H-X-Rz(2.15)-X-|----------|-|-C----------|-C-|-C----------|-C-|-C------------|-C---C--------------------C---Rx(-3.46)-X--------Rz(5.87)-X---------|-----------------|---------|-C----------|-C-|-C----------|-C-|-C------------|-C---C--------------------C---Rx(-0.81)---------------------------------------------Probability--
                     |          | | |          | | | |          | | | |            | |   |                    |                                         |                 |         | |          | | | |          | | | |            | |   |                    |                                                         |
q2 : -H--------------X-Rz(2.15)-X-|-X-Rz(2.15)-|-X-|-|----------|-|-|-|-C----------|-|-C-|---------C----------|-C-Rx(-3.46)-----------------------------X--------Rz(5.87)-X---------|-X-Rz(5.87)-|-X-|-|----------|-|-|-|-C----------|-|-C-|---------C----------|-C-Rx(-0.81)---------------------------------------------Probability--
                                  |            |   | |          | | | | |          | | | |         |          | |                                                                   |            |   | |          | | | | |          | | | |         |          | |                                                       |
q3 : -H---------------------------X---Rz(2.15)-X---|-X-Rz(2.15)-|-X-|-|-X-Rz(2.15)-|-|-X-|---------|----------|-|-C------------------C--------Rx(-3.46)-----------------------------X---Rz(5.87)-X---|-X-Rz(5.87)-|-X-|-|-X-Rz(5.87)-|-|-X-|---------|----------|-|-C------------------C--Rx(-0.81)-----------------------Probability--
                                                   |            |   | |            | |   |         |          | | |                  |                                                               |            |   | |            | |   |         |          | | |                  |                                  |
q4 : -H--------------------------------------------X---Rz(2.15)-X---|-X---Rz(2.15)-|-X---|---------X-Rz(2.15)-|-X-|------------------|--------C------------------C--------Rx(-3.46)------------------X---Rz(5.87)-X---|-X---Rz(5.87)-|-X---|---------X-Rz(5.87)-|-X-|------------------|--C------------------C--Rx(-0.81)-Probability--
                                                                    |              |     |                    |   |                  |        |                  |                                                    |              |     |                    |   |                  |  |                  |            |
q5 : -H-------------------------------------------------------------X-----Rz(2.15)-X-----X-----------Rz(2.15)-X---X---------Rz(2.15)-X--------X---------Rz(2.15)-X--------Rx(-3.46)-----------------------------------X-----Rz(5.87)-X-----X-----------Rz(5.87)-X---X---------Rz(5.87)-X--X---------Rz(5.87)-X--Rx(-0.81)-Probability--

T  : |0|1|   2    |3|4|   5    |6| 7 |   8    | 9 |10 |   11   |12 | 13  |   14   | 15  |    16     |   17   |18 |   19    |   20   |   21   |   22    |   23   |   24   |   25    |26 |   27   |28 |29 |   30   |31 | 32  |   33   | 34  |    35     |   36   |37 |   38    |   39   |40|   41    |   42   |43|   44    |Result Types|
[ ]: