Utilities

A set of helper functions

Utility and convenience functions for a number of QAOA applications.

openqaoa.utilities.XY_mixer_hamiltonian(n_qubits, qubit_connectivity='full', coeffs=None)[source]

Construct a Hamiltonian object to implement the XY mixer.

Important

The XY mixer is not implemented with \(RXY\) Gates, but with \(H_{XY}=\frac{1}{2}(\sum_{i,j} X_iX_j+Y_iY_j)\)

Parameters:
  • n_qubits (int) – The number of qubits in the system.

  • qubit_connectivity (Union[List[list],List[tuple], str]) – The connectivity of the qubits in the mixer Hamiltonian.

  • coeffs (List[float]) – The coefficients of the XY terms in the Hamiltonian.

Returns:

The Hamiltonian object corresponding to the XY mixer.

Return type:

Hamiltonian

openqaoa.utilities.X_mixer_hamiltonian(n_qubits, coeffs=None)[source]

Construct a Hamiltonian object to implement the X mixer.

Parameters:
  • n_qubits (int) – The number of qubits in the mixer Hamiltonian.

  • coeffs (List[float]) – The coefficients of the X terms in the Hamiltonian.

Returns:

The Hamiltonian object corresponding to the X mixer.

Return type:

Hamiltonian

openqaoa.utilities.bitstring_energy(hamiltonian, bitstring)[source]

Computes the energy of a given bitstring with respect to a classical cost Hamiltonian.

Parameters:
  • hamiltonian (Hamiltonian) – Hamiltonian object determining the energy levels.

  • bitstring (list or str) – A list of integers 0 and 1, or a string, representing a configuration.

Returns:

energy – The energy of the given bitstring with respect to the cost Hamiltonian.

Return type:

float

openqaoa.utilities.calculate_calibration_factors(*args, **kwargs)[source]
openqaoa.utilities.check_kwargs(list_expected_params, list_default_values, **kwargs)[source]

Checks that the given list of expected parameters can be found in the kwargs given as input. If so, it returns the parameters from kwargs, else it raises an exception.

Parameters:
  • list_expected_params – List[str] List of string containing the name of the expected parameters in kwargs

  • list_default_values – List List containing the deafult values of the expected parameters in kwargs

  • **kwargs – Keyword arguments where keys are supposed to be the expected params

Returns:

A tuple with the actual expected parameters if they are found in kwargs.

Raises:

ValueError – If one of the expected arguments is not found in kwargs and its default value is not specified.

openqaoa.utilities.convert2serialize(obj, complex_to_string=False)[source]

Recursively converts object to dictionary.

Parameters:
  • obj (object) – Object to convert to dictionary.

  • complex_to_string (bool) – If True, convert complex numbers to string, so the result can be serialized to JSON.

Returns:

dict – Dictionary representation of the object.

Return type:

dict

openqaoa.utilities.delete_keys_from_dict(obj, keys_to_delete)[source]

Recursively delete all the keys keys_to_delete from a object (or list of dictionaries) :type obj: Union[list, dict] :param obj: dictionary or list of dictionaries from which we want to delete keys :type obj: dict or list[dict] :type keys_to_delete: List[str] :param keys_to_delete: list of keys to delete from the dictionaries :type keys_to_delete: list

Returns:

obj – dictionary or list of dictionaries from which we have deleted keys

Return type:

dict or list[dict]

openqaoa.utilities.dicke_basis(excitations, n_qubits)[source]

Generates the Dicke basis state $|ek>$ with $k$ excitations

Parameters:
  • excitations (int) – Number of excitations in the basis vector

  • n_qubits (int) – Total number of qubits in the system

Returns:

Total basis states present in the expected Dicke vector in the computational basis

Return type:

np.ndarray

openqaoa.utilities.dicke_wavefunction(excitations, n_qubits)[source]

Generate the k-excitations dicke statevector

Parameters:
  • excitations (int) – The number of excitations in the basis

  • n_qubits (int) – The number of qubits in the register

Returns:

The wavefunction vector for a given cumulative Dicke states with $<=k$ excitations

Return type:

np.ndarray

openqaoa.utilities.energy_expectation(hamiltonian, measurement_counts)[source]

Computes the energy expectation value from a set of measurement counts, with respect to a classical cost Hamiltonian.

Parameters:
  • hamiltonian (Hamiltonian) – Hamiltonian object determining the energy levels.

  • measurement_counts (dict) – Measurement counts dictionary for which to calculate energy expectation.

Returns:

energy – The energy expectation value for the set of measurement outcomes

Return type:

float

openqaoa.utilities.energy_expectation_analytical(angles, hamiltonian)[source]

Computes the expectation value of the Hamiltonian for an analytical expression.

Important

Only valid for single layer QAOA Ansatz with X mixer Hamiltonian and classical Hamiltonians with up to quadratic terms.

Parameters:
  • angles (list or tuple) – QAOA angles at which the Hamiltonian expectation value is computed

  • hamiltonian (Hamiltonian) – Classical Hamiltonian from which the expectation value is computed.

openqaoa.utilities.energy_spectrum_hamiltonian(hamiltonian)[source]

Computes exactly the energy spectrum of the hamiltonian defined by terms and weights and its corresponding configuration of variables. Uses standard numpy module.

Parameters:

hamiltonian (Hamiltonian) – Hamiltonian object whose spectrum is computed.

Returns:

energies – The energy spectra of the given hamiltonian

Return type:

np.ndarray

openqaoa.utilities.exp_val_hamiltonian_termwise(hamiltonian, mixer_type, p, qaoa_optimized_angles=None, qaoa_optimized_counts=None, analytical=True)[source]

Computes the single spin expectation values <Z_{i}> and the correlation matrix Mij = <Z_{i}Z_{j}>, using the optimization results obtained from QAOA tranining the specified QAOA cost backend.

Parameters:
  • hamiltonian (Hamiltonian) – Hamiltonian object containing the problem statement.

  • p (int) – Number of layers in QAOA ansatz.

  • qaoa_optimized_angles (list) – Optimized angles of the underlying QAOA.

  • qaoa_optimized_counts (dict) – Dictionary containing the measurement counts of optimized QAOA circuit.

  • analytical (bool) – Boolean that indicates whether to use analytical or numerical expectation calculation methods.

Returns:

  • exp_vals_z (np.array) – Single spin expectation values as a numpy array.

  • corr_matrix (np.array) – Correlation matrix as a numpy Matrix object.

openqaoa.utilities.exp_val_pair(spins, prob_dict)[source]

Computes the correlation \(Mij = <Z_{i}Z_{j}>\) between qubits i,j using the QAOA optimized wavefunction.

Important

In the presence of linear terms the \(<Z_{i}><Z_{j}>\) contribution needs to be subtracted later. This is done in the exp_val_hamiltonian_termwise() function used as a wrapper for this function.

Parameters:
  • spins (tuple) – Tuple containing the spins whose correlation is computed.

  • prob_dict (dict) – The dictionary containing the configuration probabilities of each spin.

Returns:

corr – Correlation between the two spins in the term.

Return type:

float

openqaoa.utilities.exp_val_pair_analytical(spins, hamiltonian, qaoa_angles)[source]

Computes \(<Z_{i}Z_{j}>\) correlation between apair of spins analytically. It is an extension from the expression derived by Bravyi et al. in https://arxiv.org/abs/1910.08980 which includes the effect of biases.

Important

  • Only valid for single layer QAOA Ansatz with X mixer Hamiltonian.

  • In the presence of linear terms the <Z_{i}><Z_{j}> contribution needs to be subtracted later. This is done in the exp_val_hamiltonian_termwise() function used as a wrapper for this function.

  • OpenQAOA uses a different sign convention for the QAOA Ansatz than Bravy et al. - there is a relative minus sign between the cost function and the mixer in OpenQAOA, which is accounted for in this implementation. Additionally, the result below is valid for a Hadamard state initialization and in the absence of bias terms in the Hamiltonian.

Parameters:
  • spins (tuple) – Pair of spins whose correlation we compute.

  • hamiltonian (Hamiltonian) – Hamiltonian object containing the problem statement.

  • qaoa_angles (tuple) – Pair of (gamma,beta) angles defined from QAOA ansatz and obtained in the QAOA process.

Returns:

corr – Correlation <ZZ> between the specified spin pair.

Return type:

float

openqaoa.utilities.exp_val_single(spin, prob_dict)[source]

Computes expectation value <Z> of a given spin.

Parameters:
  • spin (int) – Spin whose expectation value we compute.

  • prob_dict (dict) – Dictionary containing the configuration probabilities of each spin.

Returns:

exp_val – Expectation value of the spin

Return type:

float

openqaoa.utilities.exp_val_single_analytical(spin, hamiltonian, qaoa_angles)[source]

Computes the single spin expectation value \(<Z>\) from an analytically derived expression for a single layer QAOA Ansatz.

Important

Only valid for single layer QAOA Ansatz with X mixer Hamiltonian.

Parameters:
  • spin (int) – The spin whose expectation value we compute.

  • hamiltonian (Hamiltonian) – Hamiltonian object containing the problem statement.

  • qaoa_angles (tuple) – Pair of (gamma,beta) angles defined from QAOA ansatz and obtained in the QAOA process.

  • Returns

  • -------

  • exp_val (float) – Spin expectation value <Z>.

openqaoa.utilities.flip_counts(counts_dictionary)[source]

Returns a counts/probability dictionary that have their keys flipped. This formats the bit-strings from a right-most bit representing being the first qubit to the left-most bit representing the first qubit.

Parameters:

counts_dictionary (dict) – Count dictionary whose keys are flipped.

Returns:

output_counts_dictionary – Count dictionary with flipped keys.

Return type:

dict

openqaoa.utilities.generate_timestamp()[source]

Generate a timestamp string in UTC+0. Format: YYYY-MM-DDTHH:MM:SS.

Returns:

timestamp – String representation of a timestamp.

Return type:

str

openqaoa.utilities.generate_uuid()[source]

Generate a UUID string.

Returns:

uuid – String representation of a UUID.

Return type:

str

openqaoa.utilities.get_mixer_hamiltonian(n_qubits, mixer_type='x', qubit_connectivity=None, coeffs=None)[source]
Parameters:
  • n_qubits (int) – Number of qubits in the Hamiltonian.

  • mixer_type (str) – Name of the mixer Hamiltonian. Choose from x or xy.

  • qubit_connectivity (Union[List[list],List[tuple], str], optional) – The connectivity of the qubits in the mixer Hamiltonian.

  • coeffs (List[float], optional) – The coefficients of the terms in the Hamiltonian.

  • Returns

  • --------

  • Hamiltonian – Hamiltonian object containing the specificied mixer.

Return type:

Hamiltonian

openqaoa.utilities.graph_from_hamiltonian(hamiltonian)[source]

Creates a networkx graph corresponding to a specified problem Hamiltonian.

Important

This function cannot handle non-QUBO terms. Linear terms are stored as nodes with weights.

Parameters:

hamiltonian (Hamiltonian) – The Hamiltonian of interest. Must be specified a Hamiltonian object.

Returns:

G – The corresponding networkx graph with the edge weights being the two-qubit coupling coefficients, and the node weights being the single-qubit bias terms.

Return type:

networkx.Graph

openqaoa.utilities.ground_state_hamiltonian(hamiltonian, bounded=True)[source]

Computes the exact ground state and ground state energy of a classical Hamiltonian. Uses standard numpy module.

Parameters:
  • hamiltonian (Hamiltonian) – Hamiltonian object whose ground state properties are computed.

  • 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.

Return type:

Tuple[float, list]

Returns:

  • min_energy (float) – The minimum eigenvalue of the cost Hamiltonian.

  • config (np.array) – The minimum energy eigenvector as a binary array configuration: qubit-0 as the first element in the sequence.

openqaoa.utilities.hamiltonian_from_graph(G)[source]

Builds a cost Hamiltonian as a collection of PauliOp objects from a specified networkx graph, extracting any node and edge weights.

Parameters:

G (networkx.Graph) – The specified networkx graph.

Returns:

hamiltonian – The Hamiltonian object constructed from the specified graph.

Return type:

Hamiltonian

openqaoa.utilities.is_valid_uuid(uuid_to_test)[source]

Check if a string is a valid UUID.

Parameters:

uuid_to_test (str) – String to check if it is a valid UUID.

Returns:

is_valid – Boolean indicating if the string is a valid UUID.

Return type:

bool

openqaoa.utilities.k_cumulative_excitations(k, n_qubits)[source]

Generates the Upper bound excitations basis vector $|Ek>$, which a superposition of all Dicke basis vectors upto excitation number $k$

Parameters:
  • k (int) – Upper bound on number of excitations in the basis vector

  • n_qubits (int) – Total number of qubits in the system

Returns:

wavefunction – The wavefunction vector for a given cumulative Dicke states with $<=k$ excitations

Return type:

np.ndarray

openqaoa.utilities.knapsack_balanced_basis(weight_capacity, weights_list, decision_register, slack_register)[source]

Generates the basis where the system register is balanced for Knapsack Hamiltonian, i.e. Slack register compensating the decision register state to cancel the penalty term in Hamiltonian. NOTE: Cannot cancel the penalty term if decision register weight exceeds the weight capacity of the sack

Parameters:
  • weight_capacity (int) – The knapsack capacity, i.e. the upper limit on the weights that can be added in the knapsack

  • weights_list (List) – List of item weights in the problem

  • decision_register (List) – The qubit regsiter of the decision bits

  • slack_register (List) – The qubit regsiter of the slack bits

Return type:

np.ndarray

openqaoa.utilities.low_energy_states(hamiltonian, threshold_per)[source]

Return threshold energy and the low energy states of the specified hamiltonian which are below this threshold.

Parameters:
  • hamiltonian (Hamiltonian) – Compute the low energy states of this Hamiltonian

  • threshold_per (float) – Threshold percentage away from the ground state, defining the energy we window we search in for low energy states.

Return type:

Tuple[float, list]

Returns:

  • low_energy_threshold (float) – The energy threshold below which we retrieve states.

  • states (list) – The list of low energy states that lie below the low energy threshold.

  • .. Important:: – The threshold is calculated as threshols_per factors away from the ground state of the Hamiltonian.

openqaoa.utilities.low_energy_states_overlap(hamiltonian, threshold_per, prob_dict)[source]

Calculates the overlap between the low energy states of a Hamiltonian, below a specific threshold away from the ground state energy, and an input state, expressed in terms of a probability dictionary.

Parameters:
  • hamiltonian (Hamiltonian) – Compute overlap with respect to energies of this Hamiltonian

  • threshold_per (float) – Threshold percentage away from the ground state, defining the energy we window we search in for low energy states.

  • prob_dict (dict) – The measurement outcome dictionary generated from the circuit execution.

Return type:

float

Returns:

  • total_overlap (float) – The total overlap with the low-energy states.

  • .. Important:: – The threshold is calculated as threshold_per factors away from the ground state of the Hamiltonain. For threshold_per=0 the function returns the ground state overlap of the QAOA output.

openqaoa.utilities.negate_counts_dictionary(counts_dictionary, s)[source]

Negates every bitstring of the counts dictionary according to the position of the X gates before the measurement. Used in SPAM Twirling. :type counts_dictionary: dict :param counts_dictionary: The measurement outcomes obtained from the Simulator/QPU :type counts_dictionary: dict :type s: int :param s: Syndrome whose binary representation denotes the negated qubits. For example, 4 = 100, signifies that the first qubit had an X gate just before the measurement, which requires the first digit of the every key to be classically negated inside this function. :type s: int

Returns:

The negated counts dictionary

Return type:

dict

openqaoa.utilities.permute_counts_dictionary(counts_dictionary, permutation_order)[source]

Permutes the order of the qubits in the counts dictionary to the original order if SWAP gates were used leading to modified qubit layout. :type counts_dictionary: dict :param counts_dictionary: The measurement outcomes obtained from the Simulator/QPU :type counts_dictionary: dict :type permutation_order: List[int] :param permutation_order: The qubit order to permute the dictionary with :type permutation_order: List[int]

Returns:

The permuted counts dictionary with qubits in the original place

Return type:

dict

openqaoa.utilities.plot_energy_spectrum(hamiltonian, high_k_states=None, low_k_states=None, ax=None, cmap='winter')[source]

Compute and plot the energy spectrum of a given hamiltonian on a matplotlib figure.

Parameters:
  • hamiltonian (Hamiltonian) – Hamiltonian object whose spectrum is computed.

  • high_k_states (int, optional) – Optionally plot the highest k energy levels. Defaults to None.

  • low_k_states (int, optional) – Optionally, plot the lowest k energy levels. Defaults to None.

  • ax (Matplotlib axes object, optional) – Axes to plot on. Defaults to None.

  • cmap (str, optional) – Specify the matplotlib colormap to use for plotting. Defaults to ‘winter’.

Return type:

None

openqaoa.utilities.plot_graph(G, ax=None, colormap='seismic')[source]

Plots a networkx graph.

Parameters:
  • G (Networkx Graph) – The networkx graph of interest.

  • ax (Matplotlib axes object, optional) – Matplotlib axes to plot on. Defaults to None.

  • colormap (str, optional) – Colormap to use for plotting. Defaults to ‘seismic’.

Return type:

None

openqaoa.utilities.qaoa_probabilities(*args, **kwargs)[source]
openqaoa.utilities.quick_create_mixer_for_topology(input_gatemap, n_qubits, qubit_connectivity='full', coeffs=None)[source]

Quickly generates a gatemap list and coeffs for a specific topology. Can only be used with 2-Qubit Gates.

Parameters:
  • input_gatemap (TwoQubitRotationGateMap) – The GateMap whose connectivity we are trying to create.

  • n_qubits (int) – The number of qubits in the system.

  • qubit_connectivity (Union[List[list],List[tuple], str]) – The connectivity of the qubits in the mixer.

  • coeffs (List[float], optional) – The coefficients of the GateMap in the Mixer Blocks.

Returns:

Returns tuple containing the list of gatemaps and their associated coefficients. If no coefficients were on initialisation provided, a default of 1.0 is used for all gatemap objects.

Return type:

Tuple[List[TwoQubitRotationGateMap], List[float]]

openqaoa.utilities.random_classical_hamiltonian(reg, seed=None, weighted=True, biases=True, constant=0)[source]

Creates a random classical cost hamiltonian.

Parameters:
  • reg (list) – Register to build the hamiltonian on.

  • seed (int, optional) – A seed for the random number generator. Defaults to None.

  • weighted (bool, optional) – Whether the edge weights should be uniform or different. If false, all weights are set to 1. If true, the weight is set to a random number drawn from the uniform distribution in the interval 0 to 1. Defaults to True.

  • biases (bool, optional) – Whether or not the graph nodes should be assigned a weight. If true, the weight is set to a random number drawn from the uniform distribution in the interval 0 to 1. Defaults to True.

  • constant (int, optional) – The constant term in the Hamiltonian. Defaults to 0.

Return type:

Hamiltonian

Returns:

  • random_hamil (Hamiltonian) – A random hamiltonian with randomly selected terms and coefficients and with the specified constant term.

  • .. Important:: – Randomly selects which qubits that will have a bias term, then assigns them a bias coefficient. Randomly selects which qubit pairs will have a coupling term, then assigns them a coupling coefficient. In both cases, the random coefficient is drawn from the uniform distribution on the interval [0,1).

openqaoa.utilities.random_k_regular_graph(degree, nodes, seed=None, weighted=False, biases=False)[source]

Produces a random graph with specified number of nodes, each having degree k.

Parameters:
  • degree (int) – Desired degree for the nodes.

  • nodes (list) – The node set of the graph.

  • seed (int, optional) – A seed for the random number generator.

  • weighted (bool, optional) – Whether the edge weights should be uniform or different. If false, all weights are set to 1. If true, the weight is set to a random number drawn from the uniform distribution in the interval 0 to 1.

  • biases (bool, optional) – Whether or not the graph nodes should be assigned a weight. If true, the weight is set to a random number drawn from the uniform distribution in the interval 0 to 1.

Returns:

nx.Graph – A graph with the properties as specified.

Return type:

Networkx Graph

openqaoa.utilities.ring_of_disagrees(reg)[source]

Builds the cost Hamiltonian for the “Ring of Disagrees”.

Parameters:

reg (list) – register of qubits in the system.

Return type:

Hamiltonian

Returns:

  • ring_hamil (Hamiltonian) – Hamiltonian object containing Ring of Disagrees model.

  • .. Important:: – This model is introduced in https://arxiv.org/abs/1411.4028

openqaoa.utilities.round_value(function)[source]

Round a value to a given precision. This function will be used as a decorator to round the values given by the expectation and expectation_w_uncertainty methods.

Parameters:

function (Callable) – The function to be decorated

Returns:

The rounded value(s)