Workflows

Workflows are a simple reference API to build complex quantum optimisations problems. Currently, it supports creations of QAOA and Recursive QAOA workflows.

Workflows are designed to aid the user to focus on the optimisation problem, while delegating the construction and the execution of the specific algorithm to OpenQAOA

Workflow - ABC

class openqaoa.algorithms.baseworkflow.Workflow(device=<openqaoa.backends.devices_core.DeviceLocal object>)[source]

Abstract class to represent an optimizer

It’s basic usage consists of

  1. Initialization

  2. Compilation

  3. Optimization

device

Device to be used by the optimizer

Type:

DeviceBase

backend_properties

The backend properties of the optimizer workflow. Use to set the backend properties such as the number of shots and the cvar values. For a complete list of its parameters and usage please see the method set_backend_properties

Type:

BackendProperties

classical_optimizer

The classical optimiser properties of the optimizer workflow. Use to set the classical optimiser needed for the classical optimisation part of the optimizer routine. For a complete list of its parameters and usage please see the method set_classical_optimizer

Type:

ClassicalOptimizer

local_simulators

A list containing the available local simulators

Type:

list[str]

cloud_provider

A list containing the available cloud providers

Type:

list[str]

compiled

A boolean flag to check whether the optimizer object has been correctly compiled at least once

Type:

Bool

id
Type:

TODO

exp_tags

A dictionary containing the tags of the optimizer object. The user can set this value using the set_exp_tags method.

Type:

dict

problem

The problem object that the optimizer will be optimizing.

Type:

Problem

results

The results object that will contain the results of the optimization routine.

Type:

Results

asdict(exclude_keys=[], options={})[source]

Returns a dictionary of the Optimizer object, where all objects are converted to dictionaries.

Parameters:
  • exclude_keys (List[str]) – A list of keys to exclude from the returned dictionary.

  • options (dict) –

    A dictionary of options to pass to the method that creates the dictionary to dump.
    complex_to_stringbool

    If True, converts complex numbers to strings. If False, complex numbers are not converted to strings.

    intermediate_measurementsbool

    If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

Return type:

dict

compile(problem)[source]

Method that will make sure that the problem is in the correct form for the optimizer to run and generate the atomic id. This method should be extended by the child classes to include the compilation of the problem into the correct form for the optimizer to run.

Parameters:

problem (QUBO) – The problem to be optimized. Must be in QUBO form.

dump(file_name='', file_path='', prepend_id=False, indent=2, compresslevel=0, exclude_keys=[], overwrite=False, options={})[source]

Saves the Optimizer object as json file (if compresslevel is 0). If compresslevel is not 0, saves the Optimizer object as a .gz file (which should be decompressed before use).

Parameters:
  • file_name (str) – The name of the json file.

  • file_path (str) – The path where the json file will be saved.

  • prepend_id (bool) – If True, the name will have the following format: ‘{project_id}–{experiment_id}–{atomic_id}–{file_name}.json’. If False, the name will have the following format: ‘{file_name}.json’. Default is False.

  • indent (int) – The number of spaces to indent the result in the json file. If None, the result is not indented.

  • compresslevel (int) – The compression level to use. If 0, no compression is used and a json file is saved. If 1, the fastest compression method is used. If 9, the slowest but most effective compression method is used. And a .gz file is saved.

  • exclude_keys (List[str]) – A list of keys that should not be included in the json file.

  • overwrite (bool) – If True, overwrites the file if it already exists. If False, raises an error if the file already exists.

  • options (dict) – A dictionary of options to pass to the method that creates the dictionary to dump.

  • intermediate_measurements (bool) – If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

dumps(indent=2, exclude_keys=[], options={})[source]

Returns a json string of the Optimizer object.

Parameters:
  • indent (int) – The number of spaces to indent the result in the json file. If None, the result is not indented.

  • exclude_keys (List[str]) – A list of keys to exclude from the json string.

  • options (dict) – A dictionary of options to pass to the method that creates the dictionary to dump.

  • intermediate_measurements (bool) – If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

Return type:

str

classmethod from_dict(dictionary)[source]

Creates an Optimizer object from a dictionary (which is the output of the asdict method) :type dictionary: dict :param dictionary: A dictionary with the information of the Optimizer object. :type dictionary: dict

Return type:

QAOA or RQAOA

classmethod load(file_name, file_path='')[source]

Creates an Optimizer object from a file (which is the output of the dump method) :type file_name: str :param file_name: The name of the file. :type file_name: str :type file_path: str :param file_path: The path of the file. :type file_path: str

Return type:

QAOA or RQAOA

classmethod loads(string)[source]

Creates an Optimizer object from a string (which is the output of the dumps method) :type string: str :param string: A string with the information of the Optimizer object. :type string: str

Return type:

QAOA or RQAOA

optimize()[source]
set_backend_properties(*args, **kwargs)[source]
set_classical_optimizer(*args, **kwargs)[source]
set_device(*args, **kwargs)[source]
set_error_mitigation_properties(*args, **kwargs)[source]
set_exp_tags(tags)[source]

Method to add tags to the experiment. Tags are stored in a dictionary (self.exp_tags) and can be used to identify the experiment. Name is a special tag that is used to identify the experiment in the results object, it will also be stored in the dictionary, and will overwrite any previous name.

Parameters:
  • name (str) – Name of the experiment. If None, the name will not be changed. If not None, the name will be changed to the new one.

  • tags (dict) – Dictionary containing the tags to be added to the experiment. If the tag already exists, it will be overwritten.

set_header(project_id=None, description=None, run_by=None, provider=None, target=None, cloud=None, client=None, experiment_id=None)[source]

Method to set the identification stamps of the optimizer object in self.header.

Parameters:

TODO (document the parameters) –

Workflow Properties

class openqaoa.algorithms.workflow_properties.BackendProperties(prepend_state=None, append_state=None, init_hadamard=True, n_shots=100, cvar_alpha=1, noise_model=None, initial_qubit_mapping=None, qiskit_simulation_method=None, qiskit_optimization_level=None, seed_simulator=None, active_reset=None, rewiring=None, disable_qubit_rewiring=None)[source]

Choose the backend on which to run the QAOA circuits

Parameters:
  • device (DeviceBase) – The device to use for the backend.

  • prepend_state (Union[openqaoa.basebackend.QuantumCircuitBase,numpy.ndarray(complex)]) – The state prepended to the circuit.

  • append_state (Union[QuantumCircuitBase,numpy.ndarray(complex)]) – The state appended to the circuit.

  • init_hadamard (bool) – Whether to apply a Hadamard gate to the beginning of the QAOA part of the circuit.

  • n_shots (int) – The number of shots to be used for the shot-based computation.

  • cvar_alpha (float) – The value of the CVaR parameter.

  • noise_model (NoiseModel) – The qiskit noise model to be used for the shot-based simulator.

  • initial_qubit_mapping (Union[List[int], numpy.ndarray]) –

    Mapping from physical to logical qubit indices, used to eventually

    construct the quantum circuit. For example, for a system composed by 3 qubits

    qubit_layout=[1,3,2], maps 1<->0, 3<->1, 2<->2, where the left hand side is the physical qubit

    and the right hand side is the logical qubits

  • qiskit_simulation_method (str) – Specify the simulation method to use with the qiskit.AerSimulator

  • qiskit_optimization_level (int, optional) – Specify the qiskit.transpile optimization level. Choose from 0,1,2,3

  • seed_simulator (int) – Specify a seed for qiskit simulators

  • active_reset (bool) – To use the active_reset functionality on Rigetti backends through QCS

  • rewiring (str) – Specify the rewiring strategy for compilation for Rigetti QPUs through QCS

  • disable_qubit_rewiring (bool) – enable/disbale qubit rewiring when accessing QPUs via the AWS braket

asdict()
class openqaoa.algorithms.workflow_properties.ClassicalOptimizer(optimize=True, method='cobyla', maxiter=100, maxfev=None, jac=None, hess=None, constraints=None, bounds=None, tol=None, optimizer_options=None, jac_options=None, hess_options=None, optimization_progress=False, cost_progress=True, parameter_log=True, save_intermediate=False)[source]

The classical optimizer for the QAOA optimization routine of the QAOA circuit parameters.

Parameters:
  • optimize (bool) – Whether to perform optimization routine on the given QAOA problem

  • method (str) – optimization method for QAOA e.g. ‘COBYLA’

  • maxiter (Optional[int]) – Maximum number of iterations.

  • maxfev (Optional[int]) – Maximum number of function evaluations.

  • jac (str) –

    Method to compute the gradient vector. Choose from:
    • [‘finite_difference’, ‘param_shift’, ‘stoch_param_shift’, ‘grad_spsa’]

  • hess (Optional[str]) –

    Method to compute the hessian. Choose from:
    • [‘finite_difference’, ‘param_shift’, ‘stoch_param_shift’, ‘grad_spsa’]

  • constraints (scipy.optimize.LinearConstraints, scipy.optimize.NonlinearConstraints) – Scipy-based constraints on parameters of optimization

  • bounds (scipy.scipy.optimize.Bounds) – Scipy-based bounds on parameters of optimization

  • tol (float) – Tolerance before the optimizer terminates; if tol is larger than the difference between two steps, terminate optimization.

  • optimizer_options (dict) –

    Dictionary of optimiser-specific arguments, defaults to None.
    stepsizefloat

    Step size of each gradient descent step.

    decayfloat

    Stepsize decay parameter of RMSProp.

    epsfloat

    Small number to prevent division by zero for RMSProp.

    lambdfloat

    Small number to regularize QFIM for Natural Gradient Descent.

  • jac_options (dict) – Dictionary that specifies gradient-computation options according to method chosen in ‘jac’.

  • hess_options (dict) – Dictionary that specifies Hessian-computation options according to method chosen in ‘hess’.

  • optimization_progress (bool) – Returns history of measurement outcomes/wavefunction if True. Defaults to False.

  • cost_progress (bool) – Returns history of cost values if True. Defaults to True.

  • parameter_log (bool) – Returns history of angles if True. Defaults to True.

  • save_intermediate (bool) – Outputs the jobids and parameters used for each circuit into seperate csv files. Defaults to False.

asdict()
class openqaoa.algorithms.workflow_properties.CircuitProperties(param_type='standard', init_type='ramp', qubit_register=[], p=1, q=1, annealing_time=None, linear_ramp_time=None, variational_params_dict={}, mixer_hamiltonian='x', mixer_qubit_connectivity=None, mixer_coeffs=None, seed=None)[source]

Tunable properties of the QAOA circuit to be specified by the user

property annealing_time
asdict()
property init_type
property mixer_hamiltonian
property p
property param_type

QAOA

class openqaoa.algorithms.qaoa.qaoa_workflow.QAOA(device=<openqaoa.backends.devices_core.DeviceLocal object>)[source]

A class implementing a QAOA workflow end to end.

It’s basic usage consists of 1. Initialization 2. Compilation 3. Optimization

Note

The attributes of the QAOA class should be initialized using the set methods of QAOA. For example, to set the circuit’s depth to 10 you should run set_circuit_properties(p=10)

device

Device to be used by the optimizer

Type:

DeviceBase

circuit_properties

The circuit properties of the QAOA workflow. Use to set depth p, choice of parameterization, parameter initialisation strategies, mixer hamiltonians. For a complete list of its parameters and usage please see the method set_circuit_properties

Type:

CircuitProperties

backend_properties

The backend properties of the QAOA workflow. Use to set the backend properties such as the number of shots and the cvar values. For a complete list of its parameters and usage please see the method set_backend_properties

Type:

BackendProperties

classical_optimizer

The classical optimiser properties of the QAOA workflow. Use to set the classical optimiser needed for the classical optimisation part of the QAOA routine. For a complete list of its parameters and usage please see the method set_classical_optimizer

Type:

ClassicalOptimizer

local_simulators

A list containing the available local simulators

Type:

list[str]

cloud_provider

A list containing the available cloud providers

Type:

list[str]

mixer_hamil

The desired mixer hamiltonian

Type:

Hamiltonian

cost_hamil

The desired mixer hamiltonian

Type:

Hamiltonian

qaoa_descriptor

the abstract and backend-agnostic representation of the underlying QAOA parameters

Type:

QAOADescriptor

variate_params

The variational parameters. These are the parameters to be optimised by the classical optimiser

Type:

QAOAVariationalBaseParams

backend

The openQAOA representation of the backend to be used to execute the quantum circuit

Type:

VQABaseBackend

optimizer

The classical optimiser

Type:

OptimizeVQA

result

Contains the logs of the optimisation process

Type:

Result

compiled

A boolean flag to check whether the QAOA object has been correctly compiled at least once

Type:

Bool

Examples

Examples should be written in doctest format, and should illustrate how to use the function.

>>> q = QAOA()
>>> q.compile(QUBO)
>>> q.optimize()

Where QUBO is a an instance of openqaoa.problems.problem.QUBO

If you want to use non-default parameters:

>>> q_custom = QAOA()
>>> q_custom.set_circuit_properties(
        p=10,
        param_type='extended',
        init_type='ramp',
        mixer_hamiltonian='x'
    )
>>> q_custom.set_device_properties(
        device_location = 'qcs', device_name='Aspen-11',
        cloud_credentials = {
            'name' : "Aspen11", 'as_qvm':True,
            'execution_timeout' : 10, 'compiler_timeout':10
        }
    )
>>> q_custom.set_backend_properties(n_shots=200, cvar_alpha=1)
>>> q_custom.set_classical_optimizer(method='nelder-mead', maxiter=2)
>>> q_custom.compile(qubo_problem)
>>> q_custom.optimize()
asdict(exclude_keys=[], options={})

Returns a dictionary of the Optimizer object, where all objects are converted to dictionaries.

Parameters:
  • exclude_keys (List[str]) – A list of keys to exclude from the returned dictionary.

  • options (dict) –

    A dictionary of options to pass to the method that creates the dictionary to dump.
    complex_to_stringbool

    If True, converts complex numbers to strings. If False, complex numbers are not converted to strings.

    intermediate_measurementsbool

    If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

Return type:

dict

compile(problem=None, verbose=False, routing_function=None)[source]

Initialise the trainable parameters for QAOA according to the specified strategies and by passing the problem statement

Note

Compilation is necessary because it is the moment where the problem statement and the QAOA instructions are used to build the actual QAOA circuit.

Tip

Set Verbose to false if you are running batch computations!

Parameters:
  • problem (Problem) – QUBO problem to be solved by QAOA

  • verbose (bool) – Set True to have a summary of QAOA to displayed after compilation

dump(file_name='', file_path='', prepend_id=False, indent=2, compresslevel=0, exclude_keys=[], overwrite=False, options={})

Saves the Optimizer object as json file (if compresslevel is 0). If compresslevel is not 0, saves the Optimizer object as a .gz file (which should be decompressed before use).

Parameters:
  • file_name (str) – The name of the json file.

  • file_path (str) – The path where the json file will be saved.

  • prepend_id (bool) – If True, the name will have the following format: ‘{project_id}–{experiment_id}–{atomic_id}–{file_name}.json’. If False, the name will have the following format: ‘{file_name}.json’. Default is False.

  • indent (int) – The number of spaces to indent the result in the json file. If None, the result is not indented.

  • compresslevel (int) – The compression level to use. If 0, no compression is used and a json file is saved. If 1, the fastest compression method is used. If 9, the slowest but most effective compression method is used. And a .gz file is saved.

  • exclude_keys (List[str]) – A list of keys that should not be included in the json file.

  • overwrite (bool) – If True, overwrites the file if it already exists. If False, raises an error if the file already exists.

  • options (dict) – A dictionary of options to pass to the method that creates the dictionary to dump.

  • intermediate_measurements (bool) – If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

dumps(indent=2, exclude_keys=[], options={})

Returns a json string of the Optimizer object.

Parameters:
  • indent (int) – The number of spaces to indent the result in the json file. If None, the result is not indented.

  • exclude_keys (List[str]) – A list of keys to exclude from the json string.

  • options (dict) – A dictionary of options to pass to the method that creates the dictionary to dump.

  • intermediate_measurements (bool) – If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

Return type:

str

evaluate_circuit(params)[source]

A method to evaluate the QAOA circuit at a given set of parameters

Parameters:

params (list or dict or QAOAVariationalBaseParams or None) – List of parameters or dictionary of parameters. Which will be used to evaluate the QAOA circuit. If None, the variational parameters of the QAOA object will be used.

Returns:

result – A dictionary containing the results of the evaluation: - “cost”: the expectation value of the cost Hamiltonian - “uncertainty”: the uncertainty of the expectation value of the cost Hamiltonian - “measurement_results”: either the state of the QAOA circuit output (if the QAOA circuit is evaluated on a state simulator) or the counts of the QAOA circuit output (if the QAOA circuit is evaluated on a QPU or shot-based simulator)

Return type:

dict

classmethod from_dict(dictionary)

Creates an Optimizer object from a dictionary (which is the output of the asdict method) :type dictionary: dict :param dictionary: A dictionary with the information of the Optimizer object. :type dictionary: dict

Return type:

QAOA or RQAOA

classmethod load(file_name, file_path='')

Creates an Optimizer object from a file (which is the output of the dump method) :type file_name: str :param file_name: The name of the file. :type file_name: str :type file_path: str :param file_path: The path of the file. :type file_path: str

Return type:

QAOA or RQAOA

classmethod loads(string)

Creates an Optimizer object from a string (which is the output of the dumps method) :type string: str :param string: A string with the information of the Optimizer object. :type string: str

Return type:

QAOA or RQAOA

optimize(verbose=False)[source]

A method running the classical optimisation loop

results_class

alias of QAOAResult

set_backend_properties(*args, **kwargs)
set_circuit_properties(*args, **kwargs)
set_classical_optimizer(*args, **kwargs)
set_device(*args, **kwargs)
set_error_mitigation_properties(*args, **kwargs)
set_exp_tags(tags)

Method to add tags to the experiment. Tags are stored in a dictionary (self.exp_tags) and can be used to identify the experiment. Name is a special tag that is used to identify the experiment in the results object, it will also be stored in the dictionary, and will overwrite any previous name.

Parameters:
  • name (str) – Name of the experiment. If None, the name will not be changed. If not None, the name will be changed to the new one.

  • tags (dict) – Dictionary containing the tags to be added to the experiment. If the tag already exists, it will be overwritten.

set_header(project_id=None, description=None, run_by=None, provider=None, target=None, cloud=None, client=None, experiment_id=None)

Method to set the identification stamps of the optimizer object in self.header.

Parameters:

TODO (document the parameters) –

solve_brute_force(bounded=True, verbose=False)[source]

A method to solve the QAOA problem using brute force i.e. by evaluating the cost function at all possible bitstrings

Parameters:
  • bounded (bool, optional) – If set to True, the function will not perform computations for qubit numbers above 25. If False, the user can specify any number. Defaults to True.

  • verbose (bool, optional) – If set to True, the function will print the results of the computation. Defaults to False.

flavors of RQAOA, both of which can be found in the rqaoa module:

  • The Custom (default) strategy allows the user to define the number of eliminations to be performed at each step. This defined by the parameter steps. If the parameter is set as an integer, the algorithm will use this number as the number of qubits to be eliminated at each step. Alternatively, it is possible to pass a list, which specifies the number of qubits to be eliminated at each step. For steps = 1, the algorithm reduces to the original form of RQAOA presented in [1].

  • The Adaptive strategy adaptively selects how many qubits to eliminate at each step. The maximum number of allowed eliminations is given by the parameter n_max. At each step, the algorithm selects the top n_max+1 expectation values (ranked in magnitude), computes the mean among and uses the ones lying above this value for qubit elimination. This corresopnds to a maximum of n_max possible elimnations per step. For n_max= 1, the algorithm reduces to the original form of RQAOA presented in [1].

The development of this method is associated with an internal research project at Entropica Labs and will be soon released publicly [2].

To choose the strategy, set the parameter rqaoa_type using the set_rqaoa_parameters method. To use the Adaptive strategy, pass rqaoa_type = 'adaptive'. The default strategy is Custom.

class openqaoa.algorithms.rqaoa.rqaoa_workflow.RQAOA(device=<openqaoa.backends.devices_core.DeviceLocal object>)[source]

A class implementing a RQAOA workflow end to end.

It’s basic usage consists of 1. Initialization 2. Compilation 3. Optimization

Note

The attributes of the RQAOA class should be initialized using the set methods of QAOA. For example, to set the qaoa circuit’s depth to 10 you should run set_circuit_properties(p=10)

device

Device to be used by the optimizer

Type:

DeviceBase

backend_properties

The backend properties of the RQAOA workflow. These properties will be used to run QAOA at each RQAOA step. Use to set the backend properties such as the number of shots and the cvar values. For a complete list of its parameters and usage please see the method set_backend_properties

Type:

BackendProperties

classical_optimizer

The classical optimiser properties of the RQAOA workflow. Use to set the classical optimiser needed for the classical optimisation part of the QAOA routine. For a complete list of its parameters and usage please see the method set_classical_optimizer

Type:

ClassicalOptimizer

local_simulators

A list containing the available local simulators

Type:

list[str]

cloud_provider

A list containing the available cloud providers

Type:

list[str]

compiled

A boolean flag to check whether the optimizer object has been correctly compiled at least once

Type:

Bool

circuit_properties

The circuit properties of the RQAOA workflow. These properties will be used to run QAOA at each RQAOA step. Use to set depth p, choice of parametrisation, parameter initialisation strategies, mixer hamiltonians. For a complete list of its parameters and usage please see the method set_circuit_properties

Type:

CircuitProperties

rqaoa_parameters

Set of parameters containing all the relevant information for the recursive procedure of RQAOA.

Type:

RqaoaParameters

results

The results of the RQAOA optimization. Dictionary containing all the information about the RQAOA run: the solution states and energies (key: ‘solution’), the output of the classical solver (key: ‘classical_output’), the elimination rules for each step (key: ‘elimination_rules’), the number of eliminations at each step (key: ‘schedule’), total number of steps (key: ‘number_steps’), the intermediate QUBO problems and the intermediate QAOA objects that have been optimized in each RQAOA step (key: ‘intermediate_problems’). This object (RQAOAResult) is a dictionary with some custom methods as RQAOAResult.get_hamiltonian_step(i) which get the hamiltonian of reduced problem of the i-th step. To see the full list of methods please see the RQAOAResult class.

Type:

RQAOAResult

Examples

Examples should be written in doctest format, and should illustrate how to use the function.

>>> r = RQAOA()
>>> r.compile(QUBO)
>>> r.optimize()

Where QUBO is a an instance of openqaoa.problems.problem.QUBO

If you want to use non-default parameters:

Standard/custom (default) type:

>>> r = RQAOA()
>>> r.set_circuit_properties(
        p=10,
        param_type='extended',
        init_type='ramp',
        mixer_hamiltonian='x'
    )
>>> r.set_device_properties(
        device_location='qcs',
        device_name='Aspen-11',
        cloud_credentials={
            'name' : "Aspen11",
            'as_qvm':True,
            'execution_timeout' : 10,
            'compiler_timeout':10
        }
    )
>>> r.set_backend_properties(n_shots=200, cvar_alpha=1)
>>> r.set_classical_optimizer(method='nelder-mead', maxiter=2)
>>> r.set_rqaoa_parameters(n_cutoff = 5, steps=[1,2,3,4,5])
>>> r.compile(qubo_problem)
>>> r.optimize()

Ada-RQAOA:

>>> r_adaptive = RQAOA()
>>> r.set_circuit_properties(
        p=10,
        param_type='extended',
        init_type='ramp',
        mixer_hamiltonian='x'
    )
>>> r.set_device_properties(
        device_location='qcs',
        device_name='Aspen-11',
        cloud_credentials={
            'name' : "Aspen11",
            'as_qvm':True,
            'execution_timeout' : 10,
            'compiler_timeout':10
        }
    )
>>> r_adaptive.set_backend_properties(n_shots=200, cvar_alpha=1)
>>> r_adaptive.set_classical_optimizer(method='nelder-mead', maxiter=2)
>>> r_adaptive.set_rqaoa_parameters(rqaoa_type = 'adaptive', n_cutoff = 5, n_max=5)
>>> r_adaptive.compile(qubo_problem)
>>> r_adaptive.optimize()
asdict(exclude_keys=[], options={})

Returns a dictionary of the Optimizer object, where all objects are converted to dictionaries.

Parameters:
  • exclude_keys (List[str]) – A list of keys to exclude from the returned dictionary.

  • options (dict) –

    A dictionary of options to pass to the method that creates the dictionary to dump.
    complex_to_stringbool

    If True, converts complex numbers to strings. If False, complex numbers are not converted to strings.

    intermediate_measurementsbool

    If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

Return type:

dict

compile(problem=None, verbose=False)[source]

Create a QAOA object and initialize it with the circuit properties, device, classical optimizer and backend properties specified by the user. This QAOA object will be used to run QAOA changing the problem to sove at each RQAOA step. Here, the QAOA is compiled passing the problem statement, so to check that the compliation of QAOA is correct. See the QAOA class.

Note

Compilation is necessary because it is the moment where the problem statement and the QAOA instructions are used to build the actual QAOA circuit.

Parameters:
  • problem (Problem) – QUBO problem to be solved by RQAOA

  • verbose (bool) – !NotYetImplemented! Set true to have a summary of QAOA first step to displayed after compilation

dump(file_name='', file_path='', prepend_id=False, indent=2, compresslevel=0, exclude_keys=[], overwrite=False, options={})

Saves the Optimizer object as json file (if compresslevel is 0). If compresslevel is not 0, saves the Optimizer object as a .gz file (which should be decompressed before use).

Parameters:
  • file_name (str) – The name of the json file.

  • file_path (str) – The path where the json file will be saved.

  • prepend_id (bool) – If True, the name will have the following format: ‘{project_id}–{experiment_id}–{atomic_id}–{file_name}.json’. If False, the name will have the following format: ‘{file_name}.json’. Default is False.

  • indent (int) – The number of spaces to indent the result in the json file. If None, the result is not indented.

  • compresslevel (int) – The compression level to use. If 0, no compression is used and a json file is saved. If 1, the fastest compression method is used. If 9, the slowest but most effective compression method is used. And a .gz file is saved.

  • exclude_keys (List[str]) – A list of keys that should not be included in the json file.

  • overwrite (bool) – If True, overwrites the file if it already exists. If False, raises an error if the file already exists.

  • options (dict) – A dictionary of options to pass to the method that creates the dictionary to dump.

  • intermediate_measurements (bool) – If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

dumps(indent=2, exclude_keys=[], options={})

Returns a json string of the Optimizer object.

Parameters:
  • indent (int) – The number of spaces to indent the result in the json file. If None, the result is not indented.

  • exclude_keys (List[str]) – A list of keys to exclude from the json string.

  • options (dict) – A dictionary of options to pass to the method that creates the dictionary to dump.

  • intermediate_measurements (bool) – If True, includes the intermediate measurements in the results. If False, only the final measurements are included.

Return type:

str

classmethod from_dict(dictionary)

Creates an Optimizer object from a dictionary (which is the output of the asdict method) :type dictionary: dict :param dictionary: A dictionary with the information of the Optimizer object. :type dictionary: dict

Return type:

QAOA or RQAOA

classmethod load(file_name, file_path='')

Creates an Optimizer object from a file (which is the output of the dump method) :type file_name: str :param file_name: The name of the file. :type file_name: str :type file_path: str :param file_path: The path of the file. :type file_path: str

Return type:

QAOA or RQAOA

classmethod loads(string)

Creates an Optimizer object from a string (which is the output of the dumps method) :type string: str :param string: A string with the information of the Optimizer object. :type string: str

Return type:

QAOA or RQAOA

optimize(dump=False, dump_options={}, verbose=False)[source]

Performs optimization using RQAOA with the custom method or the adaptive method. The elimination RQAOA loop will occur until the number of qubits is equal to the number of qubits specified in n_cutoff. In each loop, the QAOA will be run, then the eliminations will be computed, a new problem will be redefined and the QAOA will be recompiled with the new problem. Once the loop is complete, the final problem will be solved classically and the final solution will be reconstructed. Results will be stored in the results attribute.

Parameters:
  • dump (bool) – If true, the object will be dumped to a file. And at the end of each step, the qaoa object will be dumped to a file. Default is False.

  • dump_options (dict) – Dictionary containing the options for the dump. To see the options, see the dump method of the QAOA or RQAOA class. Default is empty.

  • verbose (bool) – TODO

results_class

alias of RQAOAResult

set_backend_properties(*args, **kwargs)
set_circuit_properties(*args, **kwargs)
set_classical_optimizer(*args, **kwargs)
set_device(*args, **kwargs)
set_error_mitigation_properties(*args, **kwargs)
set_exp_tags(tags)

Method to add tags to the experiment. Tags are stored in a dictionary (self.exp_tags) and can be used to identify the experiment. Name is a special tag that is used to identify the experiment in the results object, it will also be stored in the dictionary, and will overwrite any previous name.

Parameters:
  • name (str) – Name of the experiment. If None, the name will not be changed. If not None, the name will be changed to the new one.

  • tags (dict) – Dictionary containing the tags to be added to the experiment. If the tag already exists, it will be overwritten.

set_header(project_id=None, description=None, run_by=None, provider=None, target=None, cloud=None, client=None, experiment_id=None)

Method to set the identification stamps of the optimizer object in self.header.

Parameters:

TODO (document the parameters) –

set_rqaoa_parameters(*args, **kwargs)

RQAOA Workflow Properties

class openqaoa.algorithms.rqaoa.rqaoa_workflow_properties.RqaoaParameters(rqaoa_type='custom', n_max=1, steps=1, n_cutoff=5, original_hamiltonian=None, counter=0)[source]

Parameter class to initialise parameters to run a desired RQAOA program.

rqaoa_type

String specifying the RQAOA scheme under which eliminations are computed. The two methods are ‘custom’ and ‘adaptive’. Defaults to ‘adaptive’.

Type:

int

n_max

Maximum number of eliminations allowed at each step when using the adaptive method.

Type:

int

steps

Elimination schedule for the RQAOA algorithm. If an integer is passed, it sets the number of spins eliminated at each step. If a list is passed, the algorithm will follow the list to select how many spins to eliminate at each step. Note that the list needs enough elements to specify eliminations from the initial number of qubits up to the cutoff value. If the list contains more, the algorithm will follow instructions until the cutoff value is reached.

Type:

Union[list,int]

n_cutoff

Cutoff value at which the RQAOA algorithm obtains the solution classically.

Type:

int

original_hamiltonian

Hamiltonian encoding the original problem fed into the RQAOA algorithm.

Type:

Hamiltonian

counter

Variable to count the step in the schedule. If counter = 3 the next step is schedule[3]. Default is 0, but can be changed to start in the position of the schedule that one wants.

Type:

int

asdict()

References

[1] S. Bravyi, A. Kliesch, R. Koenig, and E. Tang, Physical Review Letters 125, 260505 (2020). [2] E.I. Rodriguez Chiacchio, V. Sharma, E. Munro (Work in progress)