VQE and QAOA utilities¶
Utility and convenience functions for a number of QAOA applications.

utilities.
bitstring_histogram
(results)¶ Plots a histogram of the output bitstrings obtained by sampling from the QVM or QPU
 Parameters
bitstrings – An array of the measured values of each qubit from all trials: array shape is (nshots x nqubits)

utilities.
cluster_accuracy
(state, true_labels)¶ Prints informative statements comparing QAOA’s returned bit string for MaxCut to the true (known) cluster labels.
 Parameters
state – A littleendian list of binary integers representing the lowest energy state of the wavefunction
true_labels – A littleendian list of binary integers representing the true solution to the MAXCUT clustering problem.

utilities.
distances_dataset
(data, metric='euclidean')¶ Computes the distance between data points in a specified dataset, according to the specified metric (default is Euclidean).
 Parameters
data (
Union
[<builtin function array>,DataFrame
,Dict
[~KT, ~VT]]) – The user’s dataset, either as an array, dictionary, or a Pandas DataFramemetric – Type of metric to calculate the distances used in
scipy.spatial.distance
 Returns
If input is a dictionary or numpy array, output is a numpy array of dimension NxN, where N is the number of data points. If input is a Pandas DataFrame, the distances are returned in this format.
 Return type
Union[np.array, pd.Dataframe]

utilities.
gaussian_2Dclusters
(n_clusters, n_points, means, cov_matrices)¶ Creates a set of clustered data points, where the distribution within each cluster is Gaussian.
 Parameters
n_clusters (
int
) – The number of clustersn_points (
int
) – A list of the number of points in each clustermeans (
List
[float
]) – A list of the means [x,y] coordinates of each cluster in the plane i.e. their centre)cov_matrices (
List
[float
]) – A list of the covariance matrices of the clusters
 Returns
data – A dict whose keys are the cluster labels, and values are a matrix of the with the x and y coordinates as its rows.
TODO – Output data as Pandas DataFrame?

utilities.
graph_from_hamiltonian
(hamiltonian)¶ Creates a networkx graph corresponding to a specified problem Hamiltonian.
 Parameters
hamiltonian (
PauliSum
) – The Hamiltonian of interest. Must be specified as a PauliSum object. Return type
Graph
 Returns
G – The corresponding networkx graph with the edge weights being the twoqubit coupling coefficients, and the node weights being the singlequbit bias terms.
TODO – Allow ndarrays to be input as hamiltonian too. Provide support for qubit placeholders.

utilities.
graph_from_hyperparams
(reg, singles, biases, pairs, couplings)¶ Builds a networkx graph from the specified QAOA hyperparameters
 Parameters
nqubits – The number of qubits (graph nodes)
singles (
List
[int
]) – The qubits that have a bias term (node weight)biases (
List
[float
]) – The values of the singlequbit biases (i.e. the node weight values)pairs (
List
[int
]) – The qubit pairs that are coupled (i.e. the nodes conected by an edge)couplings (
List
[float
]) – The strength of the coupling between the qubit pairs (i.e. the edge weights)
 Returns
Networkx graph with the specified properties
 Return type
nx.Graph

utilities.
hamiltonian_from_distances
(dist, biases=None)¶ Generates a Hamiltonian from a distance matrix and a numpy array of single qubit bias terms where the i’th indexed value of in biases is applied to the i’th qubit.
 Parameters
dist – A 2dimensional square matrix or Pandas DataFrame, where entries in row i, column j represent the distance between node i and node j. Assumed to be symmetric
biases – A dictionary of floats, with keys indicating the qubits with bias terms, and corresponding values being the bias coefficients.
 Returns
A PauliSum object modelling the Hamiltonian of the system
 Return type
PauliSum

utilities.
hamiltonian_from_graph
(G)¶ Builds a cost Hamiltonian as a PauliSum from a specified networkx graph, extracting any node biases and edge weights.
 Parameters
G (
Graph
) – The networkx graph of interest. Returns
The PauliSum representation of the networkx graph.
 Return type
PauliSum

utilities.
hamiltonian_from_hyperparams
(reg, singles, biases, pairs, couplings)¶ Builds a cost Hamiltonian as a PauliSum from a specified set of problem hyperparameters.
 Parameters
reg (
Iterable
[Union
[int
,QubitPlaceholder
]]) – The register to apply the beta rotations on.singles (
List
[int
]) – The register indices of the qubits that have a bias termbiases (
List
[float
]) – Values of the biases on the qubits specified in singles.pairs (
List
[Tuple
[int
,QubitPlaceholder
]]) – The qubit pairs that have a nonzero coupling coefficient.couplings (
List
[float
]) – The value of the couplings for each pair of qubits in pairs.
 Returns
The PauliSum built from these hyperams.
 Return type
Hamiltonian

utilities.
max_probability_bitstring
(probs)¶ Returns the lowest energy state of a QAOA run from the list of probabilities returned by pyQuil’s Wavefunction.probabilities()method.
 Parameters
probs – A numpy array of length 2^n, returned by Wavefunction.probabilities()
 Returns
A little endian list of binary integers indicating the lowest energy state of the wavefunction.
 Return type
int

utilities.
pauli_matrix
(pauli_sum, qubit_mapping={})¶ Create the matrix representation of pauli_sum.
 Parameters
qubit_mapping (
Dict
[~KT, ~VT]) – A dictionarylike object that maps from :py:class`QubitPlaceholder` toint
 Returns
A matrix representing the PauliSum
 Return type
np.matrix

utilities.
plot_cluster_data
(data)¶ Creates a scatterplot of the input data specified

utilities.
plot_graph
(G, ax=None)¶ Plots a networkx graph.
 Parameters
G – The networkx graph of interest.
ax (Matplotlib axes object) – Defaults to None. Matplotlib axes to plot on.

utilities.
plot_probabilities
(probabilities, energies, ax=None)¶ Makes a nice plot of the probabilities for each state and its energy
 Parameters
probabilities (
Union
[<builtin function array>,list
]) – The probabilites to find the state. Can be calculated via wavefunction.probabilities()energies (
Union
[<builtin function array>,list
]) – The energies of the statesax (matplotlib axes object) – The canvas to draw on

utilities.
prepare_classical_state
(reg, state)¶ Prepare a custom classical state for all qubits in the specified register reg.
 Parameters
reg (
List
[Union
[int
,QubitPlaceholder
]]) – Register to apply the state preparation circuit on. E.g. a list of qubitsstate (
List
[bool
]) – A list of 0s and 1s which represent the starting state of the register, bitwise.
 Returns
Quil Program with a circuit in an initial classical state.
 Return type
Program

utilities.
random_hamiltonian
(reg)¶ Creates a random cost hamiltonian, diagonal in the computational basis:
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).
 Parameters
reg (
List
[Union
[int
,QubitPlaceholder
]]) – register to build the hamiltonian on. Returns
A hamiltonian with random couplings and biases, as a PauliSum object.
 Return type
PauliSum

utilities.
random_k_regular_graph
(degree, nodes, seed=None, weighted=False, biases=False)¶ Produces a random graph with specified number of nodes, each having degree k.
 Parameters
degree (
int
) – Desired degree for the nodesnodes (
List
[Union
[int
,QubitPlaceholder
]]) – The node set of the graph. Can be anything that works as a qubit for PauliSums.seed (
Optional
[int
]) – A seed for the random number generatorweighted (
bool
) – 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. If true, the weight is set to a random number drawn from the uniform distribution in the interval 0 to 1.biases (
bool
) – 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
A graph with the properties as specified.
 Return type
nx.Graph

utilities.
ring_of_disagrees
(n)¶ Builds the cost Hamiltonian for the “Ring of Disagrees” described in the original QAOA paper (https://arxiv.org/abs/1411.4028), for the specified number of vertices n.
 Parameters
n (
int
) – Number of vertices in the ring Returns
The cost Hamiltonian representing the ring, as a PauliSum object.
 Return type
PauliSum

utilities.
sample_qaoa_bitstrings
(params, qvm, initial_state=None, nshots=1000)¶ Runs the QAOA circuit using the specified parameters
params
, and measures the output bitstrings fromnshots
runs. Parameters
params (
AbstractParams
) – the QAOA parameters of interestqvm (
Union
[QuantumComputer
,str
]) – the QVM or QPU to run onintial_state – a program to prepare the initial state (defaults to all
+>
)nshots (
int
) – the number of times to run the circuit and measure
 Returns
an array of shape (nshots x nqubits) with the measurement outcomes
 Return type
np.array