Results and loggers are two classes that store the results of a QAOA.

In more details, the logger is updated every-time the classical optimizer performs the otimistaion. The result, on the other hand, formats raw results from the logger in a more human-friendly way.

QAOA Result

class openqaoa.algorithms.qaoa.qaoa_result.QAOAResult(log, method, cost_hamiltonian, type_backend)[source]

Bases: object

A class to handle the results of QAOA workflows

Parameters:
  • log (Logger) – The raw logger generated from the training vqa part of the QAOA.

  • method (str) – Stores the name of the optimisation used by the classical optimiser

  • cost_hamiltonian (Hamiltonian) – The cost Hamiltonian for the problem statement

  • type_backend (QAOABaseBackend) – The type of backend used for the experiment

asdict(keep_cost_hamiltonian=True, complex_to_string=False, intermediate_measurements=True, exclude_keys=[])[source]

Returns a dictionary with the results of the optimization, where the dictionary is serializable. If the backend is a statevector backend, the measurement outcomes will be the statevector, meaning that it is a list of complex numbers, which is not serializable. If that is the case, and complex_to_string is true the complex numbers are converted to strings.

Parameters:
  • keep_cost_hamiltonian (bool) – If True, the cost hamiltonian is kept in the dictionary. If False, it is removed.

  • complex_to_string (bool) – If True, the complex numbers are converted to strings. If False, they are kept as complex numbers. This is useful for the JSON serialization.

  • intermediate_measurements (bool, optional) – If True, intermediate measurements are included in the dump. If False, intermediate measurements are not included in the dump. Default is True.

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

Returns:

return_dict – A dictionary with the results of the optimization, where the dictionary is serializable.

Return type:

dict

calculate_statistics(include_intermediate=False)[source]

A function to calculate statistics of measurement outcomes associated with a QAOA workflow

Parameters:

include_intermediate (bool) – Whether it is necessary to calculate statistics for intermediate results. Defaults to False.

Return type:

dict

classmethod from_dict(dictionary, cost_hamiltonian=None)[source]

Creates a Results object from a dictionary (which is the output of the asdict method) :type dictionary: dict :param dictionary: The dictionary to create the QAOA Result object from :type dictionary: dict

Returns:

The Result object created from the dictionary

Return type:

Result

static get_counts(measurement_outcomes)[source]

Converts probabilities to counts when the measurement outcomes are a numpy array, that is a state vector

Parameters:

measurement_outcomes (Union[np.array, dict]) – The measurement outcome as returned by the Logger. It can either be a statevector or a count dictionary

Returns:

The count dictionary obtained either throught the statevector or the actual measurement counts.

Return type:

dict

lowest_cost_bitstrings(n_bitstrings=1)[source]

Find the minimium energy from cost_hamilonian given a set of measurement outcoms

Parameters:

n_bitstrings (int) – Number of the lowest energies bistrings to get

Returns:

best_results – Returns a list of bitstring with the lowest values of the cost Hamiltonian.

Return type:

dict

plot_cost(figsize=(10, 8), label='Cost', linestyle='--', color='b', ax=None)[source]

A simpler helper function to plot the cost associated to a QAOA workflow

Parameters:
  • figsize (tuple) – The size of the figure to be plotted. Defaults to (10,8).

  • label (str) – The label of the cost line, defaults to ‘Cost’.

  • linestyle (str) – The linestyle of the poloit. Defaults to ‘–‘.

  • color (str) – The color of the line. Defaults to ‘b’.

  • ax ('matplotlib.axes._subplots.AxesSubplot') – Axis on which to plot the graph. Defaults to None

Returns:

  • fig (‘matplotlib.figure.Figure’) – The figure object

  • ax (‘matplotlib.axes._subplots.AxesSubplot’) – The axis object

plot_n_shots(figsize=(10, 8), param_to_plot=None, label=None, linestyle='--', color=None, ax=None, xlabel='Iterations', ylabel='Number of shots', title='Evolution of number of shots for gradient estimation')[source]

Helper function to plot the evolution of the number of shots used for each evaluation of the cost function when computing the gradient. It only works for shot adaptive optimizers: cans and icans. If cans was used, the number of shots will be the same for each parameter at each iteration. If icans was used, the number of shots could be different for each parameter at each iteration.

Parameters:
  • figsize (tuple) – The size of the figure to be plotted. Defaults to (10,8).

  • param_to_plot (list[int] or int) – The parameteres to plot. If None, all parameters will be plotted. Defaults to None. If a int is given, only the parameter with that index will be plotted. If a list of ints is given, the parameters with those indexes will be plotted.

  • label (list[str] or str) – The label for each parameter. Defaults to Parameter {i}. If only one parameter is plot the label can be a string, otherwise it must be a list of strings.

  • linestyle (list[str] or str) – The linestyle for each parameter. Defaults to ‘–’ for all parameters. If it is a string all parameters will use it, if it a list of strings the linestyle of each parameter will depend on one string of the list.

  • color (list[str] or str) – The color for each parameter. Defaults to None for all parameters (matplotlib will choose the colors). If only one parameter is plot the color can be a string, otherwise it must be a list of strings.

  • ax ('matplotlib.axes._subplots.AxesSubplot') – Axis on which to plot the graph. If none is given, a new figure will be created.

plot_probabilities(n_states_to_keep=None, figsize=(10, 8), label='Probability distribution', color='tab:blue', ax=None)[source]

Helper function to plot the probabilities corresponding to each basis states (with prob != 0) obtained from the optimized result

Parameters:
  • n_states_to_keep ('int) – If the user passes a value, the plot will compile with the given value of states. Else, an upper bound will be calculated depending on the total size of the measurement outcomes.

  • figsize (tuple) – The size of the figure to be plotted. Defaults to (10,8).

  • label (str) – The label of the cost line, defaults to ‘Probability distribution’.

  • color (str) – The color of the line. Defaults to ‘tab:blue’.

  • ax ('matplotlib.axes._subplots.AxesSubplot') – Axis on which to plot the graph. Defaults to None

Returns:

  • fig (‘matplotlib.figure.Figure’) – The figure object

  • ax (‘matplotlib.axes._subplots.AxesSubplot’) – The axis object

RQAOA Result

class openqaoa.algorithms.rqaoa.rqaoa_result.RQAOAResult[source]

Bases: dict

A class to handle the results of RQAOA workflows It stores the results of the RQAOA optimization as a dictionary. With some custom methods.

asdict(keep_cost_hamiltonian=True, complex_to_string=False, intermediate_measurements=True, exclude_keys=[])[source]

Returns the results as a full dictionary, meaning that the objects of the intermediate steps are also converted to dictionaries.

Parameters:
  • keep_cost_hamiltonian (bool, optional) – If True, the cost Hamiltonian is kept in the dictionary, by default True.

  • complex_to_string (bool, optional) – If True, the complex numbers are converted to strings, by default False. This is useful for JSON serialization.

  • intermediate_measurements (bool, optional) – If True, intermediate measurements are included in the dump. If False, intermediate measurements are not included in the dump. Default is True.

  • exclude_keys (list[str], optional) – A list of keys to exclude from the returned dictionary.

Returns:

The results as a dictionary.

Return type:

dict

clear() None.  Remove all items from D.
copy() a shallow copy of D
classmethod from_dict(dictionary)[source]

Creates a RQAOAResult object from a dictionary (which is the output of the asdict method). :type dictionary: dict :param dictionary: The input dictionary. :type dictionary: dict

Returns:

The RQAOAResult object.

Return type:

RQAOAResult

fromkeys(value=None, /)

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)

Return the value for key if key is in the dictionary, else default.

get_corr_matrix(step)[source]

Returns the correlation matrix of the i-th step of the RQAOA.

get_exp_vals_z(step)[source]

Returns the expectation values of the Z operator of the i-th step of the RQAOA.

get_hamiltonian(step)[source]

Returns the Hamiltonian of the i-th step of the RQAOA.

get_problem(step)[source]

Returns the QUBO problem in the i-th step of the RQAOA.

get_qaoa_optimized_angles(step)[source]

Returns the optimized angles of the i-th qaoa step of the RQAOA.

get_qaoa_results(step)[source]

Returns the i-th qaoa step of the RQAOA.

get_solution()[source]

Returns the solution of the optimization.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
plot_corr_matrix(step, cmap='cool', ax=None)[source]

Plots the correlation matrix of the i-th step of the RQAOA. TODO : add more options

pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(key, default=None, /)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() an object providing a view on D's values

Logger

class openqaoa.optimizers.logger_vqa.Logger(initialisation_variables, logger_update_structure)[source]

Bases: object

log_variables(input_dict)[source]

Updates all the histories of the logger variables. Best values of the logger variables are only updated according to the rules specified by its update structure. If the attribute is not in the update structure it isnt updated.

input_dict:

Should contain a dictionary with the key as the name of the attribute to be updated and its respective value. Note that the attribute should have been created beforehand.

property root_nodes
property update_edges