modules package
modules.graph_functions module
- modules.graph_functions.cost_graph_multi(filename: str, parameter_list: list = None, x_list: list = None, av_list: list = None, lowest_list: list = None, sliced_list: list = None, best: float = None, main_title: str = '', sub_title: str = '', x_label: str = 'Epoch', figsize: tuple = (8, 8))[source]
Plots a graph of the cost function for multiple lists
- Parameters:
filename (str)
parameter_list (list)
x_list (list)
av_list (list)
lowest_list (list)
sliced_list (list)
best (float)
main_title (str)
sub_title (str)
x_label (str)
figsize (tuple)
- modules.graph_functions.find_best_coords(x_list: ndarray, best: float) tuple[source]
Helper function for graph plotting to find coordinates for best known value line
- Parameters:
x_list (ndarray)
best (float)
- Return type:
tuple
- modules.graph_functions.find_graph_statistics(av_list: ndarray, best: float) tuple[source]
Helper function for graph plotting to find good values for ymin and ymax
- Parameters:
av_list (ndarray)
best (float)
- Return type:
tuple
- modules.graph_functions.find_i_j(count: int, rows: int) tuple[source]
Find indices for subplots
- Parameters:
count (int)
rows (int)
- Return type:
tuple
- modules.graph_functions.find_size(cost_list: list) tuple[source]
Find the number of subplots
- Parameters:
cost_list (list)
- Return type:
tuple
- modules.graph_functions.parameter_graph(filename: str, title: str, index_list: list, gradient_list: list, legend: list)[source]
Plots a graph of the parameter evolution by iteration.
- Parameters:
filename (str)
title (str)
index_list (list)
gradient_list (list)
legend (list)
- modules.graph_functions.plot_3d_graph_models(grouped_means: DataFrame, input: str, input2: str = 'layers')[source]
Plot a 3D bar graph of the given input data grouped by layers and locations
- Parameters:
grouped_means (pd.DataFrame) – DataFrame containing the grouped means data.
input (str) – The column name for the z-axis values.
input2 (str, optional) – The column name for the y-axis values (default is ‘layers’).
- modules.graph_functions.plot_3d_graph_slice(grouped_means: DataFrame, input: str, show_sem: bool = False)[source]
Plot a 3D bar graph of the given input data grouped by locations and slice.
- Parameters:
grouped_means (pd.DataFrame) – DataFrame containing the grouped means data.
input (str) – The column name for the z-axis values.
show_sem (bool, optional) – Whether to show standard error of the mean (SEM) as error bars (default is False
- modules.graph_functions.plot_heatmap(input: DataFrame, title: str, x_label: str, y_label: str) None[source]
Plot a heat map of the given input data.
- Parameters:
input (DataFrame)
title (str)
x_label (str)
y_label (str)
- Return type:
None
modules.helper_ML_functions module
- modules.helper_ML_functions.evaluate_model(model: torch.nn.Module, shots: int) dict[source]
Store the bits strings from the model in a dictionary
- Parameters:
model (torch.nn.Module)
shots (int)
- Return type:
dict
- modules.helper_ML_functions.find_device() torch.device[source]
Find out if we are using a GPU or CPU
- Return type:
torch.device
- modules.helper_ML_functions.get_ready_to_train(sdl, model: torch.nn.Module) tuple[source]
Prepare for training by setting up the target, criterion, and optimizer
- Parameters:
model (torch.nn.Module)
- Return type:
tuple
- modules.helper_ML_functions.set_up_input_hot_start(sdl, device: torch.device, bin_hot_start_list: list, print_results: bool = False) torch.Tensor[source]
If ML and Hot Start set the initial input to the hot start data
- Parameters:
device (torch.device)
bin_hot_start_list (list)
print_results (bool)
- Return type:
torch.Tensor
- modules.helper_ML_functions.set_up_input_no_hot_start(sdl, device: torch.device) torch.Tensor[source]
If ML and no Hot Start set the initial input to zero OR 0.5, depending on the mode
- Parameters:
device (torch.device)
- Return type:
torch.Tensor
- modules.helper_ML_functions.train_model(num_epochs: int, model: torch.nn.Module, my_input: torch.Tensor, target: torch.Tensor, criterion: torch.nn.Module, optimizer: torch.optim.Optimizer, print_results: bool = False, print_frequency: int = 10) tuple[source]
Train the model for a number of epochs
- Parameters:
num_epochs (int)
model (torch.nn.Module)
my_input (torch.Tensor)
target (torch.Tensor)
criterion (torch.nn.Module)
optimizer (torch.optim.Optimizer)
print_results (bool)
print_frequency (int)
- Return type:
tuple
modules.helper_functions_tsp module
- modules.helper_functions_tsp.augment_loc_list(loc_list: list, locs: int) list[source]
Completes the cycle by adding the missing location to the end of the cycle.
- Parameters:
loc_list (list) – A list of locations with a length one less than the number of locations in the problem
locs (int) – The total number of locations in the problem
- Returns:
valid – The original location list with the missing node list added to the end of the cycle
- Return type:
loc_list
- modules.helper_functions_tsp.binary_string_format(binary_string: str, bin_len: str) str[source]
Format a binary string to remove the 0b prefix
- Parameters:
binary_string (str) – A binary string
bin_len (str) – Length of the binary string
- Returns:
formatted_string – The binary string with the 0b prefix removed
- Return type:
str
- modules.helper_functions_tsp.bind_weights(params: list, rots: list, qc: QuantumCircuit) QuantumCircuit[source]
Bind parameters to rotations and return a bound quantum circuit
- Parameters:
params (list) – A list of parameters (the texts)
rots (list) – The exact values for the parameters, which are rotations of quantum gates
qc (Quantum Circuit) – A quantum circuit without bound weights
- Returns:
bc – A quantum circuit with including bound weights, ready to run an evaluation
- Return type:
Quantum Circuit
- modules.helper_functions_tsp.calculate_hot_start_data(sdl, distance_array: ndarray, cost_fn: Callable, print_results: bool = False) tuple[list, float][source]
Calculate hot start data from a distance array
- Parameters:
sdl (SubDataLogger object) – Containing key parameters
distance_array (array) – Numpy symmetric array with distances between locations
cost_fn (function) – A function that returns a distance from a binary string
print_results (bool) – If true prints out the hot start data
- Returns:
hot_start_list (list) – A list of integers showing an estimate of the lowest cycle
hot_start_distance (float) – The distance of the hot start cycle
- Return type:
tuple[list, float]
- modules.helper_functions_tsp.check_loc_list(loc_list: list, locs: int) bool[source]
Checks that the location list is a valid cycle with no repetition of nodes.
- Parameters:
loc_list (list) – A list of locations with a length one less than the number of locations in the problem
locs (int) – The total number of locations in the problem
- Returns:
valid – Whether the loc_list is a valid cycle
- Return type:
Boolean
- modules.helper_functions_tsp.convert_binary_list_to_integer(binary_list: list, gray: bool = False) int[source]
Converts list of binary numbers to an integer
- Parameters:
binary_list (list) – List of binary numbers
gray (bool) – Determines whether gray code is used.
- Returns:
result – The integer represented by the concatenated binary string
- Return type:
int
- modules.helper_functions_tsp.convert_bit_string_to_cycle(bit_string: list, locs: int, gray: bool = False, method: str = 'original') list[source]
Converts a bit string to a cycle.
- Parameters:
bit_string (list) – A list of zeros and ones produced by the quantum computer
locs (int) – The number of locations
gray (bool) – If True Gray codes are used
method (str) – ‘original’ => method from Goldsmith D, Day-Evans J. ‘new’ => method from Schnaus M, Palackal L, Poggel B, Runge X, Ehm H, Lorenz JM, et al.
- Returns:
end_cycle_list – A list of integers showing a cycle. The bit string is processed from left to right
- Return type:
list
- modules.helper_functions_tsp.convert_integer_to_binary_list(integer: int, length: int, gray: bool = False) list[source]
Converts an integer to a list of binary numbers
- Parameters:
integer (int) – The integer to be converted
length (int) – The length of the binary string
gray (bool) – If True Gray codes are used
- Returns:
result – A list of binary numbers
- Return type:
list
- modules.helper_functions_tsp.cost_fn_fact(sdl, distance_array: ndarray) Callable[[list], int][source]
Returns a cost function inside a decorator,
- Parameters:
sdl (SubDataLogger object containing key parameters:) –
- sdl.locations: int
The number of locations in the problem
- sdl.gray: bool
If True Gray codes are used
- sdl.formulation: str
’original’ => method from Goldsmith D, Day-Evans J. ‘new’ => method from Schnaus M, Palackal L, Poggel B, Runge X, Ehm H, Lorenz JM, et al.
distance_array (array) – Numpy symmetric array with distances between locations
- Returns:
cost_fn – A function of a bit string evaluating a distance for that bit string
- Return type:
cost function
- modules.helper_functions_tsp.cost_fn_tensor(input: torch.tensor, cost_fn: Callable) torch.Tensor[source]
Find the distance for each bit string input using cost_fn
- Parameters:
input (torch.tensor) – Torch array with n bit strings for analysis
cost_fn (function) – maps a bit_list to a distance
- Returns:
distance_tensor – a Torch array with one distance entry for each input
- Return type:
torch.tensor
- modules.helper_functions_tsp.cost_func_evaluate(sdl, cost_fn: Callable, model, average_slice: float = 1) tuple[float, float, list[int]][source]
Evaluate cost function on a quantum computer
- Parameters:
sdl (SubDataLogger object containing key parameters:) –
- sdl.noise: bool
If True a noisy quantum computer is used
- sdl.quantum: bool
If True a quantum computer is used. If False a classical model is used
- sdl.shots: int
The number of shots for which the quantum circuit is to be run
cost_fn (function) – A function of a bit string evaluating a distance for that bit string
model (a model to evalulate an output bit string given weights eg) –
- QuantumCircuit
A quantum circuit with bound weights for which the energy is to be found
- Classical Model
A classical model with bound weights for which the energy is to be found
average_slice (float) – average over this slice of the energy. For example: If average_slice = 1 then average over all energies. If average_slice = 0.2 then average over the bottom 20% of energies
- Returns:
cost (float) – The average cost evaluated
lowest (float) – The lowest cost found
lowest_energy_bit_string (string) – A list of the bits for the lowest energy bit string
- Return type:
tuple[float, float, list[int]]
- modules.helper_functions_tsp.create_initial_rotations(sdl, bin_hot_start_list: list = False) ndarray[source]
Initialise parameters with random weights
- Parameters:
sdl (Subdata logger with fields:) –
- sdl.qubitsint
The number of qubits in the circuit
- sdl.modeint
Controls setting the circuit up in different modes
- sdl.hot_startbool
If true hot start values are used
bin_hot_start_list (list) – Binary list containing the hot start values
- Returns:
init_rots – initial rotations
- Return type:
array
- modules.helper_functions_tsp.define_parameters(sdl) list[source]
Set up parameters and initialise text
- Parameters:
sdl (MySubDataLogger) – A sub data logger holding the parameters for the run with key fields: sdl.qubits: int - The number of qubits in the circuit sdl.mode: int - Controls setting the circuit up in different modes
- Returns:
params – A list of parameters (the texts)
- Return type:
list
- modules.helper_functions_tsp.detect_quantum_GPU_support() bool[source]
Detect if a GPU is available for quantum simulations
- Return type:
bool
- modules.helper_functions_tsp.find_bin_length(i: int) int[source]
find the length of a binary string to represent integer i
- Parameters:
i (int)
- Return type:
int
- modules.helper_functions_tsp.find_distance(loc1: int, loc2: int, distance_array: ndarray, verbose: bool = False) float[source]
Finds the distance between locations using the distance matrix
- Parameters:
loc1 (int) – First location
loc2 (int) – Second location
distance_array (np.ndarray) – An array containing the distances between locations
verbose (bool) – If True then more information is printed
- Returns:
distance – The distance between two locations
- Return type:
Float
- modules.helper_functions_tsp.find_distances_array(locations: int, print_comments: bool = False) tuple[ndarray, float][source]
Finds the array of distances between locations and the best distance
- Parameters:
locations (int)
print_comments (bool)
- Return type:
tuple[ndarray, float]
- modules.helper_functions_tsp.find_problem_size(sdl) int[source]
Finds the number of binary variables needed
- Parameters:
sdl (sub data logger containing fields) –
- sdl.locationsint
Number of locations
- sdl.formulation:
’original’ => method from Goldsmith D, Day-Evans J. ‘new’ => method from Schnaus M, Palackal L, Poggel B, Runge X, Ehm H, Lorenz JM, et al.
- Returns:
pb_dim – Length of the bit string needed to store the problem
- Return type:
int
- modules.helper_functions_tsp.find_run_stats(lowest_list: list) tuple[float, int][source]
Finds the lowest energy and the iteration at which it was found
- Parameters:
lowest_list (list) – A list of floats showing the lowest energy found at that iteration
- Returns:
lowest_energy (float) – The lowest energy found
iteration (int) – The iteration at which the lowest energy was found
- Return type:
tuple[float, int]
- modules.helper_functions_tsp.find_stats(cost_fn: Callable, counts: dict, shots: int, average_slice: float = 1) tuple[float, float, list[int]][source]
Finds the average energy of the relevant counts, and the lowest energy
- Parameters:
cost_fn (function) – A function of a bit string evaluating an energy(distance) for that bit string
counts (dict) – Dictionary holding the binary string and the counts observed
shots (integer) – number of shots
average_slice (float) – average over this slice of the energy. eg If average_slice = 1 then average over all energies. If average_slice = 0.2 then average over the bottom 20% of energies
- Returns:
average (float) – The average energy
lowest_dist (float) – The lowest energy
lowest_energy_bit_string (list) – A list of the bits for the lowest energy bit string
- Return type:
tuple[float, float, list[int]]
- modules.helper_functions_tsp.find_total_distance(int_list: list, locs: int, distance_array: ndarray) float[source]
Finds the total distance for a valid formatted bit string representing a cycle.
- Parameters:
int_list (list of integers) – A list representing a valid cycle
locs (int) – The number of locations
distance_array (array) – Numpy symmetric array with distances between locations
- Returns:
total_distance – The total distance for the cycle represented by that integer list
- Return type:
float
- modules.helper_functions_tsp.format_boolean(string_input: str) bool[source]
Convert a string to a boolean value
- Parameters:
string_input (str)
- Return type:
bool
- modules.helper_functions_tsp.hot_start(sdl, distance_array: ndarray) list[source]
Finds a route from a distance array where the distance to the next point is the shortest available
- Parameters:
sdl (SubDataLogger object containing key parameters:) –
- sdl.locations: int
The number of locations in the problem
distance_array (array) – Numpy symmetric array with distances between locations
- Returns:
end_cycle_list – A list of integers showing the an estimate of the lowest cycle
- Return type:
list
- modules.helper_functions_tsp.hot_start_list_to_string(sdl, hot_start_list: list) list[source]
Invert the hot start integer list into a string
Parameters:
- sdlSubDataLogger object containing key parameters:
- sdl.locations: int
The number of location in the problem
- sdl.gray: bool
If True Gray codes are used
- sdl.formulation: str
‘original’ => method from Goldsmith D, Day-Evans J. ‘new’ => method from Schnaus M, Palackal L, Poggel B, Runge X, Ehm H, Lorenz JM, et al.
- hot_start_list: list
A list of integers showing an estimate of the lowest cycle
- returns:
result_list – A list of bits that represents the bit string for the lowest cycle
- rtype:
list
- Parameters:
hot_start_list (list)
- Return type:
list
- modules.helper_functions_tsp.load_dict_from_json(filename: str) dict[source]
Loads a dictionary from a JSON file
- Parameters:
filename (str)
- Return type:
dict
- modules.helper_functions_tsp.my_gradient(sdl, cost_fn, qc: QuantumCircuit, params: list, rots: ndarray, average_slice: float, ck: float = 0.01) ndarray[source]
Calculate gradient for a quantum circuit with parameters and rotations
- Parameters:
sdl (SubDataLogger object containing key parameters, for example:) –
- sdl.noise: bool
If True a noisy quantum computer is used
- sdl.shots: int
The number of shots for which the quantum circuit is to be run
- sdl.s: float
Parameter shift parameter
- sdl.gradient_type: str
controls the optimiser to be used. if ‘parameter shift’ uses analytical expression if ‘SPSA’ uses a stochastical method
- sdl.ck: float
SPSA parameter, small number controlling perturbations
cost_fn (function) – A function of a bit string evaluating an energy (distance) for that bit string
qc (QuantumCircuit) – A quantum circuit for which the gradient is to be found, without the weights being bound
params (list) – A list of parameters (the texts)
rots (list) – The exact values for the parameters, which are rotations of quantum gates
average_slice (float) – Controls the amount of data to be included in the average. For example, 0.2 means that the lowest 20% of distances found is included in the average.
ck (float)
- Returns:
gradient – The gradient for each parameter
- Return type:
array
- modules.helper_functions_tsp.read_file_name(locations: int, data_sources: dict, file_type: str = 'file') str[source]
Find the filename for a certain number of locations
- Parameters:
locations (int) – Number of locations, or vertices
data_sources (dict) – Dictionary listing the filename for each problem size
source (str) – Source of data - only sim has
file_type (str)
- Returns:
filename – The filename for that problem size
- Return type:
string
- modules.helper_functions_tsp.read_index(filename: str, encoding: str) dict[source]
Reads CSV file and returns a dictionary
- Parameters:
filename (str) – The filename of the CSV file.
encoding (str) – The expected coding. If this is missed get odd charactors at start of the file
- Returns:
dict – A dictionary with the contents on the CSV file
- Return type:
dict
- modules.helper_functions_tsp.update_parameters_using_gradient(sdl, params: list, rots: ndarray, cost_fn: Callable, qc: QuantumCircuit, print_results: str = False)[source]
Updates parameters using SPSA or parameter shift gradients
- Parameters:
params (list)
rots (ndarray)
cost_fn (Callable)
qc (QuantumCircuit)
print_results (str)
- modules.helper_functions_tsp.validate_distance_array(array: ndarray, locs: int)[source]
Validates the distance array and raises an Exception if the array is not valid. Checks the array is the correct shape, and is symmetric
- Parameters:
array (array) – Numpy symmetric array with distances
locs (int) – Number of locations or vertices
- modules.helper_functions_tsp.validate_gradient_type(gradient_type)[source]
Check that the gradient type is valid
- modules.helper_functions_tsp.vqc_circuit(sdl, params: list) QuantumCircuit[source]
Set up a variational quantum circuit
- Parameters:
sdl (MySubDataLogger) – A sub data logger holding the parameters for the run with key fields: sdl.qubits: int - The number of qubits in the circuit sdl.mode: int - Controls setting the circuit up in different modes sdl.noise: bool- Controls if noise is included in the circuit
params (list) – A list of parameters (the texts)
- Returns:
qc – A quantum circuit without bound weights
- Return type:
Quantum Circuit
modules.test_ML_functions module
- modules.test_ML_functions.test_estimate_gradient()[source]
Checks gradient estimation against pre-worked example
modules.test_quantum_function module
- modules.test_quantum_function.my_cost_function1(bit_string_list: list) int[source]
A simple cost function for testing
- Parameters:
bit_string_list (list)
- Return type:
int
- modules.test_quantum_function.test_calculate_parameter_numbers_2_1()[source]
Test parameter numbers with input 2,1
modules.test_tsp_helper module
- modules.test_tsp_helper.test_augment_loc_list1()[source]
Check adding location to the end of a simple list
- modules.test_tsp_helper.test_augment_loc_list2()[source]
Check adding location to the end of a jumbled list
- modules.test_tsp_helper.test_binary_string_conversion()[source]
Test conversion of binary string to integer and back without gray code
- modules.test_tsp_helper.test_binary_string_conversion_gray()[source]
Test conversion of binary string to integer and back with gray code
- modules.test_tsp_helper.test_bit_string_cycle_conversion_orig()[source]
Test conversion of integers to binary lists without Gray code
- modules.test_tsp_helper.test_bit_string_cycle_conversion_orig2()[source]
Test conversion of integers to binary lists with Gray code
- modules.test_tsp_helper.test_bit_string_list_to_bit_string()[source]
Test LRC cache conversion of list to bit string
- modules.test_tsp_helper.test_check_loc_list_invalid1()[source]
Test validation of location list with an invalid solution
- modules.test_tsp_helper.test_check_loc_list_invalid2()[source]
Test validation of location list with an integer out of range
- modules.test_tsp_helper.test_check_loc_list_invalid3()[source]
Test validation of location list with an integer out of range at end
- modules.test_tsp_helper.test_check_loc_list_invalid4()[source]
Test validation of location list with an integer just out of range at end
- modules.test_tsp_helper.test_check_loc_list_valid1()[source]
Test validation of location list with a valid solution
- modules.test_tsp_helper.test_check_loc_list_valid2()[source]
Test validation of location list with a valid solution
- modules.test_tsp_helper.test_convert_bit_string_to_cycle_00010__not_gray()[source]
Example for 4 locations
- modules.test_tsp_helper.test_convert_bit_string_to_cycle_111_gray()[source]
Example for 4 locations
- modules.test_tsp_helper.test_convert_bit_string_to_cycle_15()[source]
Example for 15 locations without Gray code
- modules.test_tsp_helper.test_convert_bit_string_to_cycle_15_gray()[source]
Example for 15 locations with Gray code
- modules.test_tsp_helper.test_find_average_slice2()[source]
Test average slice functionality - ensure no change
- modules.test_tsp_helper.test_find_average_slice2b()[source]
Test average slice functionality - ensure no change
- modules.test_tsp_helper.test_find_average_slice3()[source]
Test average slice functionality - ensure no change
- modules.test_tsp_helper.test_find_average_slice4()[source]
Test average slice functionality - ensure no change
- modules.test_tsp_helper.test_find_average_slice5()[source]
Test average slice functionality - ensure no change
- modules.test_tsp_helper.test_find_average_slice7()[source]
Test average slice functionality - ensure no change
- modules.test_tsp_helper.test_find_total_distance()[source]
Check total distance calculation for a simple circuit
- modules.test_tsp_helper.test_four_cols()[source]
Checks that the correct error message is thrown for an array with 5 rows and 4 columns
- modules.test_tsp_helper.test_four_rows()[source]
Checks that the correct error message is thrown for an array with 4 rows and 5 columns
- modules.test_tsp_helper.test_hot_start_list_to_string_101()[source]
Hot start list with four locations in descending order
- modules.test_tsp_helper.test_hot_start_list_to_string_101_gray()[source]
Hot start list with four locations in descending order with Gray code
- modules.test_tsp_helper.test_hot_start_list_to_string_15_locs_gray()[source]
Hot start list with fifteen locations in descending order with Gray code
- modules.test_tsp_helper.test_hot_start_list_to_string_15_locs_no_gray()[source]
Hot start list with fifteen locations in descending order without Gray code
- modules.test_tsp_helper.test_list_1000_gray()[source]
Check conversion of list [1,0,0,0] with gray codes
- modules.test_tsp_helper.test_list_1110_gray()[source]
Check conversion of list [1,1,1,0] with gray codes
- modules.test_tsp_helper.test_six_locs()[source]
Checks that the correct error message is thrown for an 5 * 5 array when there are 6 locations
Module contents
modules.helper_results module
- modules.helper_results.filter_results_general(df)[source]
Filter the results table based on standard parameters
- modules.helper_results.filter_results_ml(df)[source]
Filter the results tables for the ML model based on standard parameters
- modules.helper_results.filter_results_qml(df)[source]
Filter the results table for the VQA model based on standard parameters
- modules.helper_results.find_quality(df, factor=1, round=None)[source]
Find the quantum and error metrics