repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
TEC-reduced-model
TEC-reduced-model-main/setup.py
from setuptools import setup, find_packages install_requires = [ "pybamm == 0.4.0", "matplotlib", "prettytable", "jax", "jaxlib", "SciencePlots", ] setup( name="tec_reduced_model", version="0.2", author="Ferran Brosa Planella", author_email="[email protected]", packages=find_packages(), license="LICENSE", description='Code and data for the paper "Systematic derivation and validation of' " a reduced thermal-electrochemical model for lithium-ion batteries using" ' asymptotic methods" by Ferran Brosa Planella, Muhammad Sheikh and W. Dhammika' " Widanage (2020).", install_requires=install_requires, )
692
26.72
86
py
TEC-reduced-model
TEC-reduced-model-main/tec_reduced_model/set_parameters.py
# # Definitions for the tuned parameters to the experiment # import pybamm import numpy as np from tec_reduced_model.process_experimental_data import import_thermal_data, get_idxs def set_thermal_parameters(param, h, cp, T): cp_factor = cp / param.evaluate(pybamm.ThermalParameters().rho_eff_dim(T)) h_factor = h / param.evaluate(pybamm.ThermalParameters().h_total_dim) param["Total heat transfer coefficient [W.m-2.K-1]"] *= h_factor param["Positive current collector specific heat capacity [J.kg-1.K-1]"] *= cp_factor param["Negative current collector specific heat capacity [J.kg-1.K-1]"] *= cp_factor param["Negative electrode specific heat capacity [J.kg-1.K-1]"] *= cp_factor param["Separator specific heat capacity [J.kg-1.K-1]"] *= cp_factor param["Positive electrode specific heat capacity [J.kg-1.K-1]"] *= cp_factor return param def set_experiment_parameters(param, Crate, T): if T == 25: cp0 = 17150 if Crate == 0.5: Dn = 0.9e-14 elif Crate == 1: Dn = 2e-14 elif Crate == 2: Dn = 6e-14 elif T == 10: cp0 = 17750 if Crate == 0.5: Dn = 0.4e-14 elif Crate == 1: Dn = 1e-14 elif Crate == 2: Dn = 3e-14 elif T == 0: cp0 = 18150 if Crate == 0.5: Dn = 0.22e-14 elif Crate == 1: Dn = 0.55e-14 elif Crate == 2: Dn = 1.5e-14 param["Negative electrode diffusivity [m2.s-1]"] = Dn param["Initial concentration in positive electrode [mol.m-3]"] = cp0 return param def set_ambient_temperature(param, Crate, T): dataset = import_thermal_data(Crate, T) T_end = [] for _, data in dataset.items(): idx_end = get_idxs(data, Crate * 5, 5 / 3)[1] if len(idx_end) > 1: T_end.append(data["Temp Cell [degC]"][idx_end[1]]) real_temperature = np.mean(T_end) param["Ambient temperature [K]"] = 273.15 + real_temperature param["Initial temperature [K]"] = 273.15 + real_temperature return param
2,112
29.623188
88
py
TEC-reduced-model
TEC-reduced-model-main/tec_reduced_model/process_experimental_data.py
# # Auxiliary functions to load and process experimental data # import numpy as np import pandas as pd import os def clean_dataset(dataset): new_dataset = dataset.dropna(axis=1, how="all") replace_dict = { "Step Time": "Step Time [s]", "Prog Time": "Time [s]", "Voltage": "Voltage [V]", "Current": "Current [A]", "AhAccu": "AhAccu [Ah]", "AhPrev": "AhPrev [Ah]", "WhAccu": "WhAccu [Wh]", "Watt": "Watt [W]", } if "LogTemp002" in new_dataset.columns: T_dict = {"LogTemp001": "Temp Cell [degC]", "LogTemp002": "Temp Ambient [degC]"} elif "LogTemp001" in new_dataset.columns: if "LogTempPositive" in new_dataset.columns: T_dict = { "LogTempPositive": "Temp Positive [degC]", "LogTempMid": "Temp Cell [degC]", "LogTempNegative": "Temp Negative [degC]", "LogTemp001": "Temp Ambient [degC]", } else: T_dict = {"LogTemp001": "Temp Cell [degC]"} else: T_dict = { "LogTempPositive": "Temp Positive [degC]", "LogTempMid": "Temp Cell [degC]", "LogTempNegative": "Temp Negative [degC]", } replace_dict.update(T_dict) new_dataset = new_dataset.rename(columns=replace_dict, errors="raise") return new_dataset def import_thermal_data(Crate, T): if Crate == 0.1: cells = ["781", "782", "783", "784"] elif Crate == 0.5: cells = ["785", "786", "787", "788"] elif Crate == 1: cells = ["789", "790", "791", "792"] elif Crate == 2: cells = ["793", "794", "795", "796"] else: raise ValueError("Invalid C-rate") if T not in [0, 10, 25]: raise ValueError("Invalid temperature value") datasets = {} skiprows = list(range(15)) skiprows.append(16) root = os.path.dirname(os.path.dirname(__file__)) folder = "{}degC".format(T) for cell in cells: filename = "Cell{}_{}C_".format(cell, Crate).replace(".", "p") + folder + ".csv" imported_data = pd.read_csv( os.path.join(root, "data", folder, filename), skiprows=skiprows, ) dataset = clean_dataset(imported_data) datasets.update({cell: dataset}) return datasets def get_idxs(dataset, I_dch, I_ch): i = dataset["Current [A]"] diff_i = np.diff(i) idx_start = np.where((diff_i < 0.95 * (-I_dch)) & (diff_i > 1.05 * (-I_dch))) idx_end = np.where((diff_i > 0.95 * I_ch) & (diff_i < 1.05 * I_ch)) return idx_start[0], idx_end[0]
2,621
28.133333
88
py
TEC-reduced-model
TEC-reduced-model-main/tec_reduced_model/__init__.py
0
0
0
py
TEC-reduced-model
TEC-reduced-model-main/scripts/compare_TSPMe_TDFN.py
# # Comparison between TSPMe and thermal Doyle-Fuller-Newman model # import pybamm import numpy as np import matplotlib.pyplot as plt from os import path from tec_reduced_model.set_parameters import set_thermal_parameters plt.style.use(["science", "vibrant"]) plt.rcParams.update( { "font.size": 8, "axes.labelsize": 10, } ) pybamm.set_logging_level("INFO") def compute_error(solutions): sol_TSPMe = solutions[0] sol_TDFN = solutions[1] if sol_TSPMe["Time [s]"].entries[-1] < sol_TDFN["Time [s]"].entries[-1]: time = sol_TSPMe["Time [s]"].entries else: time = sol_TDFN["Time [s]"].entries error_V = sol_TSPMe["Terminal voltage [V]"](time) - sol_TDFN[ "Terminal voltage [V]" ](time) error_T = sol_TSPMe["X-averaged cell temperature [K]"](time) - sol_TDFN[ "X-averaged cell temperature [K]" ](time) error = {} error["V"] = error_V error["RMSE_V"] = np.sqrt(np.mean(error_V ** 2)) error["peak_V"] = np.max(np.abs(error_V)) error["T"] = error_T error["RMSE_T"] = np.sqrt(np.mean(error_T ** 2)) error["peak_T"] = np.max(np.abs(error_T)) return error def print_error(error, Crate, temperature, filename=None): error_str = ( "Results for {}C and {}degC\n".format(Crate, temperature) + "RMSE V: {:.2f} mV\n".format(error["RMSE_V"] * 1e3) + "Peak error V: {:.2f} mV\n".format(error["peak_V"] * 1e3) + "RMSE T: {:.2f} °C\n".format(error["RMSE_T"]) + "Peak error T: {:.2f} °C\n\n".format(error["peak_T"]) ) if filename is None: print(error_str) else: with open(filename, "a") as f: f.write(error_str) def add_plot(axes, solutions, error, Crate): sol_TSPMe = solutions[0] sol_TDFN = solutions[1] if sol_TSPMe["Time [s]"].entries[-1] < sol_TDFN["Time [s]"].entries[-1]: time = sol_TSPMe["Time [s]"].entries else: time = sol_TDFN["Time [s]"].entries axes[0, 0].plot( sol_TDFN["Discharge capacity [A.h]"](time), sol_TDFN["Terminal voltage [V]"](time), color="black", linestyle="dashed", ) axes[0, 0].plot( sol_TSPMe["Discharge capacity [A.h]"](time), sol_TSPMe["Terminal voltage [V]"](time), label="{}C".format(Crate), ) axes[0, 0].set_xlabel("Discharge capacity (Ah)") axes[0, 0].set_ylabel("Voltage (V)") axes[0, 0].legend(loc="lower left") axes[0, 1].plot( sol_TDFN["Discharge capacity [A.h]"](time), np.abs(error["V"]) * 1e3, ) axes[0, 1].set_xlabel("Discharge capacity (Ah)") axes[0, 1].set_ylabel("Voltage error (mV)") axes[1, 0].plot( sol_TDFN["Discharge capacity [A.h]"](time), sol_TDFN["X-averaged cell temperature [K]"](time) - 273.15, color="black", linestyle="dashed", ) axes[1, 0].plot( sol_TSPMe["Discharge capacity [A.h]"](time), sol_TSPMe["X-averaged cell temperature [K]"](time) - 273.15, label="{}C".format(Crate), ) axes[1, 0].set_xlabel("Discharge capacity (Ah)") axes[1, 0].set_ylabel("Temperature (°C)") axes[1, 1].plot( sol_TDFN["Discharge capacity [A.h]"](time), np.abs(error["T"]), label="{}C".format(Crate), ) axes[1, 1].set_xlabel("Discharge capacity (Ah)") axes[1, 1].set_ylabel("Temperature error (°C)") return axes def compare_models(models, param, Crates, temperature, filename=None): fig, axes = plt.subplots(2, 2, figsize=(5.5, 4)) param["Ambient temperature [K]"] = 273.15 + temperature param["Initial temperature [K]"] = 273.15 + temperature for Crate in Crates: simulations = [None] * len(models) solutions = [None] * len(models) for i, model in enumerate(models): sim = pybamm.Simulation( model, parameter_values=param, C_rate=Crate, ) sim.solve([0, 3700 / Crate]) solutions[i] = sim.solution simulations[i] = sim # Compute and print error error = compute_error(solutions) print_error(error, Crate, temperature, filename=filename) # Plot voltage and error axes = add_plot(axes, solutions, error, Crate) fig.suptitle("Ambient temperature: {} °C".format(temperature)) fig.tight_layout() fig.subplots_adjust(top=0.88) return fig # Define TSPMe using Integrated electrolyte conductivity submodel models = [ pybamm.lithium_ion.SPMe( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", "electrolyte conductivity": "integrated", }, name="TSPMe", ), pybamm.lithium_ion.DFN( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", }, name="TDFN", ), ] # Define parameter set Chen 2020 (see PyBaMM documentation for details) # This is the reference parameter set, which will be later adjusted param = pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Chen2020) # Change simulation parameters here temperatures = [0, 10, 25] # in degC Crates = [0.5, 1, 2] root = path.dirname(path.dirname(__file__)) for temperature in temperatures: param = set_thermal_parameters(param, 20, 2.85e6, temperature) fig = compare_models( models, param, Crates, temperature, filename="errors_models.txt" ) fig.savefig( path.join(root, "figures", "comp_models_{}degC.png".format(temperature)), dpi=300, )
5,667
27.482412
81
py
TEC-reduced-model
TEC-reduced-model-main/scripts/compare_mesh_points.py
# # Comparison between different number of grid points in mesh # import pybamm from tec_reduced_model.set_parameters import set_thermal_parameters pybamm.set_logging_level("INFO") # Define TDFN with a lumped themral model model = pybamm.lithium_ion.DFN( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", }, name="TDFN", ) # Change simulation parameters here temperature = 25 # in degC Crate = 1 # Define parameter set Chen 2020 (see PyBaMM documentation for details) # This is the reference parameter set, which is later adjusted for the temperature param = pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Chen2020) param = set_thermal_parameters(param, 20, 2.85e6, temperature) mesh_factors = [1, 2, 4, 8] solutions = [] var = pybamm.standard_spatial_vars for factor in mesh_factors: var_pts = { var.x_n: 20 * factor, var.x_s: 20 * factor, var.x_p: 20 * factor, var.r_n: 30 * factor, var.r_p: 30 * factor, var.y: 10, var.z: 10, } sim = pybamm.Simulation( model, parameter_values=param, var_pts=var_pts, C_rate=Crate, ) sim.model.name sim.solve([0, 3600]) sim.solution.model.name += " x{} mesh".format(factor) solutions.append(sim.solution) pybamm.dynamic_plot(solutions)
1,378
23.192982
82
py
TEC-reduced-model
TEC-reduced-model-main/scripts/plot_OCVs.py
# # Plot OCVs # import pybamm import matplotlib.pyplot as plt from os import path plt.style.use(["science", "vibrant"]) plt.rcParams.update( { "font.size": 8, "axes.labelsize": 10, } ) pybamm.set_logging_level("INFO") root = path.dirname(path.dirname(__file__)) # Define parameter set Chen 2020 (see PyBaMM documentation for details) param = pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Chen2020) Up = param["Positive electrode OCP [V]"][1] Un = param["Negative electrode OCP [V]"][1] fig, axes = plt.subplots(1, 2, figsize=(5.5, 2.5)) axes[0].plot(Up[:, 0], Up[:, 1]) axes[0].set_xlabel("Stoichiometry") axes[0].set_ylabel("Positive electrode OCP (V)") axes[1].plot(Un[:, 0], Un[:, 1]) axes[1].set_xlabel("Stoichiometry") axes[1].set_ylabel("Negative electrode OCP (V)") plt.tight_layout() fig.savefig(path.join(root, "figures", "OCVs.png"), dpi=300)
898
20.926829
72
py
TEC-reduced-model
TEC-reduced-model-main/scripts/compare_TSPMe_data.py
# # Comparison between TSPMe and experimental data # import pybamm import numpy as np import matplotlib.pyplot as plt from os import path from tec_reduced_model.set_parameters import ( set_thermal_parameters, set_experiment_parameters, set_ambient_temperature, ) from tec_reduced_model.process_experimental_data import import_thermal_data, get_idxs plt.style.use(["science", "vibrant"]) plt.rcParams.update( { "font.size": 8, "axes.labelsize": 10, } ) pybamm.set_logging_level("INFO") def rmse(solution, x_data, y_data): error = solution(x_data) - y_data error = error[~np.isnan(error)] # remove NaNs due to extrapolation return np.sqrt(np.mean(error ** 2)) def R_squared(solution, x_data, y_data): y_bar = np.mean(y_data) SS_tot = np.sum((y_data - y_bar) ** 2) res = y_data - solution(x_data) res = res[~np.isnan(res)] # remove NaNs due to extrapolation SS_res = np.sum(res ** 2) return 1 - SS_res / SS_tot def compute_error(solution, data_conc): error = {} error["RMSE_V"] = rmse( solution["Terminal voltage [V]"], data_conc["time"], data_conc["voltage"] ) error["Rsq_V"] = R_squared( solution["Terminal voltage [V]"], data_conc["time"], data_conc["voltage"] ) error["RMSE_T"] = rmse( solution["X-averaged cell temperature [K]"], data_conc["time"], data_conc["temperature"] + 273.15, ) error["Rsq_T"] = R_squared( solution["X-averaged cell temperature [K]"], data_conc["time"], data_conc["temperature"] + 273.15, ) return error def print_error(error, Crate, temperature, filename=None): error_str = ( "Results for {}C and {}degC\n".format(Crate, temperature) + "RMSE V: {:.2f} mV\n".format(error["RMSE_V"] * 1e3) + "R^2 V: {:.2f}\n".format(error["Rsq_V"]) + "RMSE T: {:.2f} °C\n".format(error["RMSE_T"]) + "R^2 T: {:.2f} \n\n".format(error["Rsq_T"]) ) if filename is None: print(error_str) else: with open(filename, "a") as f: f.write(error_str) def plot_experimental_data(axes, Crate, temperature, cells_ignore): dataset = import_thermal_data(Crate, temperature) data_conc = {"time": [], "voltage": [], "temperature": []} for cell, data in dataset.items(): if cell in cells_ignore: continue idx_start, idx_end = get_idxs(data, Crate * 5, 5 / 3) if len(idx_end) == 1: idx_end = np.append(idx_end, len(data["Time [s]"])) axes[0].plot( data["Time [s]"][idx_start[0] : idx_end[1]] - data["Time [s]"][idx_start[0]], data["Voltage [V]"][idx_start[0] : idx_end[1]], label=cell, linewidth=1, ls="--", ) axes[1].plot( data["Time [s]"][idx_start[0] : idx_end[1]] - data["Time [s]"][idx_start[0]], data["Temp Cell [degC]"][idx_start[0] : idx_end[1]], label=cell, linewidth=1, ls="--", ) pad = 4 axes[0].annotate( "{}C".format(Crate), xy=(0, 0.5), xytext=(-axes[0].yaxis.labelpad - pad, 0), xycoords=axes[0].yaxis.label, textcoords="offset points", size="large", ha="right", va="center", ) data_conc["time"] = np.append( data_conc["time"], data["Time [s]"][idx_start[0] : idx_end[1]] - data["Time [s]"][idx_start[0]], ) data_conc["voltage"] = np.append( data_conc["voltage"], data["Voltage [V]"][idx_start[0] : idx_end[1]] ) data_conc["temperature"] = np.append( data_conc["temperature"], data["Temp Cell [degC]"][idx_start[0] : idx_end[1]], ) return axes, data_conc def plot_model_solutions(axes, solution, Crate, temperature): if solution.model.name == "TSPMe": ls = "-" color = "black" linewidth = 0.75 else: ls = ":" color = "gray" linewidth = 1 axes[0].plot( solution["Time [s]"].entries, solution["Terminal voltage [V]"].entries, color=color, label=solution.model.name, ls=ls, linewidth=linewidth, ) if solution.model.name == "TSPMe": axes[0].scatter( 0, solution["X-averaged battery open circuit voltage [V]"].entries[0], s=15, marker="x", color="black", linewidths=0.75, ) axes[0].set_xlabel("Time (s)") axes[0].set_ylabel("Voltage (V)") axes[1].plot( solution["Time [s]"].entries, solution["X-averaged cell temperature [K]"].entries - 273.15, color=color, label=solution.model.name, ls=ls, linewidth=linewidth, ) axes[1].set_xlabel("Time (s)") axes[1].set_ylabel("Cell temperature (°C)") axes[1].legend() if temperature == 25 and Crate == 1: axes[1].set_yticks([25, 28, 31, 34, 37]) return axes def compare_data(models, param, Crates, temperature, cells_ignore=None, filename=None): fig, axes = plt.subplots(3, 2, figsize=(5.7, 5.5)) for k, Crate in enumerate(Crates): param = set_experiment_parameters(param, Crate, temperature) param = set_ambient_temperature(param, Crate, temperature) experiment = pybamm.Experiment( [ "Discharge at {}C until 2.5 V (5 seconds period)".format(Crate), "Rest for 2 hours", ], period="30 seconds", ) solutions = [] axes[k, :], data_conc = plot_experimental_data( axes[k, :], Crate, temperature, cells_ignore ) for model in models: simulation = pybamm.Simulation( model, parameter_values=param, experiment=experiment, ) simulation.solve() solution = simulation.solution solutions.append(solution) axes[k, :] = plot_model_solutions(axes[k, :], solution, Crate, temperature) error = compute_error(solution, data_conc) idx = filename.index(".") new_filename = filename[:idx] + "_" + model.name + filename[idx:] print_error(error, Crate, temperature, filename=new_filename) fig.suptitle("Ambient temperature: {} °C".format(temperature)) fig.tight_layout() fig.subplots_adjust(left=0.15, top=0.92) return fig # Define models models = [ pybamm.lithium_ion.SPMe( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", "electrolyte conductivity": "integrated", }, name="TSPMe", ), pybamm.lithium_ion.DFN( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", }, name="TDFN", ), ] # Define parameter set Chen 2020 (see PyBaMM documentation for details) # This is the reference parameter set, which will be later adjusted param = pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Chen2020) # Change simulation parameters here temperatures = [0, 10, 25] # in degC Crates = [0.5, 1, 2] cells_ignore = ["791"] root = path.dirname(path.dirname(__file__)) for temperature in temperatures: param = set_thermal_parameters(param, 16, 2.32e6, temperature) fig = compare_data( models, param, Crates, temperature, cells_ignore=cells_ignore, filename="errors_experiments.txt", ) fig.savefig( path.join(root, "figures", "comp_exp_{}degC.png".format(temperature)), dpi=300, )
7,902
27.024823
87
py
TEC-reduced-model
TEC-reduced-model-main/scripts/time_TSPMe_TDFN.py
# # Get computational time for TSPMe and TDFN # import pybamm import numpy as np from prettytable import PrettyTable # Import auxiliary functions from tec_reduced_model.set_parameters import set_thermal_parameters pybamm.set_logging_level("WARNING") # Define TSPMe using Integrated electrolyte conductivity submodel models = [ pybamm.lithium_ion.SPMe( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", "electrolyte conductivity": "integrated", }, name="TSPMe", ), pybamm.lithium_ion.DFN( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", }, name="TDFN", ), ] # Define parameter set Chen 2020 (see PyBaMM documentation for details) param = pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Chen2020) # Change simulation parameters here N_solve = 20 # number of times to run the solver to get computational time temperatures = [0, 10, 25] # in degC Crates = [0.5, 1, 2] tables = [PrettyTable([model.name, "C/2", "1C", "2C"]) for model in models] for i, model in enumerate(models): print("Running simulations for", model.name) for temperature in temperatures: param = set_thermal_parameters(param, 20, 2.85e6, temperature) times = [None] * len(Crates) for k, Crate in enumerate(Crates): print("Running simulation for {}C and {}degC".format(Crate, temperature)) sim = pybamm.Simulation( model, parameter_values=param, C_rate=Crate, ) time_sublist = [] for j in range(N_solve): sim.solve([0, 3700 / Crate]) time_sublist.append(sim.solution.solve_time) times[k] = time_sublist tables[i].add_row( ["{}degC".format(temperature)] + ["{:.2f} +- {:.2f}".format(np.mean(time), np.std(time)) for time in times] ) print() print("Computational times in seconds:") for table in tables: print() print(table)
2,153
28.108108
88
py
TEC-reduced-model
TEC-reduced-model-main/scripts/compare_TSPMe_data_mean.py
# # Comparison between TSPMe and experimental data # import pybamm import numpy as np import matplotlib.pyplot as plt from os import path from tec_reduced_model.set_parameters import ( set_thermal_parameters, set_experiment_parameters, set_ambient_temperature, ) from tec_reduced_model.process_experimental_data import import_thermal_data, get_idxs from scipy.interpolate import interp1d plt.style.use(["science", "vibrant"]) plt.rcParams.update( { "font.size": 8, "axes.labelsize": 10, } ) pybamm.set_logging_level("INFO") def rmse(solution, x_data, y_data): error = solution(x_data) - y_data error = error[~np.isnan(error)] # remove NaNs due to extrapolation return np.sqrt(np.mean(error ** 2)) def R_squared(solution, x_data, y_data): y_bar = np.mean(y_data) SS_tot = np.sum((y_data - y_bar) ** 2) res = y_data - solution(x_data) res = res[~np.isnan(res)] # remove NaNs due to extrapolation SS_res = np.sum(res ** 2) return 1 - SS_res / SS_tot def compute_error(solution, data_conc): error = {} error["RMSE_V"] = rmse( solution["Terminal voltage [V]"], data_conc["time"], data_conc["voltage"] ) error["Rsq_V"] = R_squared( solution["Terminal voltage [V]"], data_conc["time"], data_conc["voltage"] ) error["RMSE_T"] = rmse( solution["X-averaged cell temperature [K]"], data_conc["time"], data_conc["temperature"] + 273.15, ) error["Rsq_T"] = R_squared( solution["X-averaged cell temperature [K]"], data_conc["time"], data_conc["temperature"] + 273.15, ) return error def print_error(error, Crate, temperature, filename=None): error_str = ( "Results for {}C and {}degC\n".format(Crate, temperature) + "RMSE V: {:.2f} mV\n".format(error["RMSE_V"] * 1e3) + "R^2 V: {:.2f}\n".format(error["Rsq_V"]) + "RMSE T: {:.2f} °C\n".format(error["RMSE_T"]) + "R^2 T: {:.2f} \n\n".format(error["Rsq_T"]) ) if filename is None: print(error_str) else: with open(filename, "a") as f: f.write(error_str) def plot_experimental_data(axes, Crate, temperature, cells_ignore): dataset = import_thermal_data(Crate, temperature) voltage_fun = {} temperature_fun = {} t_end = 0 for cell, data in dataset.items(): if cell in cells_ignore: continue idx_start, idx_end = get_idxs(data, Crate * 5, 5 / 3) if len(idx_end) == 1: idx_end = np.append(idx_end, len(data["Time [s]"])) t_end = max( t_end, data["Time [s]"][idx_end[1] - 1] - data["Time [s]"][idx_start[0]] ) if data["Time [s]"][idx_start[0]] == data["Time [s]"][idx_start[0] + 1]: data.drop([idx_start[0] + 1], inplace=True) voltage_fun.update( { cell: interp1d( data["Time [s]"][idx_start[0] : idx_end[1]] - data["Time [s]"][idx_start[0]], data["Voltage [V]"][idx_start[0] : idx_end[1]], fill_value="extrapolate", ) } ) temperature_fun.update( { cell: interp1d( data["Time [s]"][idx_start[0] : idx_end[1]] - data["Time [s]"][idx_start[0]], data["Temp Cell [degC]"][idx_start[0] : idx_end[1]], fill_value="extrapolate", ) } ) t_eval = np.linspace(0, t_end, num=1000) voltage_data = [] temperature_data = [] for cell, V in voltage_fun.items(): V = voltage_fun[cell] T = temperature_fun[cell] voltage_data.append(V(t_eval)) temperature_data.append(T(t_eval)) V_mean = np.mean(np.array(voltage_data), axis=0) V_std = np.std(np.array(voltage_data), axis=0) T_mean = np.mean(np.array(temperature_data), axis=0) T_std = np.std(np.array(temperature_data), axis=0) axes[0].fill_between( t_eval, V_mean - V_std, V_mean + V_std, alpha=0.2, ) axes[0].plot(t_eval, V_mean, label="data") axes[1].fill_between( t_eval, T_mean - T_std, T_mean + T_std, alpha=0.2, ) axes[1].plot(t_eval, T_mean, label="data") pad = 4 axes[0].annotate( "{}C".format(Crate), xy=(0, 0.5), xytext=(-axes[0].yaxis.labelpad - pad, 0), xycoords=axes[0].yaxis.label, textcoords="offset points", size="large", ha="right", va="center", ) return axes, {} def plot_model_solutions(axes, solution, Crate, temperature): if solution.model.name == "TSPMe": ls = "-" color = "black" linewidth = 0.75 else: ls = ":" color = "gray" linewidth = 1 axes[0].plot( solution["Time [s]"].entries, solution["Terminal voltage [V]"].entries, color=color, label=solution.model.name, ls=ls, linewidth=linewidth, ) if solution.model.name == "TSPMe": axes[0].scatter( 0, solution["X-averaged battery open circuit voltage [V]"].entries[0], s=15, marker="x", color="black", linewidths=0.75, ) axes[0].set_xlabel("Time (s)") axes[0].set_ylabel("Voltage (V)") axes[1].plot( solution["Time [s]"].entries, solution["X-averaged cell temperature [K]"].entries - 273.15, color=color, label=solution.model.name, ls=ls, linewidth=linewidth, ) axes[1].set_xlabel("Time (s)") axes[1].set_ylabel("Cell temperature (°C)") if Crate == 0.5: axes[1].legend() if temperature == 25 and Crate == 1: axes[1].set_yticks([25, 28, 31, 34, 37]) return axes def compare_data(models, param, Crates, temperature, cells_ignore=None, filename=None): fig, axes = plt.subplots(3, 2, figsize=(5.7, 5.5)) for k, Crate in enumerate(Crates): param = set_experiment_parameters(param, Crate, temperature) param = set_ambient_temperature(param, Crate, temperature) experiment = pybamm.Experiment( [ "Discharge at {}C until 2.5 V (5 seconds period)".format(Crate), "Rest for 2 hours", ], period="30 seconds", ) solutions = [] axes[k, :], _ = plot_experimental_data( axes[k, :], Crate, temperature, cells_ignore ) for model in models: simulation = pybamm.Simulation( model, parameter_values=param, experiment=experiment, ) simulation.solve() solution = simulation.solution solutions.append(solution) axes[k, :] = plot_model_solutions(axes[k, :], solution, Crate, temperature) fig.suptitle("Ambient temperature: {} °C".format(temperature)) fig.tight_layout() fig.subplots_adjust(left=0.15, top=0.92) return fig # Define models pybamm.lithium_ion.SPMe( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", "electrolyte conductivity": "integrated", }, name="TSPMe", ), pybamm.lithium_ion.DFN( options={ "thermal": "lumped", "dimensionality": 0, "cell geometry": "arbitrary", }, name="TDFN", ), ] # Define parameter set Chen 2020 (see PyBaMM documentation for details) # This is the reference parameter set, which will be later adjusted param = pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Chen2020) # Change simulation parameters here temperatures = [0, 10, 25] # in degC Crates = [0.5, 1, 2] cells_ignore = ["791"] root = path.dirname(path.dirname(__file__)) for temperature in temperatures: param = set_thermal_parameters(param, 16, 2.32e6, temperature) fig = compare_data( models, param, Crates, temperature, cells_ignore=cells_ignore, ) fig.savefig( path.join(root, "figures", "comp_exp_{}degC_mean.png".format(temperature)), dpi=300, )
8,391
25.726115
87
py
Anjay-zephyr-client
Anjay-zephyr-client-master/tools/validate_fota_file_size.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020-2023 AVSystem <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import os import sys # See: https://github.com/mcu-tools/mcuboot/blob/v1.10.0/scripts/imgtool/image.py#L569 # This is calculated from default values for Image._trailer_size() # (write_size=4, max_sectors=128, max_align=8) # write_size and max_align may change if CONFIG_MCUBOOT_FLASH_WRITE_BLOCK_SIZE, # but it looks that nobody does that ;) MCUBOOT_TRAILER_SIZE = 1584 def _split_path_into_components(path): result = [] while True: head, tail = os.path.split(path) if tail != '' or head != path: result.insert(0, tail) path = head else: result.insert(0, head) return result PartitionParams = collections.namedtuple('PartitionParams', ['size', 'sector_size']) def get_partition_params(dts_filename): from devicetree import dtlib dt = dtlib.DT(dts_filename) part = dt.label2node['slot0_partition'] size = part.props['reg'].to_nums()[1] sector_size = part.parent.parent.props['erase-block-size'].to_num() # nCS Partition Manager defines the partitions differently try: import yaml with open(os.path.join(os.path.dirname(os.path.dirname(dts_filename)), 'partitions.yml'), 'r') as f: partitions = yaml.load(f, yaml.SafeLoader) size = partitions['mcuboot_primary']['size'] except FileNotFoundError: pass return PartitionParams(size=size, sector_size=sector_size) def main(argv): assert len(argv) > 0 if len(argv) != 2: sys.stderr.write(f'Usage: {argv[0]} FOTA_BINARY_FILE\n') return -1 fota_binary_file = os.path.realpath(argv[1]) fota_binary_file_path = _split_path_into_components(fota_binary_file) if len(fota_binary_file_path) < 2 or fota_binary_file_path[-2] != 'zephyr': sys.stderr.write(f'The binary file is not in a Zephyr build tree\n') return -1 zephyr_build_tree = os.path.join(*fota_binary_file_path[:-2]) with open(os.path.join(zephyr_build_tree, 'mcuboot', 'zephyr', '.config'), 'r') as f: lines = [line for line in f.readlines() if 'CONFIG_BOOT_SWAP_USING_MOVE' in line] mcuboot_uses_move = ( len(lines) == 1 and lines[0].strip() == 'CONFIG_BOOT_SWAP_USING_MOVE=y') if not mcuboot_uses_move: # Only the move algorithm requires free space; return success otherwise return 0 # Find ZEPHYR_BASE with open(os.path.join(zephyr_build_tree, 'CMakeCache.txt'), 'r') as f: lines = [line for line in f.readlines() if line.startswith('ZEPHYR_BASE')] if len(lines) != 1: sys.stderr.write(f'Could not determine ZEPHYR_BASE') return -1 zephyr_base = lines[0].strip().split('=', 1)[1] sys.path.append(os.path.join(zephyr_base, 'scripts', 'dts', 'python-devicetree', 'src')) params = get_partition_params(os.path.join(zephyr_build_tree, 'zephyr', 'zephyr.dts')) # At least one empty sector and space for the trailer is required for a successful FOTA max_allowed_size = params.size - params.sector_size max_allowed_size -= params.sector_size * ( (MCUBOOT_TRAILER_SIZE - 1 + params.sector_size) // params.sector_size) fota_binary_size = os.stat(fota_binary_file).st_size if fota_binary_size > max_allowed_size: sys.stderr.write( f'{argv[1]} is {fota_binary_size} bytes, but {max_allowed_size} is the maximum size with which FOTA using the move algorithm is possible (overflow by {fota_binary_size - max_allowed_size} bytes)') return -1 return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
4,301
36.736842
208
py
Anjay-zephyr-client
Anjay-zephyr-client-master/tools/board_adapters/nrf_adapter.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020-2023 AVSystem <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import subprocess import serial import zephyr_adapter_common class TargetAdapter(zephyr_adapter_common.ZephyrAdapterCommon): @property def nrfjprog_serial(self): # As empirically checked (using PRoot and a faked contents of /sys/devices/.../serial), # nrfjprog always strips all leading zeros from the serial number return self.config['nrfjprog-serial'].strip().lstrip('0') def get_port(self): with subprocess.Popen(['nrfjprog', '-s', self.nrfjprog_serial, '--com'], stdout=subprocess.PIPE) as p: ports = [port[1] for port in (line.strip().decode().split() for line in p.stdout.readlines()) if port[2] == 'VCOM0'] if len(ports) != 1: raise Exception( f"Found {len(ports)} VCOM0 ports for given nrfjprog serial ({self.config['nrfjprog-serial']})") return ports[0] def acquire_device(self): self.device = serial.Serial(self.get_port(), self.config['baudrate'], timeout=self.config['timeout']) def flash_device(self, hex_image=None, chiperase=False): erase_option = '--chiperase' if chiperase else '--sectorerase' image = hex_image if hex_image else self.config['hex-path'] if subprocess.run(['nrfjprog', '-s', self.nrfjprog_serial, '--program', image, erase_option]).returncode != 0: raise Exception('Flash failed') if subprocess.run(['nrfjprog', '-s', self.nrfjprog_serial, '--pinreset']).returncode != 0: raise Exception('Flash failed') def release_device(self, erase=True): if self.device is not None: if erase: subprocess.run(['nrfjprog', '-s', self.nrfjprog_serial, '-e']) self.device.close() self.device = None
2,519
39
118
py
Anjay-zephyr-client
Anjay-zephyr-client-master/tools/board_adapters/zephyr_adapter_common.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020-2023 AVSystem <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import contextlib import time THROTTLED_WRITE_DELAY = 0.01 def throttled_write(device, payload): for byte in payload: device.write(bytes([byte])) device.flush() time.sleep(THROTTLED_WRITE_DELAY) class ZephyrAdapterCommon: def __init__(self, config): self.config = config self.device = None def prepare_device(self): self.flash_device() if self.config["type"] == "demo": self.prepare_device_demo() self.skip_until("registration successful") print("Device successfully registered") def prepare_device_demo(self): self.skip_until("Initializing Anjay-zephyr-client demo") self.skip_until_prompt() print("Prompt message received, configuring...") self.__write_options() print("Device configured, waiting for connection...") @contextlib.contextmanager def __override_timeout(self, timeout): old_timeout = self.device.timeout try: if timeout is not None: self.device.timeout = timeout yield finally: self.device.timeout = old_timeout def __passthrough(self, incoming): if self.config["passthrough"]: decoded_incoming = incoming.decode("ASCII", errors="ignore") print("\033[35m", end="") print(decoded_incoming, end="") print("\033[0m") def passthrough(self, timeout): result = b'' deadline = time.time() + timeout while True: new_timeout = max(deadline - time.time(), 0) with self.__override_timeout(new_timeout): result += self.device.read(65536) if new_timeout <= 0: break self.__passthrough(result) def skip_until(self, expected): expected_encoded = expected.encode("ASCII") incoming = self.device.read_until(expected_encoded) self.__passthrough(incoming) if not incoming.endswith(expected_encoded): raise Exception("skip_until timed out") return incoming def skip_until_prompt(self): return self.skip_until("uart:~$ ") def __write_options(self): throttled_write(self.device, b"\r\nanjay stop\r\n") while True: with self.__override_timeout(90): line = self.skip_until('\n') if b'Anjay stopped' in line or b'Anjay is not running' in line: break for opt_key, opt_val in self.config["device-config"].items(): print(f"Writing option {opt_key}") throttled_write(self.device, f"anjay config set {opt_key} {opt_val}\r\n".encode("ASCII")) self.skip_until_prompt() throttled_write(self.device, b"anjay config save\r\n") self.skip_until("Configuration successfully saved") time.sleep(1) throttled_write(self.device, b"kernel reboot cold\r\n")
3,642
30.678261
88
py
Anjay-zephyr-client
Anjay-zephyr-client-master/tools/board_adapters/esp_adapter.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020-2023 AVSystem <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import serial import subprocess import os import shlex import yaml import zephyr_adapter_common COLOR_OFF = "\033[0m" COLOR_MAGENTA = "\033[35m" COLOR_CYAN = "\033[36m" class TargetAdapter(zephyr_adapter_common.ZephyrAdapterCommon): def acquire_device(self): self.device = serial.Serial( self.config["device"], self.config["baudrate"], timeout=self.config["timeout"] ) def release_device(self): if self.device is not None: self.__run_with_idf([ os.environ["ESPTOOL_PATH"], "-p", self.config["device"], "erase_flash" ]) self.device.close() self.device = None def flash_device(self): if self.__run_with_idf(self.__get_flasher_command()).returncode != 0: raise Exception("Flash failed") def __get_flasher_command(self): with open(self.config["yaml_path"], mode="r", encoding="utf-8") as flasher_args_file: flasher_args = yaml.safe_load(flasher_args_file) res = [ os.environ["ESPTOOL_PATH"], "-p", self.config["device"], "--before", "default_reset", "--after", "hard_reset", "--chip", flasher_args["flash-runner"], "write_flash", "--flash_mode", "dio", "--flash_size", "detect", "--flash_freq", "40m", ] boot_addr = "" part_table_addr = "" app_addr = "" for option in flasher_args["args"][flasher_args["flash-runner"]]: if option.startswith("--esp-boot-address="): boot_addr = option.split("--esp-boot-address=")[1] elif option.startswith("--esp-partition-table-address="): part_table_addr = option.split("--esp-partition-table-address=")[1] elif option.startswith("--esp-app-address="): app_addr = option.split("--esp-app-address=")[1] res.extend([boot_addr, self.config["binaries"]["bootloader"]]) res.extend([part_table_addr, self.config["binaries"]["partitions"]]) res.extend([app_addr, self.config["binaries"]["main_app"]]) return res def __run_in_shell(self, commands): script = "\n".join([shlex.join(command) for command in commands]) print(f"{COLOR_CYAN}Running script:\n{script}{COLOR_OFF}", flush=True) return subprocess.run(["/bin/bash", "-e"], input=script.encode("utf-8")) def __run_with_idf(self, command): source_idf = [".", f"{os.environ['IDF_PATH']}/export.sh"] return self.__run_in_shell([source_idf, command])
3,443
36.434783
93
py
Anjay-zephyr-client
Anjay-zephyr-client-master/tools/board_adapters/st_adapter.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020-2023 AVSystem <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import subprocess import serial import serial.tools.list_ports import zephyr_adapter_common # Yo dawg, I heard you like hexdumps # So we put a hexdump in your hexdump so you can hexdump while you hexdump # Apparently, st-flash's required format of --serial # parameter is a hexlified ASCII-hexstring (sic!), while # pyserial displays the serial number properly. def unhexlify(hexstring): return bytes.fromhex(hexstring).decode("ASCII") class TargetAdapter(zephyr_adapter_common.ZephyrAdapterCommon): def acquire_device(self): stlink_serial_unhexlified = unhexlify(self.config["stlink-serial"]) ports = [ port for port in serial.tools.list_ports.comports() if port.serial_number == stlink_serial_unhexlified ] if len(ports) != 1: raise Exception( f"Found {len(ports)} ports for given ST-Link serial ({self.config['stlink-serial']})") self.device = serial.Serial(ports[0].device, self.config["baudrate"], timeout=self.config["timeout"]) def flash_device(self): if subprocess.run(["st-flash", "--serial", self.config["stlink-serial"], "--format", "ihex", "write", self.config["hex-path"] ]).returncode != 0: raise Exception("Flash failed") def release_device(self): if self.device is not None: subprocess.run(["st-flash", "--serial", self.config["stlink-serial"], "erase"]) self.device.close() self.device = None
2,310
34.553846
102
py
Anjay-zephyr-client
Anjay-zephyr-client-master/tools/provisioning-tool/ptool.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020-2023 AVSystem <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import importlib import importlib.util import subprocess import sys import os import shutil import tempfile import yaml import west.util from requests import HTTPError from subprocess import CalledProcessError class ZephyrImageBuilder: def __init__(self, board, image_dir, conf_file): script_directory = os.path.dirname(os.path.realpath(__file__)) self.board = board self.image_dir = image_dir if image_dir else os.path.join( os.getcwd(), 'provisioning_builds') self.conf_file = conf_file self.image_path = {} self.overlay = {} for kind in ['initial', 'final']: self.image_path[kind] = os.path.join(self.image_dir, f'{kind}.hex') self.overlay[kind] = os.path.join( script_directory, f'{kind}_overlay_nrf9160dk.conf' if board == "nrf9160dk_nrf9160_ns" and kind == 'final' else f'{kind}_overlay.conf') def __build(self, kind): current_build_directory = os.path.join(self.image_dir, kind) os.makedirs(current_build_directory, exist_ok=True) subprocess.run(['west', 'build', '-b', self.board, '-d', current_build_directory, '-p', '--', f'-DOVERLAY_CONFIG={self.overlay[kind]}', f'-DCONF_FILE={self.conf_file}' if self.conf_file and kind == 'final' else ''], check=True) shutil.move(os.path.join(current_build_directory, 'zephyr/merged.hex'), self.image_path[kind]) shutil.rmtree(current_build_directory) return self.image_path[kind] def build_initial_image(self): return self.__build('initial') def build_final_image(self): return self.__build('final') def get_images(args): initial_image = None final_image = None if args.image_dir: potential_initial_image = os.path.join(args.image_dir, 'initial.hex') if os.path.exists(potential_initial_image): initial_image = potential_initial_image print('Using provided initial.hex file as an initial provisioning image') potential_final_image = os.path.join(args.image_dir, 'final.hex') if os.path.exists(potential_final_image): final_image = potential_final_image print('Using provided final.hex file as a final provisioning image') if args.board and (initial_image is None or final_image is None): builder = ZephyrImageBuilder( args.board, args.image_dir, args.conf_file) if initial_image is None: print('Initial provisioning image not provided - building') initial_image = builder.build_initial_image() if final_image is None: print('Final provisioning image not provided - building') final_image = builder.build_final_image() if initial_image is None or final_image is None: raise ValueError('Zephyr images cannot be obtained') return initial_image, final_image def get_device_adapter(serial_number, baudrate): sys.path.append(os.path.join(os.path.dirname( os.path.realpath(__file__)), '../board_adapters')) adapter_module = importlib.import_module('nrf_adapter') config = { 'nrfjprog-serial': serial_number, 'baudrate': str(baudrate), 'timeout': 60, 'hex-path': None, 'passthrough': False } return adapter_module.TargetAdapter(config) def flash_device(device, image, chiperase, success_text): device.acquire_device() device.flash_device(image, chiperase) device.skip_until(success_text) device.skip_until_prompt() device.release_device(erase=False) print('Device flashed succesfully') def mcumgr_download(port, src, baud=115200): with tempfile.TemporaryDirectory() as dst_dir_name: dst_file_name = os.path.join(dst_dir_name, 'result.txt') connstring = f'dev={port},baud={baud}' command = ['mcumgr', '--conntype', 'serial', '--connstring', connstring, 'fs', 'download', src, dst_file_name, '-t', '30'] subprocess.run(command, cwd=os.getcwd(), universal_newlines=True, check=True) with open(dst_file_name) as dst_file: return dst_file.read() def mcumgr_upload(port, src, dst, baud=115200): subprocess.run(['mcumgr', '--conntype', 'serial', '--connstring', f'dev={port},baud={baud}', 'fs', 'upload', src, dst], cwd=os.getcwd(), universal_newlines=True, check=True) def get_anjay_zephyr_path(manifest_path): with open(manifest_path, 'r') as stream: projects = yaml.safe_load(stream)['manifest']['projects'] for project in projects: if project['name'].lower() == 'anjay-zephyr': return os.path.join(west.util.west_topdir(), project['path']) def get_manifest_path(): west_manifest_path = None west_manifest_file = None west_config = subprocess.run( ['west', 'config', '-l'], capture_output=True).stdout.split(b'\n') for config_entry in west_config: if config_entry.startswith(b'manifest.file'): west_manifest_file = config_entry.split(b'=')[1].strip() if config_entry.startswith(b'manifest.path'): west_manifest_path = config_entry.split(b'=')[1].strip() print(f'Manifest path: {west_manifest_path}') print(f'Manifest file: {west_manifest_file}') if (not west_manifest_file) or (not west_manifest_path): raise Exception('west config incomplete') return os.path.join(west_manifest_path, west_manifest_file) def main(): parser = argparse.ArgumentParser( description='Factory provisioning tool') # Arguments for building the Zephyr images parser.add_argument('-b', '--board', type=str, help='Board for which the image should be built, may be not provided if images are cached', required=False) parser.add_argument('-f', '--conf_file', type=str, help='Application configuration file(s) for final image build, by default, prj.conf is used', required=False) parser.add_argument('-i', '--image_dir', type=str, help='Directory for the cached Zephyr hex images', required=False, default=None) # Arguments for flashing parser.add_argument('-s', '--serial', type=str, help='Serial number of the device to be used', required=True) parser.add_argument('-B', '--baudrate', type=int, help='Baudrate for the used serial port', required=False, default=115200) # Arguments for factory_provisioning library parser.add_argument('-c', '--endpoint_cfg', type=str, help='Configuration file containing device information to be loaded on the device', required=True) parser.add_argument('-S', '--server', type=str, help='JSON format file containing Coiote server information', required=False) parser.add_argument('-t', '--token', type=str, help='Access token for authorization to Coiote server', required=False) parser.add_argument('-C', '--cert', type=str, help='JSON format file containing information for the generation of a self signed certificate', required=False) parser.add_argument('-k', '--pkey', type=str, help='Endpoint private key in DER format, ignored if CERT parameter is set', required=False) parser.add_argument('-r', '--pcert', type=str, help='Endpoint public cert in DER format, ignored if CERT parameter is set', required=False,) parser.add_argument('-p', '--scert', type=str, help='Server public cert in DER format', required=False) args = parser.parse_args() # This is called also as an early check if the proper west config is set manifest_path = get_manifest_path() if bool(args.server) != bool(args.token): raise Exception( 'Server and token cli arguments should be always provided together') anjay_path = os.path.join( get_anjay_zephyr_path(manifest_path), 'deps/anjay') provisioning_tool_path = os.path.join( anjay_path, 'tools/provisioning-tool') sys.path.append(provisioning_tool_path) fp = importlib.import_module('factory_prov.factory_prov') initial_image, final_image = get_images(args) print('Zephyr Images ready!') adapter = get_device_adapter(args.serial, args.baudrate) flash_device(adapter, initial_image, True, 'Device ready for provisioning.') port = adapter.get_port() endpoint_name = mcumgr_download( port, '/factory/endpoint.txt', args.baudrate) print(f'Downloaded endpoint name: {endpoint_name}') fcty = fp.FactoryProvisioning(args.endpoint_cfg, endpoint_name, args.server, args.token, args.cert) if fcty.get_sec_mode() == 'cert': if args.scert is not None: fcty.set_server_cert(args.scert) if args.cert is not None: fcty.generate_self_signed_cert() elif args.pkey is not None and args.pcert is not None: fcty.set_endpoint_cert_and_key(args.pcert, args.pkey) with tempfile.TemporaryDirectory() as temp_directory: last_cwd = os.getcwd() os.chdir(temp_directory) fcty.provision_device() mcumgr_upload(adapter.get_port(), 'SenMLCBOR', '/factory/provision.cbor', args.baudrate) os.chdir(last_cwd) if int(mcumgr_download(port, '/factory/result.txt', args.baudrate)) != 0: raise RuntimeError('Bad device provisioning result') if args.server and args.token: fcty.register() flash_device(adapter, final_image, False, 'persistence: Anjay restored from') if __name__ == '__main__': main()
10,847
37.332155
169
py
dynprog
dynprog-main/setup.py
import pathlib import setuptools NAME = "dynprog" URL = "https://github.com/erelsgl/" + NAME HERE = pathlib.Path(__file__).parent print(f"\nHERE = {HERE.absolute()}\n") README = (HERE / "README.md").read_text() REQUIRES = (HERE / "requirements.txt").read_text().strip().split("\n") REQUIRES = [lin.strip() for lin in REQUIRES] print(f'\nVERSION = {(HERE / NAME / "VERSION").absolute()}\n') VERSION = (HERE / NAME / "VERSION").read_text().strip() # See https://packaging.python.org/en/latest/guides/single-sourcing-package-version/ setuptools.setup( name=NAME, packages=setuptools.find_packages(), version=VERSION, install_requires=REQUIRES, author="Erel Segal-Halevi", author_email="[email protected]", description="Generic function for sequential dynamic programming", keywords="optimization, dynamic-programming", license="GPL", license_files=("LICENSE",), long_description=README, long_description_content_type="text/markdown", url=URL, project_urls={"Bug Reports": URL + "/issues", "Source Code": URL}, python_requires=">=3.8", include_package_data=True, classifiers=[ # see https://pypi.org/classifiers/ "Development Status :: 2 - Pre-Alpha", ], ) # Build: # Delete old folders: build, dist, *.egg_info # Then run: # python -m build # Or (old version): # python setup.py sdist bdist_wheel # Publish to test PyPI: # twine upload --repository testpypi dist/* # Publish to real PyPI: # twine upload --repository pypi dist/*
1,544
29.294118
84
py
dynprog
dynprog-main/dynprog/sequential_func.py
""" Generic dynamic programming in the iterative method. Uses a function interface. Programmer: Erel Segal-Halevi. Since: 2021-11. """ from typing import * from numbers import Number State = Any Value = Number StateValue = Tuple[State,Value] StateValueData = Tuple[State,Value,Any] import logging logger = logging.getLogger(__name__) def max_value( initial_states: Generator[StateValue, None, None], neighbors: Callable[[StateValue], Generator[StateValue, None, None]], final_states: Generator[State, None, None] = None, is_final_state: Callable[[State],bool] = None, ): """ This is a shorter function that only returns the maximum value - it does not return the optimum solution. The initial states are determined by the argument: * inital_states: a generator function, that generates tuples of the form (state,value) for all initial states. The neighbors of each state are determined by the argument: * neighbors: a generator function, that generates tuples of the form (state,value) for all neighbors of the given state. The final states are determined by one of the following arguments (you should send one of them): * final_states: a generator function, that generates all final states. * is_final_state: returns True iff the given state is final. """ open_states = [] map_state_to_value = dict() for state,value in initial_states(): open_states.append(state) map_state_to_value[state]=value num_of_processed_states = 0 while len(open_states)>0: current_state:State = open_states.pop(0) current_value = map_state_to_value[current_state] logger.info("Processing state %s with value %s", current_state,current_value) num_of_processed_states += 1 for (next_state,next_value) in neighbors(current_state, current_value): if next_state in map_state_to_value: if next_value is not None: map_state_to_value[next_state] = max(map_state_to_value[next_state], next_value) else: map_state_to_value[next_state] = next_value open_states.append(next_state) logger.info("Processed %d states", num_of_processed_states) if final_states is not None: return max([map_state_to_value[state] for state in final_states()]) elif is_final_state is not None: return max([map_state_to_value[state] for state in map_state_to_value.keys() if is_final_state(state)]) else: raise ValueError("Either final_states or is_final_state must be given") def max_value_solution( initial_states: Generator[StateValueData, None, None], neighbors: Callable[[StateValueData], Generator[StateValueData, None, None]], final_states: Generator[State, None, None] = None, is_final_state: Callable[[State],bool] = None, ): """ This function returns both the maximum value and the corresponding optimum solution. The initial states are determined by the argument: * inital_states: a generator function, that generates tuples of the form (state,value,data) for all initial states. The neighbors of each state are determined by the argument: * neighbors: a generator function, that generates tuples of the form (state,value,data) for all neighbors of the given state. The final states are determined by one of the following arguments (you should send one of them): * final_states: a generator function, that generates all final states. * is_final_state: returns True iff the given state is final. """ open_states = [] map_state_to_value = dict() map_state_to_data = dict() for state,value,data in initial_states(): open_states.append(state) map_state_to_value[state]=value map_state_to_data[state]=data num_of_processed_states = 0 while len(open_states)>0: current_state:State = open_states.pop(0) current_value = map_state_to_value[current_state] current_data = map_state_to_data[current_state] num_of_processed_states += 1 logger.info("Processing state %s with value %s and data %s", current_state,current_value,current_data) for (next_state,next_value,next_data) in neighbors(current_state, current_value, current_data): if next_state in map_state_to_value: if next_value is not None and next_value > map_state_to_value[next_state]: logger.info("Improving state %s to value %s and data %s", next_state,next_value,next_data) map_state_to_value[next_state] = next_value map_state_to_data[next_state] = next_data pass else: map_state_to_value[next_state] = next_value map_state_to_data[next_state] = next_data open_states.append(next_state) logger.info("Processed %d states", num_of_processed_states) if final_states is not None: best_final_state = max(list(final_states()), key=lambda state:map_state_to_value[state]) elif is_final_state is not None: best_final_state = max([state for state in map_state_to_value.keys() if is_final_state(state)], key=lambda state:map_state_to_value[state]) else: raise ValueError("Either final_states or is_final_state must be given") best_final_state_value = map_state_to_value[best_final_state] best_final_state_data = map_state_to_data[best_final_state] return (best_final_state, best_final_state_value, best_final_state_data, num_of_processed_states) if __name__=="__main__": import sys logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.INFO) # Example: longest palyndrome subsequence. string = "abcdba" lenstr = len(string) def initial_states_short(): # only state and value for i in range(lenstr): yield ((i,i+1),1) for i in range(lenstr): yield ((i,i),0) def initial_states_long(): # state value and data for i in range(lenstr): yield ((i,i+1),1, string[i]) for i in range(lenstr): yield ((i,i),0, "") def neighbors_short(state:Tuple[int,int], value:int): # only state and value (i,j) = state # indices: represent the string between i and j-1. if i>0 and j<lenstr and string[i-1]==string[j]: # add two letters to the palyndrome yield ((i-1,j+1),value+2) else: # add one letter in each side of the string, without extending the palyndrome if i>0: yield ((i-1,j),value) if j<lenstr: yield ((i,j+1),value) def neighbors_long(state:Tuple[int,int], value:int, data:str): # state and value and data (i,j) = state # indices: represent the string between i and j-1. if i>0 and j<lenstr and string[i-1]==string[j]: # add two letters to the palyndrome yield ((i-1,j+1),value+2,string[i-1]+data+string[j]) else: # add one letter in each side of the string, without extending the palyndrome if i>0: yield ((i-1,j),value,data) if j<lenstr: yield ((i,j+1),value,data) def final_states(): yield (0, lenstr) print(max_value(initial_states=initial_states_short,neighbors=neighbors_short,final_states=final_states)) print(max_value_solution(initial_states=initial_states_long,neighbors=neighbors_long,final_states=final_states))
7,529
44.914634
147
py
dynprog
dynprog-main/dynprog/sequential.py
#!python3 """ A sequential dynamic program - a DP that handles the inputs one by one. Based on the "Simple DP" defined by Gerhard J. Woeginger (2000) in: "When Does a Dynamic Programming Formulation Guarantee the Existence of a FPTAS?". Programmer: Erel Segal-Halevi. Since: 2021-12 """ from typing import * from dataclasses import dataclass from dynprog import logger Input = List[int] State = List[int] Value = float Solution = Any from abc import ABC, abstractmethod class SequentialDynamicProgram(ABC): ### The following abstract methods define the dynamic program. ### You should override them for each specific problem. @abstractmethod # Return a set of initial states [The set S_0 in the paper]. def initial_states(self) -> Set[State]: return {0} @abstractmethod # Return a list of functions; each function maps a pair (state,input) to a new state [The set F in the paper]. def transition_functions(self) -> List[Callable[[State, Input], State]]: return [lambda state, input: state] @abstractmethod # Return a function that maps a state to its "value" (that should be maximized). [The function g in the paper]. def value_function(self) -> Callable[[State], Value]: return lambda state: 0 # Return a set of functions; each function maps a pair (state,input) to a boolean value which is "true" iff the new state should be added [The set H from the paper]. # By default, there is no filtering - every state is legal. def filter_functions(self) -> List[Callable[[State, Input], bool]]: return [ (lambda state, input: True) for _ in self.transition_functions() ] @abstractmethod def initial_solution(self) -> Solution: return [] @abstractmethod def construction_functions( self, ) -> List[Callable[[Solution, Input], Solution]]: return [ (lambda solution, input: solution) for _ in self.transition_functions() ] def max_value(self, inputs: List[Input]): """ This function that only returns the maximum value - it does not return the optimum solution. :param inputs: the list of inputs. """ current_states = set(self.initial_states()) transition_functions = self.transition_functions() filter_functions = self.filter_functions() value_function = self.value_function() logger.info( "%d initial states, %d transition functions, %d filter functions.", len(current_states), len(transition_functions), len(filter_functions), ) num_of_processed_states = len(current_states) for input_index, input in enumerate(inputs): next_states = { f(state, input) for (f, h) in zip(transition_functions, filter_functions) for state in current_states if h(state, input) } logger.info( " Processed input %d (%s) and added %d states.", input_index, input, len(next_states), ) num_of_processed_states += len(next_states) current_states = next_states logger.info("Processed %d states.", num_of_processed_states) if len(current_states) == 0: raise ValueError("No final states!") best_final_state = max( current_states, key=lambda state: value_function(state) ) best_final_state_value = value_function(best_final_state) logger.info( "Best final state: %s, value: %s", best_final_state, best_final_state_value, ) return best_final_state_value def max_value_solution(self, inputs: List[Input]): """ This function returns both the maximum value and the corresponding optimum solution. :param inputs: the list of inputs. """ inputs = list(inputs) # allow to iterate twice. See https://stackoverflow.com/q/70381559/827927 @dataclass class StateRecord: state: State prev: Any # StateRecord transition_index: int # the index of the transition function used to go from prev to state. def __hash__(self): return hash(self.state) def __eq__(self, other): return self.state == other.state current_state_records = { StateRecord(state, None, None) for state in self.initial_states() } # Add a link to the 'previous state', which is initially None. transition_functions = self.transition_functions() filter_functions = self.filter_functions() value_function = self.value_function() construction_functions = self.construction_functions() logger.info( "%d initial states, %d transition functions, %d filter functions, %d construction functions.", len(current_state_records), len(transition_functions), len(filter_functions), len(construction_functions), ) num_of_processed_states = len(current_state_records) for input_index, input in enumerate(inputs): next_state_records = { StateRecord(f(record.state, input), record, transition_index) for (transition_index, (f, h)) in enumerate( zip(transition_functions, filter_functions) ) for record in current_state_records if h(record.state, input) } logger.info( " Processed input %d (%s) and added %d states.", input_index, input, len(next_state_records), ) num_of_processed_states += len(next_state_records) current_state_records = next_state_records logger.info("Processed %d states.", num_of_processed_states) if len(current_state_records) == 0: raise ValueError("No final states!") best_final_record = max( current_state_records, key=lambda record: value_function(record.state), ) best_final_state = best_final_record.state best_final_state_value = value_function(best_final_state) # construct path to solution path = [] record = best_final_record while record.prev is not None: path.insert(0, record.transition_index) record = record.prev logger.info("Path to best solution: %s", path) # construct solution solution = self.initial_solution() for input_index, input in enumerate(inputs): transition_index = path[input_index] logger.info( " Input %d (%s): transition %d", input_index, input, transition_index, ) solution = construction_functions[transition_index]( solution, input ) return ( best_final_state, best_final_state_value, solution, num_of_processed_states, ) if __name__ == "__main__": import sys, logging logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.INFO) # Example: subset sum with fixed capacity. capacity = 4005 class SubsetSumDP(SequentialDynamicProgram): def initial_states(self): return {0} def transition_functions(self): return [ lambda state, input: state + input, # adding the input lambda state, _: state + 0, # not adding the input ] def value_function(self): return lambda state: state def initial_solution(self): return [] def construction_functions(self): return [ lambda solution, input: solution + [input], # adding the input lambda solution, _: solution, # not adding the input ] def filter_functions(self): return [ lambda state, input: state + input <= capacity, # adding the input lambda _, __: True, # not adding the input ] inputs = [100, 200, 300, 400, 700, 1100, 1600, 2200, 2900, 3700] ssdp = SubsetSumDP() print(ssdp.max_value(inputs)) print(ssdp.max_value_solution(inputs))
8,587
34.196721
169
py
dynprog
dynprog-main/dynprog/__init__.py
""" Generic dynamic programming in the iterative method. Programmer: Erel Segal-Halevi. Since: 2021-11. """ import pathlib, logging logger = logging.getLogger(__name__) HERE = pathlib.Path(__file__).parent __version__ = (HERE / "VERSION").read_text().strip()
262
19.230769
52
py
dynprog
dynprog-main/examples/multiple_subset_sum.py
#!python3 """ Uses the sequential dynamic programming function to solve the multiple-subset-sum problem: https://en.wikipedia.org/wiki/Multiple_subset_sum The states are of the form (v1, v2, ..., vn) where n is the number of bins. The "vi" is the current sum in bin i. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog from dynprog.sequential import SequentialDynamicProgram from typing import * def max_sum(inputs: List[int], capacities:List[int])->int: """ Returns the maximum sum of values from the given `inputs` list, that can fit within m bin of the given capacities (m = len(capacities)). >>> max_sum([3,5], [2,2]) 0 >>> max_sum([3,5], [4,4]) 3 >>> max_sum([3,5], [6,6]) 8 >>> max_sum([3,5], [8,8]) 8 >>> max_sum([100,200,400,700,1100,1600,2200,2900,3700], [2005,2006]) 4000 """ return MultipleSubsetSumDP(capacities).max_value(inputs) def max_sum_solution(inputs: List[int], capacities:List[int])->int: """ Returns the maximum sum of values from the given `inputs` list, that can fit within a bin of the given 'capacity'. >>> max_sum_solution([3,5], [2,2]) [[], []] >>> max_sum_solution([3,5], [4,4]) [[], [3]] >>> max_sum_solution([3,5], [6,6]) [[5], [3]] >>> max_sum_solution([3,5], [8,8]) [[3, 5], []] >>> max_sum_solution([100,200,400,700,1100,1600,2200,2900,3700], [2005,2006]) [[400, 1600], [200, 700, 1100]] """ (best_state,best_value,best_solution,num_of_states) = MultipleSubsetSumDP(capacities).max_value_solution(inputs) return best_solution #### Dynamic program definition: class MultipleSubsetSumDP(SequentialDynamicProgram): # The states are of the form (v1, v2, ..., vn) where n is the number of bins. # The "vi" is the current sum in bin i. def __init__(self, capacities:List[int]): self.capacities = capacities self.num_of_bins = len(capacities) def initial_states(self): zero_values = self.num_of_bins*(0,) return {zero_values} def initial_solution(self): empty_bundles = [ [] for _ in range(self.num_of_bins)] return empty_bundles def transition_functions(self): return [ lambda state, input: state # do not add the input at all ] + [ lambda state, input, bin_index=bin_index: _add_input_to_bin_sum(state, bin_index, input) for bin_index in range(self.num_of_bins) ] def construction_functions(self): return [ lambda solution, input: solution # do not add the input at all ] + [ lambda solution,input,bin_index=bin_index: _add_input_to_bin(solution, bin_index, input) for bin_index in range(self.num_of_bins) ] def value_function(self): return lambda state: sum(state) def filter_functions(self): return [ lambda state,input: True # do not add the input at all ] + [ lambda state,input,bin_index=bin_index: state[bin_index]+input <= self.capacities[bin_index] for bin_index in range(self.num_of_bins) ] def _add_input_to_bin_sum(bin_sums:list, bin_index:int, input:int): """ Adds the given input integer to bin #bin_index in the given list of bins. >>> _add_input_to_bin_sum([11, 22, 33], 0, 77) (88, 22, 33) >>> _add_input_to_bin_sum([11, 22, 33], 1, 77) (11, 99, 33) >>> _add_input_to_bin_sum([11, 22, 33], 2, 77) (11, 22, 110) """ new_bin_sums = list(bin_sums) new_bin_sums[bin_index] = new_bin_sums[bin_index] + input return tuple(new_bin_sums) def _add_input_to_bin(bins:list, bin_index:int, input:int): """ Adds the given input integer to bin #bin_index in the given list of bins. >>> _add_input_to_bin([[11,22], [33,44], [55,66]], 1, 77) [[11, 22], [33, 44, 77], [55, 66]] """ new_bins = list(bins) new_bins[bin_index] = new_bins[bin_index]+[input] return new_bins if __name__=="__main__": import sys, logging dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.sequential.logger.setLevel(logging.WARNING) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests))
4,366
28.113333
118
py
dynprog
dynprog-main/examples/subset_sum.py
#!python3 """ Uses the sequential dynamic programming function to solve the subset-sum problem. The state contains a single number: the current sum. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog from dynprog.sequential import SequentialDynamicProgram from typing import * def max_value(inputs: List[int], capacity:int)->int: """ Returns the maximum sum of values from the given `inputs` list, that can fit within a bin of the given 'capacity'. >>> max_value([3,5], 2) 0 >>> max_value([3,5], 4) 3 >>> max_value([3,5], 6) 5 >>> max_value([3,5], 8) 8 >>> max_value([100,200,400,700,1100,1600,2200,2900,3700], 4005) 4000 """ return SubsetSumDP(capacity).max_value(inputs) def max_value_solution(inputs: List[int], capacity:int)->int: """ Returns the maximum sum of values from the given `inputs` list, that can fit within a bin of the given 'capacity'. >>> max_value_solution([3,5], 2) [] >>> max_value_solution([3,5], 4) [3] >>> max_value_solution([3,5], 6) [5] >>> max_value_solution([3,5], 8) [3, 5] >>> max_value_solution([100,200,400,700,1100,1600,2200,2900,3700], 4005) [100, 200, 3700] """ return SubsetSumDP(capacity).max_value_solution(inputs)[2] #### Dynamic program definition: class SubsetSumDP(SequentialDynamicProgram): # The state contains a single number: the current sum. def __init__(self, capacity:int): self.capacity = capacity def initial_states(self): return [0] def initial_solution(self): return [] def transition_functions(self): return [ lambda state,input: state+input, # adding the input lambda state,input: state+0, # not adding the input ] def construction_functions(self): return [ lambda solution,input: solution+[input], # adding the input lambda solution,_: solution, # not adding the input ] def value_function(self): return lambda state: state def filter_functions(self): return [ lambda state,input: state+input<=self.capacity, # adding the input lambda _,__: True, # not adding the input ] if __name__=="__main__": import sys, logging dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) # dynprog.logger.setLevel(logging.INFO) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests))
2,628
24.038095
118
py
dynprog
dynprog-main/examples/best_coin_picking_strategy.py
#!python3 """ Uses the generic dynamic programming function to compute an optimal strategy in a game of picking coins from a row. See here: https://www.youtube.com/watch?v=Tw1k46ywN6E, time 54:30 The states are tuples (i,j,b), where i,j are indices and b is boolean. Each pair (i,j) represents the optimal strategy for picking from the sequence i, ..., j-1. The boolean value b is "True" if it is my turn, "False" if it is the opponent's turn. NOTE: This example uses an old, function-based interface. It is better to use the new, class-based interface, in sequential.py. Programmer: Erel Segal-Halevi Since: 2021-11 """ import dynprog.sequential_func from typing import * from numbers import Number def max_value(coins: List[Number], first: bool): """ Returns the maximum value that the player can win from the given sequence of coins. `first` is true iff the current player plays first. >>> max_value([1,2,3,4], True) 6 >>> max_value([6,5,4,3,2], True) 12 >>> max_value([1,2,3,4], False) 4 >>> max_value([6,5,4,3,2], False) 8 """ num_coins = len(coins) def initial_states(): # returns (state,value) tuples for i in range(num_coins): yield ((i, i, first if num_coins % 2 == 0 else not first), 0) def neighbors( state: Tuple[int, int], value: int ): # returns (state,value) tuples ( i, j, my_turn, ) = state # indices: represent the row of coins between i and j-1. if my_turn: if i - 1 >= 0: # check the state (i-1,j) yield ((i - 1, j, False), -value) if j + 1 <= num_coins: yield ((i, j + 1, False), -value) else: if i - 1 >= 0: # check the state (i-1,j) yield ((i - 1, j, True), -value + coins[i - 1]) if j + 1 <= num_coins: yield ((i, j + 1, True), -value + coins[j]) def final_states(): yield (0, num_coins, first) value = dynprog.sequential_func.max_value( initial_states=initial_states, neighbors=neighbors, final_states=final_states, ) return value if first else -value if __name__ == "__main__": import doctest, logging dynprog.logger.addHandler(logging.StreamHandler()) dynprog.logger.setLevel(logging.WARNING) (failures, tests) = doctest.testmod(report=True) print("{} failures, {} tests".format(failures, tests))
2,485
29.317073
90
py
dynprog
dynprog-main/examples/knapsack.py
#!python3 """ Uses the sequential dynamic programming function to solve the knapsack problem. Each input contains two integers: the weight and the value. The state contains two integers: the total weight and the total value. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog from dynprog.sequential import SequentialDynamicProgram from typing import * def max_value(weights: List[int], values: List[int], capacity:int)->int: """ Returns the maximum sum of values from the given `inputs` list, that can fit within a bin of the given 'capacity'. >>> max_value([3,5], [10,20], 2) 0 >>> max_value([3,5], [10,20], 4) 10 >>> max_value([3,5], [20,10], 4) 20 >>> max_value([3,5], [10,20], 6) 20 >>> max_value([3,5], [20,10], 6) 20 >>> max_value([3,5], [10,20], 8) 30 """ return KnapsackDP(capacity).max_value(inputs=zip(weights,values)) def max_value_solution(weights: List[int], values: List[int], capacity:int)->int: """ Returns the maximum sum of values from the given `inputs` list, that can fit within a bin of the given 'capacity'. >>> max_value_solution([3,5], [10,10], 2) [] >>> max_value_solution([3,5], [10,20], 4) [(3, 10)] >>> max_value_solution([3,5], [20,10], 4) [(3, 20)] >>> max_value_solution([3,5], [10,20], 6) [(5, 20)] >>> max_value_solution([3,5], [20,10], 6) [(3, 20)] >>> max_value_solution([3,5], [10,20], 8) [(3, 10), (5, 20)] """ return KnapsackDP(capacity).max_value_solution(inputs=zip(weights,values))[2] #### Dynamic program definition: class KnapsackDP(SequentialDynamicProgram): # The state contains two numbers: (weight,value). def __init__(self, capacity:int): self.capacity = capacity def initial_states(self): return [(0,0)] def initial_solution(self): return [] def transition_functions(self): return [ lambda state,input: (state[0]+input[0], state[1]+input[1]), # adding the input lambda state,input: state, # not adding the input ] def construction_functions(self): return [ lambda solution,input: solution+[input], # adding the input lambda solution,_: solution, # not adding the input ] def value_function(self): return lambda state: state[1] # the state is: (weight,value) def filter_functions(self): return [ lambda state,input: state[0]+input[0]<=self.capacity, # adding the input: (weight,value) lambda _,__: True, # not adding the input ] if __name__=="__main__": import sys, logging dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.sequential.logger.setLevel(logging.WARNING) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests))
3,046
26.7
118
py
dynprog
dynprog-main/examples/longest_palyndrome_subsequence.py
#!python3 """ Uses the generic dynamic programming function to solve the Longest Palyndrome Subsequence problem. See here: https://www.youtube.com/watch?v=Tw1k46ywN6E The states are pairs (i,j), where i,j are indices. Each pair (i,j) represents the longest palyndromic subsequence in the substring i, i+1, ..., j-1. Programmer: Erel Segal-Halevi Since: 2021-11 """ import dynprog.sequential_func from typing import * def LPS_length(string: str): """ Returns the length of the longest palyndromic subsequence in the given string. Does *not* return the string itself - see below. >>> LPS_length("a") 1 >>> LPS_length("bb") 2 >>> LPS_length("abcdba") 5 >>> LPS_length("programming") 4 """ lenstr = len(string) def initial_states(): # returns (state,value) tuples for i in range(lenstr): yield ((i, i + 1), 1) for i in range(lenstr): yield ((i, i), 0) def neighbors( state: Tuple[int, int], value: int ): # returns (state,value) tuples (i, j) = state # indices: represent the string between i and j-1. if ( i > 0 and j < lenstr and string[i - 1] == string[j] ): # add two letters to the palyndrome yield ((i - 1, j + 1), value + 2) else: # add one letter in each side of the string, without extending the palyndrome if i > 0: yield ((i - 1, j), value) if j < lenstr: yield ((i, j + 1), value) def final_states(): yield (0, lenstr) return dynprog.sequential_func.max_value( initial_states=initial_states, neighbors=neighbors, final_states=final_states, ) def LPS_string(string: str, count_states=False): """ Finds the longest palyndromic subsequence in the given string. >>> LPS_string("a") 'a' >>> LPS_string("bb") 'bb' >>> LPS_string("abcdba") 'abcba' >>> LPS_string("programming") 'gmmg' """ lenstr = len(string) def initial_states(): # returns (state,value,data) tuples for i in range(lenstr): yield ((i, i + 1), 1, string[i]) for i in range(lenstr): yield ((i, i), 0, "") def neighbors( state: Tuple[int, int], value: int, data: str ): # returns (state,value,data) tuples (i, j) = state # indices: represent the string between i and j-1. if ( i > 0 and j < lenstr and string[i - 1] == string[j] ): # add two letters to the palyndrome yield ((i - 1, j + 1), value + 2, string[i - 1] + data + string[j]) else: # add one letter in each side of the string, without extending the palyndrome if i > 0: yield ((i - 1, j), value, data) if j < lenstr: yield ((i, j + 1), value, data) def final_states(): yield (0, lenstr) ( state, value, data, num_of_states, ) = dynprog.sequential_func.max_value_solution( initial_states=initial_states, neighbors=neighbors, final_states=final_states, ) return (state, value, data, num_of_states) if count_states else data if __name__ == "__main__": import logging, doctest dynprog.logger.addHandler(logging.StreamHandler()) dynprog.logger.setLevel(logging.WARNING) (failures, tests) = doctest.testmod(report=True) print("{} failures, {} tests".format(failures, tests)) dynprog.logger.setLevel(logging.INFO) print(LPS_length("programming")) print(LPS_string("programming")) print(LPS_string("programming", count_states=True))
3,693
27.635659
97
py
dynprog
dynprog-main/examples/allocations/max_min_partition.py
#!python3 """ Uses the sequential dynamic programming function to solve the max-min number partitioning problem. The states are of the form (v1, v2, ..., vn) where n is the number of bins. The "vi" is the current sum in bin i. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog from dynprog.sequential import SequentialDynamicProgram from typing import * from common import add_input_to_bin_sum, add_input_to_bin def max_min_value(items:List[int], num_of_bins:int): """ Returns the max-min value - does *not* return the partition itself. >>> max_min_value([1,2,3,4], 2) 5 >>> max_min_value([1,2,3,4,5], 2) 7 >>> max_min_value([11,22,33,44,55,66,77,88,99], 3) 165 """ return PartitionDP(num_of_bins).max_value(items) def max_min_partition(items:list, num_of_bins:int): """ Returns the max-min partition. >>> max_min_partition([1,2,3,4], 2) (5, [[1, 4], [2, 3]]) >>> max_min_partition([1,2,3,4,5], 2) (7, [[3, 5], [1, 2, 4]]) >>> max_min_partition([11,22,33,44,55,66,77,88,99], 3) (165, [[66, 99], [77, 88], [11, 22, 33, 44, 55]]) """ (best_state,best_value,best_solution,num_of_states) = PartitionDP(num_of_bins).max_value_solution(items) return (best_value,best_solution) #### Dynamic program definition: class PartitionDP(SequentialDynamicProgram): # The states are of the form (v1, v2, ..., vn) where n is the number of bins. # The "vi" is the current sum in bin i. def __init__(self, num_of_bins:int): self.num_of_bins = num_of_bins def initial_states(self): zero_values = self.num_of_bins*(0,) return {zero_values} def initial_solution(self): empty_bundles = [ [] for _ in range(self.num_of_bins)] return empty_bundles def transition_functions(self): return [ lambda state, input, bin_index=bin_index: add_input_to_bin_sum(state, bin_index, input) for bin_index in range(self.num_of_bins) ] def construction_functions(self): return [ lambda solution,input,bin_index=bin_index: add_input_to_bin(solution, bin_index, input) for bin_index in range(self.num_of_bins) ] def value_function(self): return lambda state: min(state) if __name__=="__main__": import sys, logging dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.sequential.logger.setLevel(logging.WARNING) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests)) dynprog.sequential.logger.setLevel(logging.INFO) print(max_min_value(5*[11]+5*[23], 2)) print(max_min_partition(5*[11]+5*[23], 2)) # Number of states should be around 100.
2,823
25.392523
108
py
dynprog
dynprog-main/examples/allocations/utilitarian_proportional_allocation.py
#!python3 """ Uses the sequential dynamic programming function to find a proportional allocation of items to agents with different valuations, with a largest sum of utilities (utilitarian value). The input is a valuation-matrix v, where v[i][j] is the value of agent i to item j. The states are of the form (v1, v2, ..., vn) where n is the number of agents. The "vi" are the value of bundle i to agent i. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog from dynprog.sequential import SequentialDynamicProgram import math, logging from typing import * from common import add_input_to_agent_value, add_input_to_bin, items_as_value_vectors logger = logging.getLogger(__name__) def utilitarian_proportional_value(valuation_matrix): """ Returns the maximum utilitarian value in a proportional allocation - does *not* return the partition itself. Returns -inf if there is no proportional allocation. >>> dynprog.sequential.logger.setLevel(logging.WARNING) >>> logger.setLevel(logging.WARNING) >>> utilitarian_proportional_value([[11,0,11],[33,44,55]]) 110 >>> utilitarian_proportional_value([[11,22,33,44],[44,33,22,11]]) 154 >>> utilitarian_proportional_value([[11,0,11,11],[0,11,11,11],[33,33,33,33]]) 88 >>> utilitarian_proportional_value([[11],[22]]) # no proportional allocation -inf """ items = items_as_value_vectors(valuation_matrix) return PartitionDP(valuation_matrix).max_value(items) def utilitarian_proportional_allocation(valuation_matrix): """ Returns the utilitarian-maximum proportional allocation and its utilitarian value. Raises an exception if there is no proportional allocation. >>> dynprog.sequential.logger.setLevel(logging.WARNING) >>> utilitarian_proportional_allocation([[11,0,11],[0,11,22]]) (44, [[0], [1, 2]]) >>> utilitarian_proportional_allocation([[11,22,33,44],[44,33,22,11]]) (154, [[2, 3], [0, 1]]) >>> utilitarian_proportional_allocation([[11,0,11,11],[0,11,11,11],[33,33,33,33]])[0] 88 >>> utilitarian_proportional_allocation([[11],[11]]) Traceback (most recent call last): ... ValueError: No proportional allocation >>> utilitarian_proportional_allocation([[37,20,34,12,71,17,55,97,79],[57,5,59,63,92,23,4,36,69],[16,3,41,42,68,47,60,39,17]]) (556, [[1, 7, 8], [0, 3, 4], [2, 5, 6]]) """ items = items_as_value_vectors(valuation_matrix) (best_state,best_value,best_solution,num_of_states) = PartitionDP(valuation_matrix).max_value_solution(items) if best_value==-math.inf: raise ValueError("No proportional allocation") return (best_value,best_solution) #### Dynamic program definition: class PartitionDP(SequentialDynamicProgram): # The states are of the form (v1, v2, ..., vn) where n is the number of agents. # The "vi" are the value of bundle i to agent i. def __init__(self, valuation_matrix): num_of_agents = self.num_of_agents = len(valuation_matrix) self.thresholds = [sum(valuation_matrix[i])/num_of_agents for i in range(num_of_agents)] def initial_states(self): zero_values = self.num_of_agents*(0,) return {zero_values} def initial_solution(self): empty_bundles = [ [] for _ in range(self.num_of_agents)] return empty_bundles def transition_functions(self): return [ lambda state, input, agent_index=agent_index: add_input_to_agent_value(state, agent_index, input) for agent_index in range(self.num_of_agents) ] def construction_functions(self): return [ lambda solution,input,agent_index=agent_index: add_input_to_bin(solution, agent_index, input[-1]) for agent_index in range(self.num_of_agents) ] def value_function(self): return lambda state: sum(state) if self._is_proportional(state) else -math.inf def _is_proportional(self, bundle_values:list)->bool: return all([bundle_values[i] >= self.thresholds[i] for i in range(self.num_of_agents)]) if __name__=="__main__": import sys dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.sequential.logger.setLevel(logging.WARNING) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.WARNING) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests)) dynprog.sequential.logger.setLevel(logging.INFO) import numpy as np valuation_matrix = np.random.randint(0,9, [3,10]) print("valuation_matrix:\n",valuation_matrix) print(utilitarian_proportional_value(valuation_matrix)) print(utilitarian_proportional_allocation(valuation_matrix)) # should have about 20k states.
4,823
36.107692
130
py
dynprog
dynprog-main/examples/allocations/utilitarian_prop1_allocation.py
#!python3 """ Uses the sequential dynamic programming function to find a PROP1 or PROPx allocation of items to agents with different valuations, with a largest sum of utilities (utilitarian value). The input is a valuation-matrix v, where v[i][j] is the value of agent i to item j. The states are of the form (v1, v2, ..., vn; b1, b2, ..., bn) where n is the number of agents. The "vi" are the value of bundle i to agent i. The "bi" are the largest value for i of an item allocated to others. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog from dynprog.sequential import SequentialDynamicProgram import math, logging from typing import * from common import add_input_to_agent_value, add_input_to_bin, items_as_value_vectors logger = logging.getLogger(__name__) def utilitarian_prop1_value(valuation_matrix, propx=False): """ Returns the maximum utilitarian value in a PROP1 allocation - does *not* return the partition itself. >>> utilitarian_prop1_value([[11,0,11],[33,44,55]]) 132 >>> utilitarian_prop1_value([[11,0,11],[33,44,55]],propx=True) 110 >>> utilitarian_prop1_value([[11,22,33,44],[44,33,22,11]]) 154 >>> utilitarian_prop1_value([[11,22,33,44],[44,33,22,11]],propx=True) 154 >>> utilitarian_prop1_value([[11,0,11,11],[0,11,11,11],[33,33,33,33]]) 132 >>> utilitarian_prop1_value([[11,0,11,11],[0,11,11,11],[33,33,33,33]],propx=True) 88 >>> utilitarian_prop1_value([[11],[22]]) 22 >>> utilitarian_prop1_value([[11],[22]],propx=True) 22 """ items = items_as_value_vectors(valuation_matrix) return PartitionDP(valuation_matrix, propx).max_value(items) def utilitarian_prop1_allocation(valuation_matrix, propx=False): """ Returns the utilitarian-maximum PROP1 allocation and its utilitarian value. >>> dynprog.sequential.logger.setLevel(logging.WARNING) >>> utilitarian_prop1_allocation([[11,0,11],[33,44,55]]) (132, [[], [0, 1, 2]]) >>> utilitarian_prop1_allocation([[11,0,11],[33,44,55]], propx=True) (110, [[0], [1, 2]]) >>> utilitarian_prop1_allocation([[11,22,33,44],[44,33,22,11]]) (154, [[2, 3], [0, 1]]) >>> utilitarian_prop1_allocation([[11,22,33,44],[44,33,22,11]], propx=True) (154, [[2, 3], [0, 1]]) >>> utilitarian_prop1_allocation([[11,0,11,11],[0,11,11,11],[33,33,33,33]]) (132, [[], [], [0, 1, 2, 3]]) >>> utilitarian_prop1_allocation([[11,0,11,11],[0,11,11,11],[33,33,33,33]], propx=True) (88, [[3], [2], [0, 1]]) >>> utilitarian_prop1_allocation([[11],[22]]) (22, [[], [0]]) >>> utilitarian_prop1_allocation([[11],[22]], propx=True) (22, [[], [0]]) >>> utilitarian_prop1_allocation([[37,20,34,12,71,17,55,97,79],[57,5,59,63,92,23,4,36,69],[16,3,41,42,68,47,60,39,17]]) (574, [[1, 7, 8], [0, 2, 3, 4], [5, 6]]) >>> utilitarian_prop1_allocation([[37,20,34,12,71,17,55,97,79],[57,5,59,63,92,23,4,36,69],[16,3,41,42,68,47,60,39,17]], propx=True) (557, [[7, 8], [0, 2, 3, 4], [1, 5, 6]]) """ items = items_as_value_vectors(valuation_matrix) (best_state,best_value,best_solution,num_of_states) = PartitionDP(valuation_matrix, propx).max_value_solution(items) if best_value==-math.inf: raise ValueError("No proportional allocation") return (best_value,best_solution) #### Dynamic program definition: class PartitionDP(SequentialDynamicProgram): # The states are of the form (v1, v2, ..., vn; b1, b2, ..., bn) where n is the number of agents. # The "vi" are the value of bundle i to agent i. # The "bi" are the largest value for i of an item allocated to others. def __init__(self, valuation_matrix, propx=False): num_of_agents = self.num_of_agents = len(valuation_matrix) self.thresholds = [sum(valuation_matrix[i])/num_of_agents for i in range(num_of_agents)] self.valuation_matrix = valuation_matrix self.propx = propx def initial_states(self): zero_values = self.num_of_agents*(0,) initial_value_to_remove = math.inf if self.propx else 0 largest_value_owned_by_others = self.num_of_agents*(initial_value_to_remove,) yield (zero_values, largest_value_owned_by_others) def initial_solution(self): empty_bundles = [ [] for _ in range(self.num_of_agents)] return empty_bundles def transition_functions(self): return [ lambda state, input, agent_index=agent_index: \ (add_input_to_agent_value(state[0], agent_index, input) , \ _update_value_owned_by_others(state[1], agent_index, input[-1], self.valuation_matrix, self.propx) ) for agent_index in range(self.num_of_agents) ] def construction_functions(self): return [ lambda solution,input,agent_index=agent_index: add_input_to_bin(solution, agent_index, input[-1]) for agent_index in range(self.num_of_agents) ] def value_function(self): return lambda state: sum(state[0]) if self._is_prop1(state[0], state[1]) else -math.inf def _is_prop1(self, bundle_values:list,largest_value_owned_by_others:list)->bool: return all([bundle_values[i] + largest_value_owned_by_others[i] >= self.thresholds[i] for i in range(self.num_of_agents)]) def _update_value_owned_by_others(largest_value_owned_by_others:list, agent_index:int, item_index:int, valuation_matrix, propx=False): """ :param input: a list of values: input[i] represents the value of the current item for agent i. Adds the given item to agent #agent_index. >>> _update_value_owned_by_others([33, 44, 66], 0, 0, [[55,66,77],[88,99,11],[22,33,44]]) (33, 88, 66) """ logger.info(largest_value_owned_by_others) new_largest_value_owned_by_others = list(largest_value_owned_by_others) num_of_agents = len(largest_value_owned_by_others) for other_agent_index in range(num_of_agents): if other_agent_index!=agent_index: other_agent_value = valuation_matrix[other_agent_index][item_index] if propx: should_replace_item = other_agent_value < new_largest_value_owned_by_others[other_agent_index] else: # prop1 should_replace_item = other_agent_value > new_largest_value_owned_by_others[other_agent_index] if should_replace_item: new_largest_value_owned_by_others[other_agent_index] = other_agent_value return tuple(new_largest_value_owned_by_others) if __name__=="__main__": import sys dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.sequential.logger.setLevel(logging.WARNING) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.WARNING) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests)) dynprog.sequential.logger.setLevel(logging.WARNING) import numpy as np valuation_matrix = np.random.randint(0,99, [3,7]) # ~ 3000 states print("Valuation matrix:\n",valuation_matrix) # print("Utilitarian PROP1 value:",utilitarian_prop1_value(valuation_matrix)) print("Utilitarian PROP1 allocation:",utilitarian_prop1_allocation(valuation_matrix)) # print("Utilitarian PROPx value:",utilitarian_prop1_value(valuation_matrix,propx=True)) print("Utilitarian PROPx allocation:",utilitarian_prop1_allocation(valuation_matrix,propx=True))
7,490
39.934426
135
py
dynprog
dynprog-main/examples/allocations/utilitarian_envyfree_allocation.py
#!python3 """ Uses the sequential dynamic programming function to find an envy-free allocation of items to agents with different valuations, with a largest sum of utilities (utilitarian value). The input is a valuation-matrix v, where v[i][j] is the value of agent i to item j. The states are the bundle-differences: (d11, d12, ..., dnn) where n is the number of agents. where dij := vi(Ai)-vi(Aj). Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog, math, logging from dynprog.sequential import SequentialDynamicProgram from common import add_input_to_bin, items_as_value_vectors from typing import * logger = logging.getLogger(__name__) def utilitarian_envyfree_value(valuation_matrix): """ Returns the maximum utilitarian value in an envy-free allocation - does *not* return the allocation itself. Returns -inf if there is no envy-free allocation. >>> logger.setLevel(logging.INFO) >>> dynprog.sequential.logger.setLevel(logging.INFO) >>> utilitarian_envyfree_value([[11,0,11],[33,44,55]]) 110.0 >>> logger.setLevel(logging.WARNING) >>> dynprog.sequential.logger.setLevel(logging.WARNING) >>> utilitarian_envyfree_value([[11,22,33,44],[44,33,22,11]]) 154.0 >>> utilitarian_envyfree_value([[11,0,11,11],[0,11,11,11],[33,33,33,33]]) 88.0 >>> utilitarian_envyfree_value([[11],[22]]) # no envy-free allocation -inf """ items = items_as_value_vectors(valuation_matrix) return PartitionDP(valuation_matrix).max_value(items) #### Dynamic program definition: class PartitionDP(SequentialDynamicProgram): # The states are the bundle-differences: (d11, d12, ..., dnn) where n is the number of agents. # where dij := vi(Ai)-vi(Aj). def __init__(self, valuation_matrix): self.num_of_agents = len(valuation_matrix) self.valuation_matrix = valuation_matrix self.sum_valuation_matrix = sum(map(sum,valuation_matrix)) def initial_states(self): zero_differences = self.num_of_agents * (self.num_of_agents*(0,),) return {zero_differences} def initial_solution(self): empty_bundles = [ [] for _ in range(self.num_of_agents)] return empty_bundles def transition_functions(self): return [ lambda state, input, agent_index=agent_index: _update_bundle_differences(state, agent_index, input) for agent_index in range(self.num_of_agents) ] def construction_functions(self): return [ lambda solution,input,agent_index=agent_index: add_input_to_bin(solution, agent_index, input[-1]) for agent_index in range(self.num_of_agents) ] def value_function(self): return lambda state: (sum(map(sum,state))+self.sum_valuation_matrix) / self.num_of_agents if self._is_envyfree(state) else -math.inf def _is_envyfree(self, bundle_differences:list)->bool: return all([bundle_differences[i][j]>=0 for i in range(self.num_of_agents) for j in range(self.num_of_agents)]) def _update_bundle_differences(bundle_differences, agent_index, item_values): """ >>> _update_bundle_differences( ((0,0),(0,0)), 0, [11,33,0] ) ((0, 11), (-33, 0)) >>> _update_bundle_differences( ((0,0),(0,0)), 1, [11,33,0] ) ((0, -11), (33, 0)) """ num_of_agents = len(bundle_differences) new_bundle_differences = [list(d) for d in bundle_differences] for other_agent_index in range(num_of_agents): if other_agent_index==agent_index: continue new_bundle_differences[agent_index][other_agent_index] += item_values[agent_index] new_bundle_differences[other_agent_index][agent_index] -= item_values[other_agent_index] new_bundle_differences = tuple((tuple(d) for d in new_bundle_differences)) return new_bundle_differences if __name__=="__main__": import sys dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.sequential.logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.INFO) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests)) dynprog.general.logger.setLevel(logging.WARNING) import numpy as np valuation_matrix = np.random.randint(0,99, [3,9]) print("valuation_matrix:\n",valuation_matrix) print(utilitarian_envyfree_value(valuation_matrix))
4,463
35
140
py
dynprog
dynprog-main/examples/allocations/common.py
#!python3 """ Common routines for dynamic programs finding fair allocations. """ def items_as_value_vectors(valuation_matrix): """ Convert a valuation matrix (an input to a fair division algorithm) into a list of value-vectors. Each value-vector v represents an item: v[i] is the value of the item for agent i (i = 0,...,n-1). The last element, v[n], is the item index. >>> items_as_value_vectors([[11,22,33],[44,55,66]]) [[11, 44, 0], [22, 55, 1], [33, 66, 2]] """ num_of_agents = len(valuation_matrix) num_of_items = len(valuation_matrix[0]) return [ # Each item is represented by a vector of values - a value for each agent. The last value is the item index. [valuation_matrix[agent_index][item_index] for agent_index in range(num_of_agents)] + [item_index] for item_index in range(num_of_items) ] def add_input_to_bin_sum(bin_sums:list, bin_index:int, input:int): """ Adds the given input integer to bin #bin_index in the given list of bins. >>> add_input_to_bin_sum([11, 22, 33], 0, 77) (88, 22, 33) >>> add_input_to_bin_sum([11, 22, 33], 1, 77) (11, 99, 33) >>> add_input_to_bin_sum([11, 22, 33], 2, 77) (11, 22, 110) """ new_bin_sums = list(bin_sums) new_bin_sums[bin_index] = new_bin_sums[bin_index] + input return tuple(new_bin_sums) def add_input_to_agent_value(agent_values:list, agent_index:int, item_values:list): """ Update the state of a dynamic program by giving an item to a specific agent. :param agent_values: the current vector of agent values, before adding the new item. :param agent_index: the agent to which the item is given. :param item_values: a list of values: input[i] represents the value of the current item for agent i. >>> add_input_to_agent_value([11, 22, 33], 0, [55,66,77,1]) (66, 22, 33) >>> add_input_to_agent_value([11, 22, 33], 1, [55,66,77,1]) (11, 88, 33) >>> add_input_to_agent_value([11, 22, 33], 2, [55,66,77,1]) (11, 22, 110) """ return add_input_to_bin_sum(agent_values, agent_index, item_values[agent_index]) def add_input_to_bin(bins:list, agent_index:int, item_index:int): """ Update the solution of a dynamic program by giving an item to a specific agent. :param bins: the current vector of agent bundles, before adding the new item. :param agent_index: the agent to which the item is given. :param item_index: the index of the given item. Adds the given input integer to bin #agent_index in the given list of bins. >>> add_input_to_bin([[11,22], [33,44], [55,66]], 1, 1) [[11, 22], [33, 44, 1], [55, 66]] """ new_bins = list(bins) new_bins[agent_index] = new_bins[agent_index]+[item_index] return new_bins if __name__=="__main__": import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests))
2,950
34.987805
122
py
dynprog
dynprog-main/examples/allocations/utilitarian_ef1_allocation.py
#!python3 """ Uses the sequential dynamic programming function to find an EF1/EFx allocation of items to agents with different valuations, with a largest sum of utilities (utilitarian value). The input is a valuation-matrix v, where v[i][j] is the value of agent i to item j. The states are of the form (d11, d12, ..., dnn; b11, b12, ..., bnn) where n is the number of agents. where dij := vi(Ai)-vi(Aj). and bij is the largest value for i of an item allocated to j. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog, math, logging from typing import * from dynprog.sequential import SequentialDynamicProgram from common import ( add_input_to_agent_value, add_input_to_bin, items_as_value_vectors, ) logger = logging.getLogger(__name__) def utilitarian_ef1_value(valuation_matrix, efx=False): """ Returns the maximum utilitarian value in a ef1 allocation - does *not* return the partition itself. >>> dynprog.logger.setLevel(logging.WARNING) >>> utilitarian_ef1_value([[11,0,11],[33,44,55]]) 110.0 >>> utilitarian_ef1_value([[11,0,11],[33,44,55]],efx=True) 110.0 >>> utilitarian_ef1_value([[11,22,33,44],[44,33,22,11]]) 154.0 >>> utilitarian_ef1_value([[11,22,33,44],[44,33,22,11]],efx=True) 154.0 >>> utilitarian_ef1_value([[11,0,11,11],[0,11,11,11],[33,33,33,33]]) 88.0 >>> utilitarian_ef1_value([[11,0,11,11],[0,11,11,11],[33,33,33,33]],efx=True) 88.0 >>> utilitarian_ef1_value([[11],[22]]) 22.0 >>> utilitarian_ef1_value([[11],[22]],efx=True) 22.0 >>> utilitarian_ef1_value([[98,91,29,50,76,94],[43,67,93,35,49,12],[45,10,62,47,82,60]]) 505.0 >>> utilitarian_ef1_value([[98,91,29,50,76,94],[43,67,93,35,49,12],[45,10,62,47,82,60]],efx=True) 481.0 """ items = items_as_value_vectors(valuation_matrix) return PartitionDP(valuation_matrix, efx).max_value(items) #### Dynamic program definition: class PartitionDP(SequentialDynamicProgram): # The states are of the form (d11, d12, ..., dnn; b11, b12, ..., bnn) where n is the number of agents. # where dij := vi(Ai)-vi(Aj). # and bij is the largest value for i of an item allocated to j. def __init__(self, valuation_matrix, efx=False): num_of_agents = self.num_of_agents = len(valuation_matrix) self.thresholds = [ sum(valuation_matrix[i]) / num_of_agents for i in range(num_of_agents) ] self.valuation_matrix = valuation_matrix self.sum_valuation_matrix = sum(map(sum, valuation_matrix)) self.efx = efx def initial_states(self): zero_differences = self.num_of_agents * (self.num_of_agents * (0,),) # print("zero_differences",zero_differences) initial_value_to_remove = math.inf if self.efx else 0 largest_value_owned_by_others = self.num_of_agents * ( self.num_of_agents * (initial_value_to_remove,), ) return {(zero_differences, largest_value_owned_by_others)} def initial_solution(self): empty_bundles = [[] for _ in range(self.num_of_agents)] return empty_bundles def transition_functions(self): return [ lambda state, input, agent_index=agent_index: ( _update_bundle_differences(state[0], agent_index, input), _update_value_owned_by_others( state[1], agent_index, input[-1], self.valuation_matrix, self.efx, ), ) for agent_index in range(self.num_of_agents) ] def construction_functions(self): return [ lambda solution, input, agent_index=agent_index: add_input_to_bin( solution, agent_index, input[-1] ) for agent_index in range(self.num_of_agents) ] def value_function(self): return ( lambda state: (sum(map(sum, state[0])) + self.sum_valuation_matrix) / self.num_of_agents if self._is_ef1(state[0], state[1]) else -math.inf ) def _is_ef1( self, bundle_differences: list, largest_value_owned_by_others: list ) -> bool: return all( [ bundle_differences[i][j] + largest_value_owned_by_others[i][j] >= 0 for i in range(self.num_of_agents) for j in range(self.num_of_agents) ] ) def _update_bundle_differences(bundle_differences, agent_index, item_values): """ >>> _update_bundle_differences( ((0,0),(0,0)), 0, [11,33,0] ) ((0, 11), (-33, 0)) >>> _update_bundle_differences( ((0,0),(0,0)), 1, [11,33,0] ) ((0, -11), (33, 0)) """ # print("bundle_differences",bundle_differences) num_of_agents = len(bundle_differences) new_bundle_differences = [list(d) for d in bundle_differences] for other_agent_index in range(num_of_agents): if other_agent_index == agent_index: continue new_bundle_differences[agent_index][other_agent_index] += item_values[ agent_index ] new_bundle_differences[other_agent_index][agent_index] -= item_values[ other_agent_index ] new_bundle_differences = tuple((tuple(d) for d in new_bundle_differences)) return new_bundle_differences def _update_value_owned_by_others( largest_value_owned_by_others: list, agent_index: int, item_index: int, valuation_matrix, efx=False, ): """ Update the matrix of largest-value-owned-by-others when the item #item_index is given to the agent #agent_index. >>> _update_value_owned_by_others([[0,0,0],[0,0,0],[0,0,0]], 0, 0, [[55,66,77],[88,99,11],[22,33,44]]) ((0, 0, 0), (88, 0, 0), (22, 0, 0)) >>> _update_value_owned_by_others([[0,20,30],[40,0,60],[70,80,0]], 0, 0, [[55,66,77],[88,99,11],[22,33,44]]) ((0, 20, 30), (88, 0, 60), (70, 80, 0)) """ num_of_agents = len(largest_value_owned_by_others) new_largest_value_owned_by_others = [ list(d) for d in largest_value_owned_by_others ] for other_agent_index in range(num_of_agents): if other_agent_index == agent_index: continue other_agent_value = valuation_matrix[other_agent_index][item_index] if efx: replace_item = ( other_agent_value < new_largest_value_owned_by_others[other_agent_index][ agent_index ] ) else: # ef1 replace_item = ( other_agent_value > new_largest_value_owned_by_others[other_agent_index][ agent_index ] ) if replace_item: new_largest_value_owned_by_others[other_agent_index][ agent_index ] = other_agent_value new_largest_value_owned_by_others = tuple( (tuple(d) for d in new_largest_value_owned_by_others) ) return new_largest_value_owned_by_others if __name__ == "__main__": import sys, doctest, random dynprog.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.logger.setLevel(logging.WARNING) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.WARNING) (failures, tests) = doctest.testmod(report=True) print("{} failures, {} tests".format(failures, tests)) dynprog.logger.setLevel(logging.INFO) valuation_matrix = [ [random.randint(0, 9) for _ in range(10)] for _ in range(3) ] # ~ 80k states print("valuation_matrix:\n", valuation_matrix) print("Utilitarian within EF1: ", utilitarian_ef1_value(valuation_matrix)) print( "Utilitarian within EFx: ", utilitarian_ef1_value(valuation_matrix, efx=True), )
7,910
33.697368
112
py
dynprog
dynprog-main/examples/allocations/egalitarian_allocation.py
#!python3 """ Uses the sequential dynamic programming function to find an egalitarian (max-min) allocation of items to agents with different valuations. This is a generalization of max_min_partition.py. The input is a valuation-matrix v, where v[i][j] is the value of agent i to item j. The states are of the form (v1, v2, ..., vn) where n is the number of agents. The "vi" are the value of bundle i to agent i. Programmer: Erel Segal-Halevi Since: 2021-12 """ import dynprog from dynprog.sequential import SequentialDynamicProgram from typing import * from common import add_input_to_bin, add_input_to_agent_value def egalitarian_value(valuation_matrix): """ Returns the max-min value - does *not* return the partition itself. >>> egalitarian_value([[11,22,33,44],[11,22,33,44]]) 55 >>> egalitarian_value([[11,22,33,44],[44,33,22,11]]) 77 >>> #dynprog.logger.setLevel(logging.INFO) >>> egalitarian_value([[11,22,33,44,55],[44,33,22,11,55],[55,66,77,88,99]]) 77 >>> egalitarian_value([[37,93,0,49,52,59,97,24,90],[62,21,31,27,67,29,24,65,47],[4,57,27,36,65,27,50,46,92]]) 187 """ num_of_agents = len(valuation_matrix) items = _items_as_value_vectors(valuation_matrix) return EgalitarianDP(num_of_agents).max_value(items) def egalitarian_allocation(valuation_matrix): """ Returns the max-min value and allocation >>> egalitarian_allocation([[11,22,33,44],[11,22,33,44]]) (55, [[0, 3], [1, 2]]) >>> egalitarian_allocation([[11,22,33,44],[44,33,22,11]]) (77, [[2, 3], [0, 1]]) >>> egalitarian_allocation([[11,22,33,44,55],[44,33,22,11,55],[55,66,77,88,99]]) (77, [[2, 3], [0, 1], [4]]) >>> egalitarian_allocation([[37,93,0,49,52,59,97,24,90],[62,21,31,27,67,29,24,65,47],[4,57,27,36,65,27,50,46,92]]) (187, [[1, 6], [0, 2, 5, 7], [3, 4, 8]]) """ num_of_agents = len(valuation_matrix) items = _items_as_value_vectors(valuation_matrix) (best_state,best_value,best_solution,num_of_states) = EgalitarianDP(num_of_agents).max_value_solution(items) return (best_value,best_solution) def _items_as_value_vectors(valuation_matrix): num_of_agents = len(valuation_matrix) num_of_items = len(valuation_matrix[0]) return [ # Each item is represented by a vector of values - a value for each agent. The last value is the item index. [valuation_matrix[agent_index][item_index] for agent_index in range(num_of_agents)] + [item_index] for item_index in range(num_of_items) ] #### Dynamic program definition: class EgalitarianDP(SequentialDynamicProgram): # The states are of the form (v1, v2, ..., vn) where n is the number of agents. # The "vi" are the value of bundle i to agent i. def __init__(self, num_of_agents:int): self.num_of_agents = num_of_agents def initial_states(self): zero_values = self.num_of_agents*(0,) return {zero_values} def initial_solution(self): empty_bundles = [ [] for _ in range(self.num_of_agents)] return empty_bundles def transition_functions(self): return [ lambda state, input, agent_index=agent_index: add_input_to_agent_value(state, agent_index, input) for agent_index in range(self.num_of_agents) ] def construction_functions(self): return [ lambda solution,input,agent_index=agent_index: add_input_to_bin(solution, agent_index, input[-1]) for agent_index in range(self.num_of_agents) ] def value_function(self): return lambda state: min(state) if __name__=="__main__": import sys, logging dynprog.sequential.logger.addHandler(logging.StreamHandler(sys.stdout)) dynprog.sequential.logger.setLevel(logging.WARNING) import doctest (failures,tests) = doctest.testmod(report=True) print ("{} failures, {} tests".format(failures,tests)) dynprog.sequential.logger.setLevel(logging.INFO) import numpy as np valuation_matrix = np.random.randint(0,9, [3,10]) # 3 agents, 10 items print("valuation_matrix:\n",valuation_matrix) print(egalitarian_value(valuation_matrix)) print(egalitarian_allocation(valuation_matrix)) # Should have about 30k-40k states.
4,277
31.907692
122
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/metrics.py
############################################################################### # (C) Quantum Economic Development Consortium (QED-C) 2021. # Technical Advisory Committee on Standards and Benchmarks (TAC) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################## # Metrics Module # # This module contains methods to initialize, store, aggregate and # plot metrics collected in the benchmark programs # # Metrics are indexed by group id (e.g. circuit size), circuit id (e.g. secret string) # and metric name. # Multiple metrics with different names may be stored, each with a single value. # # The 'aggregate' method accumulates all circuit-specific metrics for each group # and creates an average that may be reported and plotted across all groups # import os import json import time from time import gmtime, strftime from datetime import datetime import traceback import matplotlib.cm as cm import copy # Raw and aggregate circuit metrics circuit_metrics = { } circuit_metrics_detail = { } # for iterative algorithms circuit_metrics_detail_2 = { } # used to break down to 3rd dimension circuit_metrics_final_iter = { } # used to store final results for the last circuit in iterative algorithms. group_metrics = { "groups": [], "avg_create_times": [], "avg_elapsed_times": [], "avg_exec_times": [], "avg_fidelities": [], "avg_hf_fidelities": [], "avg_depths": [], "avg_xis": [], "avg_tr_depths": [], "avg_tr_xis": [], "avg_tr_n2qs": [], "avg_exec_creating_times": [], "avg_exec_validating_times": [], "avg_exec_running_times": [], "job_ids": [] } # Additional properties _properties = { "api":"unknown", "backend_id":"unknown"} # times relevant to an application run start_time = 0 end_time = 0 ##### Options # Print more detailed metrics info verbose = False # Option to save metrics to data file save_metrics = True # Option to save plot images (all of them) save_plot_images = True # Option to show plot images. Useful if it is desired to not show plots while running scripts show_plot_images = True # Option to generate volumetric positioning charts do_volumetric_plots = True # Option to include all app charts with vplots at end do_app_charts_with_all_metrics = False # Number of ticks on volumetric depth axis max_depth_log = 22 # Quantum Volume to display on volumetric background QV = 256 # Algorithmic Qubits (defaults) AQ = 22 aq_cutoff = 0.368 # below this circuits not considered successful aq_mode = 0 # 0 - use default plot behavior, 1 - use AQ modified plots # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # Base for volumetric plot logarithmic axes #depth_base = 1.66 # this stretches depth axis out, but other values have issues: #1) need to round to avoid duplicates, and 2) trailing zeros are getting removed depth_base = 2 # suppress plotting for low fidelity at this level suppress_low_fidelity_level = 0.015 # Get the current time formatted def get_timestr(): #timestr = strftime("%Y-%m-%d %H:%M:%S UTC", gmtime()) timestr = strftime("%b %d, %Y %H:%M:%S UTC", gmtime()) return timestr ###################################################################### ##### Initialize methods # Set a subtitle for the Chart def set_plot_subtitle (subtitle=None): circuit_metrics["subtitle"] = subtitle # Set properties context for this set of metrics def set_properties ( properties=None ): global _properties if properties == None: _properties = { "api":"unknown", "backend_id":"unknown" } else: _properties = properties ################################################## # DATA ANALYSIS - METRICS COLLECTION AND REPORTING # Initialize the metrics module, creating an empty table of metrics def init_metrics (): global start_time # create empty dictionary for circuit metrics circuit_metrics.clear() circuit_metrics_detail.clear() circuit_metrics_detail_2.clear() circuit_metrics_final_iter.clear() # create empty arrays for group metrics group_metrics["groups"] = [] group_metrics["avg_create_times"] = [] group_metrics["avg_elapsed_times"] = [] group_metrics["avg_exec_times"] = [] group_metrics["avg_fidelities"] = [] group_metrics["avg_hf_fidelities"] = [] group_metrics["avg_depths"] = [] group_metrics["avg_xis"] = [] group_metrics["avg_tr_depths"] = [] group_metrics["avg_tr_xis"] = [] group_metrics["avg_tr_n2qs"] = [] group_metrics["avg_exec_creating_times"] = [] group_metrics["avg_exec_validating_times"] = [] group_metrics["avg_exec_running_times"] = [] group_metrics["job_ids"] = [] # store the start of execution for the current app start_time = time.time() print(f'... execution starting at {get_timestr()}') # End metrics collection for an application def end_metrics(): global end_time end_time = time.time() total_run_time = round(end_time - start_time, 3) print(f'... execution complete at {get_timestr()} in {total_run_time} secs') print("") # Store an individual metric associate with a group and circuit in the group def store_metric (group, circuit, metric, value): group = str(group) circuit = str(circuit) if group not in circuit_metrics: circuit_metrics[group] = { } if circuit not in circuit_metrics[group]: circuit_metrics[group][circuit] = { } # if the value is a dict, store each metric provided if type(value) is dict: for key in value: # If you want to store multiple metrics in one go, # then simply provide these in the form of a dictionary under the value input # In this case, the metric input will be ignored store_metric(group, circuit, key, value[key]) else: circuit_metrics[group][circuit][metric] = value #print(f'{group} {circuit} {metric} -> {value}') def store_props_final_iter(group, circuit, metric, value): group = str(group) circuit = str(circuit) if group not in circuit_metrics_final_iter: circuit_metrics_final_iter[group] = {} if circuit not in circuit_metrics_final_iter[group]: circuit_metrics_final_iter[group][circuit] = { } if type(value) is dict: for key in value: store_props_final_iter(group, circuit, key, value[key]) else: circuit_metrics_final_iter[group][circuit][metric] = value # Aggregate metrics for a specific group, creating average across circuits in group def aggregate_metrics_for_group (group): group = str(group) # generate totals, then divide by number of circuits to calculate averages if group in circuit_metrics: num_circuits = 0 group_create_time = 0 group_elapsed_time = 0 group_exec_time = 0 group_fidelity = 0 group_hf_fidelity = 0 group_depth = 0 group_xi = 0 group_tr_depth = 0 group_tr_xi = 0 group_tr_n2q = 0 group_exec_creating_time = 0 group_exec_validating_time = 0 group_exec_running_time = 0 group_job_ids = [] # loop over circuits in group to generate totals for circuit in circuit_metrics[group]: num_circuits += 1 for metric in circuit_metrics[group][circuit]: value = circuit_metrics[group][circuit][metric] #print(f'{group} {circuit} {metric} -> {value}') if metric == "job_id": group_job_ids.append(value) if metric == "create_time": group_create_time += value if metric == "elapsed_time": group_elapsed_time += value if metric == "exec_time": group_exec_time += value if metric == "fidelity": group_fidelity += value if metric == "hf_fidelity": group_hf_fidelity += value if metric == "depth": group_depth += value if metric == "xi": group_xi += value if metric == "tr_depth": group_tr_depth += value if metric == "tr_xi": group_tr_xi += value if metric == "tr_n2q": group_tr_n2q += value if metric == "exec_creating_time": group_exec_creating_time += value if metric == "exec_validating_time": group_exec_validating_time += value if metric == "exec_running_time": group_exec_running_time += value # calculate averages avg_create_time = round(group_create_time / num_circuits, 3) avg_elapsed_time = round(group_elapsed_time / num_circuits, 3) avg_exec_time = round(group_exec_time / num_circuits, 3) avg_fidelity = round(group_fidelity / num_circuits, 3) avg_hf_fidelity = round(group_hf_fidelity / num_circuits, 3) avg_depth = round(group_depth / num_circuits, 0) avg_xi = round(group_xi / num_circuits, 3) avg_tr_depth = round(group_tr_depth / num_circuits, 0) avg_tr_xi = round(group_tr_xi / num_circuits, 3) avg_tr_n2q = round(group_tr_n2q / num_circuits, 3) avg_exec_creating_time = round(group_exec_creating_time / num_circuits, 3) avg_exec_validating_time = round(group_exec_validating_time / num_circuits, 3) avg_exec_running_time = round(group_exec_running_time / num_circuits, 3) # store averages in arrays structured for reporting and plotting by group group_metrics["groups"].append(group) group_metrics["job_ids"].append(group_job_ids) group_metrics["avg_create_times"].append(avg_create_time) group_metrics["avg_elapsed_times"].append(avg_elapsed_time) group_metrics["avg_exec_times"].append(avg_exec_time) group_metrics["avg_fidelities"].append(avg_fidelity) group_metrics["avg_hf_fidelities"].append(avg_hf_fidelity) # skip these if there is not a real circuit for this group if avg_depth > 0: group_metrics["avg_depths"].append(avg_depth) if avg_tr_depth > 0: group_metrics["avg_tr_depths"].append(avg_tr_depth) # any of these could be 0 and should be aggregated #if avg_xi > 0: group_metrics["avg_xis"].append(avg_xi) #if avg_tr_xi > 0: group_metrics["avg_tr_xis"].append(avg_tr_xi) #if avg_tr_n2q > 0: group_metrics["avg_tr_n2qs"].append(avg_tr_n2q) if avg_exec_creating_time > 0: group_metrics["avg_exec_creating_times"].append(avg_exec_creating_time) if avg_exec_validating_time > 0: group_metrics["avg_exec_validating_times"].append(avg_exec_validating_time) if avg_exec_running_time > 0: group_metrics["avg_exec_running_times"].append(avg_exec_running_time) # Aggregate all metrics by group def aggregate_metrics (): for group in circuit_metrics: aggregate_metrics_for_group(group) # Report metrics for a specific group def report_metrics_for_group (group): group = str(group) if group in group_metrics["groups"]: group_index = group_metrics["groups"].index(group) if group_index >= 0: avg_xi = 0 if len(group_metrics["avg_xis"]) > 0: avg_xi = group_metrics["avg_xis"][group_index] if len(group_metrics["avg_depths"]) > 0: avg_depth = group_metrics["avg_depths"][group_index] if avg_depth > 0: print(f"Average Circuit Algorithmic Depth, \u03BE (xi) for the {group} qubit group = {int(avg_depth)}, {avg_xi}") avg_tr_xi = 0 if len(group_metrics["avg_tr_xis"]) > 0: avg_tr_xi = group_metrics["avg_tr_xis"][group_index] avg_tr_n2q = 0 if len(group_metrics["avg_tr_n2qs"]) > 0: avg_tr_n2q = group_metrics["avg_tr_n2qs"][group_index] if len(group_metrics["avg_tr_depths"]) > 0: avg_tr_depth = group_metrics["avg_tr_depths"][group_index] if avg_tr_depth > 0: print(f"Average Normalized Transpiled Depth, \u03BE (xi), 2q gates for the {group} qubit group = {int(avg_tr_depth)}, {avg_tr_xi}, {avg_tr_n2q}") avg_create_time = group_metrics["avg_create_times"][group_index] avg_elapsed_time = group_metrics["avg_elapsed_times"][group_index] avg_exec_time = group_metrics["avg_exec_times"][group_index] print(f"Average Creation, Elapsed, Execution Time for the {group} qubit group = {avg_create_time}, {avg_elapsed_time}, {avg_exec_time} secs") #if verbose: if len(group_metrics["avg_exec_creating_times"]) > 0: avg_exec_creating_time = group_metrics["avg_exec_creating_times"][group_index] #if avg_exec_creating_time > 0: #print(f"Average Creating Time for group {group} = {avg_exec_creating_time}") if len(group_metrics["avg_exec_validating_times"]) > 0: avg_exec_validating_time = group_metrics["avg_exec_validating_times"][group_index] #if avg_exec_validating_time > 0: #print(f"Average Validating Time for group {group} = {avg_exec_validating_time}") if len(group_metrics["avg_exec_running_times"]) > 0: avg_exec_running_time = group_metrics["avg_exec_running_times"][group_index] #if avg_exec_running_time > 0: #print(f"Average Running Time for group {group} = {avg_exec_running_time}") print(f"Average Transpiling, Validating, Running Times for group {group} = {avg_exec_creating_time}, {avg_exec_validating_time}, {avg_exec_running_time} secs") avg_fidelity = group_metrics["avg_fidelities"][group_index] avg_hf_fidelity = group_metrics["avg_hf_fidelities"][group_index] print(f"Average Hellinger, Normalized Fidelity for the {group} qubit group = {avg_hf_fidelity}, {avg_fidelity}") print("") return # if group metrics not found print("") print(f"no metrics for group: {group}") # Report all metrics for all groups def report_metrics (): # loop over all groups and print metrics for that group for group in circuit_metrics: report_metrics_for_group(group) # Aggregate and report on metrics for the given groups, if all circuits in group are complete def finalize_group(group, report=True): #print(f"... finalize group={group}") # loop over circuits in group to generate totals group_done = True for circuit in circuit_metrics[group]: #print(f" ... metrics = {group} {circuit} {circuit_metrics[group][circuit]}") if "elapsed_time" not in circuit_metrics[group][circuit]: group_done = False break #print(f" ... group_done = {group} {group_done}") if group_done and report: aggregate_metrics_for_group(group) print("************") report_metrics_for_group(group) # sort the group metrics (sometimes they come back out of order) sort_group_metrics() # sort the group array as integers, then all metrics relative to it def sort_group_metrics(): # get groups as integer, then sort each metric with it igroups = [int(group) for group in group_metrics["groups"]] for key in group_metrics: if key == "groups": continue xy = sorted(zip(igroups, group_metrics[key])) group_metrics[key] = [y for x, y in xy] # save the sorted group names when all done xy = sorted(zip(igroups, group_metrics["groups"])) group_metrics["groups"] = [y for x, y in xy] ###################################################### # DATA ANALYSIS - LEVEL 2 METRICS - ITERATIVE CIRCUITS # Aggregate and report on metrics for the given groups, if all circuits in group are complete (2 levels) def finalize_group_2_level(group): #print(f"... finalize group={group} 2-level") # loop over circuits in group to generate totals group_done = True for circuit in circuit_metrics[group]: #print(f" ... metrics = {group} {circuit} {circuit_metrics[group][circuit]}") if "elapsed_time" not in circuit_metrics[group][circuit]: group_done = False break #print(f" ... group_done = {group} {group_done}") if group_done: # before aggregating, perform aggregtion at 3rd level to create a single entry # for each circuit_id and a separate table of detail metrics process_circuit_metrics_2_level(group) aggregate_metrics_for_group(group) print("************") report_metrics_for_group(group) # sort the group metrics (sometimes they come back out of order) sort_group_metrics() # Process the circuit metrics to aggregate to third level by splitting circuit_id # This is used when there is a third level of iteration. The same circuit is executed multiple times # and the metrics collected are indexed by as idx1 * 1000 and idx2 # Create a circuit_metrics_detail containing all these metrics, aggregate them to circuit_metrics # Create a circuit_metrics_detail_2 that has the detail metrics aggregated to support plotting def process_circuit_metrics_2_level(num_qubits): global circuit_metrics_detail global circuit_metrics_detail_2 group = str(num_qubits) # print out what was received #jsonDataStr = json.dumps(circuit_metrics[group], indent=2).replace('\n', '\n ') #print(" ==> circuit_metrics: %s" % jsonDataStr) #print(f"... process_circuit_metrics_2_level({num_qubits})") circuit_metrics_detail[group] = circuit_metrics[group] circuit_metrics[group] = { } circuit_metrics_detail_2[group] = { } avg_fidelity = 0 total_elapsed_time = 0 total_exec_time = 0 # loop over all the collected metrics to split the index into idx1 and idx2 count = 0 for circuit_id in circuit_metrics_detail[group]: #if count == 0: print(f"... circuit_id={circuit_id}") id = int(circuit_id) idx1 = id; idx2 = -1 if id >= 1000: idx1 = int(id / 1000) idx2 = id % 1000 #print(f"... idx1, idx2={idx1} {idx2}") # if we have metrics for this (outer) circuit_id, then we need to accumulate these metrics # as they are encountered; otherwise there will just be one added the first time. # The result is that the circuit_metrics_detail dict is created, but indexed by one index (idx1 * 1000 + idx2) if idx1 in circuit_metrics[group]: last_circuit_id = str(int(circuit_id) - 1) ''' note: do not accumulate here, it is done in the plotting code circuit_metrics_detail[group][circuit_id]["elapsed_time"] += circuit_metrics_detail[group][last_circuit_id]["elapsed_time"] circuit_metrics_detail[group][circuit_id]["exec_time"] += circuit_metrics_detail[group][last_circuit_id]["exec_time"] ''' # if there are no circuit_metrics created yet for this idx1, start a detail_2 table else: circuit_metrics_detail_2[group][idx1] = { } # copy each of the detail metrics to the detail_2 dict indexed by idx1 and idx2 as they are encountered circuit_metrics_detail_2[group][idx1][idx2] = circuit_metrics_detail[group][circuit_id] # copy each detail entry to circuit_metrics_new so last one ends up there, # storing the last entry as the primary entry for this circuit id circuit_metrics[group][idx1] = circuit_metrics_detail[group][circuit_id] # at the end we have one entry in the circuit_metrics table for the group and primary circuit_id # circuit_metrics_detail_2 has all the detail metrics indexed by group, idx1 and idx2 (where idx1=circuit_id) # circuit_metrics_detail is not used, just an intermediate count += 1 # The method below is used in one form of iteration benchmark (TDB whether to retain JN) iterations_metrics = {} # Separate out metrics for final vs. intermediate circuits def process_iteration_metrics(group_id): global circuit_metrics global iterations_metrics g_id = str(group_id) iterations_metrics[g_id] = {} for iteration, data in circuit_metrics[g_id].items(): for key, value in data.items(): if iteration == '1': iterations_metrics[g_id][key] = [] iterations_metrics[g_id][key].append(value) del circuit_metrics[g_id] return iterations_metrics # convenience functions to print all circuit metrics (for debugging) def dump_json(msg, data): jsonDataStr = json.dumps(data, indent=2).replace('\n', '\n ') print(f"{msg}: {jsonDataStr}") def print_all_circuit_metrics(): dump_json(" ==> all circuit_metrics", circuit_metrics) print(f" ==> all detail 2 circuit_metrics:") for group in circuit_metrics_detail_2: for circuit_id in circuit_metrics_detail_2[group]: print(f" group {group} circuit {circuit_id}") for it in circuit_metrics_detail_2[group][circuit_id]: mets = circuit_metrics_detail_2[group][circuit_id][it] elt = round(mets["elapsed_time"], 3) ext = round(mets["exec_time"], 3) fid = round(mets["fidelity"], 3) if "fidelity" in mets else -1 opt_ext = round(mets["opt_exec_time"], 3) if "opt_exec_time" in mets else -1 print(f" iteration {it} = {elt} {ext} {fid} {opt_ext}") ############################################ # DATA ANALYSIS - FIDELITY CALCULATIONS ## Uniform distribution function commonly used def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools import numpy as np # Compute the fidelity based on Hellinger distance between two discrete probability distributions def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ # get length of random key in correct_dist to find how many qubits measured num_measured_qubits = len(list(correct_dist.keys())[0]) # ensure that all keys in counts are zero padded to this length counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts, correct_dist) # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ############################################### # METRICS UTILITY FUNCTIONS - FOR VISUALIZATION # get the min and max width over all apps in shared_data # suppress low fidelity cells if flag set def get_min_max(shared_data, suppress_low_fidelity=False): w_max = 0 w_min = 0 for app in shared_data: group_metrics = shared_data[app]["group_metrics"] w_data = group_metrics["groups"] f_data = group_metrics["avg_fidelities"] low_fidelity_count = True for i in range(len(w_data)): y = float(w_data[i]) # need this to handle rotated groups if i >= len(f_data): break # don't include in max width, the cells that reject for low fidelity f = f_data[i] if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True w_max = max(w_max, y) w_min = min(w_min, y) return w_min, w_max #determine width for AQ def get_aq_width(shared_data, w_min, w_max, fidelity_metric): AQ=w_max for app in shared_data: group_metrics = shared_data[app]["group_metrics"] w_data = group_metrics["groups"] if "avg_tr_n2qs" not in group_metrics: continue if fidelity_metric not in group_metrics: continue n2q_data = group_metrics["avg_tr_n2qs"] fidelity_data=group_metrics[fidelity_metric] while True: n2q_cutoff=AQ*AQ fail_w=[i for i in range(len(n2q_data)) if (float(n2q_data[i]) <= n2q_cutoff and float(w_data[i]) <=AQ and float(fidelity_data[i])<aq_cutoff)] if len(fail_w)==0: break AQ-=1 if AQ<w_min: AQ=0 return AQ # Get the backend_id for current set of circuits def get_backend_id(): subtitle = circuit_metrics["subtitle"] backend_id = subtitle[9:] return backend_id # Extract short app name from the title passed in by user def get_appname_from_title(suptitle): appname = suptitle[len('Benchmark Results - '):len(suptitle)] appname = appname[:appname.index(' - ')] # for creating plot image filenames replace spaces appname = appname.replace(' ', '-') return appname ############################################ # ANALYSIS AND VISUALIZATION - METRICS PLOTS import matplotlib.pyplot as plt dir_path = os.path.dirname(os.path.realpath(__file__)) maxcut_style = os.path.join(dir_path,'maxcut.mplstyle') # plt.style.use(style_file) # Plot bar charts for each metric over all groups def plot_metrics (suptitle="Circuit Width (Number of Qubits)", transform_qubit_group = False, new_qubit_group = None, filters=None, suffix="", options=None): # get backend id for this set of circuits backend_id = get_backend_id() # Extract shorter app name from the title passed in by user appname = get_appname_from_title(suptitle) # save the metrics for current application to the DATA file, one file per device if save_metrics: # If using mid-circuit transformation, convert old qubit group to new qubit group if transform_qubit_group: original_data = group_metrics["groups"] group_metrics["groups"] = new_qubit_group store_app_metrics(backend_id, circuit_metrics, group_metrics, suptitle, start_time=start_time, end_time=end_time) group_metrics["groups"] = original_data else: store_app_metrics(backend_id, circuit_metrics, group_metrics, suptitle, start_time=start_time, end_time=end_time) if len(group_metrics["groups"]) == 0: print(f"\n{suptitle}") print(f" ****** NO RESULTS ****** ") return # sort the group metrics (in case they weren't sorted when collected) sort_group_metrics() # flags for charts to show do_creates = True do_executes = True do_fidelities = True do_hf_fidelities = False do_depths = True do_2qs = False do_vbplot = True # check if we have depth metrics to show do_depths = len(group_metrics["avg_depths"]) > 0 # in AQ mode, show different metrics if aq_mode > 0: do_fidelities = True # make this True so we can compare do_depths = False do_hf_fidelities = True do_2qs = True # if filters set, adjust these flags if filters != None: if "create" not in filters: do_creates = False if "execute" not in filters: do_executes = False if "fidelity" not in filters: do_fidelities = False if "hf_fidelity" not in filters: do_hf_fidelities = False if "depth" not in filters: do_depths = False if "2q" not in filters: do_2qs = False if "vbplot" not in filters: do_vbplot = False # generate one-column figure with multiple bar charts, with shared X axis cols = 1 fig_w = 6.0 numplots = 0 if do_creates: numplots += 1 if do_executes: numplots += 1 if do_fidelities: numplots += 1 if do_depths: numplots += 1 if do_2qs: numplots += 1 rows = numplots # DEVNOTE: this calculation is based on visual assessment of results and could be refined # compute height needed to draw same height plots, no matter how many there are fig_h = 3.5 + 2.0 * (rows - 1) + 0.25 * (rows - 1) #print(fig_h) # create the figure into which plots will be placed fig, axs = plt.subplots(rows, cols, sharex=True, figsize=(fig_w, fig_h)) # append key circuit metrics info to the title fulltitle = suptitle + f"\nDevice={backend_id} {get_timestr()}" if options != None: options_str = '' for key, value in options.items(): if len(options_str) > 0: options_str += ', ' options_str += f"{key}={value}" fulltitle += f"\n{options_str}" # and add the title to the plot plt.suptitle(fulltitle) axi = 0 xaxis_set = False if rows == 1: ax = axs axs = [ax] if do_creates: if max(group_metrics["avg_create_times"]) < 0.01: axs[axi].set_ylim([0, 0.01]) axs[axi].grid(True, axis = 'y', color='silver', zorder = 0) axs[axi].bar(group_metrics["groups"], group_metrics["avg_create_times"], zorder = 3) axs[axi].set_ylabel('Avg Creation Time (sec)') if rows > 0 and not xaxis_set: axs[axi].sharex(axs[rows-1]) xaxis_set = True plt.setp(axs[axi].get_xticklabels(), visible=False) axi += 1 if do_executes: if max(group_metrics["avg_exec_times"]) < 0.1: axs[axi].set_ylim([0, 0.1]) axs[axi].grid(True, axis = 'y', color='silver', zorder = 0) axs[axi].bar(group_metrics["groups"], group_metrics["avg_exec_times"], zorder = 3) axs[axi].set_ylabel('Avg Execution Time (sec)') if rows > 0 and not xaxis_set: axs[axi].sharex(axs[rows-1]) xaxis_set = True # none of these methods of sharing the x axis gives proper effect; makes extra white space #axs[axi].sharex(axs[2]) #plt.setp(axs[axi].get_xticklabels(), visible=False) #axs[axi].set_xticklabels([]) axi += 1 if do_fidelities: axs[axi].set_ylim([0, 1.1]) axs[axi].grid(True, axis = 'y', color='silver', zorder = 0) axs[axi].bar(group_metrics["groups"], group_metrics["avg_fidelities"], zorder = 3) axs[axi].bar(group_metrics["groups"], group_metrics["avg_hf_fidelities"], 0.4, color='skyblue', alpha = 0.8, zorder = 3) axs[axi].set_ylabel('Avg Result Fidelity') if rows > 0 and not xaxis_set: axs[axi].sharex(axs[rows-1]) xaxis_set = True axs[axi].legend(['Normalized', 'Hellinger'], loc='upper right') axi += 1 if do_depths: if max(group_metrics["avg_tr_depths"]) < 20: axs[axi].set_ylim([0, 20]) axs[axi].grid(True, axis = 'y', color='silver', zorder = 0) axs[axi].bar(group_metrics["groups"], group_metrics["avg_depths"], 0.8, zorder = 3) axs[axi].bar(group_metrics["groups"], group_metrics["avg_tr_depths"], 0.5, color='C9', zorder = 3) axs[axi].set_ylabel('Circuit Depth') if rows > 0 and not xaxis_set: axs[axi].sharex(axs[rows-1]) xaxis_set = True axs[axi].legend(['Algorithmic Depth', 'Normalized Depth'], loc='upper left') axi += 1 if do_2qs: if max(group_metrics["avg_tr_n2qs"]) < 20: axs[axi].set_ylim([0, 20]) axs[axi].grid(True, axis = 'y', color='silver', zorder = 0) axs[axi].bar(group_metrics["groups"], group_metrics["avg_tr_n2qs"], 0.5, color='C9', zorder = 3) axs[axi].set_ylabel('2Q Gates') if rows > 0 and not xaxis_set: axs[axi].sharex(axs[rows-1]) xaxis_set = True axs[axi].legend(['Normalized 2Q Gates'], loc='upper left') axi += 1 # shared x axis label axs[rows - 1].set_xlabel('Circuit Width (Number of Qubits)') fig.tight_layout() # save plot image to file if save_plot_images: save_plot_image(plt, f"{appname}-metrics" + suffix, backend_id) # show the plot for user to see if show_plot_images: plt.show() ###################### Volumetric Plot suptitle = f"Volumetric Positioning - {appname}" # append key circuit metrics info to the title fulltitle = suptitle + f"\nDevice={backend_id} {get_timestr()}" if options != None: options_str = '' for key, value in options.items(): if len(options_str) > 0: options_str += ', ' options_str += f"{key}={value}" fulltitle += f"\n{options_str}" # note: if using filters, both "depth or 2qs" and "vbplot" must be set for this to draw # with some packages, like Cirq and Braket, we do not calculate depth metrics or 2qs # generate separate figure for volumetric positioning chart of depth metrics if {do_depths or do_2qs} and do_volumetric_plots and do_vbplot: w_data = group_metrics["groups"] if aq_mode > 0: d_tr_data = group_metrics["avg_tr_n2qs"] else: d_tr_data = group_metrics["avg_tr_depths"] f_data = group_metrics["avg_fidelities"] try: vplot_anno_init() max_qubits = max([int(group) for group in w_data]) if aq_mode > 0: ax = plot_volumetric_background_aq(max_qubits=max_qubits, AQ=0, depth_base=depth_base, suptitle=fulltitle, colorbar_label="Avg Result Fidelity") else: ax = plot_volumetric_background(max_qubits=max_qubits, QV=QV, depth_base=depth_base, suptitle=fulltitle, colorbar_label="Avg Result Fidelity") # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) # If using mid-circuit transformation, convert width data to singular circuit width value if transform_qubit_group: w_data = new_qubit_group group_metrics["groups"] = w_data if aq_mode > 0: plot_volumetric_data_aq(ax, w_data, d_tr_data, f_data, depth_base, fill=True, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) else: plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False) except Exception as e: print(f'ERROR: plot_metrics(), failure when creating volumetric positioning chart') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) # save plot image to file if save_plot_images: save_plot_image(plt, f"{appname}-vplot", backend_id) #display plot if show_plot_images: plt.show() # generate separate figure for volumetric positioning chart of depth metrics if aq_mode > 0 and {do_depths or do_2qs} and do_volumetric_plots and do_vbplot: w_data = group_metrics["groups"] d_tr_data = group_metrics["avg_tr_n2qs"] f_data = group_metrics["avg_hf_fidelities"] try: vplot_anno_init() max_qubits = max([int(group) for group in w_data]) ax = plot_volumetric_background_aq(max_qubits=max_qubits, AQ=0, depth_base=depth_base, suptitle=fulltitle, colorbar_label="Avg Hellinger Fidelity") # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) # If using mid-circuit transformation, convert width data to singular circuit width value if transform_qubit_group: w_data = new_qubit_group group_metrics["groups"] = w_data plot_volumetric_data_aq(ax, w_data, d_tr_data, f_data, depth_base, fill=True, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False) except Exception as e: print(f'ERROR: plot_metrics(), failure when creating volumetric positioning chart') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) # save plot image to file if save_plot_images: save_plot_image(plt, f"{appname}-vplot-hf", backend_id) #display plot if show_plot_images: plt.show() ################################################# # DEVNOTE: this function is not used, as the overlaid rectanges are not useful # Plot metrics over all groups (2) def plot_metrics_all_overlaid (shared_data, backend_id, suptitle=None, imagename="_ALL-vplot-1"): global circuit_metrics global group_metrics subtitle = circuit_metrics["subtitle"] print("Overlaid Results From All Applications") # generate separate figure for volumetric positioning chart of depth metrics try: # determine largest width for all apps w_min, w_max = get_min_max(shared_data) # allow one more in width to accommodate the merge values below max_qubits = int(w_max) + 1 #print(f"... {w_max} {max_qubits}") if aq_mode > 0: ax = plot_volumetric_background_aq(max_qubits=max_qubits, AQ=AQ, depth_base=depth_base, suptitle=suptitle, colorbar_label="Avg Hellinger Fidelity") else: ax = plot_volumetric_background(max_qubits=max_qubits, QV=QV, depth_base=depth_base, suptitle=suptitle, colorbar_label="Avg Result Fidelity") vplot_anno_init() for app in shared_data: #print(shared_data[app]) # Extract shorter app name from the title passed in by user appname = app[len('Benchmark Results - '):len(app)] appname = appname[:appname.index(' - ')] group_metrics = shared_data[app]["group_metrics"] #print(group_metrics) if len(group_metrics["groups"]) == 0: print(f"****** NO RESULTS for {appname} ****** ") continue # check if we have depth metrics do_depths = len(group_metrics["avg_depths"]) > 0 if not do_depths: continue w_data = group_metrics["groups"] d_data = group_metrics["avg_depths"] d_tr_data = group_metrics["avg_tr_depths"] if "avg_tr_n2qs" not in group_metrics: continue n2q_tr_data = group_metrics["avg_tr_n2qs"] if aq_mode > 0: if "avg_hf_fidelities" not in group_metrics: continue f_data = group_metrics["avg_hf_fidelities"] plot_volumetric_data_aq(ax, w_data, n2q_tr_data, f_data, depth_base, fill=True, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) else: f_data = group_metrics["avg_fidelities"] plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) # do annotation separately, spreading labels for readability anno_volumetric_data(ax, depth_base, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False) except Exception as e: print(f'ERROR: plot_metrics_all_overlaid(), failure when creating volumetric positioning chart') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) # save plot image file if save_plot_images: if aq_mode > 0: imagename += '-aq' save_plot_image(plt, imagename, backend_id) #display plot if show_plot_images: plt.show() ################################################# # Plot metrics over all groups (level 2), merging data from all apps into smaller cells if not is_individual def plot_metrics_all_merged (shared_data, backend_id, suptitle=None, imagename="_ALL-vplot-2", avail_qubits=0, is_individual=False, score_metric=None, max_depth=0, suppress_low_fidelity=False): global circuit_metrics global group_metrics # determine the metric to use for scoring, i.e. the color of plot items if score_metric == None: if aq_mode > 0: score_metric = "avg_hf_fidelities" else: score_metric = "avg_fidelities" # if aq_mode, force is_individual to be True (cannot blend the circles's colors) if aq_mode > 0: is_individual = True # determine the label for the colorbar if score_metric == "avg_hf_fidelities": colorbar_label="Avg Hellinger Fidelity" elif score_metric == "avg_fidelities": colorbar_label="Avg Result Fidelity" else: colorbar_label="Unknown Measure" # generate separate figure for volumetric positioning chart of depth metrics try: # determine largest width for all apps w_min, w_max = get_min_max(shared_data, suppress_low_fidelity=suppress_low_fidelity) #determine width for AQ AQ = get_aq_width(shared_data, w_min, w_max, score_metric) # allow one more in width to accommodate the merge values below max_qubits = int(w_max) + 1 # draw the appropriate background, given the AQ mode if aq_mode > 0: ax = plot_volumetric_background_aq(max_qubits=max_qubits, AQ=AQ, depth_base=depth_base, suptitle=suptitle, avail_qubits=avail_qubits, colorbar_label=colorbar_label) else: ax = plot_volumetric_background(max_qubits=max_qubits, QV=QV, depth_base=depth_base, suptitle=suptitle, avail_qubits=avail_qubits, colorbar_label=colorbar_label) # create 2D array to hold merged value arrays with gradations, one array for each qubit size # plot rectangles representing these result gradations if not is_individual: plot_merged_result_rectangles(shared_data, ax, max_qubits, w_max, score_metric=score_metric, max_depth=max_depth, suppress_low_fidelity=suppress_low_fidelity) # Now overlay depth metrics for each app with unfilled rects, to outline each circuit # if is_individual, do filled rects as there is no background fill vplot_anno_init() # Note: the following loop is required, as it creates the array of annotation points # In this merged version of plottig, we suppress the border as it is already drawn appname = None; for app in shared_data: # Extract shorter app name from the title passed in by user appname = app[len('Benchmark Results - '):len(app)] appname = appname[:appname.index(' - ')] group_metrics = shared_data[app]["group_metrics"] # check if we have depth metrics for group if len(group_metrics["groups"]) == 0: continue if len(group_metrics["avg_depths"]) == 0: continue w_data = group_metrics["groups"] d_data = group_metrics["avg_depths"] d_tr_data = group_metrics["avg_tr_depths"] if "avg_tr_n2qs" not in group_metrics: continue n2q_tr_data = group_metrics["avg_tr_n2qs"] filled = is_individual if aq_mode > 0: if score_metric not in group_metrics: continue f_data = group_metrics[score_metric] plot_volumetric_data_aq(ax, w_data, n2q_tr_data, f_data, depth_base, fill=filled, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max, max_depth=max_depth, suppress_low_fidelity=suppress_low_fidelity) else: f_data = group_metrics[score_metric] plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=filled, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max, max_depth=max_depth, suppress_low_fidelity=suppress_low_fidelity, do_border=False) if appname == None: print(f"ERROR: cannot find data file for: {backend_id}") # do annotation separately, spreading labels for readability anno_volumetric_data(ax, depth_base, label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False) except Exception as e: print(f'ERROR: plot_metrics_all_merged(), failure when creating volumetric positioning chart') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) # save plot image file if save_plot_images: if aq_mode > 0: imagename += '-aq' save_plot_image(plt, imagename, backend_id) #display plot if show_plot_images: plt.show() # Plot filled but borderless rectangles based on merged gradations of result metrics def plot_merged_result_rectangles(shared_data, ax, max_qubits, w_max, num_grads=4, score_metric=None, max_depth=0, suppress_low_fidelity=False): depth_values_merged = [] for w in range(max_qubits): depth_values_merged.append([ None ] * (num_grads * max_depth_log)) # keep an array of the borders squares' centers borders = [] # run through depth metrics for all apps, splitting cells into gradations for app in shared_data: # Extract shorter app name from the title passed in by user appname = app[len('Benchmark Results - '):len(app)] appname = appname[:appname.index(' - ')] group_metrics = shared_data[app]["group_metrics"] if len(group_metrics["groups"]) == 0: print(f"****** NO RESULTS for {appname} ****** ") continue # check if we have depth metrics do_depths = len(group_metrics["avg_depths"]) > 0 if not do_depths: continue w_data = group_metrics["groups"] d_data = group_metrics["avg_depths"] d_tr_data = group_metrics["avg_tr_depths"] if score_metric not in group_metrics: continue f_data = group_metrics[score_metric] if aq_mode > 0: if "avg_tr_n2qs" not in group_metrics: continue n2q_tr_data = group_metrics["avg_tr_n2qs"] d_tr_data = n2q_tr_data # instead of plotting data here, split into gradations in code below #plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, #label=appname, labelpos=(0.4, 0.6), labelrot=50, type=1) # aggregate value metrics for each depth cell over all apps low_fidelity_count = True for i in range(len(d_data)): x = depth_index(d_tr_data[i], depth_base) y = float(w_data[i]) f = f_data[i] if max_depth > 0 and d_tr_data[i] > max_depth: print(f"... excessive depth, skipped; w={y} d={d_tr_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # accumulate largest width for all apps w_max = max(w_max, y) xp = x * 4 #store center of border rectangle borders.append((int(xp), y)) if x > max_depth_log - 1: print(f"... data out of chart range, skipped; w={y} d={d_tr_data[i]}") break; for grad in range(num_grads): e = depth_values_merged[int(w_data[i])][int(xp + grad)] if e == None: e = { "value": 0.0, "count": 0 } e["count"] += 1 e["value"] += f depth_values_merged[int(w_data[i])][int(xp + grad)] = e #for depth_values in depth_values_merged: #print(f"-- {depth_values}") # compute and plot the average fidelity at each width / depth gradation with narrow filled rects for wi in range(len(depth_values_merged)): w = depth_values_merged[wi] #print(f"... w = {w}") low_fidelity_count = True for di in range(len(w)): e = w[di] if e != None: e["value"] /= e["count"] e["count"] = 1 x = di / 4 # move half cell to left, to account for num grads x -= 0.25 y = float(wi) f = e["value"] # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True ax.add_patch(box4_at(x, y, f, type=1, fill=True)) # draw borders at w,d location of each cell, offset to account for the merge process above for (x,y) in borders: x = x/4 + 0.125 ax.add_patch(box_at(x, y, f, type=1, fill=False)) #print("**** merged...") #print(depth_values_merged) ################################################# ### plot metrics across all apps for a backend_id def plot_all_app_metrics(backend_id, do_all_plots=False, include_apps=None, exclude_apps=None, suffix="", avail_qubits=0, is_individual=False, score_metric=None, max_depth=0, suppress_low_fidelity=False): global circuit_metrics global group_metrics global cmap # load saved data from file api = "qiskit" shared_data = load_app_metrics(api, backend_id) # apply include / exclude lists if include_apps != None: new_shared_data = {} for app in shared_data: # Extract shorter app name from the title passed in by user appname = app[len('Benchmark Results - '):len(app)] appname = appname[:appname.index(' - ')] if appname in include_apps: new_shared_data[app] = shared_data[app] shared_data = new_shared_data if exclude_apps != None: new_shared_data = {} for app in shared_data: # Extract shorter app name from the title passed in by user appname = app[len('Benchmark Results - '):len(app)] appname = appname[:appname.index(' - ')] if appname not in exclude_apps: new_shared_data[app] = shared_data[app] shared_data = new_shared_data #print(shared_data) # since the bar plots use the subtitle field, set it here circuit_metrics["subtitle"] = f"device = {backend_id}" # show vplots if enabled if do_volumetric_plots: # this is an overlay plot, no longer used, not very useful; better to merge ''' suptitle = f"Volumetric Positioning - All Applications (Combined)\nDevice={backend_id} {get_timestr()}" plot_metrics_all_overlaid(shared_data, backend_id, suptitle=suptitle, imagename="_ALL-vplot-2") ''' # draw the volumetric plot and append the circuit metrics subtitle to the title suptitle = f"Volumetric Positioning - All Applications (Merged)" fulltitle = suptitle + f"\nDevice={backend_id} {get_timestr()}" plot_metrics_all_merged(shared_data, backend_id, suptitle=fulltitle, imagename="_ALL-vplot-2"+suffix, avail_qubits=avail_qubits, is_individual=is_individual, score_metric=score_metric, max_depth=max_depth, suppress_low_fidelity=suppress_low_fidelity) # show all app metrics charts if enabled if do_app_charts_with_all_metrics or do_all_plots: for app in shared_data: #print("") #print(app) group_metrics = shared_data[app]["group_metrics"] plot_metrics(app) ### Plot Metrics for a specific application def plot_metrics_for_app(backend_id, appname, apiname="Qiskit", filters=None, options=None, suffix=""): global circuit_metrics global group_metrics # load saved data from file api = "qiskit" shared_data = load_app_metrics(api, backend_id) # since the bar plots use the subtitle field, set it here circuit_metrics["subtitle"] = f"device = {backend_id}" app = "Benchmark Results - " + appname + " - " + apiname if app not in shared_data: print(f"ERROR: cannot find app: {appname}") return group_metrics = shared_data[app]["group_metrics"] plot_metrics(app, filters=filters, suffix=suffix, options=options) # save plot as image def save_plot_image(plt, imagename, backend_id): # don't leave slashes in the filename backend_id = backend_id.replace("/", "_") # not used currently date_of_file = datetime.now().strftime("%Y%m%d_%H%M%S") if not os.path.exists('__images'): os.makedirs('__images') if not os.path.exists(f'__images/{backend_id}'): os.makedirs(f'__images/{backend_id}') pngfilename = f"{backend_id}/{imagename}" pngfilepath = os.path.join(os.getcwd(),"__images", pngfilename + ".jpg") plt.savefig(pngfilepath) #print(f"... saving (plot) image file:{pngfilename}.jpg") pdffilepath = os.path.join(os.getcwd(),"__images", pngfilename + ".pdf") plt.savefig(pdffilepath) ################################################# # ANALYSIS AND VISUALIZATION - AREA METRICS PLOTS # map known X metrics to labels known_x_labels = { 'cumulative_create_time' : 'Cumulative Circuit Creation Time (s)', 'cumulative_elapsed_time' : 'Cumulative Elapsed Quantum Execution Time (s)', 'cumulative_exec_time' : 'Cumulative Quantum Execution Time (s)', 'cumulative_opt_exec_time' : 'Cumulative Classical Optimization Time (s)', 'cumulative_depth' : 'Cumulative Circuit Depth' } x_label_save_str = { 'create_time' : 'createTime', 'elapsed_time' : 'elapsedTime', 'exec_time' : 'execTime', 'opt_exec_time' : 'optTime', 'depth' : 'depth' } # map known Y metrics to labels known_y_labels = { #'num_qubits' : 'Circuit Width' # this is only used for max-cut area plots #'num_qubits' : 'Problem Size (Number of Variables)' # use Problem Size instead 'num_qubits' : 'Problem Size (# of Variables)' # use Problem Size instead } # map known Score metrics to labels known_score_labels = { 'approx_ratio' : 'Approximation Ratio', 'cvar_ratio' : 'CVaR Ratio', 'gibbs_ratio' : 'Gibbs Objective Function', 'bestcut_ratio' : 'Best Measurement Ratio', 'fidelity' : 'Result Fidelity', 'max_fidelity' : 'Max. Result Fidelity', 'hf_fidelity' : 'Hellinger Fidelity' } # string that will go into the name of the figure when saved score_label_save_str = { 'approx_ratio' : 'apprRatio', 'cvar_ratio' : 'CVaR', 'bestcut_ratio' : 'bestCut', 'gibbs_ratio' : 'gibbs', 'fidelity' : 'fidelity', 'hf_fidelity' : 'hf' } # Plot all the given "Score Metrics" against the given "X Metrics" and "Y Metrics" def plot_all_area_metrics(suptitle='', score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=100, y_size=None, x_size=None, x_min=None, x_max=None, offset_flag=False, options=None, suffix=''): if type(score_metric) == str: score_metric = [score_metric] if type(x_metric) == str: x_metric = [x_metric] if type(y_metric) == str: y_metric = [y_metric] # loop over all the given X and Score metrics, generating a plot for each combination for s_m in score_metric: for x_m in x_metric: for y_m in y_metric: plot_area_metrics(suptitle, s_m, x_m, y_m, fixed_metrics, num_x_bins, y_size, x_size, x_min, x_max, offset_flag=offset_flag, options=options, suffix=suffix) def get_best_restart_ind(group, which_metric = 'approx_ratio'): """ From all the restarts, obtain the restart index for which the final iteration has the highest value of the specified metric Args: group (str): circuit width which_metric (str, optional): Defaults to 'approx_ratio'. Other valid options are 'gibbs_ratio', 'cvar_ratio', 'bestcut_ratio' """ restart_indices = list(circuit_metrics_detail_2[group].keys()) fin_AR_restarts = [] for restart_ind in restart_indices: iter_inds = list(circuit_metrics_detail_2[group][restart_ind].keys()) fin_AR = circuit_metrics_detail_2[group][restart_ind][max(iter_inds)][which_metric] fin_AR_restarts.append(fin_AR) best_index = fin_AR_restarts.index(max(fin_AR_restarts)) return restart_indices[best_index] # Plot the given "Score Metric" against the given "X Metric" and "Y Metric" def plot_area_metrics(suptitle='', score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=100, y_size=None, x_size=None, x_min=None, x_max=None, offset_flag=False, options=None, suffix=''): """ Plots a score metric as an area plot, on axes defined by x_metric and y_metric fixed_metrics: (dict) A dictionary mapping metric keywords to the values they are to be held at; for example: fixed_metrics = {'rounds': 2} when the y-axis is num_qubits or fixed_metrics = {'num_qubits': 4} when the y-axis is rounds. """ # get backend id for this set of circuits backend_id = get_backend_id() # Extract shorter app name from the title passed in by user appname = get_appname_from_title(suptitle) # map known metrics to labels x_label = known_x_labels[x_metric] y_label = known_y_labels[y_metric] score_label = known_score_labels[score_metric] # process cumulative and maximum options xs, x, y, scores = [], [], [], [] cumulative_flag, maximum_flag = False, False if len(x_metric) > 11 and x_metric[:11] == 'cumulative_': cumulative_flag = True x_metric = x_metric[11:] if score_metric[:4] == 'max_': maximum_flag = True score_metric = score_metric[4:] #print(f" ==> all detail 2 circuit_metrics:") for group in circuit_metrics_detail_2: num_qubits = int(group) if 'num_qubits' in fixed_metrics: if num_qubits != fixed_metrics['num_qubits']: continue x_size_groups, x_groups, y_groups, score_groups = [], [], [], [] # Get the best AR index restart_index = get_best_restart_ind(group, which_metric = 'approx_ratio') # Each problem instance at size num_qubits; need to collate across iterations for circuit_id in [restart_index]:#circuit_metrics_detail_2[group]: # circuit_id here denotes the restart index x_last, score_last = 0, 0 x_sizes, x_points, y_points, score_points = [], [], [], [] for it in circuit_metrics_detail_2[group][circuit_id]: mets = circuit_metrics_detail_2[group][circuit_id][it] if x_metric not in mets: break if score_metric not in mets: break # get each metric and accumulate if indicated x_raw = x_now = mets[x_metric] if cumulative_flag: x_now += x_last x_last = x_now if y_metric == 'num_qubits': y_now = num_qubits else: y_now = mets[y_metric] # Count only iterations at valid fixed_metric values for fixed_m in fixed_metrics: if mets[fixed_m] != fixed_metrics[fixed_m]: continue # Support intervals e.g. {'depth': (15, 65)} elif len(fixed_metrics[fixed_m]) == 2: if mets[fixed_m]<fixed_metrics[fixed_m][0] or mets[fixed_m]>fixed_metrics[fixed_m][1]: continue if maximum_flag: score_now = max(score_last, mets[score_metric]) else: score_now = mets[score_metric] score_last = score_now # need to shift x_now by the 'size', since x_now inb the cumulative #x_points.append((x_now - x_raw) if cumulative_flag else x_now) #x_points.append((x_now - x_raw)) x_points.append(x_now - x_raw/2) y_points.append(y_now) x_sizes.append(x_raw) score_points.append(score_now) x_size_groups.append(x_sizes) x_groups.append(x_points) y_groups.append(y_points) score_groups.append(score_points) ''' don't do binning for now #print(f" ... x_ = {num_x_bins} {len(x_groups)} {x_groups}") #x_sizes_, x_, y_, scores_ = x_bin_averaging(x_size_groups, x_groups, y_groups, score_groups, num_x_bins=num_x_bins) ''' # instead use the last of the groups i_last = len(x_groups) - 1 x_sizes_ = x_size_groups[i_last] x_ = x_groups[i_last] y_ = y_groups[i_last] scores_ = score_groups[i_last] #print(f" ... x_ = {len(x_)} {x_}") #print(f" ... x_sizes_ = {len(x_sizes_)} {x_sizes_}") xs = xs + x_sizes_ x = x + x_ y = y + y_ scores = scores + scores_ # append the circuit metrics subtitle to the title fulltitle = suptitle + f"\nDevice={backend_id} {get_timestr()}" if options != None: options_str = '' for key, value in options.items(): if len(options_str) > 0: options_str += ', ' options_str += f"{key}={value}" fulltitle += f"\n{options_str}" # if the y axis data is sparse or non-linear, linearize the axis data and sort all arrays if needs_linearize(y, gap=2): # sort the data by y axis values, as it may be loaded out of order from file storage z = sorted(zip(y,x,xs,scores)) y = [_y for _y,_x,_xs,_s in z] x = [_x for _y,_x,_xs,_s in z] xs = [_xs for _y,_x,_xs,_s in z] scores = [_s for _y,_x,_xs,_s in z] # convert irregular y-axis data to linear if any non-linear gaps in the data yy, ylabels = linearize_axis(y, gap=2, outer=2, fill=True) else: yy = y ylabels = None # the x axis min/max values will be min(x)/max(x) or values supplied by caller if x_min == None: #x_min = min(x) x_min = 0 # if not supplied, always use 0 for area plots, as leftmost time is 0 if x_max == None: x_max = max(x) x_max += max(xs)/2 # if not supplied, rightmost time must include the width else: x_max = x_max - 1 # subtract one to account for the auto-label algorithm in background function with plt.style.context(maxcut_style): # plot the metrics background with its title ax = plot_metrics_background(fulltitle, y_label, x_label, score_label, y_max=max(yy), x_max=x_max, y_min=min(yy), x_min=x_min, ylabels=ylabels) if y_size == None: y_size = 1.0 #print(f"... num: {num_x_bins} {len(x)} {x_size} {x}") # add a grid on the x axis (with the maxcut style of alpha=0.5, this color is best for pdf) ax.grid(True, axis = 'x', zorder = 0, color='silver') # plot all bars, with width specified as an array that matches array size of the x,y values plot_volumetric_data(ax, yy, x, scores, depth_base=-1, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, x_size=xs, y_size=y_size, zorder=3, offset_flag=offset_flag) plt.tight_layout() if save_plot_images: save_plot_image(plt, os.path.join(f"{appname}-area-" + score_label_save_str[score_metric] + '-' + x_label_save_str[x_metric] + '-' + suffix), backend_id) # Check if axis data needs to be linearized # Returns true if data sparse or non-linear; sparse means with any gap > gap size def needs_linearize(values, gap=2): #print(f"{values = }") # if only one element, no need to linearize if len(values) < 2: return False # simple logic for now: return if any gap > 2 for i in range(len(values)): if i > 0: delta = values[i] - values[i - 1] if delta > gap: return True # no need to linearize if all small gaps return False # convert irregular axis data to linear, with minimum gap size # only show labels for the actual data points # (the labels assume that the return data will be plotted with 2 points before and after) # DEVNOTE: the use of this function is limited to the special case of the maxcut plots for now, # given the limited range of problem definitions def linearize_axis(values, gap=2, outer=2, fill=True): #print(f"{values = }") #print(f"{outer = }") # if only one element, no need to linearize if len(values) < 2: return values, None # use this flag to test if there are gaps > gap gaps_exist = False # add labels at beginning basis = [None] * outer; # loop over values and generate new values that are separated by the gap value newvalues = []; for i in range(len(values)): newvalues.append(values[i]) # first point is unchanged if i == 0: basis.append(values[i]) # subsequent points are unchanged if same, but modified by gap if different if i > 0: delta = values[i] - values[i - 1] if delta == 0: #print("delta 0") newvalues[i] = newvalues[i - 1] elif delta > gap: #print("delta 1+") gaps_exist = True newvalues[i] = newvalues[i - 1] + gap if fill and gap > 1: basis.append(None) # put space between items if gap > 1 basis.append(values[i]) # add labels at end basis += [None] * outer #print(f"{newvalues = }") #print(f"{basis = }") # format new labels as strings, showing only the actual values (non-zero) ylabels = [format_number(yb) if yb != None else '' for yb in basis] #print(f"{ylabels = }") if gaps_exist: return newvalues, ylabels else: return values, None # Helper function to bin for averaging metrics, for instances occurring at equal num_qubits # DEVNOTE: this binning approach creates unevenly spaced bins, cannot use the delta between then for size def x_bin_averaging(x_size_groups, x_groups, y_groups, score_groups, num_x_bins): # find min and max across all the groups bin_xs, bin_x, bin_y, bin_s = {}, {}, {}, {} x_min, x_max = x_groups[0][0], x_groups[0][0] for group in x_groups: min_, max_ = min(group), max(group) if min_ < x_min: x_min = min_ if max_ > x_max: x_max = max_ step = (x_max - x_min)/num_x_bins # loop over each group for group in range(len(x_groups)): # for each item in the group, accumulate into bins # place into a new bin, if if has larger x value than last one k = 0 for i in range(len(x_groups[group])): while x_groups[group][i] >= x_min + k*step: k += 1 if k not in bin_x: bin_xs[k] = [] bin_x[k] = [] bin_y[k] = [] bin_s[k] = [] bin_xs[k] = bin_xs[k] + [x_size_groups[group][i]] bin_x[k] = bin_x[k] + [x_groups[group][i]] bin_y[k] = bin_y[k] + [y_groups[group][i]] bin_s[k] = bin_s[k] + [score_groups[group][i]] # for each bin, compute average from all the elements in the bin new_xs, new_x, new_y, new_s = [], [], [], [] for k in bin_x: new_xs.append(sum(bin_xs[k])/len(bin_xs[k])) new_x.append(sum(bin_x[k])/len(bin_x[k])) new_y.append(sum(bin_y[k])/len(bin_y[k])) new_s.append(sum(bin_s[k])/len(bin_s[k])) return new_xs, new_x, new_y, new_s def plot_ECDF(suptitle="", options=None, suffix=None): """ Plot the ECDF (Empirical Cumulative Distribution Function) for each circuit width and degree Parameters ---------- suptitle : options : suffix : """ # get backend id for this set of circuits backend_id = get_backend_id() # Extract shorter app name from the title passed in by user appname = get_appname_from_title(suptitle) with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1)#, figsize=(6.4,4.8))#, constrained_layout=True, figsize=(6,4))#, sharex=True # Create more appropriate title suptitle = "Cumulative Distribution (ECDF) - " + appname # append key circuit metrics info to the title fulltitle = suptitle + f"\nDevice={backend_id} {get_timestr()}" if options != None: options_str = '' for key, value in options.items(): if len(options_str) > 0: options_str += ', ' options_str += f"{key}={value}" fulltitle += f"\n{options_str}" # and add the title to the plot plt.title(fulltitle) for group in circuit_metrics_final_iter: best_restart_ind = str(get_best_restart_ind(group)) for restart_ind in [best_restart_ind]:#circuit_metrics_final_iter[group]: cumul_counts = circuit_metrics_final_iter[group][restart_ind]['cumul_counts'] unique_sizes = circuit_metrics_final_iter[group][restart_ind]['unique_sizes'] optimal_value = circuit_metrics_final_iter[group][restart_ind]['optimal_value'] axs.plot(np.array(unique_sizes) / optimal_value, np.array(cumul_counts) / cumul_counts[-1], marker='o', #ls = '-', label = f"Width={group}")#" degree={deg}") # lw=1, ls = '-', label = f"Problem Size={group}")#" degree={deg}") # lw=1, axs.set_ylabel('Fraction of Total Counts') axs.set_xlabel(r'$\frac{\mathrm{Cut\ Size}}{\mathrm{Max\ Cut\ Size}}$') axs.grid() axs.legend(loc='upper left')#loc='center left', bbox_to_anchor=(1, 0.5)) fig.tight_layout() # save plot image to file if save_plot_images: save_plot_image(plt, f"{appname}-ECDF-" + suffix, backend_id) # show the plot for user to see if show_plot_images: plt.show() def plot_cutsize_distribution(suptitle="Circuit Width (Number of Qubits)", list_of_widths = [], options=None, suffix=None): """ For each circuit size and degree, plot the measured distribution of cutsizes corresponding to the last optimizer iteration, as well as uniform random sampling """ if not list_of_widths: # If list_of_widths is emply, set it to contain all widths list_of_widths = list(circuit_metrics_final_iter.keys()) # Convert list_of_widths elements to string list_of_widths = [str(width) for width in list_of_widths] group_metrics_optgaps = get_distribution_and_stats() # 'quantile_optgaps' for width in list_of_widths: plot_cutsize_distribution_single_width(width, suptitle, options, group_metrics_optgaps, suffix) def plot_cutsize_distribution_single_width(width, suptitle, options, group_metrics_optgaps, suffix): # get backend id backend_id = get_backend_id() # Extract shorter app name from the title passed in by user appname = get_appname_from_title(suptitle) with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1) suptitle = "Empirical Distribution of Cut Sizes - " + appname fulltitle = get_full_title( #suptitle, options) + "\nwidth={}".format(width) suptitle, options) + "\nProblem Size = {}".format(width) plt.title(fulltitle) indx = group_metrics_optgaps['groups'].index(int(width)) # get index corresponding to width # Plot distribution of cut sizes for circuit dist = group_metrics_optgaps['cutsize_ratio_dist'] axs.plot(dist['ratios'][indx], dist['frequencies'][indx], marker='o', ls='-', c='k', ms=2, mec='k', mew=0.4, lw=1, label=f"Circuit Sampling") # " degree={deg}") # lw=1, # Also plot the distribution obtained from uniform random sampling dist = group_metrics_optgaps['random_cutsize_ratio_dist'] axs.plot(dist['ratios'][indx], dist['frequencies'][indx], marker='o', ms=1, mec = 'k',mew=0.2, lw=10,alpha=0.5, ls = '-', label = "Uniform Random Sampling", c = "pink") # " degree={deg}") # lw=1, # Plot vertical lines corresponding to the various metrics plotted_metric_values = [] for metric in ['approx_ratio', 'cvar_ratio', 'bestcut_ratio', 'gibbs_ratio']: curdict = group_metrics_optgaps[metric] curmetricval = curdict['ratiovals'][indx] lw=1; ls='solid' if curmetricval in plotted_metric_values: # for lines that will coincide, assign different styles to distinguish them lw=1.5; ls='dashed' plotted_metric_values.append(curmetricval) axs.axvline(x=curmetricval, color=curdict['color'], label=curdict['label'], lw=lw, ls=ls) axs.set_ylabel('Fraction of Total Counts') axs.set_xlabel(r'$\frac{\mathrm{Cut\ Size}}{\mathrm{Max\ Cut\ Size}}$') axs.grid() axs.set_xlim(left=-0.02, right=1.02) axs.legend(loc='upper left') fig.tight_layout() # save plot image to file if save_plot_images: save_plot_image(plt, f"{appname}-cutsize_dist-" + suffix + "width-{}".format(width), backend_id) # show the plot for user to see if show_plot_images: plt.show() def get_full_title(suptitle = '', options = dict()): """ Return title for figure """ # get backend id for this set of circuits backend_id = get_backend_id() fulltitle = suptitle + f"\nDevice={backend_id} {get_timestr()}" if options != None: options_str = '' for key, value in options.items(): if len(options_str) > 0: options_str += ', ' options_str += f"{key}={value}" fulltitle += f"\n{options_str}" return fulltitle # Plot angles def plot_angles_polar(suptitle = '', options=None, suffix = ''): """ Create a polar angle plot, showing the beta and gamma angles Parameters ---------- options : dictionary Returns ------- None. """ widths = group_metrics['groups'] num_widths = len(widths) maxRadius = 10 minRadius = 2 radii = np.linspace(minRadius, maxRadius,num_widths) angles_arr = [] for ind, width_str in enumerate(widths): deg = list(circuit_metrics[width_str].keys())[0] angles = circuit_metrics_final_iter[width_str][str(deg)]['converged_thetas_list'] angles_arr.append(angles) rounds = len(angles_arr[0]) // 2 fulltitle = get_full_title(suptitle=suptitle, options=options) cmap_beta = cm.get_cmap('autumn') cmap_gamma = cm.get_cmap('winter') colors = np.linspace(0.05,0.95, rounds) colors_beta = [cmap_beta(i) for i in colors] colors_gamma = [cmap_gamma(i) for i in colors] with plt.style.context(maxcut_style): fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) plt.title(fulltitle) for i in range(rounds): # plot betas # Note: Betas go from 0 to pi, while gammas go from 0 to 2pi # Hence, plot 2*beta and 1*gamma to cover the entire circle betas = [2 * angles_arr[rind][i] for rind in range(num_widths)] ax.plot(betas, radii, marker='o', ms=7, ls = 'None', mec = 'k', mew=0.5,alpha=0.7, c=colors_beta[i], label=r'$2\beta_{}$'.format(i+1)) for i in range(rounds): # plot gammas gammas = [angles_arr[rind][i+rounds] for rind in range(num_widths)] ax.plot(gammas, radii, marker='s', ms=7, ls = 'None', mec = 'k', mew=0.5, alpha=0.7, c=colors_gamma[i], label=r'$\gamma_{}$'.format(i+1)) ax.set_rmax(maxRadius+1) ax.set_rticks(radii) ax.set_yticklabels(labels=widths) ax.set_xticks(np.pi/2 * np.arange(4)) ax.set_xticklabels(labels=[r'$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$'], fontsize=15) ax.set_rlabel_position(0) ax.grid(True) fig.tight_layout() ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5)) # save plot image to file if save_plot_images: backend_id = get_backend_id() appname = get_appname_from_title(suptitle) save_plot_image(plt, f"{appname}-angles-" + suffix, backend_id) # show the plot for user to see if show_plot_images: plt.show() def get_distribution_and_stats(): """Returns a dictionary with values, colors and labels for various metrics. Returns: dictionary """ group_metrics_optgaps = {'approx_ratio' : {'color' : 'r', 'label': 'Approx. Ratio', 'gapvals' : [], 'ratiovals':[]}, 'cvar_ratio' : {'color' : 'g', 'label': 'CVaR Ratio', 'gapvals' : [],'ratiovals':[]}, 'bestcut_ratio' : {'color' : 'm', 'label': 'Best Measurement Ratio', 'gapvals' : [],'ratiovals':[]}, 'gibbs_ratio' : {'color' : 'y', 'label' : 'Gibbs Objective Function', 'gapvals' : [],'ratiovals':[]}, 'quantile_optgaps' : {'gapvals' : [],'ratiovals':[]}, 'violin' : {'gapvals' : []},# gapvals is a list of [xlist, ylist], 'cutsize_ratio_dist' : {'ratios':[],'frequencies':[]}, 'random_cutsize_ratio_dist' : {'ratios':[],'frequencies':[]}, 'groups' : []} #widths # circuit_metrics_detail_2.keys() may not be in an ascending order. Sort the groups (i.e. widths) groups = list(circuit_metrics_detail_2.keys()) groups = sorted(groups, key=lambda x: int(x)) group_metrics_optgaps["groups"] = [int(g) for g in groups] for group in groups: best_restart_ind = get_best_restart_ind(group) for circuit_id in [best_restart_ind]:#circuit_metrics_detail_2[group]: # save the metric from the last iteration last_ind = max(circuit_metrics_detail_2[group][circuit_id].keys()) mets = circuit_metrics_detail_2[group][circuit_id][last_ind] # Store the ratio values for objective functions group_metrics_optgaps['approx_ratio']['ratiovals'].append(mets["approx_ratio"]) group_metrics_optgaps['cvar_ratio']['ratiovals'].append(mets["cvar_ratio"]) group_metrics_optgaps['bestcut_ratio']['ratiovals'].append(mets["bestcut_ratio"]) group_metrics_optgaps['gibbs_ratio']['ratiovals'].append(mets["gibbs_ratio"]) # Compute optimality gaps for the objective function types group_metrics_optgaps['approx_ratio']['gapvals'].append(abs(1.0 - mets["approx_ratio"]) * 100) group_metrics_optgaps['cvar_ratio']['gapvals'].append(abs(1.0 - mets["cvar_ratio"]) * 100) group_metrics_optgaps['bestcut_ratio']['gapvals'].append(abs(1.0 - mets["bestcut_ratio"]) * 100) group_metrics_optgaps['gibbs_ratio']['gapvals'].append(abs(1.0 - mets["gibbs_ratio"]) * 100) # Also store the optimality gaps at the three quantiles values # Here, optgaps are defined as weight(cut)/weight(maxcut) * 100 q_vals = mets["quantile_optgaps"] # in fraction form. List of floats q_vals = [q_vals[i] * 100 for i in range(len(q_vals))] # In percentages group_metrics_optgaps['quantile_optgaps']['gapvals'].append(q_vals) # Store empirical distribution of cut size values / optimal value unique_sizes = circuit_metrics_final_iter[group][str(circuit_id)]['unique_sizes'] unique_counts = circuit_metrics_final_iter[group][str(circuit_id)]['unique_counts'] optimal_value = circuit_metrics_final_iter[group][str(circuit_id)]['optimal_value'] full_size_list = list(range(optimal_value + 1)) full_counts_list = [unique_counts[unique_sizes.index(s)] if s in unique_sizes else 0 for s in full_size_list] group_metrics_optgaps['cutsize_ratio_dist']['ratios'].append(np.array(full_size_list) / optimal_value) group_metrics_optgaps['cutsize_ratio_dist']['frequencies'].append(np.array(full_counts_list) / sum(full_counts_list)) # Also store locations for the half-violin plots to be plotted in the detailed opt-gap plots # gap values for the violin plot will be 1 - unique_sizes / optimal size violin_yvals = 100 * (1 - np.array(full_size_list) / optimal_value) # Normalize the violin plot so that the max width will be 1 unit along horizontal axis violin_xvals = np.array(full_counts_list) / max(full_counts_list) group_metrics_optgaps['violin']['gapvals'].append([violin_xvals, violin_yvals]) # Store empirican distribution of cut size values / optimal value for random sampling unique_sizes_unif = circuit_metrics_final_iter[group][str(circuit_id)]['unique_sizes_unif'] unique_counts_unif = circuit_metrics_final_iter[group][str(circuit_id)]['unique_counts_unif'] full_size_list = list(range(optimal_value + 1)) full_counts_list_unif = [unique_counts_unif[unique_sizes_unif.index(s)] if s in unique_sizes_unif else 0 for s in full_size_list] group_metrics_optgaps['random_cutsize_ratio_dist']['ratios'].append(np.array(full_size_list) / optimal_value) # hack to avoid crash if all zeros sum_full_counts_list_unif = sum(full_counts_list_unif) if sum_full_counts_list_unif <= 0: sum_full_counts_list_unif = 1 group_metrics_optgaps['random_cutsize_ratio_dist']['frequencies'].append(np.array(full_counts_list_unif) / sum_full_counts_list_unif) return group_metrics_optgaps # Plot detailed optgaps def plot_metrics_optgaps (suptitle="", transform_qubit_group = False, new_qubit_group = None, filters=None, suffix="", objective_func_type = 'cvar_ratio', which_metrics_to_plot = "all", options=None): """ Create and two plots: 1. Bar plots showing the optimality gap in terms of the approximation ratio vs circuit widths. Also plot quartiles on top. 2. Line plots showing the optimality gaps measured in terms of all available objective function types. Also plot quartiles, and violin plots. Currently only used for maxcut """ # get backend id for this set of circuits backend_id = get_backend_id() # Extract shorter app name from the title passed in by user appname = get_appname_from_title(suptitle) if len(group_metrics["groups"]) == 0: print(f"\n{suptitle}") print(" ****** NO RESULTS ****** ") return # sort the group metrics (in case they weren't sorted when collected) sort_group_metrics() # DEVNOTE: Add to group metrics here; this should be done during execute # Create a dictionary, with keys specifying metric type, and values specifying corresponding optgap values group_metrics_optgaps = get_distribution_and_stats() if which_metrics_to_plot == 'all' or type(which_metrics_to_plot) != list: which_metrics_to_plot = ['approx_ratio', 'cvar_ratio', 'bestcut_ratio', 'gibbs_ratio', 'quantile_optgaps', 'violin'] # check if we have sparse or non-linear axis data and linearize if so xvalues = group_metrics_optgaps["groups"] xlabels = None if needs_linearize(xvalues, gap=2): #print("... needs linearize") # convert irregular x-axis data to linear if any non-linear gaps in the data xx, xlabels = linearize_axis(xvalues, gap=2, outer=0, fill=False) xvalues = xx # Create title for the plots fulltitle = get_full_title(suptitle=suptitle, options=options) ############################################################ ##### Optimality gaps bar plot with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1) plt.title(fulltitle) axs.set_ylabel(r'Optimality Gap ($\%$)') #axs.set_xlabel('Circuit Width (Number of Qubits)') axs.set_xlabel(known_y_labels['num_qubits']) # indirection axs.set_xticks(xvalues) if xlabels != None: plt.xticks(xvalues, xlabels) limopts = max(group_metrics_optgaps['approx_ratio']['gapvals']) if limopts > 5: axs.set_ylim([0, max(40, limopts) * 1.1]) else: axs.set_ylim([0, 5.0]) axs.grid(True, axis = 'y', color='silver', zorder = 0) # other bars use this silver color #axs.grid(True, axis = 'y', zorder = 0) axs.bar(xvalues, group_metrics_optgaps['approx_ratio']['gapvals'], 0.8, zorder = 3) # NOTE: Can move the calculation or the errors variable to before the plotting. This code is repeated in the detailed plotting as well. # Plot quartiles q_vals = group_metrics_optgaps['quantile_optgaps']['gapvals'] # list of lists; shape (number of circuit widths, 3) # Indices are of the form (circuit width index, quantile index) center_optgaps = [q_vals[i][1] for i in range(len(q_vals))] down_error = [q_vals[i][0] - q_vals[i][1] for i in range(len(q_vals))] up_error = [q_vals[i][1] - q_vals[i][2] for i in range(len(q_vals))] errors = [up_error, down_error] axs.errorbar(xvalues, center_optgaps, yerr = errors, ecolor = 'k', elinewidth = 1, barsabove = False, capsize=5,ls='', marker = "D", markersize = 8, mfc = 'c', mec = 'k', mew = 0.5,label = 'Quartiles', alpha = 0.75, zorder = 5) fig.tight_layout() axs.legend() # save plot image to file if save_plot_images: save_plot_image(plt, f"{appname}-optgaps-bar" + suffix, backend_id) # show the plot for user to see if show_plot_images: plt.show() ############################################################ ##### Detailed optimality gaps plot with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1) plt.title(fulltitle) axs.set_ylabel(r'Optimality Gap ($\%$)') #axs.set_xlabel('Circuit Width (Number of Qubits)') axs.set_xlabel(known_y_labels['num_qubits']) # indirection axs.set_xticks(xvalues) if xlabels != None: plt.xticks(xvalues, xlabels) if 'violin' in which_metrics_to_plot: list_of_violins = group_metrics_optgaps['violin']['gapvals'] # violinx_list = [x for [x,y] in list_of_violins] # violiny_list = [y for [x,y] in list_of_violins] violin_list_locs = xvalues for loc, vxy in zip(violin_list_locs, list_of_violins): vy = vxy[1] vx = vxy[0] axs.fill_betweenx(vy, loc, loc + vx, color='r', alpha=0.2,lw=0) # Plot violin plots plt_handles = dict() # Plot the quantile optimality gaps as errorbars if 'quantile_optgaps' in which_metrics_to_plot: q_vals = group_metrics_optgaps['quantile_optgaps']['gapvals'] # list of lists; shape (number of circuit widths, 3) # Indices are of the form (circuit width index, quantile index) center_optgaps = [q_vals[i][1] for i in range(len(q_vals))] down_error = [q_vals[i][0] - q_vals[i][1] for i in range(len(q_vals))] up_error = [q_vals[i][1] - q_vals[i][2] for i in range(len(q_vals))] errors = [up_error, down_error] plt_handles['quantile_optgaps'] = axs.errorbar(xvalues, center_optgaps, yerr = errors,ecolor = 'k', elinewidth = 1, barsabove = False, capsize=5,ls='', marker = "D", markersize = 8, mfc = 'c', mec = 'k', mew = 0.5,label = 'Quartiles', alpha = 0.75) for metric_str in set(which_metrics_to_plot) - set(["quantile_optgaps", "violin"]): # For all metrics to be plotted, except quantile optgaps and violin plots, plot a line # Plot a solid line for the objective function, and dashed otherwise ls = '-' if metric_str == objective_func_type else '--' plt_handles[metric_str], = axs.plot(xvalues, group_metrics_optgaps[metric_str]['gapvals'],marker='o', lw=1,ls = ls,color = group_metrics_optgaps[metric_str]['color'],label = group_metrics_optgaps[metric_str]['label']) # Put up the legend, but with labels arranged in the order specified by ideal_lgnd_seq ideal_lgnd_seq = ['approx_ratio', 'cvar_ratio', 'gibbs_ratio', 'bestcut_ratio', 'quantile_optgaps'] handles_list= [plt_handles[s] for s in ideal_lgnd_seq if s in plt_handles] axs.legend(handles=handles_list, ncol=2, loc='upper right')# loc='center left', bbox_to_anchor=(1, 0.5)) # For now, we are only plotting for degree 3, and not -3 # Set y limits ylim_top = 0 for o_f in ['approx_ratio', 'cvar_ratio', 'bestcut_ratio', 'gibbs_ratio']: ylim_top = max(ylim_top, max(group_metrics_optgaps[o_f]['gapvals'])) ylim_top = max(ylim_top, max(map(max, group_metrics_optgaps['quantile_optgaps']['gapvals']))) if ylim_top > 60: ylim_top = 100 + 3 bottom = 0 - 3 elif ylim_top > 10: ylim_top = 60 + 3 bottom = 0 - 3 else: ylim_top = 8 + 1 bottom = 0 - 1 axs.set_ylim(bottom=bottom, top = ylim_top) # axs.set_ylim(bottom=0,top=100) # Add grid plt.grid() fig.tight_layout() # save plot image to file if save_plot_images: save_plot_image(plt, f"{appname}-optgaps-" + suffix, backend_id) # show the plot for user to see if show_plot_images: plt.show() ############################################# # ANALYSIS AND VISUALIZATION - DATA UTILITIES ##### Data File Methods # Save the application metrics data to a shared file for the current device def store_app_metrics (backend_id, circuit_metrics, group_metrics, app, start_time=None, end_time=None): # print(f"... storing {title} {group_metrics}") # don't leave slashes in the filename backend_id = backend_id.replace("/", "_") # load the current data file of all apps api = "qiskit" shared_data = load_app_metrics(api, backend_id) # if there are no previous data for this app, init empty dict if app not in shared_data: shared_data[app] = { "circuit_metrics":None, "group_metrics":None } shared_data[app]["backend_id"] = backend_id shared_data[app]["start_time"] = start_time shared_data[app]["end_time"] = end_time shared_data[app]["group_metrics"] = group_metrics # if saving raw circuit data, add it too #shared_data[app]["circuit_metrics"] = circuit_metrics # be sure we have a __data directory if not os.path.exists('__data'): os.makedirs('__data') # create filename based on the backend_id filename = f"__data/DATA-{backend_id}.json" # overwrite the existing file with the merged data with open(filename, 'w+') as f: json.dump(shared_data, f, indent=2, sort_keys=True) f.close() # Load the application metrics from the given data file # Returns a dict containing circuit and group metrics def load_app_metrics (api, backend_id): # don't leave slashes in the filename backend_id = backend_id.replace("/", "_") filename = f"__data/DATA-{backend_id}.json" shared_data = None # attempt to load shared_data from file if os.path.exists(filename) and os.path.isfile(filename): with open(filename, 'r') as f: # attempt to load shared_data dict as json try: shared_data = json.load(f) except: pass # create empty shared_data dict if not read from file if shared_data == None: shared_data = {} # temporary: to read older format files ... for app in shared_data: #print(app) # this is very old and could potentially be removed (but would need testing) if "group_metrics" not in shared_data[app]: print(f"... upgrading version of app data {app}") shared_data[app] = { "circuit_metrics":None, "group_metrics":shared_data[app] } group_metrics = shared_data[app]["group_metrics"] #print(group_metrics) # need to include avg_hf_fidelities if "avg_hf_fidelities" not in group_metrics: print(f"... upgrading version of app data {app}") #print(f"... upgrading version of app data {app}, adding avg_hf_fidelities") group_metrics["avg_hf_fidelities"] = copy.copy(group_metrics["avg_fidelities"]) # need to include avg_tr_n2qs if "avg_tr_n2qs" not in group_metrics: #print(f"... upgrading version of app data {app}, adding avg_tr_n2qs") group_metrics["avg_tr_n2qs"] = copy.copy(group_metrics["avg_tr_depths"]) for i in range(len(group_metrics["avg_tr_n2qs"])): group_metrics["avg_tr_n2qs"][i] *= group_metrics["avg_tr_xis"][i] #print(group_metrics) return shared_data ############################################## # VOLUMETRIC PLOT import math from matplotlib.patches import Rectangle from matplotlib.patches import Circle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): print("... set custom map style") global cmap, cmap_custom_spectral cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral cmap_custom_spectral = create_custom_spectral_cmap() ############### Helper functions def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) def bkg_box_at(x, y, value): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (.9,.9,.9), fill=True, lw=0.5) def bkg_empty_box_at(x, y, value): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" ##### Volumetric Plots # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 8192 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow if QV0 == 0: ax.add_patch(bkg_empty_box_at(id, w, 0.5)) else: ax.add_patch(bkg_box_at(id, w, 0.5)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w, 0.5)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax def plot_volumetric_background_aq(max_qubits=11, AQ=22, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Algorithmic Qubits = {AQ}" AQ0 = AQ aq_estimate = False est_str = "" if AQ == 0: AQ=20 if AQ < 0: AQ0 = 0 # AQ < 0 indicates "add est. to label" AQ = -AQ aq_estimate = True est_str = " (est.)" max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 #print(f"... {avail_qubits} {max_qubits} {max_width}") seed = 6.8 #plot_width = 0.5 + seed * (max_width / max_depth_log) plot_width = seed plot_height = 0.5 + seed * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Number of 2Q gates') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) #log2AQsq = math.log2(AQ*AQ) AQ_width = AQ AQ_depth = AQ*AQ # show a quantum volume rectangle of AQ = 6 e.g. (6 x 36) if AQ0 != 0: ax.add_patch(qv_box_at(1, 1, AQ_width, AQ_depth, 0.87, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = AQ_depth for w in range(1, max_width): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # if circuit would fail here, don't draw box if d > maxprod: continue if (w-1) > maxprod: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow if AQ0 == 0: ax.add_patch(bkg_empty_box_at(id, w, 0.5)) else: ax.add_patch(bkg_box_at(id, w, 0.5)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w, 0.5)) # Add annotation showing quantum volume if AQ0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"AQ{est_str}={AQ}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Linear Background Analog of the QV Volumetric Background, to allow arbitrary metrics on each axis def plot_metrics_background(suptitle, ylabel, x_label, score_label, y_max, x_max, y_min=0, x_min=0, ylabels=None): if suptitle == None: suptitle = f"{ylabel} vs. {x_label}, Parameter Positioning of {score_label}" # plot_width = 6.8 # plot_height = 5.0 # assume y max is the max of the y data # we only do circuit width for now, so show 3 qubits more than the max max_width = y_max + 3 min_width = y_min - 3 fig, ax = plt.subplots() #constrained_layout=True, figsize=(plot_width, plot_height)) plt.title(suptitle) # DEVNOTE: this code could be made more general, rounding the axis max to 20 divs nicely # round the max up to be divisible evenly (in multiples of 0.05 or 0.005) by num_xdivs num_xdivs = 20 max_base = num_xdivs * 0.05 if x_max != None and x_max > 1.0: x_max = max_base * int((x_max + max_base) / max_base) if x_max != None and x_max > 0.1: max_base = num_xdivs * 0.005 x_max = max_base * int((x_max + max_base) / max_base) #print(f"... {x_min} {x_max} {max_base}") if x_min < 0.1: x_min = 0 # and compute the step size for the tick divisions step = (x_max - x_min) / num_xdivs plt.xlim(x_min - step/2, x_max + step/2) #plt.ylim(y_min*0.5, y_max*1.5) plt.ylim(min_width, max_width) # circuit metrics (x axis) xround = [step * x for x in range(num_xdivs + 1)] # format x labels > 1 to N decimal places, depending on total range digits = 0 if x_max < 24: digits = 1 if x_max < 10: digits = 2 xlabels = [format_number(x, digits=digits) for x in xround] ax.set_xlabel(x_label) ax.set_xticks(xround) plt.xticks(xround, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # circuit metrics (y axis) ybasis = [y for y in range(min_width + 1, max_width)] #yround = [(y_max - y_min)/12 * y for y in range(0,25,2)] # not used now, since we only do circuit width #ylabels = [format_number(y) for y in yround] ax.set_ylabel(ylabel) #ax.set_yticks(yround) ax.set_yticks(ybasis) if ylabels != None: plt.yticks(ybasis, ylabels) # add colorbar to right of plot (scale if normalize function installed) plt.colorbar(cm.ScalarMappable(cmap=cmap, norm=cmap_norm), shrink=0.6, label=score_label, panchor=(0.0, 0.7)) return ax x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) def plot_volumetric_data_aq(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True for i in range(len(d_data)): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True ax.add_patch(circle_at(x, y, f, type=type, fill=fill)) if y >= y_anno: x_anno = x y_anno = y i_anno = i x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) #################################### # TEST METHODS # Test metrics module, with simple test data def test_metrics (): init_metrics() store_metric('group1', 'circuit1', 'create_time', 123) store_metric('group1', 'circuit2', 'create_time', 234) store_metric('group2', 'circuit1', 'create_time', 156) store_metric('group2', 'circuit2', 'create_time', 278) store_metric('group1', 'circuit1', 'exec_time', 223) store_metric('group1', 'circuit2', 'exec_time', 334) store_metric('group2', 'circuit1', 'exec_time', 256) store_metric('group2', 'circuit2', 'exec_time', 378) store_metric('group1', 'circuit1', 'fidelity', 1.0) store_metric('group1', 'circuit2', 'fidelity', 0.8) store_metric('group2', 'circuit1', 'fidelity', 0.9) store_metric('group2', 'circuit2', 'fidelity', 0.7) aggregate_metrics() report_metrics() #report_metrics_for_group("badgroup") plot_metrics() #test_metrics()
131,092
37.946227
260
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/braket/execute.py
# (C) Quantum Economic Development Consortium (QED-C) 2021. # Technical Advisory Committee on Standards and Benchmarks (TAC) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################### # Execute Module - Qiskit # # This module provides a way to submit a series of circuits to be executed in a batch. # When the batch is executed, each circuit is launched as a 'job' to be executed on the target system. # Upon completion, the results from each job are processed in a custom 'result handler' function # in order to calculate metrics such as fidelity. Relevant benchmark metrics are stored for each circuit # execution, so they can be aggregated and presented to the user. # import time import copy import metrics import importlib import os # AWS imports: Import Braket SDK modules from braket.aws import AwsDevice, AwsQuantumTask from braket.devices import LocalSimulator # Enter the S3 bucket you created during onboarding in the environment variables queried here my_bucket = os.environ.get("AWS_BRAKET_S3_BUCKET", "my_bucket") # the name of the bucket my_prefix = os.environ.get("AWS_BRAKET_S3_PREFIX", "my_prefix") # the name of the folder in the bucket# s3_folder = (my_bucket, my_prefix) # the selected Braket device device = None # default noise model, can be overridden using set_noise_model #noise = NoiseModel() noise = None # Initialize circuit execution module # Create array of batched circuits and a dict of active circuits # Configure a handler for processing circuits on completion batched_circuits = [] active_circuits = {} result_handler = None verbose = False # Special object class to hold job information and used as a dict key class Job: pass # Initialize the execution module, with a custom result handler def init_execution(handler): global batched_circuits, result_handler batched_circuits.clear() active_circuits.clear() result_handler = handler # Set the backend for execution def set_execution_target(backend_id='simulator'): """ Used to run jobs on a real hardware :param backend_id: device name. List of available devices depends on the provider example usage. set_execution_target(backend_id='arn:aws:braket:::device/quantum-simulator/amazon/sv1') """ global device if backend_id == None or backend_id == "": device = None elif backend_id == "simulator": device = LocalSimulator() else: device = AwsDevice(backend_id) if verbose: print(f"... using Braket device = {device}") # create an informative device name device_name = device.name device_str = str(device) if device_str.find(":device/") > 0: idx = device_str.rindex(":device/") device_name = device_str[idx+8:-1] metrics.set_plot_subtitle(f"Device = {device_name}") return device ''' def set_noise_model(noise_model = None): # see reference on setting up noise in Braket here: # https://github.com/aws/amazon-braket-examples/blob/main/examples/braket_features/Simulating_Noise_On_Amazon_Braket.ipynb global noise noise = noise_model ''' # Submit circuit for execution # This version executes immediately and calls the result handler def submit_circuit(qc, group_id, circuit_id, shots=100): # store circuit in array with submission time and circuit info batched_circuits.append( { "qc": qc, "group": str(group_id), "circuit": str(circuit_id), "submit_time": time.time(), "shots": shots } ); # print("... submit circuit - ", str(batched_circuits[len(batched_circuits)-1])) # Launch execution of all batched circuits def execute_circuits(): for batched_circuit in batched_circuits: execute_circuit(batched_circuit) batched_circuits.clear() # Launch execution of one batched circuit def execute_circuit(batched_circuit): active_circuit = copy.copy(batched_circuit) active_circuit["launch_time"] = time.time() # Initiate execution (currently, waits for completion) job = Job() job.result = braket_execute(batched_circuit["qc"], batched_circuit["shots"]) # put job into the active circuits with circuit info active_circuits[job] = active_circuit # print("... active_circuit = ", str(active_circuit)) ############## # Here we complete the job immediately job_complete(job) # Process a completed job def job_complete(job): active_circuit = active_circuits[job] # get job result result = job.result if result != None: #print(f"... result = {result}") #print(f"... result metadata = {result.task_metadata}") #print(f"... shots = {result.task_metadata.shots}") # this appears to include queueing time, so may not be what is needed if verbose: print(f"... task times = {result.task_metadata.createdAt} {result.task_metadata.endedAt}") # this only applies to simulator and does not appear to reflect actual exec time #print(f"... execution duration = {result.additional_metadata.simulatorMetadata.executionDuration}") # counts = result.measurement_counts # print("Total counts are:", counts) # obtain timing info from the results object ''' result_obj = result.to_dict() results_obj = result.to_dict()['results'][0] #print(f"result_obj = {result_obj}") #print(f"results_obj = {results_obj}") if "time_taken" in result_obj: exec_time = result_obj["time_taken"] elif "time_taken" in results_obj: exec_time = results_obj["time_taken"] else: #exec_time = 0; exec_time = time.time() - active_circuit["launch_time"] ''' # currently, we just use elapsed time, which includes queue time exec_time = time.time() - active_circuit["launch_time"] #print(f"exec time = {exec_time}") metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'elapsed_time', time.time() - active_circuit["launch_time"]) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) # If a handler has been established, invoke it here with result object if result_handler: result_handler(active_circuit["qc"], result, active_circuit["group"], active_circuit["circuit"]) del active_circuits[job] job = None # Wait for all executions to complete (not implemented yet) def wait_for_completion(): # check and sleep if not complete pass # return only when all circuits complete # Braket circuit execution code; this code waits for completion and returns result object def braket_execute(qc, shots=100): if qc == None: print("ERROR: No circuit to execute") return None # run circuit on selected device #print(f"device={device}") # immediate completion if Local Simulator if isinstance(device, LocalSimulator): result = device.run(qc, shots).result() # returns task object if managed device else: task = device.run(qc, s3_folder, shots) # if result is a Task object, loop until complete task_id = task.id # get status status = task.state() done = False pollcount = 0 while not done: status = task.state() #print('-- Status of (reconstructed) task:', status) pollcount += 1 if status == "FAILED": result = None print(f"... circuit execution failed") break if status == "CANCELLED": result = None print(f"... circuit execution cancelled") break elif status == "COMPLETED": result = task.result() break else: if verbose: #if pollcount <= 1: print('') print('.', end='') # delay a bit, increasing the delay periodically sleeptime = 1 if pollcount > 10: sleeptime = 10 elif pollcount > 20: sleeptime = 30 time.sleep(sleeptime) if pollcount > 1: if verbose: print('') # return result in either case return result # Test circuit execution def test_execution(): pass
9,199
31.857143
126
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/qiskit/benchmark_runner.py
import importlib import ast import argparse import os import sys benchmark_algorithms = [ "amplitude-estimation", "bernstein-vazirani", "deutsch-jozsa", "grovers", "hamiltonian-simulation", "hidden-shift", "maxcut", "monte-carlo", "phase-estimation", "quantum-fourier-transform", "shors", "vqe", ] # Add algorithms to path: for algorithm in benchmark_algorithms: sys.path.insert(1, os.path.join(f"{algorithm}", "qiskit")) import ae_benchmark import bv_benchmark import dj_benchmark import grovers_benchmark import hamiltonian_simulation_benchmark import hs_benchmark import maxcut_benchmark import mc_benchmark import pe_benchmark import qft_benchmark import shors_benchmark import vqe_benchmark if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run benchmarking") # Universal arguments: These arguments are used by all algorithms in the benchmarking suite. parser.add_argument("--algorithm", default="quantum-fourier-transform", help="Benchmarking algorithm to run.", type=str) parser.add_argument("--min_qubits", default=2, help="Minimum number of qubits.", type=int) parser.add_argument("--max_qubits", default=8, help="Maximum number of qubits", type=int) parser.add_argument("--max_circuits", default=3, help="Maximum number of circuits", type=int) parser.add_argument("--num_shots", default=100, help="Number of shots.", type=int) parser.add_argument("--backend_id", default="qasm_simulator", help="Backend simulator or hardware string", type=str) parser.add_argument("--provider_backend", default=None, help="Provider backend name.", type=str) parser.add_argument("--hub", default="ibm-q", help="Computing group hub.", type=str) parser.add_argument("--group", default="open", help="Group status", type=str) parser.add_argument("--project", default="main", help="Project", type=str) parser.add_argument("--provider_module_name", default=None, help="Hardware Provider Module Name", type= str) parser.add_argument("--provider_class_name", default=None, help="Hardware Provider Class Name", type= str) parser.add_argument("--noise_model", default=None, help="Custom Noise model defined in Custom Folder", type= str) parser.add_argument("--exec_options", default={}, help="Additional execution options", type=ast.literal_eval) # Additional arguments required by other algorithms. parser.add_argument("--epsilon", default=0.05, help="Used for Monte-Carlo", type=float) parser.add_argument("--degree", default=2, help="Used for Monte-Carlo", type=int) parser.add_argument("--use_mcx_shim", default=False, help="Used for Grovers", type=bool) parser.add_argument("--use_XX_YY_ZZ", default=False, help="Used for Hamiltonian-Simulation", type=bool) parser.add_argument("--num_state_qubits", default=1, help="Used for amplitude-estimation and Monte-Carlo", type=int) parser.add_argument("--method", default=1, help="Used for Bernstein-Vazirani, MaxCut, Monte-Carlo, QFT, Shor, and VQE", type=int) # Additional arguments required (only for MaxCut). parser.add_argument("--rounds", default=1, help="Used for MaxCut", type=int) parser.add_argument("--alpha", default=0.1, help="Used for MaxCut", type=float) parser.add_argument("--thetas_array", default=None, help="Used for MaxCut", type=list) parser.add_argument("--parameterized", default=False, help="Used for MaxCut", type=bool) parser.add_argument("--do_fidelities", default=True, help="Used for MaxCut", type=bool) parser.add_argument("--max_iter", default=30, help="Used for MaxCut", type=int) parser.add_argument("--score_metric", default="fidelity", help="Used for MaxCut", type=str) parser.add_argument("--x_metric", default="cumulative_exec_time", help="Used for MaxCut", type=str) parser.add_argument("--y_metric", default="num_qubits", help="Used for MaxCut", type=str) parser.add_argument("--fixed_metrics", default={}, help="Used for MaxCut", type=ast.literal_eval) parser.add_argument("--num_x_bins", default=15, help="Used for MaxCut", type=int) parser.add_argument("--x_size", default=None, help="Used for MaxCut", type=int) parser.add_argument("--y_size", default=None, help="Used for MaxCut", type=int) parser.add_argument("--use_fixed_angles", default=False, help="Used for MaxCut", type=bool) parser.add_argument("--objective_func_type", default='approx_ratio', help="Used for MaxCut", type=str) parser.add_argument("--plot_results", default=True, help="Used for MaxCut", type=bool) parser.add_argument("--save_res_to_file", default=False, help="Used for MaxCut", type=bool) parser.add_argument("--save_final_counts", default=False, help="Used for MaxCut", type=bool) parser.add_argument("--detailed_save_names", default=False, help="Used for MaxCut", type=bool) parser.add_argument("--comfort", default=False, help="Used for MaxCut", type=bool) parser.add_argument("--eta", default=0.5, help="Used for MaxCut", type=float) parser.add_argument("--_instance", default=None, help="Used for MaxCut", type=str) # Grouping for "common options" # i.e. show_plot_images etc. (others in metrics.py) args = parser.parse_args() # For Inserting the Noise model default into exec option as it is function call if args.noise_model is not None : if args.noise_model == 'None': args.exec_options["noise_model"] = None else: module,method = args.noise_model.split(".") module = importlib.import_module(f"custom.{module}") method = method.split("(")[0] custom_noise = getattr(module, method) noise = custom_noise() args.exec_options["noise_model"] = noise # Provider detail update using provider module name and class name if args.provider_module_name is not None and args.provider_class_name is not None: provider_class = getattr(importlib.import_module(args.provider_module_name), args.provider_class_name) provider = provider_class() provider_backend = provider.get_backend(args.backend_id) args.provider_backend = provider_backend algorithm = args.algorithm # Parsing universal arguments. universal_args = { "min_qubits": args.min_qubits, "max_qubits": args.max_qubits, "num_shots": args.num_shots, "backend_id": args.backend_id, "provider_backend": args.provider_backend, "hub": args.hub, "group": args.group, "project": args.project, "exec_options": args.exec_options, } # Parsing additional arguments used in some algorithms. additional_args = { "epsilon": args.epsilon, "degree": args.degree, "use_mcx_shim": args.use_mcx_shim, "use_XX_YY_ZZ": args.use_XX_YY_ZZ, "num_state_qubits": args.num_state_qubits, "method": args.method, } # Parsing arguments for MaxCut maxcut_args = { "rounds": args.rounds, "alpha": args.alpha, "thetas_array": args.thetas_array, "parameterized": args.parameterized, "do_fidelities": args.do_fidelities, "max_iter": args.max_iter, "score_metric": args.score_metric, "x_metric": args.x_metric, "y_metric": args.y_metric, "fixed_metrics": args.fixed_metrics, "num_x_bins": args.num_x_bins, "x_size": args.x_size, "y_size": args.y_size, "use_fixed_angles": args.use_fixed_angles, "objective_func_type": args.objective_func_type, "plot_results": args.plot_results, "save_res_to_file": args.save_res_to_file, "save_final_counts": args.save_final_counts, "detailed_save_names": args.detailed_save_names, "comfort": args.comfort, "eta": args.eta, "_instance": args._instance, } if algorithm == "amplitude-estimation": universal_args["num_state_qubits"] = additional_args["num_state_qubits"] ae_benchmark.run(**universal_args) elif algorithm == "bernstein-vazirani": universal_args["method"] = additional_args["method"] bv_benchmark.run(**universal_args) elif algorithm == "deutsch-jozsa": dj_benchmark.run(**universal_args) elif algorithm == "grovers": universal_args["use_mcx_shim"] = additional_args["use_mcx_shim"] grovers_benchmark.run(**universal_args) elif algorithm == "hamiltonian-simulation": universal_args["use_XX_YY_ZZ"] = additional_args["use_XX_YY_ZZ"] hamiltonian_simulation_benchmark.run(**universal_args) elif algorithm == "hidden-shift": hs_benchmark.run(**universal_args) elif algorithm == "maxcut": maxcut_args = {} maxcut_args.update(universal_args) maxcut_args.update(maxcut_args) maxcut_args["method"] = additional_args["method"] maxcut_args["degree"] = additional_args["degree"] maxcut_benchmark.run(**maxcut_args) elif algorithm == "monte-carlo": universal_args["epsilon"] = additional_args["epsilon"] universal_args["method"] = additional_args["method"] universal_args["degree"] = additional_args["degree"] mc_benchmark.run(**universal_args) elif algorithm == "phase-estimation": pe_benchmark.run(**universal_args) elif algorithm == "quantum-fourier-transform": universal_args["method"] = additional_args["method"] qft_benchmark.run(**universal_args) elif algorithm == "shors": universal_args["method"] = additional_args["method"] shors_benchmark.run(**universal_args) elif algorithm == "vqe": universal_args["method"] = additional_args["method"] vqe_benchmark.run(**universal_args) else: raise ValueError(f"Algorithm {algorithm} not supported.")
9,928
44.131818
133
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/qiskit/execute.py
# (C) Quantum Economic Development Consortium (QED-C) 2021. # Technical Advisory Committee on Standards and Benchmarks (TAC) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################### # Execute Module - Qiskit # # This module provides a way to submit a series of circuits to be executed in a batch. # When the batch is executed, each circuit is launched as a 'job' to be executed on the target system. # Upon completion, the results from each job are processed in a custom 'result handler' function # in order to calculate metrics such as fidelity. Relevant benchmark metrics are stored for each circuit # execution, so they can be aggregated and presented to the user. # import time import copy import metrics import importlib import traceback from collections import Counter import logging import numpy as np from datetime import datetime, timedelta from qiskit import execute, Aer, transpile from qiskit import IBMQ from qiskit.providers.jobstatus import JobStatus # Noise from qiskit.providers.aer.noise import NoiseModel, ReadoutError from qiskit.providers.aer.noise import depolarizing_error, reset_error ########################## # JOB MANAGEMENT VARIABLES # these are defined globally currently, but will become class variables later #### these variables are currently accessed as globals from user code # maximum number of active jobs max_jobs_active = 5 # job mode: False = wait, True = submit multiple jobs job_mode = False # Print progress of execution verbose = False # Print additional time metrics for each stage of execution verbose_time = False #### the following variables are accessed only through functions ... # specify whether to execute using sessions (and currently using Sampler only) use_sessions = False # internal session variables: users do not access service = None session = None sampler = None # logger for this module logger = logging.getLogger(__name__) # Use Aer qasm_simulator by default backend = Aer.get_backend("qasm_simulator") # Execution options, passed to transpile method backend_exec_options = None # Create array of batched circuits and a dict of active circuits batched_circuits = [] active_circuits = {} # Cached transpiled circuit, used for parameterized execution cached_circuits = {} # Configure a handler for processing circuits on completion # user-supplied result handler result_handler = None # Option to perform explicit transpile to collect depth metrics do_transpile_metrics = True # Option to perform transpilation prior to execution (disable to execute unmodified circuit) do_transpile_for_execute = True # Intercept function to post-process results result_processor = None width_processor = None # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] ####################### # SUPPORTING CLASSES # class BenchmarkResult is made for sessions runs. This is because # qiskit primitive job result instances don't have a get_counts method # like backend results do. As such, a get counts method is calculated # from the quasi distributions and shots taken. class BenchmarkResult(object): def __init__(self, qiskit_result): super().__init__() self.qiskit_result = qiskit_result self.metadata = qiskit_result.metadata def get_counts(self, qc=0): counts= self.qiskit_result.quasi_dists[0].binary_probabilities() for key in counts.keys(): counts[key] = int(counts[key] * self.qiskit_result.metadata[0]['shots']) return counts ##################### # DEFAULT NOISE MODEL # default noise model, can be overridden using set_noise_model() def default_noise_model(): noise = NoiseModel() # Add depolarizing error to all single qubit gates with error rate 0.05% # and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.0005 depol_two_qb_error = 0.005 noise.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% # and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise.add_all_qubit_readout_error(error_meas) # assign a quantum volume (measured using the values below) noise.QV = 2048 return noise noise = default_noise_model() ###################################################################### # INITIALIZATION METHODS # Initialize the execution module, with a custom result handler def init_execution(handler): global batched_circuits, result_handler batched_circuits.clear() active_circuits.clear() result_handler = handler cached_circuits.clear() # On initialize, always set trnaspilation for metrics and execute to True set_tranpilation_flags(do_transpile_metrics=True, do_transpile_for_execute=True) # Set the backend for execution def set_execution_target(backend_id='qasm_simulator', provider_module_name=None, provider_name=None, provider_backend=None, hub=None, group=None, project=None, exec_options=None): """ Used to run jobs on a real hardware :param backend_id: device name. List of available devices depends on the provider :param group: used to load IBMQ accounts. :param project: used to load IBMQ accounts. :param provider_module_name: If using a provider other than IBMQ, the string of the module that contains the Provider class. For example, for honeywell, this would be 'qiskit.providers.honeywell' :param provider_name: If using a provider other than IBMQ, the name of the provider class. For example, for Honeywell, this would be 'Honeywell'. :provider_backend: a custom backend object created and passed in, use backend_id as identifier example usage. set_execution_target(backend_id='honeywell_device_1', provider_module_name='qiskit.providers.honeywell', provider_name='Honeywell') """ global backend authentication_error_msg = "No credentials for {0} backend found. Using the simulator instead." # if a custom provider backend is given, use it ... # in this case, the backend_id is an arbitrary identifier that shows up in plots if provider_backend != None: backend = provider_backend # handle QASM simulator specially elif backend_id == 'qasm_simulator': backend = Aer.get_backend("qasm_simulator") # handle 'fake' backends here elif 'fake' in backend_id: backend = getattr( importlib.import_module( f'qiskit.providers.fake_provider.backends.{backend_id.split("_")[-1]}.{backend_id}' ), backend_id.title().replace('_', '') ) backend = backend() logger.info(f'Set {backend = }') # otherwise use the given provider and backend_id to find the backend else: # if provider_module name and provider_name are provided, obtain a custom provider if provider_module_name and provider_name: provider = getattr(importlib.import_module(provider_module_name), provider_name) try: # try, since not all custom providers have the .stored_account() method provider.load_account() backend = provider.get_backend(backend_id) except: print(authentication_error_msg.format(provider_name)) # otherwise, assume the backend_id is given and assume it is IBMQ device else: if IBMQ.stored_account(): # load a stored account IBMQ.load_account() # if use sessions, setup runtime service, Session, and Sampler if use_sessions: from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session global service service = QiskitRuntimeService() global session global sampler backend = service.backend(backend_id) session= Session(service=service, backend=backend_id) sampler = Sampler(session=session) # otherwise, use provider and old style backend # for IBM, create backend from IBMQ provider and given backend_id else: provider = IBMQ.get_provider(hub=hub, group=group, project=project) backend = provider.get_backend(backend_id) else: print(authentication_error_msg.format("IBMQ")) # create an informative device name for plots device_name = backend_id metrics.set_plot_subtitle(f"Device = {device_name}") #metrics.set_properties( { "api":"qiskit", "backend_id":backend_id } ) # save execute options with backend global backend_exec_options backend_exec_options = exec_options # Set the state of the transpilation flags def set_tranpilation_flags(do_transpile_metrics = True, do_transpile_for_execute = True): globals()['do_transpile_metrics'] = do_transpile_metrics globals()['do_transpile_for_execute'] = do_transpile_for_execute def set_noise_model(noise_model = None): """ See reference on NoiseModel here https://qiskit.org/documentation/stubs/qiskit.providers.aer.noise.NoiseModel.html Need to pass in a qiskit noise model object, i.e. for amplitude_damping_error: ``` from qiskit.providers.aer.noise import amplitude_damping_error noise = NoiseModel() one_qb_error = 0.005 noise.add_all_qubit_quantum_error(amplitude_damping_error(one_qb_error), ['u1', 'u2', 'u3']) two_qb_error = 0.05 noise.add_all_qubit_quantum_error(amplitude_damping_error(two_qb_error).tensor(amplitude_damping_error(two_qb_error)), ['cx']) set_noise_model(noise_model=noise) ``` Can also be used to remove noisy simulation by setting `noise_model = None`: ``` set_noise_model() ``` """ global noise noise = noise_model # set flag to control use of sessions def set_use_sessions(val = False): global use_sessions use_sessions = val ###################################################################### # CIRCUIT EXECUTION METHODS # Submit circuit for execution # Execute immediately if possible or put into the list of batched circuits def submit_circuit(qc, group_id, circuit_id, shots=100, params=None): # create circuit object with submission time and circuit info circuit = { "qc": qc, "group": str(group_id), "circuit": str(circuit_id), "submit_time": time.time(), "shots": shots, "params": params } if verbose: print(f'... submit circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={circuit["params"]}') ''' if params != None: for param in params.items(): print(f"{param}") print([param[1] for param in params.items()]) ''' # logger doesn't like unicode, so just log the array values for now #logger.info(f'Submitting circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={str(circuit["params"])}') logger.info(f'Submitting circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={[param[1] for param in params.items()] if params else None}') # immediately post the circuit for execution if active jobs < max if len(active_circuits) < max_jobs_active: execute_circuit(circuit) # or just add it to the batch list for execution after others complete else: batched_circuits.append(circuit) if verbose: print(" ... added circuit to batch") # Launch execution of one job (circuit) def execute_circuit(circuit): logging.info('Entering execute_circuit') active_circuit = copy.copy(circuit) active_circuit["launch_time"] = time.time() active_circuit["pollcount"] = 0 shots = circuit["shots"] qc = circuit["qc"] # do the decompose before obtaining circuit metrics so we expand subcircuits to 2 levels # Comment this out here; ideally we'd generalize it here, but it is intended only to # 'flatten out' circuits with subcircuits; we do it in the benchmark code for now so # it only affects circuits with subcircuits (e.g. QFT, AE ...) # qc = qc.decompose() # qc = qc.decompose() # obtain initial circuit metrics qc_depth, qc_size, qc_count_ops, qc_xi, qc_n2q = get_circuit_metrics(qc) # default the normalized transpiled metrics to the same, in case exec fails qc_tr_depth = qc_depth qc_tr_size = qc_size qc_tr_count_ops = qc_count_ops qc_tr_xi = qc_xi; qc_tr_n2q = qc_n2q #print(f"... before tp: {qc_depth} {qc_size} {qc_count_ops}") try: # transpile the circuit to obtain size metrics using normalized basis if do_transpile_metrics: qc_tr_depth, qc_tr_size, qc_tr_count_ops, qc_tr_xi, qc_tr_n2q = transpile_for_metrics(qc) # use noise model from execution options if given for simulator this_noise = noise # make a clone of the backend options so we can remove elements that we use, then pass to .run() global backend_exec_options backend_exec_options_copy = copy.copy(backend_exec_options) ''' # if 'executor' provided, perform all execution there and return if backend_exec_options_copy != None: executor = backend_exec_options_copy.pop("executor", None) if executor: st = time.time() executor(circuit["qc"], shots=shots, backend=backend, result_handler=result_handler, **backend_exec_options_copy) if verbose_time: print(f" *** executor() time = {time.time() - st}") continue with job ''' # get noise model from options; used only in simulator for now if backend_exec_options_copy != None and "noise_model" in backend_exec_options_copy: this_noise = backend_exec_options_copy["noise_model"] #print(f"... using custom noise model: {this_noise}") # extract execution options if set if backend_exec_options_copy == None: backend_exec_options_copy = {} optimization_level = backend_exec_options_copy.pop("optimization_level", None) layout_method = backend_exec_options_copy.pop("layout_method", None) routing_method = backend_exec_options_copy.pop("routing_method", None) transpile_attempt_count = backend_exec_options_copy.pop("transpile_attempt_count", None) transformer = backend_exec_options_copy.pop("transformer", None) global result_processor, width_processor postprocessors = backend_exec_options_copy.pop("postprocessor", None) if postprocessors: result_processor, width_processor = postprocessors if use_sessions: logger.info(f"Executing on backend: {backend.name}") else: logger.info(f"Executing on backend: {backend.name()}") #************************************************ # Initiate execution (with noise if specified and this is a simulator backend) if this_noise is not None and not use_sessions and backend.name().endswith("qasm_simulator"): logger.info(f"Performing noisy simulation, shots = {shots}") # if the noise model has associated QV value, copy it to metrics module for plotting if hasattr(this_noise, "QV"): metrics.QV = this_noise.QV simulation_circuits = circuit["qc"] # we already have the noise model, just need to remove it from the options # (only for simulator; for other backends, it is treaded like keyword arg) dummy = backend_exec_options_copy.pop("noise_model", None) # transpile and bind circuit with parameters; use cache if flagged trans_qc = transpile_and_bind_circuit(circuit["qc"], circuit["params"], backend) simulation_circuits = trans_qc # apply transformer pass if provided if transformer: logger.info("applying transformer to noisy simulator") simulation_circuits, shots = invoke_transformer(transformer, trans_qc, backend=backend, shots=shots) # Indicate number of qubits about to be executed if width_processor: width_processor(qc) # for noisy simulator, use execute() which works; # no need for transpile above unless there are options like transformer logger.info(f'Running circuit on noisy simulator, shots={shots}') st = time.time() ''' some circuits, like Grover's behave incorrectly if we use run() job = backend.run(simulation_circuits, shots=shots, noise_model=this_noise, basis_gates=this_noise.basis_gates, **backend_exec_options_copy) ''' job = execute(simulation_circuits, backend, shots=shots, noise_model=this_noise, basis_gates=this_noise.basis_gates, **backend_exec_options_copy) logger.info(f'Finished Running on noisy simulator - {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** qiskit.execute() time = {round(time.time() - st, 5)}") #************************************************ # Initiate execution for all other backends and noiseless simulator else: # if set, transpile many times and pick shortest circuit # DEVNOTE: this does not handle parameters yet, or optimizations if transpile_attempt_count: trans_qc = transpile_multiple_times(circuit["qc"], circuit["params"], backend, transpile_attempt_count, optimization_level=None, layout_method=None, routing_method=None) # transpile and bind circuit with parameters; use cache if flagged else: trans_qc = transpile_and_bind_circuit(circuit["qc"], circuit["params"], backend, optimization_level=optimization_level, layout_method=layout_method, routing_method=routing_method) # apply transformer pass if provided if transformer: trans_qc, shots = invoke_transformer(transformer, trans_qc, backend=backend, shots=shots) # Indicate number of qubits about to be executed if width_processor: width_processor(qc) #************************************* # perform circuit execution on backend logger.info(f'Running trans_qc, shots={shots}') st = time.time() if use_sessions: job = sampler.run(trans_qc, shots=shots, **backend_exec_options_copy) else: job = backend.run(trans_qc, shots=shots, **backend_exec_options_copy) logger.info(f'Finished Running trans_qc - {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** qiskit.run() time = {round(time.time() - st, 5)}") except Exception as e: print(f'ERROR: Failed to execute circuit {active_circuit["group"]} {active_circuit["circuit"]}') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) return # print("Job status is ", job.status() ) # put job into the active circuits with circuit info active_circuits[job] = active_circuit # print("... active_circuit = ", str(active_circuit)) # store circuit dimensional metrics metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'depth', qc_depth) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'size', qc_size) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'xi', qc_xi) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'n2q', qc_n2q) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_depth', qc_tr_depth) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_size', qc_tr_size) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_xi', qc_tr_xi) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_n2q', qc_tr_n2q) # also store the job_id for future reference metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'job_id', job.job_id()) if verbose: print(f"... executing job {job.job_id()}") # special handling when only runnng one job at a time: wait for result here # so the status check called later immediately returns done and avoids polling if max_jobs_active <= 1: wait_on_job_result(job, active_circuit) # return, so caller can do other things while waiting for jobs to complete # block and wait for the job result to be returned # handle network timeouts by doing up to 40 retries once every 15 seconds def wait_on_job_result(job, active_circuit): retry_count = 0 result = None while retry_count < 40: try: retry_count += 1 #print(f"... calling job.result()") result = job.result() break except Exception as e: print(f'... error occurred during job.result() for circuit {active_circuit["group"]} {active_circuit["circuit"]} -- retry {retry_count}') time.sleep(15) continue if result == None: print(f'ERROR: during job.result() for circuit {active_circuit["group"]} {active_circuit["circuit"]}') raise ValueError("Failed to execute job") else: #print(f"... job.result() is done, with result data, continuing") pass # Check and return job_status # handle network timeouts by doing up to 40 retries once every 15 seconds def get_job_status(job, active_circuit): retry_count = 0 status = None while retry_count < 3: try: retry_count += 1 #print(f"... calling job.status()") status = job.status() break except Exception as e: print(f'... error occurred during job.status() for circuit {active_circuit["group"]} {active_circuit["circuit"]} -- retry {retry_count}') time.sleep(15) continue if status == None: print(f'ERROR: during job.status() for circuit {active_circuit["group"]} {active_circuit["circuit"]}') raise ValueError("Failed to get job status") else: #print(f"... job.result() is done, with result data, continuing") pass return status # Get circuit metrics fom the circuit passed in def get_circuit_metrics(qc): logger.info('Entering get_circuit_metrics') #print(qc) # obtain initial circuit size metrics qc_depth = qc.depth() qc_size = qc.size() qc_count_ops = qc.count_ops() qc_xi = 0 qc_n2q = 0 # iterate over the ordereddict to determine xi (ratio of 2 qubit gates to one qubit gates) n1q = 0; n2q = 0 if qc_count_ops != None: for key, value in qc_count_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value qc_xi = n2q / (n1q + n2q) qc_n2q = n2q return qc_depth, qc_size, qc_count_ops, qc_xi, qc_n2q # Transpile the circuit to obtain normalized size metrics against a common basis gate set def transpile_for_metrics(qc): logger.info('Entering transpile_for_metrics') #print("*** Before transpile ...") #print(qc) st = time.time() # use either the backend or one of the basis gate sets if basis_selector == 0: logger.info(f"Start transpile with {basis_selector = }") qc = transpile(qc, backend) logger.info(f"End transpile with {basis_selector = }") else: basis_gates = basis_gates_array[basis_selector] logger.info(f"Start transpile with basis_selector != 0") qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) logger.info(f"End transpile with basis_selector != 0") #print(qc) qc_tr_depth = qc.depth() qc_tr_size = qc.size() qc_tr_count_ops = qc.count_ops() #print(f"*** after transpile: {qc_tr_depth} {qc_tr_size} {qc_tr_count_ops}") # iterate over the ordereddict to determine xi (ratio of 2 qubit gates to one qubit gates) n1q = 0; n2q = 0 if qc_tr_count_ops != None: for key, value in qc_tr_count_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): n2q += value else: n1q += value qc_tr_xi = n2q / (n1q + n2q) qc_tr_n2q = n2q #print(f"... qc_tr_xi = {qc_tr_xi} {n1q} {n2q}") logger.info(f'transpile_for_metrics - {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** transpile_for_metrics() time = {round(time.time() - st, 5)}") return qc_tr_depth, qc_tr_size, qc_tr_count_ops, qc_tr_xi, qc_tr_n2q # Return a transpiled and bound circuit # Cache the transpiled, and use it if do_transpile_for_execute not set # DEVNOTE: this approach does not permit passing of untranspiled circuit through # DEVNOTE: currently this only caches a single circuit def transpile_and_bind_circuit(circuit, params, backend, optimization_level=None, layout_method=None, routing_method=None): logger.info(f'transpile_and_bind_circuit()') st = time.time() if do_transpile_for_execute: logger.info('transpiling for execute') trans_qc = transpile(circuit, backend, optimization_level=optimization_level, layout_method=layout_method, routing_method=routing_method) # cache this transpiled circuit cached_circuits["last_circuit"] = trans_qc else: logger.info('use cached transpiled circuit for execute') if verbose_time: print(f" ... using cached circuit, no transpile") ##trans_qc = circuit["qc"] # for now, use this cached transpiled circuit (should be separate flag to pass raw circuit) trans_qc = cached_circuits["last_circuit"] #print(trans_qc) #print(f"... trans_qc name = {trans_qc.name}") # obtain name of the transpiled or cached circuit trans_qc_name = trans_qc.name # if parameters provided, bind them to circuit if params != None: # Note: some loggers cannot handle unicode in param names, so only show the values #logger.info(f"Binding parameters to circuit: {str(params)}") logger.info(f"Binding parameters to circuit: {[param[1] for param in params.items()]}") if verbose_time: print(f" ... binding parameters") trans_qc = trans_qc.bind_parameters(params) #print(trans_qc) # store original name in parameterized circuit, so it can be found with get_result() trans_qc.name = trans_qc_name #print(f"... trans_qc name = {trans_qc.name}") logger.info(f'transpile_and_bind_circuit - {trans_qc_name} {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** transpile_and_bind() time = {round(time.time() - st, 5)}") return trans_qc # Transpile a circuit multiple times for optimal results # DEVNOTE: this does not handle parameters yet def transpile_multiple_times(circuit, params, backend, transpile_attempt_count, optimization_level=None, layout_method=None, routing_method=None): logger.info(f"transpile_multiple_times({transpile_attempt_count})") st = time.time() # array of circuits that have been transpile trans_qc_list = [ transpile( circuit, backend, optimization_level=optimization_level, layout_method=layout_method, routing_method=routing_method ) for _ in range(transpile_attempt_count) ] best_op_count = [] for circ in trans_qc_list: # check if there are cx in transpiled circs if 'cx' in circ.count_ops().keys(): # get number of operations best_op_count.append( circ.count_ops()['cx'] ) # check if there are sx in transpiled circs elif 'sx' in circ.count_ops().keys(): # get number of operations best_op_count.append( circ.count_ops()['sx'] ) # print(f"{best_op_count = }") if best_op_count: # pick circuit with lowest number of operations best_idx = np.where(best_op_count == np.min(best_op_count))[0][0] trans_qc = trans_qc_list[best_idx] else: # otherwise just pick the first in the list best_idx = 0 trans_qc = trans_qc_list[0] logger.info(f'transpile_multiple_times - {best_idx} {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** transpile_multiple_times() time = {round(time.time() - st, 5)}") return trans_qc # Invoke a circuit transformer, returning modifed circuit (array) and modifed shots def invoke_transformer(transformer, circuit, backend=backend, shots=100): logger.info('Invoking Transformer') st = time.time() # apply the transformer and get back either a single circuit or a list of circuits tr_circuit = transformer(circuit, backend=backend) # if transformer results in multiple circuits, divide shot count # results will be accumulated in job_complete # NOTE: this will need to set a flag to distinguish from multiple circuit execution if isinstance(tr_circuit, list) and len(tr_circuit) > 1: shots = int(shots / len(tr_circuit)) logger.info(f'Transformer - {round(time.time() - st, 5)} (ms)') if verbose_time:print(f" *** transformer() time = {round(time.time() - st, 5)} (ms)") return tr_circuit, shots ########################################################################### # Process a completed job def job_complete(job): active_circuit = active_circuits[job] if verbose: print(f'\n... job complete - group={active_circuit["group"]} id={active_circuit["circuit"]} shots={active_circuit["shots"]}') logger.info(f'job complete - group={active_circuit["group"]} id={active_circuit["circuit"]} shots={active_circuit["shots"]}') # compute elapsed time for circuit; assume exec is same, unless obtained from result elapsed_time = time.time() - active_circuit["launch_time"] # report exec time as 0 unless valid measure returned exec_time = 0.0 # store these initial time measures now, in case job had error metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'elapsed_time', elapsed_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) # get job result (DEVNOTE: this might be different for diff targets) result = None if job.status() == JobStatus.DONE: result = job.result() # print("... result = ", str(result)) # counts = result.get_counts(qc) # print("Total counts are:", counts) # if we are using sessions, structure of result object is different; # use a BenchmarkResult object to hold session result and provide a get_counts() # that returns counts to the benchmarks in the same form as without sessions if use_sessions: result = BenchmarkResult(result) #counts = result.get_counts() actual_shots = result.metadata[0]['shots'] result_obj = result.metadata[0] results_obj = result.metadata[0] else: result_obj = result.to_dict() results_obj = result.to_dict()['results'][0] # get the actual shots and convert to int if it is a string # DEVNOTE: this summation currently applies only to randomized compiling # and may cause problems with other use cases (needs review) actual_shots = 0 for experiment in result_obj["results"]: actual_shots += experiment["shots"] #print(f"result_obj = {result_obj}") #print(f"results_obj = {results_obj}") #print(f'shots = {results_obj["shots"]}') # convert actual_shots to int if it is a string if type(actual_shots) is str: actual_shots = int(actual_shots) # check for mismatch of requested shots and actual shots if actual_shots != active_circuit["shots"]: print(f'WARNING: requested shots not equal to actual shots: {active_circuit["shots"]} != {actual_shots} ') # allow processing to continue, but use the requested shot count actual_shots = active_circuit["shots"] # obtain timing info from the results object # the data has been seen to come from both places below if "time_taken" in result_obj: exec_time = result_obj["time_taken"] elif "time_taken" in results_obj: exec_time = results_obj["time_taken"] # override the initial value with exec_time returned from successful execution metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) # process additional detailed step times, if they exist (this might override exec_time too) process_step_times(job, result, active_circuit) # remove from list of active circuits del active_circuits[job] # If a result handler has been established, invoke it here with result object if result != None and result_handler: # invoke a result processor if specified in exec_options if result_processor: logger.info(f'result_processor(...)') result = result_processor(result) # The following computes the counts by summing them up, allowing for the case where # <result> contains results from multiple circuits # DEVNOTE: This will need to change; currently the only case where we have multiple result counts # is when using randomly_compile; later, there will be other cases if not use_sessions and type(result.get_counts()) == list: total_counts = dict() for count in result.get_counts(): total_counts = dict(Counter(total_counts) + Counter(count)) # make a copy of the result object so we can return a modified version orig_result = result result = copy.copy(result) # replace the results array with an array containing only the first results object # then populate other required fields results = copy.copy(result.results[0]) results.header.name = active_circuit["qc"].name # needed to identify the original circuit results.shots = actual_shots results.data.counts = total_counts result.results = [ results ] try: result_handler(active_circuit["qc"], result, active_circuit["group"], active_circuit["circuit"], active_circuit["shots"] ) except Exception as e: print(f'ERROR: failed to execute result_handler for circuit {active_circuit["group"]} {active_circuit["circuit"]}') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) # Process detailed step times, if they exist def process_step_times(job, result, active_circuit): #print("... processing step times") exec_creating_time = 0 exec_validating_time = 0 exec_queued_time = 0 exec_running_time = 0 # get breakdown of execution time, if method exists # this attribute not available for some providers and only for circuit-runner model; if not use_sessions and "time_per_step" in dir(job) and callable(job.time_per_step): time_per_step = job.time_per_step() if verbose: print(f"... job.time_per_step() = {time_per_step}") creating_time = time_per_step.get("CREATING") validating_time = time_per_step.get("VALIDATING") queued_time = time_per_step.get("QUEUED") running_time = time_per_step.get("RUNNING") completed_time = time_per_step.get("COMPLETED") # for testing, since hard to reproduce on some systems #running_time = None # make these all slightly non-zero so averaging code is triggered (> 0.001 required) exec_creating_time = 0.001 exec_validating_time = 0.001 exec_queued_time = 0.001 exec_running_time = 0.001 # this is note used exec_quantum_classical_time = 0.001 # compute the detailed time metrics if validating_time and creating_time: exec_creating_time = (validating_time - creating_time).total_seconds() if queued_time and validating_time: exec_validating_time = (queued_time - validating_time).total_seconds() if running_time and queued_time: exec_queued_time = (running_time - queued_time).total_seconds() if completed_time and running_time: exec_running_time = (completed_time - running_time).total_seconds() # when sessions and sampler used, we obtain metrics differently if use_sessions: job_timestamps= job.metrics()['timestamps'] if verbose: print(f"... job.metrics() = {job.metrics()}") print(f"... job.result().metadata[0] = {result.metadata[0]}") # occasionally, these metrics come back as None, so try to use them try: created_time = datetime.strptime(job_timestamps['created'][11:-1],"%H:%M:%S.%f") created_time_delta = timedelta(hours=created_time.hour, minutes=created_time.minute, seconds=created_time.second, microseconds = created_time.microsecond) finished_time = datetime.strptime(job_timestamps['finished'][11:-1],"%H:%M:%S.%f") finished_time_delta = timedelta(hours=finished_time.hour, minutes=finished_time.minute, seconds=finished_time.second, microseconds = finished_time.microsecond) running_time = datetime.strptime(job_timestamps['running'][11:-1],"%H:%M:%S.%f") running_time_delta = timedelta(hours=running_time.hour, minutes=running_time.minute, seconds=running_time.second, microseconds = running_time.microsecond) # compute the total seconds for creating and running the circuit exec_creating_time = (running_time_delta - created_time_delta).total_seconds() exec_running_time = (finished_time_delta - running_time_delta).total_seconds() # these do not seem to be avaiable exec_validating_time = 0.001 exec_queued_time = 0.001 # DEVNOTE: we do not compute this yet # exec_quantum_classical_time = job.metrics()['bss'] #metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_quantum_classical_time', exec_quantum_classical_time) # when using sessions, the 'running_time' is the 'quantum exec time' - override it. metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_running_time) except Exception as e: if verbose: print(f'WARNING: incomplete time metrics for circuit {active_circuit["group"]} {active_circuit["circuit"]}') print(f"... job = {job.job_id()} exception = {e}") # In metrics, we use > 0.001 to indicate valid data; need to floor these values to 0.001 exec_creating_time = max(0.001, exec_creating_time) exec_validating_time = max(0.001, exec_validating_time) exec_queued_time = max(0.001, exec_queued_time) exec_running_time = max(0.001, exec_running_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_creating_time', exec_creating_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_validating_time', 0.001) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_queued_time', 0.001) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_running_time', exec_running_time) #print("... time_per_step = ", str(time_per_step)) if verbose: print(f"... computed exec times: queued = {exec_queued_time}, creating/transpiling = {exec_creating_time}, validating = {exec_validating_time}, running = {exec_running_time}") # Process a job, whose status cannot be obtained def job_status_failed(job): active_circuit = active_circuits[job] if verbose: print(f'\n... job status failed - group={active_circuit["group"]} id={active_circuit["circuit"]} shots={active_circuit["shots"]}') # compute elapsed time for circuit; assume exec is same, unless obtained from result elapsed_time = time.time() - active_circuit["launch_time"] # report exec time as 0 unless valid measure returned exec_time = 0.0 # remove from list of active circuits del active_circuits[job] metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'elapsed_time', elapsed_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) ###################################################################### # JOB MANAGEMENT METHODS # Job management involves coordinating the batching, queueing, # and completion processing of circuits that are submitted for execution. # Throttle the execution of active and batched jobs. # Wait for active jobs to complete. As each job completes, # check if there are any batched circuits waiting to be executed. # If so, execute them, removing them from the batch. # Execute the user-supplied completion handler to allow user to # check if a group of circuits has been completed and report on results. # Then, if there are no more circuits remaining in batch, exit, # otherwise continue to wait for additional active circuits to complete. def throttle_execution(completion_handler=metrics.finalize_group): logger.info('Entering throttle_execution') #if verbose: #print(f"... throttling execution, active={len(active_circuits)}, batched={len(batched_circuits)}") # check and sleep if not complete done = False pollcount = 0 while not done: # check if any jobs complete check_jobs(completion_handler) # return only when all jobs complete if len(batched_circuits) < 1: break # delay a bit, increasing the delay periodically sleeptime = 0.25 if pollcount > 6: sleeptime = 0.5 if pollcount > 60: sleeptime = 1.0 time.sleep(sleeptime) pollcount += 1 if verbose: if pollcount > 0: print("") #print(f"... throttling execution(2), active={len(active_circuits)}, batched={len(batched_circuits)}") # Wait for all active and batched circuits to complete. # Execute the user-supplied completion handler to allow user to # check if a group of circuits has been completed and report on results. # Return when there are no more active circuits. # This is used as a way to complete all groups of circuits and report results. def finalize_execution(completion_handler=metrics.finalize_group, report_end=True): #if verbose: #print("... finalize_execution") # check and sleep if not complete done = False pollcount = 0 while not done: # check if any jobs complete check_jobs(completion_handler) # return only when all jobs complete if len(active_circuits) < 1: break # delay a bit, increasing the delay periodically sleeptime = 0.10 # was 0.25 if pollcount > 6: sleeptime = 0.20 # 0.5 if pollcount > 60: sleeptime = 0.5 # 1.0 time.sleep(sleeptime) pollcount += 1 if verbose: if pollcount > 0: print("") # indicate we are done collecting metrics (called once at end of app) if report_end: metrics.end_metrics() # also, close any active session at end of the app global session if report_end and use_sessions and session != None: if verbose: print("... closing active session!\n") session.close() session = None # Check if any active jobs are complete - process if so # Before returning, launch any batched jobs that will keep active circuits < max # When any job completes, aggregate and report group metrics if all circuits in group are done # then return, don't sleep def check_jobs(completion_handler=None): for job, circuit in active_circuits.items(): try: #status = job.status() status = get_job_status(job, circuit) # use this version, robust to network failure #print("Job status is ", status) except Exception as e: print(f'ERROR: Unable to retrieve job status for circuit {circuit["group"]} {circuit["circuit"]}') print(f"... job = {job.job_id()} exception = {e}") # finish the job by removing from active list job_status_failed(job) break circuit["pollcount"] += 1 # if job not complete, provide comfort ... if status == JobStatus.QUEUED: if verbose: if circuit["pollcount"] < 32 or (circuit["pollcount"] % 15 == 0): print('.', end='') continue elif status == JobStatus.INITIALIZING: if verbose: print('i', end='') continue elif status == JobStatus.VALIDATING: if verbose: print('v', end='') continue elif status == JobStatus.RUNNING: if verbose: print('r', end='') continue # when complete, canceled, or failed, process the job if status == JobStatus.CANCELLED: print(f"... circuit execution cancelled.") if status == JobStatus.ERROR: print(f"... circuit execution failed.") if hasattr(job, "error_message"): print(f" job = {job.job_id()} {job.error_message()}") if status == JobStatus.DONE or status == JobStatus.CANCELLED or status == JobStatus.ERROR: #if verbose: print("Job status is ", job.status() ) active_circuit = active_circuits[job] group = active_circuit["group"] # process the job and its result data job_complete(job) # call completion handler with the group id if completion_handler != None: completion_handler(group) break # if not at maximum jobs and there are jobs in batch, then execute another if len(active_circuits) < max_jobs_active and len(batched_circuits) > 0: # pop the first circuit in the batch and launch execution circuit = batched_circuits.pop(0) if verbose: print(f'... pop and submit circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]}') execute_circuit(circuit) # Test circuit execution def test_execution(): pass ######################################## # DEPRECATED METHODS # these methods are retained for reference and in case needed later # Wait for active and batched circuits to complete # This is used as a way to complete a group of circuits and report # results before continuing to create more circuits. # Deprecated: maintained for compatibility until all circuits are modified # to use throttle_execution(0 and finalize_execution() def execute_circuits(): # deprecated code ... ''' for batched_circuit in batched_circuits: execute_circuit(batched_circuit) batched_circuits.clear() ''' # wait for all jobs to complete wait_for_completion() # Wait for all active and batched jobs to complete # deprecated version, with no completion handler def wait_for_completion(): if verbose: print("... waiting for completion") # check and sleep if not complete done = False pollcount = 0 while not done: # check if any jobs complete check_jobs() # return only when all jobs complete if len(active_circuits) < 1: break # delay a bit, increasing the delay periodically sleeptime = 0.25 if pollcount > 6: sleeptime = 0.5 if pollcount > 60: sleeptime = 1.0 time.sleep(sleeptime) pollcount += 1 if verbose: if pollcount > 0: print("") # Wait for a single job to complete, return when done # (replaced by wait_for_completion, which handle multiple jobs) def job_wait_for_completion(job): done=False pollcount = 0 while not done: status = job.status() #print("Job status is ", status) if status == JobStatus.DONE: break if status == JobStatus.CANCELLED: break if status == JobStatus.ERROR: break if status == JobStatus.QUEUED: if verbose: if pollcount < 44 or (pollcount % 15 == 0): print('.', end='') elif status == JobStatus.INITIALIZING: if verbose: print('i', end='') elif status == JobStatus.VALIDATING: if verbose: print('v', end='') elif status == JobStatus.RUNNING: if verbose: print('r', end='') pollcount += 1 # delay a bit, increasing the delay periodically sleeptime = 0.25 if pollcount > 8: sleeptime = 0.5 if pollcount > 100: sleeptime = 1.0 time.sleep(sleeptime) if pollcount > 0: if verbose: print("") #if verbose: print("Job status is ", job.status() ) if job.status() == JobStatus.CANCELLED: print(f"\n... circuit execution cancelled.") if job.status() == JobStatus.ERROR: print(f"\n... circuit execution failed.")
53,550
39.143178
184
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/postprocessors/mthree/mthree_em.py
################################################################# # # Post-processor module: mthree error mitigation handlers import importlib import mthree from qiskit import Aer mit = None mit_num_qubits = 2 verbose = False # Handler called to postprocess results before they are passed to calling program def mthree_handler(result): if verbose: print(f'Before: {dict(sorted(result.results[0].data.counts.items())) = }') raw_counts = result.get_counts() shots = sum(raw_counts.values()) quasi_counts = mit.apply_correction(raw_counts, range(len(list(raw_counts.keys())[0]))) for k, v in quasi_counts.items(): quasi_counts[k] = round(v * shots) if verbose: print(f'Quasi: {quasi_counts = }') qmin = min(quasi_counts.values()) qmax = max(quasi_counts.values()) qshots = sum(quasi_counts.values()) qrange = (qmax - qmin) if verbose: print(f"{qmin = } {qmax = } {qrange = } {qshots = } {shots = }") # store modified counts in result object result.results[0].data.counts = quasi_counts if verbose: print(f'After: {result.results[0].data.counts = }') return result # Handler called to configure mthree for number of qubits in executing circuit def mthree_width_handler(circuit): global mit_num_qubits num_qubits = circuit.num_qubits # print(circuit) if num_qubits != mit_num_qubits: if verbose: print(f'... updating mthree width to {num_qubits = }') mit_num_qubits = num_qubits mit.cals_from_system(range(num_qubits)) # Routine to initialize mthree and return two handlers def get_mthree_handlers(backend_id, provider_backend): global mit # special handling for qasm_simulator if backend_id.endswith("qasm_simulator"): provider_backend = Aer.get_backend(backend_id) # special handling for fake backends elif 'fake' in backend_id: backend = getattr( importlib.import_module( f'qiskit.providers.fake_provider.backends.{backend_id.split("_")[-1]}.{backend_id}' ), backend_id.title().replace('_', '') ) provider_backend = backend() # initialize mthree with given backend mit = mthree.M3Mitigation(provider_backend) if verbose: print(f"... initializing mthree for backend_id = {backend_id}") mit.cals_from_system(range(mit_num_qubits)) return (mthree_handler, mthree_width_handler)
2,448
30.805195
99
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/custom/custom_qiskit_noise_model.py
# # Define a custom noise model to be used during execution of Qiskit Aer simulator # # Note: this custom definition is the same as the default noise model provided # The code is provided here for users to copy to their own file and customize from qiskit.providers.aer.noise import NoiseModel, ReadoutError from qiskit.providers.aer.noise import depolarizing_error, reset_error def my_noise_model(): noise = NoiseModel() # Add depolarizing error to all single qubit gates with error rate 0.3% # and to all two qubit gates with error rate 3.0% depol_one_qb_error = 0.003 depol_two_qb_error = 0.03 noise.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% # and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise.add_all_qubit_readout_error(error_meas) # assign a quantum volume (measured using the values below) noise.QV = 32 #print("... using custom noise model") return noise
1,862
40.4
107
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/cirq/execute.py
# (C) Quantum Economic Development Consortium (QED-C) 2021. # Technical Advisory Committee on Standards and Benchmarks (TAC) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################### # Execute Module - Cirq # # This module provides a way to submit a series of circuits to be executed in a batch. # When the batch is executed, each circuit is launched as a 'job' to be executed on the target system. # Upon completion, the results from each job are processed in a custom 'result handler' function # in order to calculate metrics such as fidelity. Relevant benchmark metrics are stored for each circuit # execution, so they can be aggregated and presented to the user. # import time import copy import metrics import cirq backend = cirq.Simulator() # Use Cirq Simulator by default #noise = 'DEFAULT' noise=None # Initialize circuit execution module # Create array of batched circuits and a dict of active circuits # Configure a handler for processing circuits on completion batched_circuits = [ ] active_circuits = { } result_handler = None device=None # Special object class to hold job information and used as a dict key class Job: pass # Initialize the execution module, with a custom result handler def init_execution (handler): global batched_circuits, result_handler batched_circuits.clear() active_circuits.clear() result_handler = handler # create an informative device name # this should be move to set_execution_target method later device_name = "simulator" metrics.set_plot_subtitle(f"Device = {device_name}") # Set the backend for execution def set_execution_target(backend_id='simulator', provider_backend=None): """ Used to run jobs on a real hardware :param backend_id: device name. List of available devices depends on the provider :provider_backend: a custom backend object created and passed in, use backend_id as identifier example usage. set_execution_target(backend_id='aqt_qasm_simulator', provider_backende=aqt.backends.aqt_qasm_simulator) """ global backend # if a custom provider backend is given, use it ... if provider_backend != None: backend = provider_backend # otherwise test for simulator elif backend_id == 'simulator': backend = cirq.Simulator() # nothing else is supported yet, default to simulator else: print(f"ERROR: Unknown backend_id: {backend_id}, defaulting to Cirq Simulator") backend = cirq.Simulator() backend_id = "simulator" # create an informative device name device_name = backend_id metrics.set_plot_subtitle(f"Device = {device_name}") def set_noise_model(noise_model = None): # see reference on NoiseModel here https://quantumai.google/cirq/noise global noise noise = noise_model # Submit circuit for execution # This version executes immediately and calls the result handler def submit_circuit (qc, group_id, circuit_id, shots=100): # store circuit in array with submission time and circuit info batched_circuits.append( { "qc": qc, "group": str(group_id), "circuit": str(circuit_id), "submit_time": time.time(), "shots": shots } ); #print("... submit circuit - ", str(batched_circuits[len(batched_circuits)-1])) # Launch execution of all batched circuits def execute_circuits (): for batched_circuit in batched_circuits: execute_circuit(batched_circuit) batched_circuits.clear() # Launch execution of one batched circuit def execute_circuit (batched_circuit): active_circuit = copy.copy(batched_circuit) active_circuit["launch_time"] = time.time() shots = batched_circuit["shots"] # Initiate execution job = Job() circuit = batched_circuit["qc"] if type(noise) == str and noise == "DEFAULT": # depolarizing noise on all qubits circuit = circuit.with_noise(cirq.depolarize(0.05)) elif noise is not None: # otherwise we expect it to be a NoiseModel # see documentation at https://quantumai.google/cirq/noise circuit = circuit.with_noise(noise) # experimental, for testing AQT device if device != None: circuit.device=device device.validate_circuit(circuit) job.result = backend.run(circuit, repetitions=shots) # put job into the active circuits with circuit info active_circuits[job] = active_circuit #print("... active_circuit = ", str(active_circuit)) ############## # Here we complete the job immediately job_complete(job) # Process a completed job def job_complete (job): active_circuit = active_circuits[job] # get job result (DEVNOTE: this might be different for diff targets) result = job.result #print("... result = ", str(result)) # counts = result.get_counts(qc) # print("Total counts are:", counts) # get measurement array and shot count measurements = result.measurements['result'] actual_shots = len(measurements) #print(f"actual_shots = {actual_shots}") if actual_shots != active_circuit["shots"]: print(f"WARNING: requested shots not equal to actual shots: {actual_shots}") metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'elapsed_time', time.time() - active_circuit["submit_time"]) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', time.time() - active_circuit["launch_time"]) # If a handler has been established, invoke it here with result object if result_handler: result_handler(active_circuit["qc"], result, active_circuit["group"], active_circuit["circuit"], active_circuit["shots"]) del active_circuits[job] # Wait for all executions to complete def wait_for_completion(): # check and sleep if not complete pass # return only when all circuits complete # Test circuit execution def test_execution(): pass
6,623
32.286432
104
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/cirq/cirq_utils.py
import cirq class to_gate(cirq.Gate): def __init__(self, num_qubits, circ, name="G"): self.num_qubits=num_qubits self.circ = circ self.name = name def _num_qubits_(self): return self.num_qubits def _decompose_(self, qubits): # `sorted()` needed to correct error in `all_qubits()` not returning a reasonable order for all of the qubits qbs = sorted(list(self.circ.all_qubits())) mapping = {} for t in range(self.num_qubits): mapping[qbs[t]] = qubits[t] def f_map(q): return mapping[q] circ_new = self.circ.transform_qubits(f_map) return circ_new.all_operations() def _circuit_diagram_info_(self, args): return [self.name] * self._num_qubits_()
808
30.115385
117
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/ocean/execute.py
# (C) Quantum Economic Development Consortium (QED-C) 2021. # Technical Advisory Committee on Standards and Benchmarks (TAC) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################### # Execute Module - Qiskit # # This module provides a way to submit a series of circuits to be executed in a batch. # When the batch is executed, each circuit is launched as a 'job' to be executed on the target system. # Upon completion, the results from each job are processed in a custom 'result handler' function # in order to calculate metrics such as fidelity. Relevant benchmark metrics are stored for each circuit # execution, so they can be aggregated and presented to the user. # import time import copy import metrics import importlib import traceback from collections import Counter import logging import numpy as np import csv from itertools import count import json import math from dwave.system.samplers import DWaveSampler from dwave.system import DWaveSampler, EmbeddingComposite, FixedEmbeddingComposite from neal import SimulatedAnnealingSampler # this seems to be required for embedding to work import dwave.inspector import HamiltonianCircuitProxy logger = logging.getLogger(__name__) # the currently selected provider_backend backend = None device_name = None # Execution options, passed to transpile method backend_exec_options = None # Cached transpiled circuit, used for parameterized execution cached_circuits = {} # embedding variables cached during execution embedding_flag = True embedding = None # The "num_sweeps" variable used by Neal simulator to generate reasonable distributions for testing. # A value of 1 will provide the most random behavior. num_sweeps = 10 ########################## # JOB MANAGEMENT VARIABLES # Configure a handler for processing circuits on completion # user-supplied result handler result_handler = None # Print progress of execution verbose = False # Print additional time metrics for each stage of execution verbose_time = False ###################################################################### # INITIALIZATION METHODS # Initialize the execution module, with a custom result handler def init_execution(handler): global result_handler result_handler = handler cached_circuits.clear() # Set the backend for execution def set_execution_target(backend_id='pegasus', provider_module_name=None, provider_name=None, provider_backend=None, hub=None, group=None, project=None, exec_options=None): """ Used to run jobs on a real hardware :param backend_id: device name. List of available devices depends on the provider :param group: used to load IBMQ accounts. :param project: used to load IBMQ accounts. :param provider_module_name: If using a provider other than IBMQ, the string of the module that contains the Provider class. For example, for honeywell, this would be 'qiskit.providers.honeywell' :param provider_name: If using a provider other than IBMQ, the name of the provider class. For example, for Honeywell, this would be 'Honeywell'. :provider_backend: a custom backend object created and passed in, use backend_id as identifier example usage. set_execution_target(backend_id='honeywell_device_1', provider_module_name='qiskit.providers.honeywell', provider_name='Honeywell') """ global backend, device_name authentication_error_msg = "No credentials for {0} backend found. Using the simulator instead." # if a custom provider backend is given, use it ... if provider_backend != None: backend = provider_backend # create an informative device name device_name = backend_id metrics.set_plot_subtitle(f"Device = {device_name}") #metrics.set_properties( { "api":"ocean", "backend_id":backend_id } ) # save execute options with backend global backend_exec_options backend_exec_options = exec_options print(f"... using backend_id = {backend_id}") # Set the state of the transpilation flags def set_embedding_flag(embedding_flag = True): globals()['embedding_flag'] = embedding_flag ###################################################################### # CIRCUIT EXECUTION METHODS # Submit circuit for execution # Execute immediately if possible or put into the list of batched circuits def submit_circuit(qc:HamiltonianCircuitProxy, group_id, circuit_id, shots=100, params=None): # create circuit object with submission time and circuit info circuit = { "qc": qc, "group": str(group_id), "circuit": str(circuit_id), "submit_time": time.time(), "shots": shots, "params": params } if verbose: print(f'... submit circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={circuit["params"]}') # logger doesn't like unicode, so just log the array values for now #logger.info(f'Submitting circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={str(circuit["params"])}') ''' DEVNOTE: doesn't work with our simple annealing time params logger.info(f'Submitting circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={[param[1] for param in params.items()] if params else None}') ''' if backend != None: execute_circuit(circuit) else: print(f"ERROR: No provider_backend specified, cannot execute program") return # Launch execution of one job (circuit) def execute_circuit(circuit): logging.info('Entering execute_circuit') active_circuit = copy.copy(circuit) st = active_circuit["launch_time"] = time.time() active_circuit["pollcount"] = 0 shots = circuit["shots"] qc = circuit["qc"] annealing_time=circuit["params"][0] sampleset = None try: logger.info(f"Executing on backend: {device_name}") # perform circuit execution on backend logger.info(f'Running trans_qc, shots={circuit["shots"]}') # this flag is true on the first iteration of a group if embedding_flag: globals()["embedding"] = None total_elapsed_time = 0 total_exec_time = 0 total_opt_time = 0 #*************************************** # execute on D-Wave Neal simulator (not really simulator, for us it 'mimics' D-Wave behavior) if device_name == "pegasus": sampler = backend # for simulation purposes, add a little time for embedding ts = time.time() #if (embedding_flag): #time.sleep(0.3) opt_exec_time = time.time() - ts # mimic the annealing operation ts = time.time() num_sweeps = math.log(annealing_time, 2) sampleset = sampler.sample_ising(qc.h, qc.J, num_reads=shots, num_sweeps=num_sweeps, annealing_time=annealing_time) sampleset.resolve() elapsed_time = time.time() - ts elapsed_time *= (annealing_time / 8) # funky way to fake elapsed time exec_time = elapsed_time / 2 # faking exec time too opt_exec_time += elapsed_time / 8 #*************************************** # execute on D-Wave hardware else: # prepare the sampler with embedding or use a cached embedding ts = time.time() if (embedding_flag): if verbose: print("... CREATE embedding") sampler = EmbeddingComposite(backend) else: if verbose: print("... USE embedding") sampler = FixedEmbeddingComposite(backend, embedding=embedding) opt_exec_time = time.time() - ts # perform the annealing operation ts = time.time() sampleset = sampler.sample_ising(qc.h, qc.J, num_reads=shots, annealing_time=annealing_time) sampleset.resolve() elapsed_time = time.time() - ts exec_time = (sampleset.info["timing"]["qpu_access_time"] / 1000000) opt_exec_time += (sampleset.info["timing"]["total_post_processing_time"] / 1000000) opt_exec_time += (sampleset.info["timing"]["qpu_access_overhead_time"] / 1000000) # if embedding context is returned and we haven't already cached it, cache it here if embedding == None: if "embedding_context" in sampleset.info: globals()["embedding"] = sampleset.info["embedding_context"]["embedding"] if verbose_time: print(json.dumps(sampleset.info["timing"], indent=2)) #if verbose: print(sampleset.info) if verbose: print(sampleset.record) elapsed_time = round(elapsed_time, 5) exec_time = round(exec_time, 5) opt_exec_time = round(opt_exec_time, 5) logger.info(f'Finished Running ocean.execute() - elapsed, exec, opt time = {elapsed_time} {exec_time} {opt_exec_time} (sec)') if verbose_time: print(f" ... ocean.execute() elapsed, exec, opt time = {elapsed_time}, {exec_time}, {opt_exec_time} (sec)") metrics.store_metric(circuit["group"], circuit["circuit"], 'elapsed_time', elapsed_time) metrics.store_metric(circuit["group"], circuit["circuit"], 'exec_time', exec_time) metrics.store_metric(circuit["group"], circuit["circuit"], 'opt_exec_time', opt_exec_time) def process_to_bitstring(cut_list): # DEVNOTE : Check if the mapping is correct # Convert 1 to 0 and -1 to 1 cut_list = ['0' if i == 1 else '1' for i in cut_list] # (-(cut_array - 1)/2).astype('int32') return "".join(cut_list) # for Neal simulator (mimicker), compute counts from each record returned, one per shot if device_name == "pegasus": all_cuts = [elem[0].tolist() for elem in sampleset.record] all_cuts = [process_to_bitstring(cut) for cut in all_cuts] unique_cuts = list(set(all_cuts)) cut_occurances = [all_cuts.count(cut) for cut in unique_cuts] result = { cut : count for (cut,count) in zip(unique_cuts, cut_occurances)} #print(result) # for hardware execution, generate counts by repeating records based on the number of times seen else: all_cuts = [elem[0].tolist() for elem in sampleset.record] all_counts = [int(elem[2]) for elem in sampleset.record] all_cuts = [process_to_bitstring(cut) for cut in all_cuts] result = { cut : count for (cut,count) in zip(all_cuts, all_counts)} #print(result) result_handler(circuit["qc"], result, circuit["group"], circuit["circuit"], circuit["shots"]) except Exception as e: print(f'ERROR: Failed to execute {circuit["group"]} {circuit["circuit"]}') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) return # store circuit dimensional metrics qc_depth = 20 qc_size = 20 qc_xi = 0.5 qc_n2q = 12 qc_tr_depth = 30 qc_tr_size = 30 qc_tr_xi = .5 qc_tr_n2q = 12 metrics.store_metric(circuit["group"], circuit["circuit"], 'depth', qc_depth) metrics.store_metric(circuit["group"], circuit["circuit"], 'size', qc_size) metrics.store_metric(circuit["group"], circuit["circuit"], 'xi', qc_xi) metrics.store_metric(circuit["group"], circuit["circuit"], 'n2q', qc_n2q) metrics.store_metric(circuit["group"], circuit["circuit"], 'tr_depth', qc_tr_depth) metrics.store_metric(circuit["group"], circuit["circuit"], 'tr_size', qc_tr_size) metrics.store_metric(circuit["group"], circuit["circuit"], 'tr_xi', qc_tr_xi) metrics.store_metric(circuit["group"], circuit["circuit"], 'tr_n2q', qc_tr_n2q) #print(sampleset) return sampleset # Get circuit metrics fom the circuit passed in def get_circuit_metrics(qc): logger.info('Entering get_circuit_metrics') #print(qc) # obtain initial circuit size metrics qc_depth = qc.depth() qc_size = qc.size() qc_count_ops = qc.count_ops() qc_xi = 0 qc_n2q = 0 # iterate over the ordereddict to determine xi (ratio of 2 qubit gates to one qubit gates) n1q = 0; n2q = 0 if qc_count_ops != None: for key, value in qc_count_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value qc_xi = n2q / (n1q + n2q) qc_n2q = n2q return qc_depth, qc_size, qc_count_ops, qc_xi, qc_n2q # Wait for all active and batched circuits to complete. # Execute the user-supplied completion handler to allow user to # check if a group of circuits has been completed and report on results. # Return when there are no more active circuits. # This is used as a way to complete all groups of circuits and report results. def finalize_execution(completion_handler=metrics.finalize_group, report_end=True): if verbose: print("... finalize_execution") # indicate we are done collecting metrics (called once at end of app) if report_end: metrics.end_metrics() ########################################################################### # Test circuit execution def test_execution(): pass
14,394
36.881579
182
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/ocean/HamiltonianCircuitProxy.py
class HamiltonianCircuitProxy(object): h = None J = None sampler = None embedding = None def __init__(self): self.h = None self.J = None self.sampler = None self.embedding = None
232
18.416667
38
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/transformers/qiskit_passmgr.py
# # Qiskit Pass Manger - Examples # # Dynamic Decoupling # # Some circuits can be sparse or have long idle periods. # Dynamical decoupling can echo away static ZZ errors during those idling periods. # Set up a pass manager to add the decoupling pulses to the circuit before executing from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ALAPSchedule, DynamicalDecoupling from qiskit.circuit.library import XGate def do_transform(circuit, backend): print(" ... performing dynamic decoupling.") durations = InstructionDurations.from_backend(backend) dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence)]) return pm.run(circuit)
787
34.818182
84
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/transformers/tket_optimiser.py
from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit from pytket.passes import ( # type: ignore auto_rebase_pass, RemoveRedundancies, SequencePass, SynthesiseTket, CXMappingPass, DecomposeBoxes, FullPeepholeOptimise, CliffordSimp, SimplifyInitial, KAKDecomposition, PauliSimp, RemoveBarriers, RemoveImplicitQubitPermutation, RebaseTket, ) from pytket.architecture import Architecture from pytket.placement import NoiseAwarePlacement from pytket.extensions.qiskit.qiskit_convert import ( process_characterisation, get_avg_characterisation, ) from pytket import OpType from qiskit.circuit.quantumcircuit import QuantumCircuit from pytket.circuit.display import render_circuit_jupyter def rebase_pass(): return auto_rebase_pass({OpType.CX, OpType.X, OpType.SX, OpType.Rz}) def tket_transformer_generator( cx_fidelity=1.0, pauli_simp=False, remove_barriers=True, resynthesise=True, ): """Generator for transformer using TKET passes :param quick: Perform quick optimisation, defaults to False :type quick: bool, optional :param cx_fidelity: Estimated CX gate fidelity, defaults to 1.0 :type cx_fidelity: float, optional :param pauli_simp: True if the circuit contains a large number of Pauli gadgets (exponentials of pauli strings). :type pauli_simp: bool, optional """ def transformation_method( circuit: QuantumCircuit, backend ) -> list[QuantumCircuit]: """Transformer using TKET optimisation passes. :param circuit: Circuit to be optimised :type circuit: QuantumCircuit :param backend: Backed on which circuit is run. :return: List of transformed circuits :rtype: list[QuantumCircuit] """ tk_circuit = qiskit_to_tk(circuit) if remove_barriers: RemoveBarriers().apply(tk_circuit) DecomposeBoxes().apply(tk_circuit) # Obtain device data for noise aware placement. characterisation = process_characterisation(backend) averaged_errors = get_avg_characterisation(characterisation) # If the circuit contains a large number of pauli gadgets, # run PauliSimp if pauli_simp: if len(tk_circuit.commands_of_type(OpType.Reset)) > 0: raise Exception( "PauliSimp does not support reset operations." ) auto_rebase_pass( {OpType.CX, OpType.Rz, OpType.Rx} ).apply(tk_circuit) PauliSimp().apply(tk_circuit) # Initialise pass list and perform thorough optimisation. if resynthesise: FullPeepholeOptimise().apply(tk_circuit) # Add noise aware placement and routing to pass list. coupling_map = backend.configuration().coupling_map if coupling_map: arch = Architecture(coupling_map) CXMappingPass( arch, NoiseAwarePlacement( arch, averaged_errors["node_errors"], averaged_errors["edge_errors"], averaged_errors["readout_errors"], ), directed_cx=False, delay_measures=False, ).apply(tk_circuit) if resynthesise: KAKDecomposition(cx_fidelity=cx_fidelity).apply(tk_circuit) CliffordSimp().apply(tk_circuit) SynthesiseTket().apply(tk_circuit) # Rebase to backend gate set and perform basic optimisation rebase_pass().apply(tk_circuit) RemoveRedundancies().apply(tk_circuit) SimplifyInitial( allow_classical=False, create_all_qubits=True, ).apply(tk_circuit) circuit = tk_to_qiskit(tk_circuit) return circuit return transformation_method
3,914
30.829268
72
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/_common/transformers/trueq_rc.py
''' Keysight TrueQ - Randomized Compilation ''' import trueq as tq import numpy as np import trueq.compilation as tqc import qiskit as qs # The following option applies randomized compilation through the True-Q software. This compilation technique allocates the total shot budget over randomized implementations of the circuit, which typically results in suppressing the effect of coherent noise processes. def full_rc(circuit, backend, n_compilations=20): tq.interface.qiskit.set_from_backend(backend) circuit_tq, metadata = tq.interface.qiskit.to_trueq_circ(circuit) circuit_tq = tqc.UnmarkCycles().apply(circuit_tq) rc_collection = [] for _ in range(n_compilations): c = compiler.compile(circuit_tq) c = split(c) c = mark_measurements(c) c = compiler_full_RC.compile(c) rc_collection += [tq.interface.qiskit.from_trueq_circ(c, metadata=metadata)] return rc_collection # The following applies a local variant of randomized compiling, in which twirling is only applied to active qubits in a given cycle, i.e. idling qubits are not twirled. For sparse circuits, this variant reduces the gate count and depth as compared to full RC, but is less effective in suppressing the effect of coherent crosstalk involving the idling qubits. def local_rc(circuit, backend, n_compilations=20): tq.interface.qiskit.set_from_backend(backend) circuit_tq, metadata = tq.interface.qiskit.to_trueq_circ(circuit) circuit_tq = tqc.UnmarkCycles().apply(circuit_tq) rc_collection = [] for _ in range(n_compilations): c = compiler.compile(circuit_tq) c = split(c) c = mark_measurements(c) c = compiler_local_RC.compile(c) rc_collection += [tq.interface.qiskit.from_trueq_circ(c, metadata=metadata)] return rc_collection ################################################################################################ # Helper functions ################################################################################################ def split(circuit): new_circuit = tq.Circuit() for cycle in circuit.cycles[:-1]: if len(cycle.gates_single) > 0 and len(cycle.gates_multi) > 0: new_circuit.append(cycle.gates_single) new_circuit.append(cycle.gates_multi) else: new_circuit.append(cycle) if len(circuit.cycles[-1].gates) > 0 and len(circuit.cycles[-1].meas) > 0: new_circuit.append(circuit.cycles[-1].gates) new_circuit.append(circuit.cycles[-1].meas) else: new_circuit.append(circuit.cycles[-1]) new_circuit = tq.compilation.UnmarkCycles().apply(new_circuit) return new_circuit def mark_measurements(circuit): max_marker = max(cycle.marker for cycle in circuit.cycles) new_circuit = tq.Circuit() if circuit[-1].n_meas > 0 and circuit[-1].marker == 0: for cycle in circuit.cycles[:-1]: new_circuit.append(cycle) new_circuit.append(tq.Cycle(circuit[-1].operations, marker=max_marker+1)) return new_circuit else: return circuit.copy() ################################################################################################ # Compilers ################################################################################################ class Native1QSparse(tqc.Parallel): def __init__(self, factories, mode="ZXZXZ", angles=None, **_): replacements = [tqc.NativeExact(factories), tqc.Native1QMode(factories) ] super().__init__(tqc.TryInOrder(replacements)) x90 = tq.config.GateFactory.from_hamiltonian("x90", [["X", 90]]) x180 = tq.config.GateFactory.from_hamiltonian("x180", [["X", 180]]) z = tq.config.GateFactory.from_hamiltonian("z", [["Z", "theta"]]) cnot = tq.config.GateFactory.from_matrix("cx", tq.Gate.cnot.mat) factories = [x90, x180, z, cnot] compiler = tq.Compiler( [ tqc.Native2Q(factories), tqc.UnmarkCycles(), tqc.Merge(), tqc.RemoveId(), tqc.Justify(), tqc.RemoveEmptyCycle() ] ) compiler_local_RC = tq.Compiler( [ tqc.MarkBlocks(), tqc.RCLocal(), Native1QSparse(factories) ] ) compiler_full_RC = tq.Compiler( [ tqc.MarkBlocks(), tqc.RCCycle(), Native1QSparse(factories) ] )
4,437
33.944882
359
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/_common/common.py
import os import json INSTANCE_DIR = 'instances' # Utility functions for processing Max-Cut data files # If _instances is None, read from data file. If a dict, extract from a named field # (second form used for Qiskit Runtime and similar systems) def read_maxcut_instance(file_path, _instances=None): if isinstance(_instances, dict): inst = os.path.splitext(os.path.basename(file_path))[0] return _instances.get(inst, {}).get("instance", (None, None)) if os.path.exists(file_path) and os.path.isfile(file_path): with open(file_path, 'r') as file: nodes = int(file.readline()) edges = [] for line in file.readlines(): parts = line.split() edges.append((int(parts[0]), int(parts[1]))) return nodes, edges else: return None, None def read_maxcut_solution(file_path, _instances=None): if isinstance(_instances, dict): inst = os.path.splitext(os.path.basename(file_path))[0] return _instances.get(inst, {}).get("sol", (None, None)) if os.path.exists(file_path) and os.path.isfile(file_path): with open(file_path, 'r') as file: objective = int(file.readline()) solution = [int(v) for v in file.readline().split()] return objective, solution else: return None, None def eval_cut(nodes, edges, solution, reverseStep = 1): assert(nodes == len(solution)) solution = solution[::reverseStep] # If reverseStep is -1, the solution string is reversed before evaluating the cut size cut_size = 0 for i,j in edges: if solution[i] != solution[j]: cut_size += 1 return cut_size # Load from given filename and return a list of lists # containing fixed angles (betas, gammas) for multiple degrees and rounds def read_fixed_angles(file_path, _instances=None): if isinstance(_instances, dict): #inst = os.path.splitext(os.path.basename(file_path))[0] #return _instances.get(inst, {}).get("fixed_angles", (None, None)) return _instances.get("fixed_angles", (None, None)) if os.path.exists(file_path) and os.path.isfile(file_path): with open(file_path, 'r') as json_file: # 'thetas_array', 'approx_ratio_list', 'num_qubits_list fixed_angles = json.load(json_file) return fixed_angles else: return None # return the thetas array containing betas and gammas for specific degree and rounds def get_fixed_angles_for(fixed_angles, degree, rounds): if str(degree) in fixed_angles and str(rounds) in fixed_angles[str(degree)]: param_pairs = fixed_angles[str(degree)][str(rounds)] return [param_pairs['beta'] + param_pairs['gamma']] else: return None
2,847
33.313253
125
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/_common/instances/compute-maxcut-opt-files.py
#!/usr/bin/env python3 import os from gurobipy import Model, GRB def read_maxcut_instance(file_path): with open(file_path, 'r') as file: nodes = int(file.readline()) edges = [] for line in file.readlines(): parts = line.split() edges.append((int(parts[0]), int(parts[1]))) return nodes, edges instance_files = [] for root, dirs, files in os.walk('.'): for name in files: if name.endswith('.txt'): instance_files.append(os.path.join(root, name)) instance_files.sort() print('instances found: {}'.format(len(instance_files))) for path in instance_files: #print() print('working on: {}'.format(path)) nodes, edges = read_maxcut_instance(path) m = Model() variables = [m.addVar(lb=0, ub=1, vtype=GRB.BINARY, name='x_'+str(i)) for i in range(nodes)] m.update() obj = 0 for i,j in edges: obj += -2*variables[i]*variables[j] + variables[i] + variables[j] m.setObjective(obj, GRB.MAXIMIZE) m.optimize() objective = int(m.ObjVal) solution = [0 if variables[i].X <= 0.5 else 1 for i in range(nodes)] solution_path = path.replace('.txt', '.sol') with open(solution_path, 'w') as file: file.write('{}\n'.format(objective)) for v in solution: file.write('{} '.format(v)) file.write('\n')
1,368
25.326923
96
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/_common/instances/generate-instances.py
#!/usr/bin/env python3 import os import networkx INSTANCE_DIR = '.' SEEDS = 1 N_MIN = 4 N_MAX = 26 R = 3 R_minus = 3 for n in range(N_MIN, N_MAX+1, 2): for s in range(0,SEEDS): print('instance config: {} {} {}'.format(n, R, s)) graph = networkx.random_regular_graph(R, n, seed=s) file_name = 'mc_{:03d}_{:03d}_{:03d}.txt'.format(n, R, s) file_path = os.path.join(INSTANCE_DIR, file_name) with open(file_path, 'w') as file: file.write('{}\n'.format(len(graph.nodes))) for i,j in graph.edges: file.write('{} {}\n'.format(i, j)) for n in range(N_MIN, N_MAX+1, 2): for s in range(0,SEEDS): regularity = n-R_minus if regularity <= 3: continue print('instance config: {} {} {}'.format(n, regularity, s)) graph = networkx.random_regular_graph(regularity, n, seed=s) file_name = 'mc_{:03d}_{:03d}_{:03d}.txt'.format(n, regularity, s) file_path = os.path.join(INSTANCE_DIR, file_name) with open(file_path, 'w') as file: file.write('{}\n'.format(len(graph.nodes))) for i,j in graph.edges: file.write('{} {}\n'.format(i, j)) for n in [40, 80, 160, 320]: for s in range(0,SEEDS): print('instance config: {} {} {}'.format(n, R, s)) graph = networkx.random_regular_graph(R, n, seed=s) file_name = 'mc_{:03d}_{:03d}_{:03d}.txt'.format(n, R, s) file_path = os.path.join(INSTANCE_DIR, file_name) with open(file_path, 'w') as file: file.write('{}\n'.format(len(graph.nodes))) for i,j in graph.edges: file.write('{} {}\n'.format(i, j))
1,711
29.035088
74
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/qiskit/auxiliary_functions.py
import maxcut_benchmark import metrics import os import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np import json maxcut_benchmark.verbose = False maxcut_style = os.path.join('..', '..', '_common', 'maxcut.mplstyle') #%% Functions for analyzing the effects of initial conditions def plot_effects_of_initial_conditions(): num_qubits = list(metrics.circuit_metrics_detail_2.keys())[0] restart_keys = list(metrics.circuit_metrics_detail_2[num_qubits].keys()) starting_angles_list = [0] * len(restart_keys) final_angles_list = [0] * len(restart_keys) final_AR_list = [0] * len(restart_keys) for ind, restart_key in enumerate(restart_keys): thisRestart = metrics.circuit_metrics_detail_2[num_qubits][restart_key] minimizer_keys = list(thisRestart.keys()) starting_angles_list[ind] = thisRestart[0]['thetas_array'] final_angles_list[ind] = thisRestart[max( minimizer_keys)]['thetas_array'] final_AR_list[ind] = thisRestart[max(minimizer_keys)]['approx_ratio'] worst_ind = final_AR_list.index(min(final_AR_list)) best_ind = final_AR_list.index(max(final_AR_list)) worst_restart_key = restart_keys[worst_ind] best_restart_key = restart_keys[best_ind] worst_dict = metrics.circuit_metrics_final_iter[str( num_qubits)][str(worst_restart_key)] best_dict = metrics.circuit_metrics_final_iter[str( num_qubits)][str(best_restart_key)] plot_worst_best_init_conditions(worst_dict, best_dict) plot_AR_histogram(final_AR_list) def plot_AR_histogram(final_AR_list): with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1) # Create more appropriate title suptitle = "Histogram of Approximation Ratios" options = get_options_effect_init() fulltitle = get_title(suptitle, options) # and add the title to the plot plt.suptitle(fulltitle) ########################################################### n, bins, patches = axs.hist( x=final_AR_list, density=False, bins=25, color='k', rwidth=0.85, alpha=0.8) ########################################################### axs.set_ylabel('Counts') axs.set_xlabel(r'Approximation Ratio') # axs.grid() axs.grid(axis='y') axs.set_xlim(xmax=1) axs.set_yticks(list(range(0, 5 * (1 + int(n.max()) // 5), 5))) # axs.legend() fig.tight_layout() # figName = os.path.join(figLoc, 'histogram_of_ARs') # plt.savefig(figName + '.pdf') # plt.savefig(figName + '.png') def get_title(suptitle, options): # append key circuit metrics info to the title maxcut_inputs = maxcut_benchmark.maxcut_inputs backend_id = maxcut_inputs.get('backend_id') fulltitle = suptitle + f"\nDevice={backend_id} {metrics.get_timestr()}" if options != None: options_str = '' for key, value in options.items(): if len(options_str) > 0: options_str += ', ' options_str += f"{key}={value}" fulltitle += f"\n{options_str}" return fulltitle def get_options_effect_init(): maxcut_inputs = maxcut_benchmark.maxcut_inputs num_shots = maxcut_inputs.get('num_shots') width = maxcut_inputs.get('max_qubits') degree = maxcut_inputs.get('degree') restarts = maxcut_inputs.get('max_circuits') options = dict(shots=num_shots, width=width, degree=degree, restarts=restarts) return options def plot_worst_best_init_conditions(worst_dict, best_dict): # Get 2 colors for QAOA, and one for uniform sampling cmap = cm.get_cmap('RdYlGn') clr_random = 'pink' # colors = [cmap(0.1), cmap(0.4), cmap(0.8)] colors = np.linspace(0.05, 0.95, 2, endpoint=True) colors = [cmap(i) for i in colors] #### Good vs Bad Initial Conditions with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1) # Create more appropriate title suptitle = "Empirical Distribution of cut sizes" options = get_options_effect_init() fulltitle = get_title(suptitle, options) # and add the title to the plot plt.suptitle(fulltitle) ########################################################### # Plot the distribution obtained from uniform random sampling unique_counts_unif = worst_dict['unique_counts_unif'] unique_sizes_unif = worst_dict['unique_sizes_unif'] optimal_value = worst_dict['optimal_value'] color = clr_random uniform_approx_ratio = - maxcut_benchmark.compute_sample_mean( worst_dict['unique_counts_unif'], worst_dict['unique_sizes_unif']) / optimal_value axs.plot(np.array(unique_sizes_unif) / optimal_value, np.array(unique_counts_unif) / sum(unique_counts_unif), marker='o', ms=1, mec='k', mew=0.2, lw=10, alpha=0.5, ls='-', label="Random Sampling", c=color) # " degree={deg}") # lw=1, , c = colors[1] axs.axvline(x=uniform_approx_ratio, color=color, alpha=0.5) ########################################################### ########################################################### # Plot best distribution unique_counts = best_dict['unique_counts'] unique_sizes = best_dict['unique_sizes'] optimal_value = best_dict['optimal_value'] fin_appr_ratio = - maxcut_benchmark.compute_sample_mean( best_dict['unique_counts'], best_dict['unique_sizes']) / optimal_value color = colors[1] axs.plot(np.array(unique_sizes) / optimal_value, np.array(unique_counts) / sum(unique_counts), marker='o', ls='-', ms=4, mec='k', mew=0.2, lw=2, label="Initial Condition 1", c=color) # " degree={deg}") # lw=1, , # label = 'Approx Ratio (Best Run)' axs.axvline(x=fin_appr_ratio, color=color, alpha=0.5) # thet = best['converged_thetas_list'] # thet = ['{:.2f}'.format(val) for val in thet] # thet=','.join(str(x) for x in thet) # axs.text(fin_appr_ratio, 1, "{:.2f}".format(fin_appr_ratio) ,fontsize = 10,c=color,rotation=75) ########################################################### ########################################################### # Plot the worst distribution unique_counts = worst_dict['unique_counts'] unique_sizes = worst_dict['unique_sizes'] optimal_value = worst_dict['optimal_value'] fin_appr_ratio = - maxcut_benchmark.compute_sample_mean( worst_dict['unique_counts'], worst_dict['unique_sizes']) / optimal_value color = colors[0] axs.plot(np.array(unique_sizes) / optimal_value, np.array(unique_counts) / sum(unique_counts), marker='o', ls='-', ms=4, mec='k', mew=0.2, lw=2, label="Initial Condition 2", c=color) # " degree={deg}") # lw=1, , c = colors[1] # , label = 'Approx Ratio (Worst Run)') axs.axvline(x=fin_appr_ratio, color=color, alpha=0.5) ########################################################### axs.set_ylabel('Fraction of Total Counts') axs.set_xlabel(r'$\frac{\mathrm{Cut\ Size}}{\mathrm{Max\ Cut\ Size}}$') axs.grid() # axs.legend(loc='center left', bbox_to_anchor=(1, 0.5)) axs.legend() fig.tight_layout() # figName = os.path.join(figLoc, 'good_vs_bad') # plt.savefig(figName + '.pdf') # plt.savefig(figName + '.png') #%% Radar plot def radar_plot(min_qubits=4, max_qubits=6, num_shots=1000, restarts=10, objective_func_type='approx_ratio', rounds=1, degree=3, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None, ): # Implement the runs maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=restarts, num_shots=num_shots, method=2, rounds=rounds, degree=degree, alpha=0.1, N=10, parameterized=False, num_x_bins=15, max_iter=30, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, objective_func_type=objective_func_type, do_fidelities=False, save_res_to_file=False, save_final_counts=False, plot_results=False, detailed_save_names=False ) # thetas_array = thetas_array # Get the inputs as a dictionary gen_prop = maxcut_benchmark.maxcut_inputs gen_prop['widths'] = list(metrics.group_metrics['groups']) # Data for plotting radar_plot_data = rearrange_radar_data_for_plotting(gen_prop) plot_from_data(gen_prop, radar_plot_data) def load_fixed_angles(): fixed_angle_file = os.path.join('..', '_common', 'angles_regular_graphs.json') with open(fixed_angle_file, 'r') as json_file: # 'thetas_array', 'approx_ratio_list', 'num_qubits_list' fixed_angle_data = json.load(json_file) return fixed_angle_data def get_radar_full_title(gen_prop): objective_func_type = gen_prop.get('objective_func_type') num_shots = gen_prop.get('num_shots') rounds = gen_prop.get('rounds') method = gen_prop.get('method') suptitle = f"Benchmark Results - MaxCut ({method}) - Qiskit" obj_str = metrics.known_score_labels[objective_func_type] options = {'rounds': rounds, 'Objective Function': obj_str, 'num_shots' : num_shots} fulltitle = get_title(suptitle=suptitle, options=options) return fulltitle def plot_from_data(gen_prop, radar_plot_data): fulltitle = get_radar_full_title(gen_prop) rounds = gen_prop.get('rounds') degree = gen_prop.get('degree') widths = gen_prop.get('widths') # load fixed angle data fixed_angle_data = load_fixed_angles()[str(degree)][str(rounds)] ar_fixed = fixed_angle_data['AR'] thetas_fixed = fixed_angle_data['beta'] + fixed_angle_data['gamma'] arranged_thetas_arr = radar_plot_data.get('arranged_thetas_arr') arranged_AR_arr = radar_plot_data.get('arranged_AR_arr') radii_arr = radar_plot_data.get('radii_arr') num_widths = len(widths) radii = radii_arr[:, 0] maxRadius = max(radii) for ind in range(2 * rounds): # For each angle, plot and save with plt.style.context(maxcut_style): fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) # Get figure name and title for figure if ind < rounds: # betas go from 0 to pi addnlabel = r'$2\beta_{}$'.format(ind + 1) fname = 'beta-{}'.format(ind+1) else: # gammas go from 0 to 2 pi addnlabel = r'$\gamma_{}$'.format(ind - rounds + 1) fname = 'gamma-{}'.format(ind - rounds + 1) plt.suptitle(fulltitle + '\n' + addnlabel) # Get the angles if ind < rounds: # then we are plotting 2 * betas, so multiply by 2 angles = 2 * arranged_thetas_arr[:, :, ind].flatten() else: # we are plotting gammas, so do not multiple angles = arranged_thetas_arr[:, :, ind].flatten() # Plot the dots on the radar plot ars = arranged_AR_arr.flatten() # approximation ratios radii_plt = radii_arr.flatten() restart_dots = ax.scatter(angles, radii_plt, c=ars, s=100, cmap='YlGn', marker='o', alpha=0.8, label=r'Converged Angles'.format(0+1), linewidths=0) # Plot the fixed angles if ind < rounds: # 2 beta, so multiply by 2 fixed_ang = [thetas_fixed[ind] * 2] * num_widths else: # 1 * gamma, do not multiply fixed_ang = [thetas_fixed[ind]] * num_widths ax.scatter(fixed_ang, radii, c=[ar_fixed] * num_widths, s=100, cmap='YlGn', marker='s', alpha=0.8, edgecolor='k', label='Fixed Angels') ax.set_rmax(maxRadius+1) ax.set_rticks(radii, labels=[str(w) for w in widths], fontsize=5) ax.set_xticks(np.pi/2 * np.arange(4), labels=[ r'$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$'], fontsize=15) ax.set_rlabel_position(0) ax.grid(True) # ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5)) cbar = plt.colorbar(restart_dots, location='left', shrink=0.8, orientation='vertical', aspect=15) cbar.set_label("Energy Approximation Ratio") fig.tight_layout() ## For now, not saving the plots. # fold = os.path.join( # '__radarPlots', 'rounds-{}_shots-{}'.format(rounds, num_shots), 'final') # if not os.path.exists(fold): # os.makedirs(fold) # filename = os.path.join(fold, fname) # plt.savefig(filename + '.jpg') # plt.savefig(filename + '.pdf') def rearrange_radar_data_for_plotting(gen_prop): """ Return a dictionary with radii, and angles of the final and initial points of the minimizer, along with the initial and final approximation ratios Returns: dictionary """ # First, retrieve radar data radar_data = get_radar_data_from_metrics() widths = gen_prop.get('widths') num_widths = len(list(radar_data.keys())) maxRadius = 10 # of polar plot minRadius = 2 # of polar plot radii = np.linspace(minRadius, maxRadius, num_widths) niter = gen_prop.get("max_circuits") rounds = gen_prop.get("rounds") radii_arr = np.zeros((num_widths, niter)) arranged_AR_arr = np.zeros((num_widths, niter)) arranged_thetas_arr = np.zeros((num_widths, niter, 2 * rounds)) arranged_initthetas_arr = np.zeros((num_widths, niter, 2 * rounds)) arranged_init_AR_arr = np.zeros((num_widths, niter)) for width_ind, width in enumerate(widths): radii_arr[width_ind, :] = radii[width_ind] for iter_ind in range(niter): # Get color of dot ar = radar_data[width]['ARs'][iter_ind] # Get final angle location thetas = radar_data[width]['final_angles'][iter_ind] # Put these values in a list arranged_AR_arr[width_ind, iter_ind] = ar arranged_thetas_arr[width_ind, iter_ind, :] = thetas # Put initial values in list arranged_init_AR_arr[width_ind, iter_ind] = radar_data[width]['init_AR'][iter_ind] arranged_initthetas_arr[width_ind, iter_ind, :] = radar_data[width]['init_angles'][iter_ind] return dict(arranged_AR_arr=arranged_AR_arr, arranged_thetas_arr=arranged_thetas_arr, arranged_init_AR_arr=arranged_init_AR_arr, arranged_initthetas_arr=arranged_initthetas_arr, radii_arr=radii_arr ) def get_radar_data_from_metrics(): """ Extract only the initial angles, final angles and approximation ratios from data stored in metrics Returns: dictionary: with initial and final angles, and initial and final approximation ratios """ restarts = maxcut_benchmark.maxcut_inputs.get("max_circuits") detail2 = metrics.circuit_metrics_detail_2 widths = list(detail2.keys()) radar_data = {width: dict(ARs=[], init_angles=[], final_angles=[], init_AR=[]) for width in widths } for width in widths: iter_inds = list(range(1, restarts + 1)) for iter_ind in iter_inds: cur_mets = detail2[width][iter_ind] # Initial angles and ARs starting_iter_index = min(list(cur_mets.keys())) cur_init_thetas = cur_mets[starting_iter_index]['thetas_array'] cur_init_AR = cur_mets[starting_iter_index]['approx_ratio'] radar_data[width]['init_angles'].append(cur_init_thetas) radar_data[width]['init_AR'].append(cur_init_AR) # Final angles and ARs fin_iter_index = max(list(cur_mets.keys())) cur_final_thetas = cur_mets[fin_iter_index]['thetas_array'] cur_AR = cur_mets[fin_iter_index]['approx_ratio'] radar_data[width]['ARs'].append(cur_AR) radar_data[width]['final_angles'].append(cur_final_thetas) return radar_data
16,664
40.352357
150
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/qiskit/maxcut_benchmark.py
""" MaxCut Benchmark Program - Qiskit """ import datetime import json import logging import math import os import re import sys import time from collections import namedtuple import numpy as np from scipy.optimize import minimize from qiskit import (Aer, ClassicalRegister, # for computing expectation tables QuantumCircuit, QuantumRegister, execute, transpile) from qiskit.circuit import ParameterVector sys.path[1:1] = [ "_common", "_common/qiskit", "maxcut/_common" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit", "../../maxcut/_common/" ] import common import execute as ex import metrics as metrics logger = logging.getLogger(__name__) fname, _, ext = os.path.basename(__file__).partition(".") log_to_file = True try: if log_to_file: logging.basicConfig( # filename=f"{fname}_{datetime.datetime.now().strftime('%Y_%m_%d_%S')}.log", filename=f"{fname}.log", filemode='w', encoding='utf-8', level=logging.INFO, format='%(asctime)s %(name)s - %(levelname)s:%(message)s' ) else: logging.basicConfig( level=logging.INFO, format='%(asctime)s %(name)s - %(levelname)s:%(message)s') except Exception as e: print(f'Exception {e} occured while configuring logger: bypassing logger config to prevent data loss') pass np.random.seed(0) maxcut_inputs = dict() #inputs to the run method verbose = False print_sample_circuit = True # Indicates whether to perform the (expensive) pre compute of expectations do_compute_expectation = True # saved circuits for display QC_ = None Uf_ = None # based on examples from https://qiskit.org/textbook/ch-applications/qaoa.html QAOA_Parameter = namedtuple('QAOA_Parameter', ['beta', 'gamma']) # Qiskit uses the little-Endian convention. Hence, measured bit-strings need to be reversed while evaluating cut sizes reverseStep = -1 #%% MaxCut circuit creation and fidelity analaysis functions def create_qaoa_circ(nqubits, edges, parameters): qc = QuantumCircuit(nqubits) # initial_state for i in range(0, nqubits): qc.h(i) for par in parameters: #print(f"... gamma, beta = {par.gamma} {par.beta}") # problem unitary for i,j in edges: qc.rzz(- par.gamma, i, j) qc.barrier() # mixer unitary for i in range(0, nqubits): qc.rx(2 * par.beta, i) return qc def MaxCut (num_qubits, secret_int, edges, rounds, thetas_array, parameterized, measured = True): if parameterized: return MaxCut_param(num_qubits, secret_int, edges, rounds, thetas_array) # if no thetas_array passed in, create defaults if thetas_array is None: thetas_array = 2*rounds*[1.0] #print(f"... incoming thetas_array={thetas_array} rounds={rounds}") # get number of qaoa rounds (p) from length of incoming array p = len(thetas_array)//2 # if rounds passed in is less than p, truncate array if rounds < p: p = rounds thetas_array = thetas_array[:2*rounds] # if more rounds requested than in thetas_array, give warning (can fill array later) elif rounds > p: rounds = p print(f"WARNING: rounds is greater than length of thetas_array/2; using rounds={rounds}") logger.info(f'*** Constructing NON-parameterized circuit for {num_qubits = } {secret_int}') # create parameters in the form expected by the ansatz generator # this is an array of betas followed by array of gammas, each of length = rounds betas = thetas_array[:p] gammas = thetas_array[p:] parameters = [QAOA_Parameter(*t) for t in zip(betas,gammas)] # and create the circuit, without measurements qc = create_qaoa_circ(num_qubits, edges, parameters) # pre-compute and save an array of expected measurements if do_compute_expectation: logger.info('Computing expectation') compute_expectation(qc, num_qubits, secret_int) # add the measure here if measured: qc.measure_all() # save small circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc, None ############### Circuit Definition - Parameterized version # Create ansatz specific to this problem, defined by G = nodes, edges, and the given parameters # Do not include the measure operation, so we can pre-compute statevector def create_qaoa_circ_param(nqubits, edges, betas, gammas): qc = QuantumCircuit(nqubits) # initial_state for i in range(0, nqubits): qc.h(i) for beta, gamma in zip(betas, gammas): #print(f"... gamma, beta = {gammas}, {betas}") # problem unitary for i,j in edges: qc.rzz(- gamma, i, j) qc.barrier() # mixer unitary for i in range(0, nqubits): qc.rx(2 * beta, i) return qc _qc = None beta_params = [] gamma_params = [] # Create the benchmark program circuit # Accepts optional rounds and array of thetas (betas and gammas) def MaxCut_param (num_qubits, secret_int, edges, rounds, thetas_array): # if no thetas_array passed in, create defaults if thetas_array is None: thetas_array = 2*rounds*[1.0] #print(f"... incoming thetas_array={thetas_array} rounds={rounds}") # get number of qaoa rounds (p) from length of incoming array p = len(thetas_array)//2 # if rounds passed in is less than p, truncate array if rounds < p: p = rounds thetas_array = thetas_array[:2*rounds] # if more rounds requested than in thetas_array, give warning (can fill array later) elif rounds > p: rounds = p print(f"WARNING: rounds is greater than length of thetas_array/2; using rounds={rounds}") #print(f"... actual thetas_array={thetas_array}") # create parameters in the form expected by the ansatz generator # this is an array of betas followed by array of gammas, each of length = rounds global _qc global betas global gammas # create the circuit the first time, add measurements if ex.do_transpile_for_execute: logger.info(f'*** Constructing parameterized circuit for {num_qubits = } {secret_int}') betas = ParameterVector("𝞫", p) gammas = ParameterVector("𝞬", p) _qc = create_qaoa_circ_param(num_qubits, edges, betas, gammas) # add the measure here, only after circuit is created _qc.measure_all() params = {betas: thetas_array[:p], gammas: thetas_array[p:]} #logger.info(f"Binding parameters {params = }") logger.info(f"Create binding parameters for {thetas_array}") qc = _qc #print(qc) # pre-compute and save an array of expected measurements if do_compute_expectation: logger.info('Computing expectation') compute_expectation(qc, num_qubits, secret_int, params=params) # save small circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc, params ############### Expectation Tables # DEVNOTE: We are building these tables on-demand for now, but for larger circuits # this will need to be pre-computed ahead of time and stored in a data file to avoid run-time delays. # dictionary used to store pre-computed expectations, keyed by num_qubits and secret_string # these are created at the time the circuit is created, then deleted when results are processed expectations = {} # Compute array of expectation values in range 0.0 to 1.0 # Use statevector_simulator to obtain exact expectation def compute_expectation(qc, num_qubits, secret_int, backend_id='statevector_simulator', params=None): #ts = time.time() if params != None: qc = qc.bind_parameters(params) #execute statevector simulation sv_backend = Aer.get_backend(backend_id) sv_result = execute(qc, sv_backend).result() # get the probability distribution counts = sv_result.get_counts() #print(f"... statevector expectation = {counts}") # store in table until circuit execution is complete id = f"_{num_qubits}_{secret_int}" expectations[id] = counts #print(f" ... time to execute statevector simulator: {time.time() - ts}") # Return expected measurement array scaled to number of shots executed def get_expectation(num_qubits, degree, num_shots): # find expectation counts for the given circuit id = f"_{num_qubits}_{degree}" if id in expectations: counts = expectations[id] # scale to number of shots for k, v in counts.items(): counts[k] = round(v * num_shots) # delete from the dictionary del expectations[id] return counts else: return None ############### Result Data Analysis expected_dist = {} # Compare the measurement results obtained with the expected measurements to determine fidelity def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): global expected_dist # obtain counts from the result object counts = result.get_counts(qc) # retrieve pre-computed expectation values for the circuit that just completed expected_dist = get_expectation(num_qubits, secret_int, num_shots) # if the expectation is not being calculated (only need if we want to compute fidelity) # assume that the expectation is the same as measured counts, yielding fidelity = 1 if expected_dist == None: expected_dist = counts if verbose: print(f"For width {num_qubits} problem {secret_int}\n measured: {counts}\n expected: {expected_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, expected_dist) if verbose: print(f"For secret int {secret_int} fidelity: {fidelity}") return counts, fidelity #%% Computation of various metrics, such as approximation ratio, etc. def compute_cutsizes(results, nodes, edges): """ Given a result object, extract the values of meaasured cuts and the corresponding counts into ndarrays. Also compute and return the corresponding cut sizes. Returns ------- cuts : list of strings each element is a bitstring denoting a cut counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) """ cuts = list(results.get_counts().keys()) counts = list(results.get_counts().values()) sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in cuts] return cuts, counts, sizes def get_size_dist(counts, sizes): """ For given measurement outcomes, i.e. combinations of cuts, counts and sizes, return counts corresponding to each cut size. """ unique_sizes = list(set(sizes)) unique_counts = [0] * len(unique_sizes) for i, size in enumerate(unique_sizes): corresp_counts = [counts[ind] for ind,s in enumerate(sizes) if s == size] unique_counts[i] = sum(corresp_counts) # Make sure that the scores are in ascending order s_and_c_list = [[a,b] for (a,b) in zip(unique_sizes, unique_counts)] s_and_c_list = sorted(s_and_c_list, key = lambda x : x[0]) unique_sizes = [x[0] for x in s_and_c_list] unique_counts = [x[1] for x in s_and_c_list] cumul_counts = np.cumsum(unique_counts) return unique_counts, unique_sizes, cumul_counts.tolist() # Compute the objective function on a given sample def compute_sample_mean(counts, sizes, **kwargs): """ Compute the mean of cut sizes (i.e. the weighted average of sizes weighted by counts) This approximates the expectation value of the state at the end of the circuit Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) **kwargs : optional arguments will be ignored Returns ------- float """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) return - np.sum(counts * sizes) / np.sum(counts) def compute_cvar(counts, sizes, alpha = 0.1, **kwargs): """ Obtains the Conditional Value at Risk or CVaR for samples measured at the end of the variational circuit. Reference: Barkoutsos, P. K., Nannicini, G., Robert, A., Tavernelli, I. & Woerner, S. Improving Variational Quantum Optimization using CVaR. Quantum 4, 256 (2020). Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) alpha : float, optional Confidence interval value for CVaR. The default is 0.1. Returns ------- float CVaR value """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) # Sort the negative of the cut sizes in a non-decreasing order. # Sort counts in the same order as sizes, so that i^th element of each correspond to each other sort_inds = np.argsort(-sizes) sizes = sizes[sort_inds] counts = counts[sort_inds] # Choose only the top num_avgd = ceil(alpha * num_shots) cuts. These will be averaged over. num_avgd = math.ceil(alpha * np.sum(counts)) # Compute cvar cvar_sum = 0 counts_so_far = 0 for c, s in zip(counts, sizes): if counts_so_far + c >= num_avgd: cts_to_consider = num_avgd - counts_so_far cvar_sum += cts_to_consider * s break else: counts_so_far += c cvar_sum += c * s return - cvar_sum / num_avgd def compute_gibbs(counts, sizes, eta = 0.5, **kwargs): """ Compute the Gibbs objective function for given measurements Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) eta : float, optional Inverse Temperature Returns ------- float - Gibbs objective function value / optimal value """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) ls = max(sizes)#largest size shifted_sizes = sizes - ls # gibbs = - np.log( np.sum(counts * np.exp(eta * sizes)) / np.sum(counts)) gibbs = - eta * ls - np.log(np.sum (counts / np.sum(counts) * np.exp(eta * shifted_sizes))) return gibbs def compute_best_cut_from_measured(counts, sizes, **kwargs): """From the measured cuts, return the size of the largest cut """ return - np.max(sizes) def compute_quartiles(counts, sizes): """ Compute and return the sizes of the cuts at the three quartile values (i.e. 0.25, 0.5 and 0.75) Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) Returns ------- quantile_sizes : ndarray of of 3 floats sizes of cuts corresponding to the three quartile values. """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) # Sort sizes and counts in the sequence of non-decreasing values of sizes sort_inds = np.argsort(sizes) sizes = sizes[sort_inds] counts = counts[sort_inds] num_shots = np.sum(counts) q_vals = [0.25, 0.5, 0.75] ct_vals = [math.floor(q * num_shots) for q in q_vals] cumsum_counts = np.cumsum(counts) locs = np.searchsorted(cumsum_counts, ct_vals) quantile_sizes = sizes[locs] return quantile_sizes def uniform_cut_sampling(num_qubits, degree, num_shots, _instances=None): """ For a given problem, i.e. num_qubits and degree values, sample cuts uniformly at random from all possible cuts, num_shots number of times. Return the corresponding cuts, counts and cut sizes. """ # First, load the nodes and edges corresponding to the problem instance_filename = os.path.join(os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{degree:03d}_000.txt") nodes, edges = common.read_maxcut_instance(instance_filename, _instances) # Obtain num_shots number of uniform random samples between 0 and 2 ** num_qubits unif_cuts = np.random.randint(2 ** num_qubits, size=num_shots).tolist() unif_cuts_uniq = list(set(unif_cuts)) # Get counts corresponding to each sampled int/cut unif_counts = [unif_cuts.count(cut) for cut in unif_cuts_uniq] unif_cuts = list(set(unif_cuts)) def int_to_bs(numb): # Function for converting from an integer to (bit)strings of length num_qubits strr = format(numb, "b") #convert to binary strr = '0' * (num_qubits - len(strr)) + strr return strr unif_cuts = [int_to_bs(i) for i in unif_cuts] unif_sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in unif_cuts] # Also get the corresponding distribution of cut sizes unique_counts_unif, unique_sizes_unif, cumul_counts_unif = get_size_dist(unif_counts, unif_sizes) return unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif def get_random_angles(rounds, restarts): """Create max_circuit number of random initial conditions Args: rounds (int): number of rounds in QAOA restarts (int): number of random initial conditions Returns: restarts (list of lists of floats): list of length restarts. Each list element is a list of angles """ # restarts = min(10, restarts) # Create random angles theta_min = [0] * 2 * rounds # Upper limit for betas=pi; upper limit for gammas=2pi theta_max = [np.pi] * rounds + [2 * np.pi] * rounds thetas = np.random.uniform( low=theta_min, high=theta_max, size=(restarts, 2 * rounds) ) thetas = thetas.tolist() return thetas def get_restart_angles(thetas_array, rounds, restarts): """ Create random initial conditions for the restart loop. thetas_array takes precedence over restarts. If the user inputs valid thetas_array, restarts will be inferred accordingly. If thetas_array is None and restarts is 1, return all 1's as initial angles. If thetas_array is None and restarts >1, generate restarts number of random initial conditions If only one set of random angles are desired, then the user needs to create them and send as thetas_array Args: thetas_array (list of lists of floats): list of initial angles. restarts (int): number of random initial conditions rounds (int): of QAOA Returns: thetas (list of lists. Shape = (max_circuits, 2 * rounds)) restarts : int """ assert type(restarts) == int and restarts > 0, "max_circuits must be an integer greater than 0" default_angles = [[1] * 2 * rounds] default_restarts = 1 if thetas_array is None: if restarts == 1: # if the angles are none, but restarts equals 1, use default of all 1's return default_angles, default_restarts else: # restarts can only be greater than 1. return get_random_angles(rounds, restarts), restarts if type(thetas_array) != list: # thetas_array is not None, but is also not a list. print("thetas_array is not a list. Using random angles.") return get_random_angles(rounds, restarts), restarts # At this point, thetas_array is a list. check if thetas_array is a list of lists if not all([type(item) == list for item in thetas_array]): # if every list element is not a list, return random angles print("thetas_array is not a list of lists. Using random angles.") return get_random_angles(rounds, restarts), restarts if not all([len(item) == 2 * rounds for item in thetas_array]): # If not all list elements are lists of the correct length... print("Each element of thetas_array must be a list of length 2 * rounds. Using random angles.") return get_random_angles(rounds, restarts), restarts # At this point, thetas_array is a list of lists of length 2*rounds. All conditions are satisfied. Return inputted angles. return thetas_array, len(thetas_array) #%% Storing final iteration data to json file, and to metrics.circuit_metrics_final_iter def save_runtime_data(result_dict): # This function will need changes, since circuit metrics dictionaries are now different cm = result_dict.get('circuit_metrics') detail = result_dict.get('circuit_metrics_detail', None) detail_2 = result_dict.get('circuit_metrics_detail_2', None) benchmark_inputs = result_dict.get('benchmark_inputs', None) final_iter_metrics = result_dict.get('circuit_metrics_final_iter') backend_id = result_dict.get('benchmark_inputs').get('backend_id') metrics.circuit_metrics_detail_2 = detail_2 for width in detail_2: # unique_id = restart_ind * 1000 + minimizer_iter_ind restart_ind_list = list(detail_2.get(width).keys()) for restart_ind in restart_ind_list: degree = cm[width]['1']['degree'] opt = final_iter_metrics[width]['1']['optimal_value'] instance_filename = os.path.join(os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{int(width):03d}_{int(degree):03d}_000.txt") metrics.circuit_metrics[width] = detail.get(width) metrics.circuit_metrics['subtitle'] = cm.get('subtitle') finIterDict = final_iter_metrics[width][restart_ind] if benchmark_inputs['save_final_counts']: # if the final iteration cut counts were stored, retrieve them iter_dist = {'cuts' : finIterDict['cuts'], 'counts' : finIterDict['counts'], 'sizes' : finIterDict['sizes']} else: # The value of iter_dist does not matter otherwise iter_dist = None # Retrieve the distribution of cut sizes for the final iteration for this width and degree iter_size_dist = {'unique_sizes' : finIterDict['unique_sizes'], 'unique_counts' : finIterDict['unique_counts'], 'cumul_counts' : finIterDict['cumul_counts']} converged_thetas_list = finIterDict.get('converged_thetas_list') parent_folder_save = os.path.join('__data', f'{backend_id}') store_final_iter_to_metrics_json( num_qubits=int(width), degree = int(degree), restart_ind=int(restart_ind), num_shots=int(benchmark_inputs['num_shots']), converged_thetas_list=converged_thetas_list, opt=opt, iter_size_dist=iter_size_dist, iter_dist = iter_dist, dict_of_inputs=benchmark_inputs, parent_folder_save=parent_folder_save, save_final_counts=False, save_res_to_file=True, _instances=None ) def store_final_iter_to_metrics_json(num_qubits, degree, restart_ind, num_shots, converged_thetas_list, opt, iter_size_dist, iter_dist, parent_folder_save, dict_of_inputs, save_final_counts, save_res_to_file, _instances=None): """ For a given graph (specified by num_qubits and degree), 1. For a given restart, store properties of the final minimizer iteration to metrics.circuit_metrics_final_iter, and 2. Store various properties for all minimizer iterations for each restart to a json file. Parameters ---------- num_qubits, degree, restarts, num_shots : ints parent_folder_save : string (location where json file will be stored) dict_of_inputs : dictionary of inputs that were given to run() save_final_counts: bool. If true, save counts, cuts and sizes for last iteration to json file. save_res_to_file: bool. If False, do not save data to json file. iter_size_dist : dictionary containing distribution of cut sizes. Keys are 'unique_sizes', 'unique_counts' and 'cumul_counts' opt (int) : Max Cut value """ # In order to compare with uniform random sampling, get some samples unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif = uniform_cut_sampling( num_qubits, degree, num_shots, _instances) unif_dict = {'unique_counts_unif': unique_counts_unif, 'unique_sizes_unif': unique_sizes_unif, 'cumul_counts_unif': cumul_counts_unif} # store only the distribution of cut sizes, and not the cuts themselves # Store properties such as (cuts, counts, sizes) of the final iteration, the converged theta values, as well as the known optimal value for the current problem, in metrics.circuit_metrics_final_iter. Also store uniform cut sampling results metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt) metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_size_dist) metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list) metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict) # metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_dist) # do not store iter_dist, since it takes a lot of memory for larger widths, instead, store just iter_size_dist if save_res_to_file: # Save data to a json file dump_to_json(parent_folder_save, num_qubits, degree, restart_ind, iter_size_dist, iter_dist, dict_of_inputs, converged_thetas_list, opt, unif_dict, save_final_counts=save_final_counts) def dump_to_json(parent_folder_save, num_qubits, degree, restart_ind, iter_size_dist, iter_dist, dict_of_inputs, converged_thetas_list, opt, unif_dict, save_final_counts=False): """ For a given problem (specified by number of qubits and graph degree) and restart_index, save the evolution of various properties in a json file. Items stored in the json file: Data from all iterations (iterations), inputs to run program ('general properties'), converged theta values ('converged_thetas_list'), max cut size for the graph (optimal_value), distribution of cut sizes for random uniform sampling (unif_dict), and distribution of cut sizes for the final iteration (final_size_dist) if save_final_counts is True, then also store the distribution of cuts """ if not os.path.exists(parent_folder_save): os.makedirs(parent_folder_save) store_loc = os.path.join(parent_folder_save,'width_{}_restartInd_{}.json'.format(num_qubits, restart_ind)) # Obtain dictionary with iterations data corresponding to given restart_ind all_restart_ids = list(metrics.circuit_metrics[str(num_qubits)].keys()) ids_this_restart = [r_id for r_id in all_restart_ids if int(r_id) // 1000 == restart_ind] iterations_dict_this_restart = {r_id : metrics.circuit_metrics[str(num_qubits)][r_id] for r_id in ids_this_restart} # Values to be stored in json file dict_to_store = {'iterations' : iterations_dict_this_restart} dict_to_store['general_properties'] = dict_of_inputs dict_to_store['converged_thetas_list'] = converged_thetas_list dict_to_store['optimal_value'] = opt dict_to_store['unif_dict'] = unif_dict dict_to_store['final_size_dist'] = iter_size_dist # Also store the value of counts obtained for the final counts if save_final_counts: dict_to_store['final_counts'] = iter_dist #iter_dist.get_counts() # Now save the output with open(store_loc, 'w') as outfile: json.dump(dict_to_store, outfile) #%% Loading saved data (from json files) def load_data_and_plot(folder, backend_id=None, **kwargs): """ The highest level function for loading stored data from a previous run and plotting optgaps and area metrics Parameters ---------- folder : string Directory where json files are saved. """ _gen_prop = load_all_metrics(folder, backend_id=backend_id) if _gen_prop != None: gen_prop = {**_gen_prop, **kwargs} plot_results_from_data(**gen_prop) def load_all_metrics(folder, backend_id=None): """ Load all data that was saved in a folder. The saved data will be in json files in this folder Parameters ---------- folder : string Directory where json files are saved. Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # Note: folder here should be the folder where only the width=... files are stored, and not a folder higher up in the directory assert os.path.isdir(folder), f"Specified folder ({folder}) does not exist." metrics.init_metrics() list_of_files = os.listdir(folder) width_restart_file_tuples = [(*get_width_restart_tuple_from_filename(fileName), fileName) for (ind, fileName) in enumerate(list_of_files) if fileName.startswith("width")] # list with elements that are tuples->(width,restartInd,filename) width_restart_file_tuples = sorted(width_restart_file_tuples, key=lambda x:(x[0], x[1])) #sort first by width, and then by restartInd distinct_widths = list(set(it[0] for it in width_restart_file_tuples)) list_of_files = [ [tup[2] for tup in width_restart_file_tuples if tup[0] == width] for width in distinct_widths ] # connot continue without at least one dataset if len(list_of_files) < 1: print("ERROR: No result files found") return None for width_files in list_of_files: # For each width, first load all the restart files for fileName in width_files: gen_prop = load_from_width_restart_file(folder, fileName) # next, do processing for the width method = gen_prop['method'] if method == 2: num_qubits, _ = get_width_restart_tuple_from_filename(width_files[0]) metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(str(num_qubits)) # override device name with the backend_id if supplied by caller if backend_id != None: metrics.set_plot_subtitle(f"Device = {backend_id}") return gen_prop def load_from_width_restart_file(folder, fileName): """ Given a folder name and a file in it, load all the stored data and store the values in metrics.circuit_metrics. Also return the converged values of thetas, the final counts and general properties. Parameters ---------- folder : string folder where the json file is located fileName : string name of the json file Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # Extract num_qubits and s from file name num_qubits, restart_ind = get_width_restart_tuple_from_filename(fileName) print(f"Loading from {fileName}, corresponding to {num_qubits} qubits and restart index {restart_ind}") with open(os.path.join(folder, fileName), 'r') as json_file: data = json.load(json_file) gen_prop = data['general_properties'] converged_thetas_list = data['converged_thetas_list'] unif_dict = data['unif_dict'] opt = data['optimal_value'] if gen_prop['save_final_counts']: # Distribution of measured cuts final_counts = data['final_counts'] final_size_dist = data['final_size_dist'] backend_id = gen_prop.get('backend_id') metrics.set_plot_subtitle(f"Device = {backend_id}") # Update circuit metrics for circuit_id in data['iterations']: # circuit_id = restart_ind * 1000 + minimizer_loop_ind for metric, value in data['iterations'][circuit_id].items(): metrics.store_metric(num_qubits, circuit_id, metric, value) method = gen_prop['method'] if method == 2: metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt) metrics.store_props_final_iter(num_qubits, restart_ind, None, final_size_dist) metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list) metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict) if gen_prop['save_final_counts']: metrics.store_props_final_iter(num_qubits, restart_ind, None, final_counts) return gen_prop def get_width_restart_tuple_from_filename(fileName): """ Given a filename, extract the corresponding width and degree it corresponds to For example the file "width=4_degree=3.json" corresponds to 4 qubits and degree 3 Parameters ---------- fileName : TYPE DESCRIPTION. Returns ------- num_qubits : int circuit width degree : int graph degree. """ pattern = 'width_([0-9]+)_restartInd_([0-9]+).json' match = re.search(pattern, fileName) # assert match is not None, f"File {fileName} found inside folder. All files inside specified folder must be named in the format 'width_int_restartInd_int.json" num_qubits = int(match.groups()[0]) degree = int(match.groups()[1]) return (num_qubits,degree) #%% Run method: Benchmarking loop MAX_QUBITS = 24 iter_dist = {'cuts' : [], 'counts' : [], 'sizes' : []} # (list of measured bitstrings, list of corresponding counts, list of corresponding cut sizes) iter_size_dist = {'unique_sizes' : [], 'unique_counts' : [], 'cumul_counts' : []} # for the iteration being executed, stores the distribution for cut sizes saved_result = { } instance_filename = None def run (min_qubits=3, max_qubits=6, max_circuits=1, num_shots=100, method=1, rounds=1, degree=3, alpha=0.1, thetas_array=None, parameterized= False, do_fidelities=True, max_iter=30, score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, use_fixed_angles=False, objective_func_type = 'approx_ratio', plot_results = True, save_res_to_file = False, save_final_counts = False, detailed_save_names = False, comfort=False, backend_id='qasm_simulator', provider_backend=None, eta=0.5, hub="ibm-q", group="open", project="main", exec_options=None, _instances=None): """ Parameters ---------- min_qubits : int, optional The smallest circuit width for which benchmarking will be done The default is 3. max_qubits : int, optional The largest circuit width for which benchmarking will be done. The default is 6. max_circuits : int, optional Number of restarts. The default is None. num_shots : int, optional Number of times the circut will be measured, for each iteration. The default is 100. method : int, optional If 1, then do standard metrics, if 2, implement iterative algo metrics. The default is 1. rounds : int, optional number of QAOA rounds. The default is 1. degree : int, optional degree of graph. The default is 3. thetas_array : list, optional list or ndarray of beta and gamma values. The default is None. use_fixed_angles : bool, optional use betas and gammas obtained from a 'fixed angles' table, specific to degree and rounds N : int, optional For the max % counts metric, choose the highest N% counts. The default is 10. alpha : float, optional Value between 0 and 1. The default is 0.1. parameterized : bool, optional Whether to use parametrized circuits or not. The default is False. do_fidelities : bool, optional Compute circuit fidelity. The default is True. max_iter : int, optional Number of iterations for the minimizer routine. The default is 30. score_metric : list or string, optional Which metrics are to be plotted in area metrics plots. The default is 'fidelity'. x_metric : list or string, optional Horizontal axis for area plots. The default is 'cumulative_exec_time'. y_metric : list or string, optional Vertical axis for area plots. The default is 'num_qubits'. fixed_metrics : TYPE, optional DESCRIPTION. The default is {}. num_x_bins : int, optional DESCRIPTION. The default is 15. y_size : TYPint, optional DESCRIPTION. The default is None. x_size : string, optional DESCRIPTION. The default is None. backend_id : string, optional DESCRIPTION. The default is 'qasm_simulator'. provider_backend : string, optional DESCRIPTION. The default is None. hub : string, optional DESCRIPTION. The default is "ibm-q". group : string, optional DESCRIPTION. The default is "open". project : string, optional DESCRIPTION. The default is "main". exec_options : string, optional DESCRIPTION. The default is None. objective_func_type : string, optional Objective function to be used by the classical minimizer algorithm. The default is 'approx_ratio'. plot_results : bool, optional Plot results only if True. The default is True. save_res_to_file : bool, optional Save results to json files. The default is True. save_final_counts : bool, optional If True, also save the counts from the final iteration for each problem in the json files. The default is True. detailed_save_names : bool, optional If true, the data and plots will be saved with more detailed names. Default is False confort : bool, optional If true, print comfort dots during execution """ # Store all the input parameters into a dictionary. # This dictionary will later be stored in a json file # It will also be used for sending parameters to the plotting function dict_of_inputs = locals() # Get angles for restarts. Thetas = list of lists. Lengths are max_circuits and 2*rounds thetas, max_circuits = get_restart_angles(thetas_array, rounds, max_circuits) # Update the dictionary of inputs dict_of_inputs = {**dict_of_inputs, **{'thetas_array': thetas, 'max_circuits' : max_circuits}} # Delete some entries from the dictionary for key in ["hub", "group", "project", "provider_backend"]: dict_of_inputs.pop(key) global maxcut_inputs maxcut_inputs = dict_of_inputs global QC_ global circuits_done global minimizer_loop_index global opt_ts print("MaxCut Benchmark Program - Qiskit") QC_ = None # Create a folder where the results will be saved. Folder name=time of start of computation # In particular, for every circuit width, the metrics will be stored the moment the results are obtained # In addition to the metrics, the (beta,gamma) values obtained by the optimizer, as well as the counts # measured for the final circuit will be stored. # Use the following parent folder, for a more detailed if detailed_save_names: start_time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type, f'run_start_{start_time_str}') else: parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type) if save_res_to_file and not os.path.exists(parent_folder_save): os.makedirs(os.path.join(parent_folder_save)) # validate parameters max_qubits = max(4, max_qubits) max_qubits = min(MAX_QUBITS, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) degree = max(3, degree) rounds = max(1, rounds) # don't compute exectation unless fidelity is is needed global do_compute_expectation do_compute_expectation = do_fidelities # given that this benchmark does every other width, set y_size default to 1.5 if y_size == None: y_size = 1.5 # Choose the objective function to minimize, based on values of the parameters possible_approx_ratios = {'cvar_ratio', 'approx_ratio', 'gibbs_ratio', 'bestcut_ratio'} non_objFunc_ratios = possible_approx_ratios - { objective_func_type } function_mapper = {'cvar_ratio' : compute_cvar, 'approx_ratio' : compute_sample_mean, 'gibbs_ratio' : compute_gibbs, 'bestcut_ratio' : compute_best_cut_from_measured} # if using fixed angles, get thetas array from table if use_fixed_angles: # Load the fixed angle tables from data file fixed_angles = common.read_fixed_angles( os.path.join(os.path.dirname(__file__), '..', '_common', 'angles_regular_graphs.json'), _instances) thetas_array = common.get_fixed_angles_for(fixed_angles, degree, rounds) if thetas_array == None: print(f"ERROR: no fixed angles for rounds = {rounds}") return # **************************** # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) def execution_handler2 (qc, result, num_qubits, s_int, num_shots): # Stores the results to the global saved_result variable global saved_result saved_result = result # Initialize execution module using the execution result handler above and specified backend_id # for method=2 we need to set max_jobs_active to 1, so each circuit completes before continuing if method == 2: ex.max_jobs_active = 1 ex.init_execution(execution_handler2) else: ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete # DEVNOTE: increment by 2 to match the collection of problems in 'instance' folder for num_qubits in range(min_qubits, max_qubits + 1, 2): if method == 1: print(f"************\nExecuting [{max_circuits}] circuits for num_qubits = {num_qubits}") else: print(f"************\nExecuting [{max_circuits}] restarts for num_qubits = {num_qubits}") # If degree is negative, if degree < 0 : degree = max(3, (num_qubits + degree)) # Load the problem and its solution global instance_filename instance_filename = os.path.join( os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{degree:03d}_000.txt", ) nodes, edges = common.read_maxcut_instance(instance_filename, _instances) opt, _ = common.read_maxcut_solution( instance_filename[:-4] + ".sol", _instances ) # if the file does not exist, we are done with this number of qubits if nodes == None: print(f" ... problem not found.") break for restart_ind in range(1, max_circuits + 1): # restart index should start from 1 # Loop over restarts for a given graph # if not using fixed angles, get initial or random thetas from array saved earlier # otherwise use random angles (if restarts > 1) or [1] * 2 * rounds if not use_fixed_angles: thetas_array = thetas[restart_ind - 1] if method == 1: # create the circuit for given qubit size and secret string, store time metric ts = time.time() # if using fixed angles in method 1, need to access first element # DEVNOTE: eliminate differences between method 1 and 2 and handling of thetas_array thetas_array_0 = thetas_array if use_fixed_angles: thetas_array_0 = thetas_array[0] qc, params = MaxCut(num_qubits, restart_ind, edges, rounds, thetas_array_0, parameterized) metrics.store_metric(num_qubits, restart_ind, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, restart_ind, shots=num_shots, params=params) if method == 2: # a unique circuit index used inside the inner minimizer loop as identifier minimizer_loop_index = 0 # Value of 0 corresponds to the 0th iteration of the minimizer start_iters_t = time.time() # Always start by enabling transpile ... ex.set_tranpilation_flags(do_transpile_metrics=True, do_transpile_for_execute=True) logger.info(f'=============== Begin method 2 loop, enabling transpile') def expectation(thetas_array): # Every circuit needs a unique id; add unique_circuit_index instead of s_int global minimizer_loop_index unique_id = restart_ind * 1000 + minimizer_loop_index # store thetas_array metrics.store_metric(num_qubits, unique_id, 'thetas_array', thetas_array.tolist()) #************************************************ #*** Circuit Creation and Decomposition start *** # create the circuit for given qubit size, secret string and params, store time metric ts = time.time() qc, params = MaxCut(num_qubits, unique_id, edges, rounds, thetas_array, parameterized) metrics.store_metric(num_qubits, unique_id, 'create_time', time.time()-ts) # also store the 'rounds' and 'degree' for each execution # DEVNOTE: Currently, this is stored for each iteration. Reduce this redundancy metrics.store_metric(num_qubits, unique_id, 'rounds', rounds) metrics.store_metric(num_qubits, unique_id, 'degree', degree) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # Circuit Creation and Decomposition end #************************************************ #************************************************ #*** Quantum Part: Execution of Circuits *** # submit circuit for execution on target with the current parameters ex.submit_circuit(qc2, num_qubits, unique_id, shots=num_shots, params=params) # Must wait for circuit to complete #ex.throttle_execution(metrics.finalize_group) ex.finalize_execution(None, report_end=False) # don't finalize group until all circuits done # after first execution and thereafter, no need for transpilation if parameterized if parameterized: ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False) logger.info(f'**** First execution complete, disabling transpile') #************************************************ global saved_result # Fidelity Calculation and Storage _, fidelity = analyze_and_print_result(qc, saved_result, num_qubits, unique_id, num_shots) metrics.store_metric(num_qubits, unique_id, 'fidelity', fidelity) #************************************************ #*** Classical Processing of Results - essential to optimizer *** global opt_ts dict_of_vals = dict() # Start counting classical optimizer time here again tc1 = time.time() cuts, counts, sizes = compute_cutsizes(saved_result, nodes, edges) # Compute the value corresponding to the objective function first dict_of_vals[objective_func_type] = function_mapper[objective_func_type](counts, sizes, alpha = alpha) # Store the optimizer time as current time- tc1 + ts - opt_ts, since the time between tc1 and ts is not time used by the classical optimizer. metrics.store_metric(num_qubits, unique_id, 'opt_exec_time', time.time() - tc1 + ts - opt_ts) # Note: the first time it is stored it is just the initialization time for optimizer #************************************************ #************************************************ #*** Classical Processing of Results - not essential for optimizer. Used for tracking metrics *** # Compute the distribution of cut sizes; store them under metrics unique_counts, unique_sizes, cumul_counts = get_size_dist(counts, sizes) global iter_size_dist iter_size_dist = {'unique_sizes' : unique_sizes, 'unique_counts' : unique_counts, 'cumul_counts' : cumul_counts} metrics.store_metric(num_qubits, unique_id, None, iter_size_dist) # Compute and the other metrics (eg. cvar, gibbs and max N % if the obj function was set to approx ratio) for s in non_objFunc_ratios: dict_of_vals[s] = function_mapper[s](counts, sizes, alpha = alpha) # Store the ratios dict_of_ratios = { key : -1 * val / opt for (key, val) in dict_of_vals.items()} dict_of_ratios['gibbs_ratio'] = dict_of_ratios['gibbs_ratio'] / eta metrics.store_metric(num_qubits, unique_id, None, dict_of_ratios) # Get the best measurement and store it best = - compute_best_cut_from_measured(counts, sizes) metrics.store_metric(num_qubits, unique_id, 'bestcut_ratio', best / opt) # Also compute and store the weights of cuts at three quantile values quantile_sizes = compute_quartiles(counts, sizes) # Store quantile_optgaps as a list (allows storing in json files) metrics.store_metric(num_qubits, unique_id, 'quantile_optgaps', (1 - quantile_sizes / opt).tolist()) # Also store the cuts, counts and sizes in a global variable, to allow access elsewhere global iter_dist iter_dist = {'cuts' : cuts, 'counts' : counts, 'sizes' : sizes} minimizer_loop_index += 1 #************************************************ if comfort: if minimizer_loop_index == 1: print("") print(".", end ="") # reset timer for optimizer execution after each iteration of quantum program completes opt_ts = time.time() return dict_of_vals[objective_func_type] # after first execution and thereafter, no need for transpilation if parameterized # DEVNOTE: this appears to NOT be needed, as we can turn these off after def callback(xk): if parameterized: ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False) opt_ts = time.time() # perform the complete algorithm; minimizer invokes 'expectation' function iteratively ##res = minimize(expectation, thetas_array, method='COBYLA', options = { 'maxiter': max_iter}, callback=callback) res = minimize(expectation, thetas_array, method='COBYLA', options = { 'maxiter': max_iter}) # To-do: Set bounds for the minimizer unique_id = restart_ind * 1000 + 0 metrics.store_metric(num_qubits, unique_id, 'opt_exec_time', time.time()-opt_ts) if comfort: print("") # Save final iteration data to metrics.circuit_metrics_final_iter # This data includes final counts, cuts, etc. store_final_iter_to_metrics_json(num_qubits=num_qubits, degree=degree, restart_ind=restart_ind, num_shots=num_shots, converged_thetas_list=res.x.tolist(), opt=opt, iter_size_dist=iter_size_dist, iter_dist=iter_dist, parent_folder_save=parent_folder_save, dict_of_inputs=dict_of_inputs, save_final_counts=save_final_counts, save_res_to_file=save_res_to_file, _instances=_instances) # for method 2, need to aggregate the detail metrics appropriately for each group # Note that this assumes that all iterations of the circuit have completed by this point if method == 2: metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(str(num_qubits)) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) global print_sample_circuit if print_sample_circuit: # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") #if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes if method == 1: metrics.plot_metrics(f"Benchmark Results - MaxCut ({method}) - Qiskit", options=dict(shots=num_shots,rounds=rounds)) elif method == 2: #metrics.print_all_circuit_metrics() if plot_results: plot_results_from_data(**dict_of_inputs) def plot_results_from_data(num_shots=100, rounds=1, degree=3, max_iter=30, max_circuits = 1, objective_func_type='approx_ratio', method=2, use_fixed_angles=False, score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, x_min=None, x_max=None, offset_flag=False, # default is False for QAOA detailed_save_names=False, **kwargs): """ Plot results """ if detailed_save_names: # If detailed names are desired for saving plots, put date of creation, etc. cur_time=datetime.datetime.now() dt = cur_time.strftime("%Y-%m-%d_%H-%M-%S") short_obj_func_str = metrics.score_label_save_str[objective_func_type] suffix = f'-s{num_shots}_r{rounds}_d{degree}_mi{max_iter}_of-{short_obj_func_str}_{dt}' #of=objective function else: short_obj_func_str = metrics.score_label_save_str[objective_func_type] suffix = f'of-{short_obj_func_str}' #of=objective function obj_str = metrics.known_score_labels[objective_func_type] options = {'shots' : num_shots, 'rounds' : rounds, 'degree' : degree, 'restarts' : max_circuits, 'fixed_angles' : use_fixed_angles, '\nObjective Function' : obj_str} suptitle = f"Benchmark Results - MaxCut ({method}) - Qiskit" metrics.plot_all_area_metrics(f"Benchmark Results - MaxCut ({method}) - Qiskit", score_metric=score_metric, x_metric=x_metric, y_metric=y_metric, fixed_metrics=fixed_metrics, num_x_bins=num_x_bins, x_size=x_size, y_size=y_size, x_min=x_min, x_max=x_max, offset_flag=offset_flag, options=options, suffix=suffix) metrics.plot_metrics_optgaps(suptitle, options=options, suffix=suffix, objective_func_type = objective_func_type) # this plot is deemed less useful #metrics.plot_ECDF(suptitle=suptitle, options=options, suffix=suffix) all_widths = list(metrics.circuit_metrics_final_iter.keys()) all_widths = [int(ii) for ii in all_widths] list_of_widths = [all_widths[-1]] metrics.plot_cutsize_distribution(suptitle=suptitle,options=options, suffix=suffix, list_of_widths = list_of_widths) metrics.plot_angles_polar(suptitle = suptitle, options = options, suffix = suffix) # if main, execute method if __name__ == '__main__': run() # %%
59,569
42.801471
352
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/qiskit/runtime_utils.py
# This script is intended to replace sh_script.sh and script.sed # The objective of this script is the create the maxcut_runtime.py file import re import sys import os import json from collections import defaultdict sys.path[1:1] = [ "_common", "_common/qiskit", "maxcut/_common" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit", "../../maxcut/_common/" ] import common import execute import metrics import maxcut_benchmark from qiskit_ibm_runtime import QiskitRuntimeService def remove_imports_calls(string): pattern_list = [ "sys.*]\n", "import metrics.*\n", "import execute as ex\n", "import common\n", "common\.", "ex\.", "(?<!_)metrics\.", # "# print a sample circuit.*\n.*\n" "# if main, execute method", "if __name__ == '__main__':.*$", ] # remove the printing of sample circuit for pattern in pattern_list: string = re.sub(pattern, "", string, flags=re.MULTILINE) return string def create_runtime_script(file_name="maxcut_runtime.py"): list_of_files = [ os.path.abspath(common.__file__), os.path.abspath(metrics.__file__), os.path.abspath(execute.__file__), os.path.abspath(maxcut_benchmark.__file__), ] # Concatenate files all_catted_string = "" for file in list_of_files: with open(file, "r", encoding="utf8") as opened: data = opened.read() all_catted_string = all_catted_string + "\n" + data all_catted_string = remove_imports_calls(all_catted_string) # add main file with open("add_main.py", "r", encoding="utf8") as text_file: data = text_file.read() all_catted_string += "\n" + data with open(file_name, "w", encoding="utf8") as text_file: text_file.write(all_catted_string) def prepare_instances(): insts = defaultdict(dict) instance_dir = os.path.join("..", "_common", "instances") files = (file for file in os.listdir(instance_dir) if file.startswith("mc")) for f in files: p = os.path.join(instance_dir, f"{f}") k, _, _ = f.partition('.') if 'txt' in f: insts[k]['instance'] = common.read_maxcut_instance(p) if 'sol' in f: insts[k]['sol'] = common.read_maxcut_solution(p) common_dir = os.path.join("..", "_common") insts['fixed_angles'] = common.read_fixed_angles( os.path.join(common_dir, 'angles_regular_graphs.json')) return insts def get_status(service, job_id): return service.job(job_id=job_id).status().name def save_jobinfo(backend_id, job_id, job_status): path = os.path.join("__data", backend_id) line = f"{job_id},{job_status}" os.makedirs(path, exist_ok=True) with open(os.path.join(path, "jobs.txt"), "w+") as file: file.write(line) ''' def save_jobinfo(backend_id, job_id, job_status): path = os.path.join("__data", backend_id) line = f"{job_id},{job_status}\n" os.makedirs(path, exist_ok=True) try: with open(os.path.join(path, "jobs.txt"), "r+") as file: data = file.readlines() except FileNotFoundError: with open(os.path.join(path, "jobs.txt"), "w+") as file: data = file.readlines() if line in data: return with open(os.path.join(path, "jobs.txt"), "w+") as file: if job_status == "DONE": data[-1] = data[-1].replace("RUNNING", job_status) else: data.append(line) file.write("".join(data)) ''' def get_jobinfo(backend_id): path = os.path.join("__data", backend_id, "jobs.txt") try: with open(path, "r") as file: data = file.read() except FileNotFoundError: return [None, None] job_id, status = data.strip().split(",") job = QiskitRuntimeService().job(job_id=job_id) return job, status def get_id(path): if not os.path.exists(path): return None with open(path, "r") as file: data = file.read() job_id, status = data.split(",") return job_id, status def get_response(service, path): if not os.path.exists(path): return "continue" job_id = get_id(path) status = get_status(service, job_id) print( f"WARNING: Job file already exists! Job {job_id} is {status}" ) response = input( f"Would you like to continue and overwrite your previous data in {os.path.dirname(path)}? (y/n)" ) return response def process_results(job_id, backend_id, service): path = os.path.join("__data", f"{backend_id}") # Will wait for job to finish result = service.job(job_id).result() maxcut_benchmark.save_runtime_data(result) maxcut_benchmark.load_data_and_plot(path) def run(**kwargs): service = QiskitRuntimeService() options = { 'backend_name': kwargs['backend_id'] } runtime_inputs = { "backend_id": kwargs['backend_id'], "method": 2, "_instances": kwargs['_instances'], "min_qubits": kwargs['min_qubits'], "max_qubits": kwargs['max_qubits'], "max_circuits": kwargs['max_circuits'], "num_shots": kwargs['num_shots'], "degree": kwargs['degree'], "rounds": kwargs['rounds'], "max_iter": kwargs['max_iter'], "parameterized": kwargs['parameterized'], "do_fidelities": False, # To keep plots consistent "hub": kwargs['hub'], "group": kwargs['group'], "project": kwargs['project'] } job_file_path = os.path.join( "__data", f"{kwargs['backend_id']}", "job.txt" ) if os.path.exists(job_file_path): response = get_response(service, job_file_path) job_id = get_id(job_file_path) if response.strip().lower() == "n": print("Aborting without executing any procedures.") return status = get_status(service, job_id) if status != 'ERROR' or status != 'CANCELLED': print("Fetching previously submitted job:") process_results(job_id, kwargs["backend_id"], service) os.remove(job_file_path) return RUNTIME_FILENAME = 'maxcut_runtime.py' create_runtime_script(file_name=RUNTIME_FILENAME) program_id = service.upload_program( data=RUNTIME_FILENAME, metadata=kwargs["meta"] ) ## Uses previously uploaded program instead of uploading a new one. # program_id = list( # filter( # lambda x: x.program_id.startswith("qedc"), # service.programs() # ) # )[0].program_id job = service.run( program_id=program_id, options=options, inputs=runtime_inputs, instance=f'{kwargs["hub"]}/{kwargs["group"]}/{kwargs["project"]}' ) try: with open(job_file_path, "w+") as file: file.write(f"{job.job_id},{job.status().name}") except FileNotFoundError: os.mkdir(os.path.join('__data', f"{kwargs['backend_id']}")) with open(job_file_path, "w+") as file: file.write(f"{job.job_id},{job.status().name}") process_results(job.job_id, kwargs["backend_id"], service) return job
7,226
28.618852
104
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/qiskit/add_main.py
import inspect from qiskit.providers.ibmq.runtime import UserMessenger import time def main(backend, user_messenger=UserMessenger(), **kwargs): # Stores all default parameters in dictionary argspec = inspect.getfullargspec(run) _args = {x: y for (x, y) in zip(argspec.args, argspec.defaults)} _args["provider_backend"] = backend _args["backend_id"] = backend.name() # Removing saving and plotting because they will not work on runtime servers _args["save_res_to_file"] = False _args["save_final_counts"] = False _args["plot_results"] = False args = {**_args, **kwargs} start = time.perf_counter() run(**args) _wall_time = time.perf_counter() - start # Remove provider_backend becuase it is not JSON Serializable args['provider_backend'] = None # Remove instances because we already have them stored and they are large args.pop('_instances') final_out = dict( circuit_metrics=circuit_metrics, circuit_metrics_final_iter=circuit_metrics_final_iter, circuit_metrics_detail = circuit_metrics_detail, circuit_metrics_detail_2 = circuit_metrics_detail_2, benchmark_inputs=args, wall_time=_wall_time, ) return final_out
1,249
31.894737
81
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/maxcut/ocean/maxcut_benchmark.py
""" MaxCut Benchmark Program - Ocean """ import datetime import json import logging import math import os import re import sys import time from collections import namedtuple import numpy as np sys.path[1:1] = [ "_common", "_common/ocean", "maxcut/_common" ] sys.path[1:1] = [ "../../_common", "../../_common/ocean", "../../maxcut/_common/" ] import common import execute as ex import metrics as metrics import HamiltonianCircuitProxy logger = logging.getLogger(__name__) fname, _, ext = os.path.basename(__file__).partition(".") log_to_file = True # Big-endian format is used in dwave. no need to reverse bitstrings reverseStep = 1 try: if log_to_file: logging.basicConfig( # filename=f"{fname}_{datetime.datetime.now().strftime('%Y_%m_%d_%S')}.log", filename=f"{fname}.log", filemode='w', encoding='utf-8', level=logging.INFO, format='%(asctime)s %(name)s - %(levelname)s:%(message)s' ) else: logging.basicConfig( level=logging.INFO, format='%(asctime)s %(name)s - %(levelname)s:%(message)s') except Exception as e: print(f'Exception {e} occured while configuring logger: bypassing logger config to prevent data loss') pass np.random.seed(0) maxcut_inputs = dict() #inputs to the run method verbose = False print_sample_circuit = True # Indicates whether to perform the (expensive) pre compute of expectations do_compute_expectation = True # saved circuits for display QC_ = None Uf_ = None #%% MaxCut circuit creation and fidelity analaysis functions def create_circ(nqubits, edges): h = {} J = {} for e in edges: if e in J: J[e] += 1 else: J[e] = 1 circuitProxy = HamiltonianCircuitProxy.HamiltonianCircuitProxy() circuitProxy.h = h circuitProxy.J = J return circuitProxy def MaxCut (num_qubits, secret_int, edges, measured = True): logger.info(f'*** Constructing NON-parameterized circuit for {num_qubits = } {secret_int}') # and create the hamiltonian circuitProxy = create_circ(num_qubits, edges) # pre-compute and save an array of expected measurements if do_compute_expectation: logger.info('Computing expectation') #compute_expectation(qc, num_qubits, secret_int) # return a handle on the circuit return circuitProxy, None _qc = [] beta_params = [] gamma_params = [] ############### Expectation Tables # DEVNOTE: We are building these tables on-demand for now, but for larger circuits # this will need to be pre-computed ahead of time and stored in a data file to avoid run-time delays. # dictionary used to store pre-computed expectations, keyed by num_qubits and secret_string # these are created at the time the circuit is created, then deleted when results are processed expectations = {} # Compute array of expectation values in range 0.0 to 1.0 # Use statevector_simulator to obtain exact expectation def compute_expectation(qc, num_qubits, secret_int, backend_id='statevector_simulator', params=None): #ts = time.time() if params != None: qc = qc.bind_parameters(params) #execute statevector simulation sv_backend = Aer.get_backend(backend_id) sv_result = execute(qc, sv_backend).result() # get the probability distribution counts = sv_result.get_counts() #print(f"... statevector expectation = {counts}") # store in table until circuit execution is complete id = f"_{num_qubits}_{secret_int}" expectations[id] = counts #print(f" ... time to execute statevector simulator: {time.time() - ts}") # Return expected measurement array scaled to number of shots executed def get_expectation(num_qubits, degree, num_shots): # find expectation counts for the given circuit id = f"_{num_qubits}_{degree}" if id in expectations: counts = expectations[id] # scale to number of shots for k, v in counts.items(): counts[k] = round(v * num_shots) # delete from the dictionary del expectations[id] return counts else: return None ############### Result Data Analysis expected_dist = {} # Compare the measurement results obtained with the expected measurements to determine fidelity def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): global expected_dist # obtain counts from the result object counts = result.get_counts(qc) # retrieve pre-computed expectation values for the circuit that just completed expected_dist = get_expectation(num_qubits, secret_int, num_shots) # if the expectation is not being calculated (only need if we want to compute fidelity) # assume that the expectation is the same as measured counts, yielding fidelity = 1 if expected_dist == None: expected_dist = counts if verbose: print(f"For width {num_qubits} problem {secret_int}\n measured: {counts}\n expected: {expected_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, expected_dist) if verbose: print(f"For secret int {secret_int} fidelity: {fidelity}") return counts, fidelity #%% Computation of various metrics, such as approximation ratio, etc. def compute_cutsizes(results, nodes, edges): """ Given a result object, extract the values of meaasured cuts and the corresponding counts into ndarrays. Also compute and return the corresponding cut sizes. Returns ------- cuts : list of strings each element is a bitstring denoting a cut counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) """ cuts = list(results.keys()) counts = list(results.values()) sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in cuts] return cuts, counts, sizes def get_size_dist(counts, sizes): """ For given measurement outcomes, i.e. combinations of cuts, counts and sizes, return counts corresponding to each cut size. """ unique_sizes = list(set(sizes)) unique_counts = [0] * len(unique_sizes) for i, size in enumerate(unique_sizes): corresp_counts = [counts[ind] for ind,s in enumerate(sizes) if s == size] unique_counts[i] = sum(corresp_counts) # Make sure that the scores are in ascending order s_and_c_list = [[a,b] for (a,b) in zip(unique_sizes, unique_counts)] s_and_c_list = sorted(s_and_c_list, key = lambda x : x[0]) unique_sizes = [x[0] for x in s_and_c_list] unique_counts = [x[1] for x in s_and_c_list] cumul_counts = np.cumsum(unique_counts) return unique_counts, unique_sizes, cumul_counts.tolist() # Compute the objective function on a given sample def compute_sample_mean(counts, sizes, **kwargs): """ Compute the mean of cut sizes (i.e. the weighted average of sizes weighted by counts) This approximates the expectation value of the state at the end of the circuit Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) **kwargs : optional arguments will be ignored Returns ------- float """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) return - np.sum(counts * sizes) / np.sum(counts) def compute_cvar(counts, sizes, alpha = 0.1, **kwargs): """ Obtains the Conditional Value at Risk or CVaR for samples measured at the end of the variational circuit. Reference: Barkoutsos, P. K., Nannicini, G., Robert, A., Tavernelli, I. & Woerner, S. Improving Variational Quantum Optimization using CVaR. Quantum 4, 256 (2020). Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) alpha : float, optional Confidence interval value for CVaR. The default is 0.1. Returns ------- float CVaR value """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) # Sort the negative of the cut sizes in a non-decreasing order. # Sort counts in the same order as sizes, so that i^th element of each correspond to each other sort_inds = np.argsort(-sizes) sizes = sizes[sort_inds] counts = counts[sort_inds] # Choose only the top num_avgd = ceil(alpha * num_shots) cuts. These will be averaged over. num_avgd = math.ceil(alpha * np.sum(counts)) # Compute cvar cvar_sum = 0 counts_so_far = 0 for c, s in zip(counts, sizes): if counts_so_far + c >= num_avgd: cts_to_consider = num_avgd - counts_so_far cvar_sum += cts_to_consider * s break else: counts_so_far += c cvar_sum += c * s return - cvar_sum / num_avgd def compute_gibbs(counts, sizes, eta = 0.5, **kwargs): """ Compute the Gibbs objective function for given measurements Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) eta : float, optional Inverse Temperature Returns ------- float - Gibbs objective function value / optimal value """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) ls = max(sizes)#largest size shifted_sizes = sizes - ls # gibbs = - np.log( np.sum(counts * np.exp(eta * sizes)) / np.sum(counts)) gibbs = - eta * ls - np.log(np.sum (counts / np.sum(counts) * np.exp(eta * shifted_sizes))) return gibbs def compute_best_cut_from_measured(counts, sizes, **kwargs): """From the measured cuts, return the size of the largest cut """ return - np.max(sizes) def compute_quartiles(counts, sizes): """ Compute and return the sizes of the cuts at the three quartile values (i.e. 0.25, 0.5 and 0.75) Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) Returns ------- quantile_sizes : ndarray of of 3 floats sizes of cuts corresponding to the three quartile values. """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) # Sort sizes and counts in the sequence of non-decreasing values of sizes sort_inds = np.argsort(sizes) sizes = sizes[sort_inds] counts = counts[sort_inds] num_shots = np.sum(counts) q_vals = [0.25, 0.5, 0.75] ct_vals = [math.floor(q * num_shots) for q in q_vals] cumsum_counts = np.cumsum(counts) locs = np.searchsorted(cumsum_counts, ct_vals) quantile_sizes = sizes[locs] return quantile_sizes def uniform_cut_sampling(num_qubits, degree, num_shots, _instances=None): """ For a given problem, i.e. num_qubits and degree values, sample cuts uniformly at random from all possible cuts, num_shots number of times. Return the corresponding cuts, counts and cut sizes. """ # First, load the nodes and edges corresponding to the problem instance_filename = os.path.join(os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{degree:03d}_000.txt") nodes, edges = common.read_maxcut_instance(instance_filename, _instances) # Obtain num_shots number of uniform random samples between 0 and 2 ** num_qubits unif_cuts = np.random.randint(2 ** num_qubits, size=num_shots).tolist() unif_cuts_uniq = list(set(unif_cuts)) # Get counts corresponding to each sampled int/cut unif_counts = [unif_cuts.count(cut) for cut in unif_cuts_uniq] unif_cuts = list(set(unif_cuts)) def int_to_bs(numb): # Function for converting from an integer to (bit)strings of length num_qubits strr = format(numb, "b") #convert to binary strr = '0' * (num_qubits - len(strr)) + strr return strr unif_cuts = [int_to_bs(i) for i in unif_cuts] unif_sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in unif_cuts] # Also get the corresponding distribution of cut sizes unique_counts_unif, unique_sizes_unif, cumul_counts_unif = get_size_dist(unif_counts, unif_sizes) return unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif #%% Storing final iteration data to json file, and to metrics.circuit_metrics_final_iter ### DEVNOTE: this only applies for Qiskit, not Ocean def save_runtime_data(result_dict): # This function will need changes, since circuit metrics dictionaries are now different cm = result_dict.get('circuit_metrics') detail = result_dict.get('circuit_metrics_detail', None) detail_2 = result_dict.get('circuit_metrics_detail_2', None) benchmark_inputs = result_dict.get('benchmark_inputs', None) final_iter_metrics = result_dict.get('circuit_metrics_final_iter') backend_id = result_dict.get('benchmark_inputs').get('backend_id') metrics.circuit_metrics_detail_2 = detail_2 for width in detail_2: # unique_id = restart_ind * 1000 + minimizer_iter_ind restart_ind_list = list(detail_2.get(width).keys()) for restart_ind in restart_ind_list: degree = cm[width]['1']['degree'] opt = final_iter_metrics[width]['1']['optimal_value'] instance_filename = os.path.join(os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{int(width):03d}_{int(degree):03d}_000.txt") metrics.circuit_metrics[width] = detail.get(width) metrics.circuit_metrics['subtitle'] = cm.get('subtitle') finIterDict = final_iter_metrics[width][restart_ind] if benchmark_inputs['save_final_counts']: # if the final iteration cut counts were stored, retrieve them iter_dist = {'cuts' : finIterDict['cuts'], 'counts' : finIterDict['counts'], 'sizes' : finIterDict['sizes']} else: # The value of iter_dist does not matter otherwise iter_dist = None # Retrieve the distribution of cut sizes for the final iteration for this width and degree iter_size_dist = {'unique_sizes' : finIterDict['unique_sizes'], 'unique_counts' : finIterDict['unique_counts'], 'cumul_counts' : finIterDict['cumul_counts']} converged_thetas_list = finIterDict.get('converged_thetas_list') parent_folder_save = os.path.join('__data', f'{backend_id}') store_final_iter_to_metrics_json( num_qubits=int(width), degree = int(degree), restart_ind=int(restart_ind), num_shots=int(benchmark_inputs['num_shots']), converged_thetas_list=converged_thetas_list, opt=opt, iter_size_dist=iter_size_dist, iter_dist = iter_dist, dict_of_inputs=benchmark_inputs, parent_folder_save=parent_folder_save, save_final_counts=False, save_res_to_file=True, _instances=None ) def store_final_iter_to_metrics_json(num_qubits, degree, restart_ind, num_shots, converged_thetas_list, opt, iter_size_dist, iter_dist, parent_folder_save, dict_of_inputs, save_final_counts, save_res_to_file, _instances=None): """ For a given graph (specified by num_qubits and degree), 1. For a given restart, store properties of the final minimizer iteration to metrics.circuit_metrics_final_iter, and 2. Store various properties for all minimizer iterations for each restart to a json file. Parameters ---------- num_qubits, degree, restarts, num_shots : ints parent_folder_save : string (location where json file will be stored) dict_of_inputs : dictionary of inputs that were given to run() save_final_counts: bool. If true, save counts, cuts and sizes for last iteration to json file. save_res_to_file: bool. If False, do not save data to json file. iter_size_dist : dictionary containing distribution of cut sizes. Keys are 'unique_sizes', 'unique_counts' and 'cumul_counts' opt (int) : Max Cut value """ # In order to compare with uniform random sampling, get some samples ''' DEVNOTE: Not needed unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif = uniform_cut_sampling( num_qubits, degree, num_shots, _instances) unif_dict = {'unique_counts_unif': unique_counts_unif, 'unique_sizes_unif': unique_sizes_unif, 'cumul_counts_unif': cumul_counts_unif} # store only the distribution of cut sizes, and not the cuts themselves ''' unif_dict = {'unique_counts_unif': [], 'unique_sizes_unif': [], 'cumul_counts_unif': [] } # Store properties such as (cuts, counts, sizes) of the final iteration, the converged theta values, as well as the known optimal value for the current problem, in metrics.circuit_metrics_final_iter. Also store uniform cut sampling results metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt) metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_size_dist) metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list) metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict) # metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_dist) # do not store iter_dist, since it takes a lot of memory for larger widths, instead, store just iter_size_dist if save_res_to_file: # Save data to a json file dump_to_json(parent_folder_save, num_qubits, degree, restart_ind, iter_size_dist, iter_dist, dict_of_inputs, converged_thetas_list, opt, unif_dict, save_final_counts=save_final_counts) def dump_to_json(parent_folder_save, num_qubits, degree, restart_ind, iter_size_dist, iter_dist, dict_of_inputs, converged_thetas_list, opt, unif_dict, save_final_counts=False): """ For a given problem (specified by number of qubits and graph degree) and restart_index, save the evolution of various properties in a json file. Items stored in the json file: Data from all iterations (iterations), inputs to run program ('general properties'), converged theta values ('converged_thetas_list'), max cut size for the graph (optimal_value), distribution of cut sizes for random uniform sampling (unif_dict), and distribution of cut sizes for the final iteration (final_size_dist) if save_final_counts is True, then also store the distribution of cuts """ if not os.path.exists(parent_folder_save): os.makedirs(parent_folder_save) store_loc = os.path.join(parent_folder_save,'width_{}_restartInd_{}.json'.format(num_qubits, restart_ind)) # Obtain dictionary with iterations data corresponding to given restart_ind all_restart_ids = list(metrics.circuit_metrics[str(num_qubits)].keys()) ids_this_restart = [r_id for r_id in all_restart_ids if int(r_id) // 1000 == restart_ind] iterations_dict_this_restart = {r_id : metrics.circuit_metrics[str(num_qubits)][r_id] for r_id in ids_this_restart} # Values to be stored in json file dict_to_store = {'iterations' : iterations_dict_this_restart} dict_to_store['general_properties'] = dict_of_inputs dict_to_store['converged_thetas_list'] = converged_thetas_list dict_to_store['optimal_value'] = opt dict_to_store['unif_dict'] = unif_dict dict_to_store['final_size_dist'] = iter_size_dist # Also store the value of counts obtained for the final counts if save_final_counts: dict_to_store['final_counts'] = iter_dist #iter_dist.get_counts() # Now save the output with open(store_loc, 'w') as outfile: json.dump(dict_to_store, outfile) #%% Loading saved data (from json files) def load_data_and_plot(folder, backend_id=None, **kwargs): """ The highest level function for loading stored data from a previous run and plotting optgaps and area metrics Parameters ---------- folder : string Directory where json files are saved. """ _gen_prop = load_all_metrics(folder, backend_id=backend_id) if _gen_prop != None: gen_prop = {**_gen_prop, **kwargs} plot_results_from_data(**gen_prop) def load_all_metrics(folder, backend_id=None): """ Load all data that was saved in a folder. The saved data will be in json files in this folder Parameters ---------- folder : string Directory where json files are saved. Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # Note: folder here should be the folder where only the width=... files are stored, and not a folder higher up in the directory assert os.path.isdir(folder), f"Specified folder ({folder}) does not exist." metrics.init_metrics() list_of_files = os.listdir(folder) width_restart_file_tuples = [(*get_width_restart_tuple_from_filename(fileName), fileName) for (ind, fileName) in enumerate(list_of_files) if fileName.startswith("width")] # list with elements that are tuples->(width,restartInd,filename) width_restart_file_tuples = sorted(width_restart_file_tuples, key=lambda x:(x[0], x[1])) #sort first by width, and then by restartInd distinct_widths = list(set(it[0] for it in width_restart_file_tuples)) list_of_files = [ [tup[2] for tup in width_restart_file_tuples if tup[0] == width] for width in distinct_widths ] # connot continue without at least one dataset if len(list_of_files) < 1: print("ERROR: No result files found") return None for width_files in list_of_files: # For each width, first load all the restart files for fileName in width_files: gen_prop = load_from_width_restart_file(folder, fileName) # next, do processing for the width method = gen_prop['method'] if method == 2: num_qubits, _ = get_width_restart_tuple_from_filename(width_files[0]) metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(str(num_qubits)) # override device name with the backend_id if supplied by caller if backend_id != None: metrics.set_plot_subtitle(f"Device = {backend_id}") return gen_prop def load_from_width_restart_file(folder, fileName): """ Given a folder name and a file in it, load all the stored data and store the values in metrics.circuit_metrics. Also return the converged values of thetas, the final counts and general properties. Parameters ---------- folder : string folder where the json file is located fileName : string name of the json file Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # Extract num_qubits and s from file name num_qubits, restart_ind = get_width_restart_tuple_from_filename(fileName) print(f"Loading from {fileName}, corresponding to {num_qubits} qubits and restart index {restart_ind}") with open(os.path.join(folder, fileName), 'r') as json_file: data = json.load(json_file) gen_prop = data['general_properties'] converged_thetas_list = data['converged_thetas_list'] unif_dict = data['unif_dict'] opt = data['optimal_value'] if gen_prop['save_final_counts']: # Distribution of measured cuts final_counts = data['final_counts'] final_size_dist = data['final_size_dist'] backend_id = gen_prop.get('backend_id') metrics.set_plot_subtitle(f"Device = {backend_id}") # Update circuit metrics for circuit_id in data['iterations']: # circuit_id = restart_ind * 1000 + minimizer_loop_ind for metric, value in data['iterations'][circuit_id].items(): metrics.store_metric(num_qubits, circuit_id, metric, value) method = gen_prop['method'] if method == 2: metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt) metrics.store_props_final_iter(num_qubits, restart_ind, None, final_size_dist) metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list) metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict) if gen_prop['save_final_counts']: metrics.store_props_final_iter(num_qubits, restart_ind, None, final_counts) # after loading data, need to convert times to deltas (compatibility with metrics plots) convert_times_to_deltas(num_qubits) return gen_prop def get_width_restart_tuple_from_filename(fileName): """ Given a filename, extract the corresponding width and degree it corresponds to For example the file "width=4_degree=3.json" corresponds to 4 qubits and degree 3 Parameters ---------- fileName : TYPE DESCRIPTION. Returns ------- num_qubits : int circuit width degree : int graph degree. """ pattern = 'width_([0-9]+)_restartInd_([0-9]+).json' match = re.search(pattern, fileName) # assert match is not None, f"File {fileName} found inside folder. All files inside specified folder must be named in the format 'width_int_restartInd_int.json" num_qubits = int(match.groups()[0]) degree = int(match.groups()[1]) return (num_qubits,degree) #%% Run method: Benchmarking loop MAX_QUBITS = 320 iter_dist = {'cuts' : [], 'counts' : [], 'sizes' : []} # (list of measured bitstrings, list of corresponding counts, list of corresponding cut sizes) iter_size_dist = {'unique_sizes' : [], 'unique_counts' : [], 'cumul_counts' : []} # for the iteration being executed, stores the distribution for cut sizes saved_result = { } instance_filename = None minimizer_loop_index = 0 def run (min_qubits=3, max_qubits=6, max_circuits=1, num_shots=100, method=1, degree=3, alpha=0.1, thetas_array=None, parameterized= False, do_fidelities=True, max_iter=30, min_annealing_time=1, max_annealing_time=200, score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, objective_func_type = 'approx_ratio', plot_results = True, save_res_to_file = False, save_final_counts = False, detailed_save_names = False, comfort=False, backend_id='qasm_simulator', provider_backend=None, eta=0.5, hub="ibm-q", group="open", project="main", exec_options=None, _instances=None): """ Parameters ---------- min_qubits : int, optional The smallest circuit width for which benchmarking will be done The default is 3. max_qubits : int, optional The largest circuit width for which benchmarking will be done. The default is 6. max_circuits : int, optional Number of restarts. The default is None. num_shots : int, optional Number of times the circut will be measured, for each iteration. The default is 100. method : int, optional If 1, then do standard metrics, if 2, implement iterative algo metrics. The default is 1. degree : int, optional degree of graph. The default is 3. thetas_array : list, optional list or ndarray of beta and gamma values. The default is None. N : int, optional For the max % counts metric, choose the highest N% counts. The default is 10. alpha : float, optional Value between 0 and 1. The default is 0.1. parameterized : bool, optional Whether to use parametrized circuits or not. The default is False. do_fidelities : bool, optional Compute circuit fidelity. The default is True. max_iter : int, optional Number of iterations for the minimizer routine. The default is 30. min_annealing_time : int, optional Minimum annealing time. The default is 1. max_annealing_time : int, optional Maximum annealing time. The default is 200. score_metric : list or string, optional Which metrics are to be plotted in area metrics plots. The default is 'fidelity'. x_metric : list or string, optional Horizontal axis for area plots. The default is 'cumulative_exec_time'. y_metric : list or string, optional Vertical axis for area plots. The default is 'num_qubits'. fixed_metrics : TYPE, optional DESCRIPTION. The default is {}. num_x_bins : int, optional DESCRIPTION. The default is 15. y_size : TYPint, optional DESCRIPTION. The default is None. x_size : string, optional DESCRIPTION. The default is None. backend_id : string, optional DESCRIPTION. The default is 'qasm_simulator'. provider_backend : string, optional DESCRIPTION. The default is None. hub : string, optional DESCRIPTION. The default is "ibm-q". group : string, optional DESCRIPTION. The default is "open". project : string, optional DESCRIPTION. The default is "main". exec_options : string, optional DESCRIPTION. The default is None. objective_func_type : string, optional Objective function to be used by the classical minimizer algorithm. The default is 'approx_ratio'. plot_results : bool, optional Plot results only if True. The default is True. save_res_to_file : bool, optional Save results to json files. The default is True. save_final_counts : bool, optional If True, also save the counts from the final iteration for each problem in the json files. The default is True. detailed_save_names : bool, optional If true, the data and plots will be saved with more detailed names. Default is False confort : bool, optional If true, print comfort dots during execution """ # Store all the input parameters into a dictionary. # This dictionary will later be stored in a json file # It will also be used for sending parameters to the plotting function dict_of_inputs = locals() # Delete some entries from the dictionary for key in ["hub", "group", "project", "provider_backend"]: dict_of_inputs.pop(key) global maxcut_inputs maxcut_inputs = dict_of_inputs #print(f"{dict_of_inputs = }") print("MaxCut Benchmark Program - Ocean") QC_ = None # Create a folder where the results will be saved. Folder name=time of start of computation # In particular, for every circuit width, the metrics will be stored the moment the results are obtained # In addition to the metrics, the (beta,gamma) values obtained by the optimizer, as well as the counts # measured for the final circuit will be stored. # Use the following parent folder, for a more detailed if detailed_save_names: start_time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type, f'run_start_{start_time_str}') else: parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type) if save_res_to_file and not os.path.exists(parent_folder_save): os.makedirs(os.path.join(parent_folder_save)) # validate parameters max_qubits = max(4, max_qubits) max_qubits = min(MAX_QUBITS, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) degree = max(3, degree) # don't compute exectation unless fidelity is is needed global do_compute_expectation do_compute_expectation = False # given that this benchmark does every other width, set y_size default to 1.5 if y_size == None: y_size = 1.5 # Choose the objective function to minimize, based on values of the parameters possible_approx_ratios = {'cvar_ratio', 'approx_ratio', 'gibbs_ratio', 'bestcut_ratio'} non_objFunc_ratios = possible_approx_ratios - { objective_func_type } function_mapper = {'cvar_ratio' : compute_cvar, 'approx_ratio' : compute_sample_mean, 'gibbs_ratio' : compute_gibbs, 'bestcut_ratio' : compute_best_cut_from_measured} # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) def execution_handler2 (qc, result, num_qubits, s_int, num_shots): # Stores the results to the global saved_result variable global saved_result saved_result = result # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler2) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for anneal times in powers of 2 # Accumulate metrics asynchronously as circuits complete # loop over available problem sizes from min_qubits up to max_qubits for num_qubits in [4, 8, 12, 16, 20, 24, 40, 80, 160, 320]: if num_qubits < min_qubits: continue if num_qubits > max_qubits: break if method == 1: print(f"************\nExecuting [{max_circuits}] circuits for num_qubits = {num_qubits}") else: print(f"************\nExecuting [{max_circuits}] restarts for num_qubits = {num_qubits}") # If degree is negative, if degree < 0 : degree = max(3, (num_qubits + degree)) # Load the problem and its solution global instance_filename instance_filename = os.path.join( os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{degree:03d}_000.txt", ) nodes, edges = common.read_maxcut_instance(instance_filename, _instances) opt, _ = common.read_maxcut_solution( instance_filename[:-4] + ".sol", _instances ) # if the file does not exist, we are done with this number of qubits if nodes == None: print(f" ... problem not found.") break for restart_ind in range(1, max_circuits + 1): # restart index should start from 1 # Loop over restarts for a given graph if method == 1: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc, params = MaxCut(num_qubits, restart_ind, edges, parameterized) ### DEVNOTE: remove param? metrics.store_metric(num_qubits, restart_ind, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, restart_ind, shots=num_shots, params=params) if method == 2: global minimizer_loop_index # a unique circuit index used inside the inner minimizer loop as identifier minimizer_loop_index = 0 # Value of 0 corresponds to the 0th iteration of the minimizer start_iters_t = time.time() # Always start by enabling embed ... ex.set_embedding_flag(embedding_flag=True) if verbose: print(f'=============== Begin method 2 loop, enabling embed') annealing_time = min_annealing_time while annealing_time <= max_annealing_time: if verbose: print(f"... using anneal time: {annealing_time}") # Every circuit needs a unique id; add unique_circuit_index instead of s_int #global minimizer_loop_index unique_id = restart_ind * 1000 + minimizer_loop_index #************************************************ #*** Circuit Creation # create the circuit for given qubit size, secret string and params, store time metric ts = time.time() qc, params = MaxCut(num_qubits, unique_id, edges, parameterized) params = [annealing_time] metrics.store_metric(num_qubits, unique_id, 'create_time', time.time()-ts) # also store the 'degree' for each execution # DEVNOTE: Currently, this is stored for each iteration. Reduce this redundancy metrics.store_metric(num_qubits, unique_id, 'degree', degree) #************************************************ #*** Quantum Part: Execution of Circuits *** # submit circuit for execution on target with the current parameters ex.submit_circuit(qc, num_qubits, unique_id, shots=num_shots, params=params) # Must wait for circuit to complete #ex.throttle_execution(metrics.finalize_group) ex.finalize_execution(None, report_end=False) # don't finalize group until all circuits done ''' # after first execution and thereafter, no need for embed (actually NOT) #since we are benchmarking, we want to compare performance across anneal times # so we do not want to use embedding, or it wouldn't be a valid comparison #ex.set_embedding_flag(embedding_flag=False) ex.set_embedding_flag(embedding_flag=True) if verbose: print(f'**** First execution complete, disabling embed') ''' global saved_result #print(saved_result) #************************************************ #*** Classical Processing of Results - essential to optimizer *** global opt_ts dict_of_vals = dict() # Start counting classical optimizer time here again tc1 = time.time() cuts, counts, sizes = compute_cutsizes(saved_result, nodes, edges) # Compute the value corresponding to the objective function first dict_of_vals[objective_func_type] = function_mapper[objective_func_type](counts, sizes, alpha = alpha) # Store the optimizer time as current time- tc1 + ts - opt_ts, since the time between tc1 and ts is not time used by the classical optimizer. # metrics.store_metric(num_qubits, unique_id, 'opt_exec_time', time.time() - tc1 + ts - opt_ts) # Note: the first time it is stored it is just the initialization time for optimizer #************************************************ if verbose: print(dict_of_vals) #************************************************ #*** Classical Processing of Results - not essential for optimizer. Used for tracking metrics *** # Compute the distribution of cut sizes; store them under metrics unique_counts, unique_sizes, cumul_counts = get_size_dist(counts, sizes) global iter_size_dist iter_size_dist = {'unique_sizes' : unique_sizes, 'unique_counts' : unique_counts, 'cumul_counts' : cumul_counts} metrics.store_metric(num_qubits, unique_id, None, iter_size_dist) # Compute and the other metrics (eg. cvar, gibbs and max N % if the obj function was set to approx ratio) for s in non_objFunc_ratios: dict_of_vals[s] = function_mapper[s](counts, sizes, alpha = alpha) # Store the ratios dict_of_ratios = { key : -1 * val / opt for (key, val) in dict_of_vals.items()} dict_of_ratios['gibbs_ratio'] = dict_of_ratios['gibbs_ratio'] / eta metrics.store_metric(num_qubits, unique_id, None, dict_of_ratios) # Get the best measurement and store it best = - compute_best_cut_from_measured(counts, sizes) metrics.store_metric(num_qubits, unique_id, 'bestcut_ratio', best / opt) # Also compute and store the weights of cuts at three quantile values quantile_sizes = compute_quartiles(counts, sizes) # Store quantile_optgaps as a list (allows storing in json files) metrics.store_metric(num_qubits, unique_id, 'quantile_optgaps', (1 - quantile_sizes / opt).tolist()) # Also store the cuts, counts and sizes in a global variable, to allow access elsewhere global iter_dist iter_dist = {'cuts' : cuts, 'counts' : counts, 'sizes' : sizes} minimizer_loop_index += 1 #************************************************ # reset timer for optimizer execution after each iteration of quantum program completes opt_ts = time.time() # double the annealing time for the next iteration annealing_time *= 2 # DEVNOTE: Do this here, if we want to save deltas to file (which we used to do) # for this benchmark, need to convert times to deltas (for compatibility with metrics) #convert_times_to_deltas(num_qubits) # Save final iteration data to metrics.circuit_metrics_final_iter # This data includes final counts, cuts, etc. store_final_iter_to_metrics_json(num_qubits=num_qubits, degree=degree, restart_ind=restart_ind, num_shots=num_shots, #converged_thetas_list=res.x.tolist(), converged_thetas_list=[[0],[0]], opt=opt, iter_size_dist=iter_size_dist, iter_dist=iter_dist, parent_folder_save=parent_folder_save, dict_of_inputs=dict_of_inputs, save_final_counts=save_final_counts, save_res_to_file=save_res_to_file, _instances=_instances) # after saving data, convert times to deltas (for compatibility with metrics plots) convert_times_to_deltas(num_qubits) # for method 2, need to aggregate the detail metrics appropriately for each group # Note that this assumes that all iterations of the circuit have completed by this point if method == 2: metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(str(num_qubits)) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # Plot metrics for all problem sizes if method == 1: metrics.plot_metrics(f"Benchmark Results - MaxCut ({method}) - Ocean", options=dict(shots=num_shots)) elif method == 2: #metrics.print_all_circuit_metrics() if plot_results: plot_results_from_data(**dict_of_inputs) # Convert elapsed/exec/opt_exec times to deltas from absolute # for this benchmark, need to convert the times to deltas (for compatibility with metrics) # since there is wobble in some of the times, don't go below delta = 0 def convert_times_to_deltas(num_qubits): elapsed_time = exec_time = opt_exec_time = 0 for circuit_id in metrics.circuit_metrics[str(num_qubits)]: circuit = metrics.circuit_metrics[str(num_qubits)][circuit_id] #print(f"... id = {circuit_id}, times = {circuit['elapsed_time']} {circuit['exec_time']} {circuit['opt_exec_time']}") d_elapsed_time = max(0, circuit['elapsed_time'] - elapsed_time) d_exec_time = max(0, circuit['exec_time'] - exec_time) d_opt_exec_time = max(0, circuit['opt_exec_time'] - opt_exec_time) elapsed_time = max(elapsed_time, circuit['elapsed_time']) exec_time = max(exec_time, circuit['exec_time']) opt_exec_time = max(opt_exec_time, circuit['opt_exec_time']) #print(f" ... max times = {elapsed_time} {exec_time} {opt_exec_time}") #print(f" ... delta times = {d_elapsed_time} {d_exec_time} {d_opt_exec_time}") circuit['elapsed_time'] = d_elapsed_time circuit['exec_time'] = d_exec_time circuit['opt_exec_time'] = d_opt_exec_time # Method to plot the results from the collected data def plot_results_from_data(num_shots=100, degree=3, max_iter=30, max_circuits = 1, objective_func_type='approx_ratio', method=2, score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, x_min=None, x_max=None, offset_flag=True, # default is True for QA detailed_save_names=False, **kwargs): """ Plot results """ if detailed_save_names: # If detailed names are desired for saving plots, put date of creation, etc. cur_time=datetime.datetime.now() dt = cur_time.strftime("%Y-%m-%d_%H-%M-%S") short_obj_func_str = metrics.score_label_save_str[objective_func_type] suffix = f'-s{num_shots}_d{degree}_mi{max_iter}_of-{short_obj_func_str}_{dt}' #of=objective function else: short_obj_func_str = metrics.score_label_save_str[objective_func_type] suffix = f'of-{short_obj_func_str}' #of=objective function obj_str = metrics.known_score_labels[objective_func_type] options = {'shots' : num_shots, 'degree' : degree, 'restarts' : max_circuits, '\nObjective Function' : obj_str} suptitle = f"Benchmark Results - MaxCut ({method}) - Ocean" metrics.plot_all_area_metrics(f"Benchmark Results - MaxCut ({method}) - Ocean", score_metric=score_metric, x_metric=x_metric, y_metric=y_metric, fixed_metrics=fixed_metrics, num_x_bins=num_x_bins, x_size=x_size, y_size=y_size, x_min=x_min, x_max=x_max, offset_flag=offset_flag, options=options, suffix=suffix) metrics.plot_metrics_optgaps(suptitle, options=options, suffix=suffix, objective_func_type = objective_func_type) # this plot is deemed less useful #metrics.plot_ECDF(suptitle=suptitle, options=options, suffix=suffix) all_widths = list(metrics.circuit_metrics_final_iter.keys()) all_widths = [int(ii) for ii in all_widths] list_of_widths = [all_widths[-1]] metrics.plot_cutsize_distribution(suptitle=suptitle,options=options, suffix=suffix, list_of_widths = list_of_widths) # not needed for Ocean version #metrics.plot_angles_polar(suptitle = suptitle, options = options, suffix = suffix) # if main, execute method if __name__ == '__main__': run() # %%
50,056
43.180936
352
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/_common/shors_utils.py
""" This file contains various helper functions for the various Shor's algorithm benchmarks, including order finding and factoring. """ import math from math import gcd import numpy as np ############### Data Used in Shor's Algorithm Benchmark # Array of prime numbers used to construct numbers to be factored primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] # Function to generate numbers for factoring def generate_numbers(): # Numbers available for factoring (multiples of primes) indexed by number of qubits to use numbers = [None] * 21 for f1 in primes: for f2 in primes: if f1 >= f2: continue number = f1 * f2 idx = int(math.ceil(math.log(number, 2))) if idx >= len(numbers): continue if numbers[idx] == None: numbers[idx] = [] # if len(numbers[idx]) > 20: continue # limit to 20 choices # don't limit, as it skews the choices numbers[idx].append(number) return numbers ############### General Functions for factoring analysis # Verifies base**order mod number = 1 def verify_order(base, number, order): return base ** order % number == 1 # Generates the base for base**order mod number = 1 def generate_base(number, order): # Max values for a and x a = number x = math.log(number ** order - 1, number) # a must be less than number while a >= number or not verify_order(a, number, order): a = int((number ** x + 1) ** (1 / order)) x -= 1 / a return a # Choose a base at random < N / 2 without a common factor of N def choose_random_base(N): # try up to 100 times to find a good base for guess in range(100): a = int(np.random.random() * (N / 2)) if gcd(a, N) == 1: return a print(f"Ooops, chose non relative prime {a}, gcd={gcd(a, N)}, giving up ...") return 0 # Determine factors from the period def determine_factors(r, a, N): # try to determine the factors if r % 2 != 0: r *= 2 apowrhalf = pow(a, r >> 1, N) f1 = gcd(apowrhalf + 1, N) f2 = gcd(apowrhalf - 1, N) # if this f1 and f2 are not the factors # and not both 1 # and if multiplied together divide N evenly # --> then try multiplying them together and dividing into N to obtain the factors f12 = f1 * f2 if ((not f12 == N) and f12 > 1 and int(1. * N / (f12)) * f12 == N): f1, f2 = f12, int(N / (f12)) return f1, f2 ############### Functions for Circuit Derivation def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m # TODO: Merge the following Angle functions or change the names # Function that calculates the angle of a phase shift in the sequential QFT based on the binary digits of a. # a represents a possible value of the classical register def getAngle(a, n): #convert the number a to a binary string with length n s=bin(int(a))[2:].zfill(n) angle = 0 for i in range(0, n): # if the digit is 1, add the corresponding value to the angle if s[n-1-i] == '1': angle += math.pow(2, -(n-i)) angle *= np.pi return angle # Function that calculates the array of angles to be used in the addition in Fourier Space def getAngles(a,n): #convert the number a to a binary string with length n s=bin(int(a))[2:].zfill(n) angles=np.zeros([n]) for i in range(0, n): for j in range(i,n): if s[j]=='1': angles[n-i-1]+=math.pow(2, -(j-i)) angles[n-i-1]*=np.pi return angles
4,651
34.242424
108
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/braket/shors_benchmark.py
""" Shor's Order Finding Algorithm Benchmark - Braket (WIP) """ import math import sys import time from braket.circuits import Circuit # AWS imports: Import Braket SDK modules import numpy as np sys.path[1:1] = ["_common", "_common/braket", "shors/_common", "quantum-fourier-transform/braket"] sys.path[1:1] = ["../../_common", "../../_common/braket", "../../shors/_common", "../../quantum-fourier-transform/braket"] import execute as ex import metrics as metrics from shors_utils import getAngles, getAngle, modinv, generate_base, verify_order from qft_benchmark import inv_qft_gate, qft_gate np.random.seed(0) verbose = False QC_ = None PHIADD_ = None CCPHIADDMODN_ = None CMULTAMODN_ = None CUA_ = None QFT_ = None ############### Circuit Definition # Creation of the circuit that performs addition by a in Fourier Space # Can also be used for subtraction by setting the parameter inv to a value different from 0 def phiADD(num_qubits, a): qc = Circuit() angle = getAngles(a, num_qubits) for i in range(num_qubits): # addition qc.rz(i, angle[i]) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return qc # TODO: Create braket function # Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a).to_gate() cphiadd_gate = phiadd_gate.control(1) return cphiadd_gate # TODO: Create braket function # Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a).to_gate() ccphiadd_gate = phiadd_gate.control(2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = QuantumRegister(2) qr_main = QuantumRegister(num_qubits + 1) qr_ancilla = QuantumRegister(1) qc = Circuit() # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits + 1, a) ccphiadda_inv_gate = ccphiADD(num_qubits + 1, a).inverse() phiaddN_inv_gate = phiADD(num_qubits + 1, N).inverse(); phiaddN_inv_gate.name = "inv_\u03C6ADD" cphiaddN_gate = cphiADD(num_qubits + 1, N) # Create relevant temporary qubit lists ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main]) anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main]) # Create circuit qc.append(ccphiadda_gate, ctl_main_qubits) qc.append(phiaddN_inv_gate, qr_main) qc.append(inv_qft_gate(num_qubits + 1), qr_main) qc.cx(qr_main[-1], qr_ancilla[0]) qc.append(qft_gate(num_qubits + 1), qr_main) qc.append(cphiaddN_gate, anc_main_qubits) qc.append(ccphiadda_inv_gate, ctl_main_qubits) qc.append(inv_qft_gate(num_qubits + 1), qr_main) qc.x(qr_main[-1]) qc.cx(qr_main[-1], qr_ancilla[0]) qc.x(qr_main[-1]) qc.append(qft_gate(num_qubits + 1), qr_main) qc.append(ccphiadda_gate, ctl_main_qubits) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return qc # Circuit that implements the inverse of doubly controlled modular addition by a def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse() cchpiAddmodN_inv_circ.name = "inv_cchpiAddmodN" return cchpiAddmodN_inv_circ # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits # needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n + 1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name="cMULTamodN") # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n + 1), qr_main) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2 ** i) * a % N, N) # Create relevant temporary qubit list qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]]) qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]]) qc.append(ccphiADDmodN_gate, qubits) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n + 1), qr_main) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return qc # Creates circuit that implements single controlled Ua gate. n represents the number of bits # needed to represent the integer number N def controlled_Ua(n, a, exponent, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n) qr_ancilla = QuantumRegister(2) qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name=f"C-U^{a ** exponent}") # Generate Gates a_inv = modinv(a ** exponent, N) cMULTamodN_gate = cMULTamodN(n, a ** exponent, N) cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse(); cMULTamodN_inv_gate.name = "inv_cMULTamodN" # Create relevant temporary qubit list qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main]) qubits.extend([i for i in qr_ancilla]) qc.append(cMULTamodN_gate, qubits) for i in range(n): qc.cswap(qr_ctl, qr_x[i], qr_main[i]) qc.append(cMULTamodN_inv_gate, qubits) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return qc # Execute Shor's Order Finding Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' def ShorsAlgorithm(number, base, method, verbose=verbose): # Create count of qubits to use to represent the number to factor # NOTE: this should match the number of bits required to represent (number) n = int(math.ceil(math.log(number, 2))) # Standard Shors Algorithm if method == 1: num_qubits = 4 * n + 2 if verbose: print( f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") # Create a circuit and allocate necessary qubits qr_up = QuantumRegister(2 * n) # Register for sequential QFT qr_down = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT qc = QuantumCircuit(qr_up, qr_down, qr_aux, cr_data, name="main") # Initialize down register to 1 and up register to superposition state qc.h(qr_up) qc.x(qr_down[0]) qc.barrier() # Apply Multiplication Gates for exponentiation for i in reversed(range(2 * n)): cUa_gate = controlled_Ua(n, int(base), 2 ** (2 * n - 1 - i), number) # Create relevant temporary qubit list qubits = [qr_up[i]]; qubits.extend([i for i in qr_down]); qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) qc.barrier() qc.append(inv_qft_gate(2 * n), qr_up) # Measure up register qc.measure(qr_up, cr_data) elif method == 2: # Create a circuit and allocate necessary qubits num_qubits = 2 * n + 3 if verbose: print( f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") qr_up = QuantumRegister(1) # Single qubit for sequential QFT qr_down = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT cr_aux = ClassicalRegister( 1) # Register to reset the state of the up register based on previous measurements qc = QuantumCircuit(qr_up, qr_down, qr_aux, cr_data, cr_aux, name="main") # Initialize down register to 1 qc.x(qr_down[0]) # perform modular exponentiation 2*n times for k in range(2 * n): qc.barrier() # Reset the top qubit to 0 if the previous measurement was 1 qc.x(qr_up).c_if(cr_aux, 1) qc.h(qr_up) cUa_gate = controlled_Ua(n, base, 2 ** (2 * n - 1 - k), number) # Create relevant temporary qubit list qubits = [qr_up[0]]; qubits.extend([i for i in qr_down]); qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2 ** k): qc.p(getAngle(i, k), qr_up[0]).c_if(cr_data, i) qc.h(qr_up) qc.measure(qr_up[0], cr_data[k]) qc.measure(qr_up[0], cr_aux[0]) global QC_, QFT_ if QC_ == None or n <= 2: if n < 3: QC_ = qc if QFT_ == None or n <= 2: if n < 3: QFT_ = qft_gate(n + 1) return qc ############### Circuit end def expected_shor_dist(num_bits, order, num_shots): # num_bits represent the number of bits to represent the number N in question # Qubits measureed always 2 * num_bits for the three methods implemented in this benchmark qubits_measured = 2 * num_bits dist = {} # Conver float to int r = int(order) # Generate expected distribution q = int(2 ** (qubits_measured)) for i in range(r): key = bin(int(q * (i / r)))[2:].zfill(qubits_measured) dist[key] = num_shots / r ''' for c in range(2 ** qubits_measured): key = bin(c)[2:].zfill(qubits_measured) amp = 0 for i in range(int(q/r) - 1): amp += np.exp(2*math.pi* 1j * i * (r * c % q)/q ) amp = amp * np.sqrt(r) / q dist[key] = abs(amp) ** 2 ''' return dist # Print analyzed results # Analyze and print measured results # Expected result is always the order r, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method): if method == 1: num_bits = int((num_qubits - 2) / 4) elif method == 2: num_bits = int((num_qubits - 3) / 2) elif method == 3: num_bits = int((num_qubits - 2) / 2) # obtain bit_counts from the result object counts = result.get_counts(qc) # Only classical data qubits are important and removing first auxiliary qubit from count if method == 2: temp_counts = {} for key, item in counts.items(): temp_counts[key[2:]] = item counts = temp_counts # generate correct distribution correct_dist = expected_shor_dist(num_bits, order, num_shots) if verbose: print(f"For order value {order}, measured: {counts}") print(f"For order value {order}, correct_dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity #################### Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_circuits=1, max_qubits=18, num_shots=100, method=1, verbose=verbose, backend_id='simulator'): print("Shor's Order Finding Algorithm Benchmark - Qiskit") print(f"... using circuit method {method}") # Each method has a different minimum amount of qubits to run and a certain multiple of qubits that can be run qubit_multiple = 2 # Standard for Method 2 and 3 max_qubits = max(max_qubits, min_qubits) # max must be >= min if method == 1: min_qubits = max(min_qubits, 10) # need min of 10 qubit_multiple = 4 elif method == 2: min_qubits = max(min_qubits, 7) # need min of 7 elif method == 3: min_qubits = max(min_qubits, 6) # need min of 6 if max_qubits < min_qubits: print( f"Max number of qubits {max_qubits} is too low to run method {method} of Shor's Order Finding") return # Initialize metrics module metrics.init_metrics() # Define custom result handler # number_order contains an array of length 2 with the number and order def execution_handler(qc, result, num_qubits, number_order, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) # Must convert number_order from string to array order = eval(number_order)[1] counts, fidelity = analyze_and_print_result(qc, result, num_qubits, order, num_shots, method) metrics.store_metric(num_qubits, number_order, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, qubit_multiple): input_size = num_qubits - 1 if method == 1: num_bits = int((num_qubits - 2) / 4) elif method == 2: num_bits = int((num_qubits - 3) / 2) elif method == 3: num_bits = int((num_qubits - 2) / 2) # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") for _ in range(num_circuits): base = 1 while base == 1: # Ensure N is a number using the greatest bit number = np.random.randint(2 ** (num_bits - 1) + 1, 2 ** num_bits) order = np.random.randint(2, number) base = generate_base(number, order) # Checking if generated order can be reduced. Can also run through prime list in shors utils if order % 2 == 0: order = 2 if order % 3 == 0: order = 3 number_order = (number, order) if verbose: print(f"Generated {number=}, {base=}, {order=}") # create the circuit for given qubit size and order, store time metric ts = time.time() qc = ShorsAlgorithm(number, base, method=method, verbose=verbose) metrics.store_metric(num_qubits, number_order, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, number_order, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # print the last circuit created print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Ua Operator 'cUa' ="); print(CUA_ if CUA_ != None else " ... too large!") print("\nControlled Multiplier Operator 'cMULTamodN' ="); print(CMULTAMODN_ if CMULTAMODN_ != None else " ... too large!") print("\nControlled Modular Adder Operator 'ccphiamodN' ="); print(CCPHIADDMODN_ if CCPHIADDMODN_ != None else " ... too large!") print("\nPhi Adder Operator '\u03C6ADD' ="); print(PHIADD_ if PHIADD_ != None else " ... too large!") print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Shor's Order Finding ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run() # max_qubits = 6, max_circuits = 5, num_shots=100)
16,073
33.717063
122
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/shors_benchmark.py
""" Shor's Order Finding Algorithm Benchmark - Qiskit """ import math import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qiskit", "shors/_common", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../shors/_common", "../../quantum-fourier-transform/qiskit"] import execute as ex import metrics as metrics from shors_utils import getAngles, getAngle, modinv, generate_base, verify_order from qft_benchmark import inv_qft_gate from qft_benchmark import qft_gate np.random.seed(0) verbose = False QC_ = None PHIADD_ = None CCPHIADDMODN_ = None CMULTAMODN_ = None CUA_ = None QFT_ = None ############### Circuit Definition #Creation of the circuit that performs addition by a in Fourier Space #Can also be used for subtraction by setting the parameter inv to a value different from 0 def phiADD(num_qubits, a): qc = QuantumCircuit(num_qubits, name = "\u03C6ADD") angle = getAngles(a, num_qubits) for i in range(0, num_qubits): # addition qc.p(angle[i], i) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return qc #Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() cphiadd_gate = phiadd_gate.control(1) return cphiadd_gate #Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() ccphiadd_gate = phiadd_gate.control(2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = QuantumRegister(2) qr_main = QuantumRegister(num_qubits+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_main,qr_ancilla, name = "cc\u03C6ADDmodN") # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits+1, a) ccphiadda_inv_gate = ccphiADD(num_qubits+1, a).inverse() phiaddN_inv_gate = phiADD(num_qubits+1, N).inverse(); phiaddN_inv_gate.name = "inv_\u03C6ADD" cphiaddN_gate = cphiADD(num_qubits+1, N) # Create relevant temporary qubit lists ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main]) anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main]) #Create circuit qc.append(ccphiadda_gate, ctl_main_qubits) qc.append(phiaddN_inv_gate, qr_main) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.cx(qr_main[-1], qr_ancilla[0]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(cphiaddN_gate, anc_main_qubits) qc.append(ccphiadda_inv_gate, ctl_main_qubits) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.x(qr_main[-1]) qc.cx(qr_main[-1], qr_ancilla[0]) qc.x(qr_main[-1]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(ccphiadda_gate, ctl_main_qubits) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return qc # Circuit that implements the inverse of doubly controlled modular addition by a def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse() cchpiAddmodN_inv_circ.name = "inv_cchpiAddmodN" return cchpiAddmodN_inv_circ # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits # needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = "cMULTamodN") # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n+1), qr_main) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2**i)*a % N, N) # Create relevant temporary qubit list qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]]) qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]]) qc.append(ccphiADDmodN_gate, qubits) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n+1), qr_main) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return qc # Creates circuit that implements single controlled Ua gate. n represents the number of bits # needed to represent the integer number N def controlled_Ua(n,a,exponent,N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n) qr_ancilla = QuantumRegister(2) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = f"C-U^{a**exponent}") # Generate Gates a_inv = modinv(a**exponent,N) cMULTamodN_gate = cMULTamodN(n, a**exponent, N) cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse(); cMULTamodN_inv_gate.name = "inv_cMULTamodN" # Create relevant temporary qubit list qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main]) qubits.extend([i for i in qr_ancilla]) qc.append(cMULTamodN_gate, qubits) for i in range(n): qc.cswap(qr_ctl, qr_x[i], qr_main[i]) qc.append(cMULTamodN_inv_gate, qubits) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return qc # Execute Shor's Order Finding Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' def ShorsAlgorithm(number, base, method, verbose=verbose): # Create count of qubits to use to represent the number to factor # NOTE: this should match the number of bits required to represent (number) n = int(math.ceil(math.log(number, 2))) # Standard Shors Algorithm if method == 1: num_qubits = 4*n + 2 if verbose: print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") # Create a circuit and allocate necessary qubits qr_counting = QuantumRegister(2*n) # Register for sequential QFT qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n+2) # Register for addition and multiplication cr_data = ClassicalRegister(2*n) # Register for measured values of QFT qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, name="main") # Initialize multiplication register to 1 and counting register to superposition state qc.h(qr_counting) qc.x(qr_mult[0]) qc.barrier() # Apply Multiplication Gates for exponentiation for i in reversed(range(2*n)): cUa_gate = controlled_Ua(n,int(base),2**(2*n-1-i),number) # Create relevant temporary qubit list qubits = [qr_counting[i]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) qc.barrier() qc.append(inv_qft_gate(2*n),qr_counting) # Measure counting register qc.measure(qr_counting, cr_data) elif method == 2: # Create a circuit and allocate necessary qubits num_qubits = 2*n + 3 if verbose: print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") qr_counting = QuantumRegister(1) # Single qubit for sequential QFT qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n+2) # Register for addition and multiplication cr_data = ClassicalRegister(2*n) # Register for measured values of QFT cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, cr_aux, name="main") # Initialize mult register to 1 qc.x(qr_mult[0]) # perform modular exponentiation 2*n times for k in range(2*n): qc.barrier() # Reset the counting qubit to 0 if the previous measurement was 1 qc.x(qr_counting).c_if(cr_aux,1) qc.h(qr_counting) cUa_gate = controlled_Ua(n, base,2**(2*n-1-k), number) # Create relevant temporary qubit list qubits = [qr_counting[0]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2**k): qc.p(getAngle(i, k), qr_counting[0]).c_if(cr_data, i) qc.h(qr_counting) qc.measure(qr_counting[0], cr_data[k]) qc.measure(qr_counting[0], cr_aux[0]) global QC_, QFT_ if QC_ == None or n <= 2: if n < 3: QC_ = qc if QFT_ == None or n <= 2: if n < 3: QFT_ = qft_gate(n+1) return qc ############### Circuit end def expected_shor_dist(num_bits, order, num_shots): # num_bits represent the number of bits to represent the number N in question # Qubits measureed always 2 * num_bits for the three methods implemented in this benchmark qubits_measured = 2 * num_bits dist = {} #Conver float to int r = int(order) #Generate expected distribution q = int(2 ** (qubits_measured)) for i in range(r): key = bin(int(q*(i/r)))[2:].zfill(qubits_measured) dist[key] = num_shots/r ''' for c in range(2 ** qubits_measured): key = bin(c)[2:].zfill(qubits_measured) amp = 0 for i in range(int(q/r) - 1): amp += np.exp(2*math.pi* 1j * i * (r * c % q)/q ) amp = amp * np.sqrt(r) / q dist[key] = abs(amp) ** 2 ''' return dist # Print analyzed results # Analyze and print measured results # Expected result is always the order r, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method): if method == 1: num_bits = int((num_qubits - 2) / 4) elif method == 2: num_bits = int((num_qubits - 3) / 2) elif method == 3: num_bits = int((num_qubits - 2) / 2) # obtain bit_counts from the result object counts = result.get_counts(qc) # Only classical data qubits are important and removing first auxiliary qubit from count if method == 2: temp_counts = {} for key, item in counts.items(): temp_counts[key[2:]] = item counts = temp_counts # generate correct distribution correct_dist = expected_shor_dist(num_bits, order, num_shots) if verbose: print(f"For order value {order}, measured: {counts}") print(f"For order value {order}, correct_dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity #################### Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_circuits=1, max_qubits=18, num_shots=100, method = 1, verbose=verbose, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Shor's Order Finding Algorithm Benchmark - Qiskit") print(f"... using circuit method {method}") # Each method has a different minimum amount of qubits to run and a certain multiple of qubits that can be run qubit_multiple = 2 #Standard for Method 2 and 3 max_qubits = max(max_qubits, min_qubits) # max must be >= min if method == 1: min_qubits = max(min_qubits, 10) # need min of 10 qubit_multiple = 4 elif method ==2: min_qubits = max(min_qubits, 7) # need min of 7 elif method == 3: min_qubits = max(min_qubits,6) # need min of 6 if max_qubits < min_qubits: print(f"Max number of qubits {max_qubits} is too low to run method {method} of Shor's Order Finding") return # Initialize metrics module metrics.init_metrics() # Define custom result handler # number_order contains an array of length 2 with the number and order def execution_handler(qc, result, num_qubits, number_order, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #Must convert number_order from string to array order = eval(number_order)[1] counts, fidelity = analyze_and_print_result(qc, result, num_qubits, order, num_shots, method) metrics.store_metric(num_qubits, number_order, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, qubit_multiple): input_size = num_qubits - 1 if method == 1: num_bits = int((num_qubits -2)/4) elif method == 2: num_bits = int((num_qubits -3)/2) elif method == 3: num_bits = int((num_qubits -2)/2) # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") for _ in range(num_circuits): base = 1 while base == 1: # Ensure N is a number using the greatest bit number = np.random.randint(2 ** (num_bits - 1) + 1, 2 ** num_bits) order = np.random.randint(2, number) base = generate_base(number, order) # Checking if generated order can be reduced. Can also run through prime list in shors utils if order % 2 == 0: order = 2 if order % 3 == 0: order = 3 number_order = (number, order) if verbose: print(f"Generated {number=}, {base=}, {order=}") # create the circuit for given qubit size and order, store time metric ts = time.time() qc = ShorsAlgorithm(number, base, method=method, verbose=verbose) metrics.store_metric(num_qubits, number_order, 'create_time', time.time()-ts) # collapse the 4 sub-circuit levels used in this benchmark (for qiskit) qc = qc.decompose().decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, number_order, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print the last circuit created print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Ua Operator 'cUa' ="); print(CUA_ if CUA_ != None else " ... too large!") print("\nControlled Multiplier Operator 'cMULTamodN' ="); print(CMULTAMODN_ if CMULTAMODN_!= None else " ... too large!") print("\nControlled Modular Adder Operator 'ccphiamodN' ="); print(CCPHIADDMODN_ if CCPHIADDMODN_ != None else " ... too large!") print("\nPhi Adder Operator '\u03C6ADD' ="); print(PHIADD_ if PHIADD_ != None else " ... too large!") print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Shor's Order Finding ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run() #max_qubits = 6, max_circuits = 5, num_shots=100)
16,395
36.179138
133
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/WIP_benchmarks/shors_factoring_benchmark_WIP.py
""" Shor's Factoring Algorithm Benchmark - Qiskit """ import sys sys.path[1:1] = ["_common", "_common/qiskit", "shors/_common", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../shors/_common", "../../quantum-fourier-transform/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import math from math import gcd from fractions import Fraction import time import random import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate from qft_benchmark import qft_gate import copy from utils import getAngles, getAngle, modinv, generate_numbers, choose_random_base, determine_factors verbose = True ############### Circuit Definition # Creation of the circuit that performs addition by a in Fourier Space # Can also be used for subtraction by setting the parameter inv to a value different from 0 def phiADD(num_qubits, a): qc = QuantumCircuit(num_qubits, name="\u03C6ADD") angle = getAngles(a, num_qubits) for i in range(0, num_qubits): # addition qc.u1(angle[i], i) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return qc # Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a).to_gate() cphiadd_gate = phiadd_gate.control(1) return cphiadd_gate # Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a).to_gate() ccphiadd_gate = phiadd_gate.control(2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = QuantumRegister(2) qr_main = QuantumRegister(num_qubits + 1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_main, qr_ancilla, name="cc\u03C6ADDmodN") # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits + 1, a) ccphiadda_inv_gate = ccphiADD(num_qubits + 1, a).inverse() phiaddN_inv_gate = phiADD(num_qubits + 1, N).inverse() cphiaddN_gate = cphiADD(num_qubits + 1, N) # Create relevant temporary qubit lists ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main]) anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main]) # Create circuit qc.append(ccphiadda_gate, ctl_main_qubits) qc.append(phiaddN_inv_gate, qr_main) qc.append(inv_qft_gate(num_qubits + 1), qr_main) qc.cx(qr_main[-1], qr_ancilla[0]) qc.append(qft_gate(num_qubits + 1), qr_main) qc.append(cphiaddN_gate, anc_main_qubits) qc.append(ccphiadda_inv_gate, ctl_main_qubits) qc.append(inv_qft_gate(num_qubits + 1), qr_main) qc.x(qr_main[-1]) qc.cx(qr_main[-1], qr_ancilla[0]) qc.x(qr_main[-1]) qc.append(qft_gate(num_qubits + 1), qr_main) qc.append(ccphiadda_gate, ctl_main_qubits) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return qc # Circuit that implements the inverse of doubly controlled modular addition by a def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse() return cchpiAddmodN_inv_circ # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits # needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n + 1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name="cMULTamodN") # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n + 1), qr_main) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2 ** i) * a % N, N) # Create relevant temporary qubit list qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]]) qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]]) qc.append(ccphiADDmodN_gate, qubits) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n + 1), qr_main) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return qc # Creates circuit that implements single controlled Ua gate. n represents the number of bits # needed to represent the integer number N def controlled_Ua(n, a, exponent, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n) qr_ancilla = QuantumRegister(2) qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name=f"C-U^{a}^{exponent}") # Generate Gates a_inv = modinv(a ** exponent, N) cMULTamodN_gate = cMULTamodN(n, a ** exponent, N) cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse() # Create relevant temporary qubit list qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main]) qubits.extend([i for i in qr_ancilla]) qc.append(cMULTamodN_gate, qubits) for i in range(n): qc.cswap(qr_ctl, qr_x[i], qr_main[i]) qc.append(cMULTamodN_inv_gate, qubits) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return qc # Execute Shor's Order Finding Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' def ShorsAlgorithm(number, base, method, verbose=verbose): # Create count of qubits to use to represent the number to factor # NOTE: this should match the number of bits required to represent (number) n = int(math.ceil(math.log(number, 2))) # this will hold the 2n measurement results measurements = [0] * (2 * n) # Standard Shors Algorithm if method == 1: num_qubits = 4 * n + 2 if verbose: print( f"... running Shors to factor number [ {number} ] with base={base} using num_qubits={n}") # Create a circuit and allocate necessary qubits qr_up = QuantumRegister(2 * n) # Register for sequential QFT qr_down = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT qc = QuantumCircuit(qr_up, qr_down, qr_aux, cr_data, name="main") # Initialize down register to 1 and up register to superposition state qc.h(qr_up) qc.x(qr_down[0]) qc.barrier() # Apply Multiplication Gates for exponentiation for i in range(2 * n): cUa_gate = controlled_Ua(n, int(base), 2 ** i, number) # Create relevant temporary qubit list qubits = [qr_up[i]]; qubits.extend([i for i in qr_down]); qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) qc.barrier() i = 0 while i < ((qr_up.size - 1) / 2): qc.swap(qr_up[i], qr_up[2 * n - 1 - i]) i = i + 1 qc.append(inv_qft_gate(2 * n), qr_up) # Measure up register qc.measure(qr_up, cr_data) elif method == 2: # Create a circuit and allocate necessary qubits num_qubits = 2 * n + 3 if verbose: print(f"... running Shors to factor number [ {number} ] with base={base} using num_qubits={n}") qr_up = QuantumRegister(1) # Single qubit for sequential QFT qr_down = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements qc = QuantumCircuit(qr_down, qr_up, qr_aux, cr_data, cr_aux, name="main") # Initialize down register to 1 qc.x(qr_down[0]) # perform modular exponentiation 2*n times for k in range(2 * n): # one iteration of 1-qubit QPE # Reset the top qubit to 0 if the previous measurement was 1 qc.x(qr_up).c_if(cr_aux, 1) qc.h(qr_up) cUa_gate = controlled_Ua(n, base ** (2 ** (2 * n - 1 - k)), number) qc.append(cUa_gate, [qr_up[0], qr_down, qr_aux]) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2 ** k): qc.u1(getAngle(i, k), qr_up[0]).c_if(cr_data, i) qc.h(qr_up) qc.measure(qr_up[0], cr_data[k]) qc.measure(qr_up[0], cr_aux[0]) global QC_, QFT_ if QC_ == None or n <= 2: if n < 3: QC_ = qc if QFT_ == None or n <= 2: if n < 3: QFT_ = qft_gate(n + 1) # turn the measured values into a number in [0,1) by summing their binary values ma = [(measurements[2 * n - 1 - i]*1. / (1 << (i + 1))) for i in range(2 * n)] y = sum(ma) y = 0.833 # continued fraction expansion to get denominator (the period?) r = Fraction(y).limit_denominator(number - 1).denominator f = Fraction(y).limit_denominator(number - 1) if verbose: print(f" ... y = {y} fraction = {f.numerator} / {f.denominator} r = {f.denominator}") # return the (potential) period return r # DEVNOTE: need to resolve this; currently not using the standard 'execute module' # measure and flush are taken care of in other methods; do not add here return qc # Execute Shor's Factoring Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' # Filter function, which defines the gate set for the first optimization # (don't decompose QFTs and iQFTs to make cancellation easier) ''' def high_level_gates(eng, cmd): g = cmd.gate if g == QFT or get_inverse(g) == QFT or g == Swap: return True if isinstance(g, BasicMathGate): #return False return True print("***************** should never get here !") if isinstance(g, AddConstant): return True elif isinstance(g, AddConstantModN): return True return False return eng.next_engine.is_available(cmd) ''' # Attempt to execute Shor's Algorithm to find factors, up to a max number of tries # Returns number of failures, 0 if success def attempt_factoring(input_size, number, verbose): max_tries = 5 trials = 0 failures = 0 while trials < max_tries: trials += 1 # choose a base at random base = choose_random_base(number) if base == 0: break # execute the algorithm which determines the period given this base r = ShorsAlgorithm(input_size, number, base, verbose=verbose) # try to determine the factors from the period 'r' f1, f2 = determine_factors(r, base, number) # Success! if these are the factors and both are greater than 1 if (f1 * f2) == number and f1 > 1 and f2 > 1: if verbose: print(f" ==> Factors found :-) : {f1} * {f2} = {number}") break else: failures += 1 if verbose: print(f" ==> Bad luck: Found {f1} and {f2} which are not the factors") print(f" ... trying again ...") return failures ############### Circuit end # Print analyzed results # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots): if verbose: print(f"For marked item {marked_item} measured: {result}") key = format(marked_item, f"0{num_qubits}b")[::-1] fidelity = result[key] return fidelity # Define custom result handler def execution_handler(result, num_qubits, number, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) fidelity = analyze_and_print_result(result, num_qubits - 1, int(number), num_shots) metrics.store_metric(num_qubits, number, 'fidelity', fidelity) #################### Benchmark Loop # Execute program with default parameters def run(min_qubits=5, max_circuits=3, max_qubits=10, num_shots=100, verbose=verbose, interactive=False, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main"): print("Shor's Factoring Algorithm Benchmark - Qiskit") # Generate array of numbers to factor numbers = generate_numbers() min_qubits = max(min_qubits, 5) # need min of 5 max_qubits = max(max_qubits, min_qubits) # max must be >= min max_qubits = min(max_qubits, len(numbers)) # max cannot exceed available numbers # Initialize metrics module metrics.init_metrics() # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project) if interactive: do_interactive_test(verbose=verbose) return; # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print( f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}, input_size = {input_size}") ##print(f"... choices at {input_size} = {numbers[input_size]}") # determine array of numbers to factor numbers_to_factor = np.random.choice(numbers[input_size], num_circuits, False) ##print(f"... numbers = {numbers_to_factor}") # Number of times the factoring attempts failed for each qubit size failures = 0 # loop over all of the numbers to factor for number in numbers_to_factor: # convert from np form (created by np.random) number = int(number) # create the circuit for given qubit size and secret string, store time metric ts = time.time() # not currently used # n_iterations = int(np.pi * np.sqrt(2 ** input_size) / 4) # attempt to execute Shor's Algorithm to find factors failures += attempt_factoring(input_size, number, verbose) metrics.store_metric(num_qubits, number, 'create_time', time.time() - ts) metrics.store_metric(num_qubits, number, 'exec_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) # ex.submit_circuit(eng, qureg, num_qubits, number, num_shots) # Report how many factoring failures occurred if failures > 0: print(f"*** Factoring attempts failed {failures} times!") # execute all circuits for this group, aggregate and report metrics when complete # ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print the last circuit created # print(qc) # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Shor's Factoring Algorithm - Qiskit") # For interactive_shors_factoring testing def do_interactive_test(verbose): done = False while not done: s = input('\nEnter the number to factor: ') if len(s) < 1: break number = int(s) print(f"Factoring number = {number}\n") input_size = int(math.ceil(math.log(number, 2))) # attempt to execute Shor's Algorithm to find factors failures = attempt_factoring(input_size, number, verbose) # Report how many factoring failures occurred if failures > 0: print(f"*** Factoring attempts failed {failures} times!") print("... exiting") # if main, execute method if __name__ == '__main__': run() # max_qubits = 6, max_circuits = 5, num_shots=100)
16,795
33.138211
123
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/Test_classical_after_quantum.py
""" This file allows to test the calculations done after creating the quantum circuit It implements the continued fractions to find a possible r and then: If r found is odd, tries next approximation of the continued fractions method If r found is even, tries to get the factors of N and then: If the factors are found, exits If the factors are not found, asks user if he wants to continue looking (only if already tried too many times it exits automatically) """ from cfunctions import get_factors """ Main program """ if __name__ == '__main__': print('Forcing a case of the AP3421 lectures, with N=143, a=5, x_value=1331 and 11 qubits used to get x_value.') print('Check main in source file to change\n') """ These numbers can be changed to check the desired case. The values that are here by default is to test the case of the slide 28 of lecture 10 of the AP3421 course. The fucntion get_dactors does the continued fractions for ( x_value / ( 2^(number_qubits_used_to_get_x_value) ) ) """ N = 143 a = 5 number_qubits_used_to_get_x_value = 11 x_value = 1331 # To check the case of slide 27 of lecture 10 of the AP3421 course, just change x_value to 101 d=get_factors(int(x_value),int(number_qubits_used_to_get_x_value),int(N),int(a))
1,326
46.392857
141
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/qfunctions.py
""" This file contains quantum code in support of Shor's Algorithm """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import sys import math import numpy as np """ ********* QFT Functions *** """ """ Function to create QFT """ def create_QFT(circuit,up_reg,n,with_swaps): i=n-1 """ Apply the H gates and Cphases""" """ The Cphases with |angle| < threshold are not created because they do nothing. The threshold is put as being 0 so all CPhases are created, but the clause is there so if wanted just need to change the 0 of the if-clause to the desired value """ while i>=0: circuit.h(up_reg[i]) j=i-1 while j>=0: if (np.pi)/(pow(2,(i-j))) > 0: circuit.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] ) j=j-1 i=i-1 """ If specified, apply the Swaps at the end """ if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 """ Function to create inverse QFT """ def create_inverse_QFT(circuit,up_reg,n,with_swaps): """ If specified, apply the Swaps at the beginning""" if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 """ Apply the H gates and Cphases""" """ The Cphases with |angle| < threshold are not created because they do nothing. The threshold is put as being 0 so all CPhases are created, but the clause is there so if wanted just need to change the 0 of the if-clause to the desired value """ i=0 while i<n: circuit.h(up_reg[i]) if i != n-1: j=i+1 y=i while y>=0: if (np.pi)/(pow(2,(j-y))) > 0: circuit.cu1( - (np.pi)/(pow(2,(j-y))) , up_reg[j] , up_reg[y] ) y=y-1 i=i+1 """ ********* Arithmetic Functions *** """ """ Helper Functions """ def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m """Function that calculates the angle of a phase shift in the sequential QFT based on the binary digits of a.""" """a represents a possible value of the classical register""" def getAngle(a, N): """convert the number a to a binary string with length N""" s=bin(int(a))[2:].zfill(N) angle = 0 for i in range(0, N): """if the digit is 1, add the corresponding value to the angle""" if s[N-1-i] == '1': angle += math.pow(2, -(N-i)) angle *= np.pi return angle """Function that calculates the array of angles to be used in the addition in Fourier Space""" def getAngles(a,N): s=bin(int(a))[2:].zfill(N) angles=np.zeros([N]) for i in range(0, N): for j in range(i,N): if s[j]=='1': angles[N-i-1]+=math.pow(2, -(j-i)) angles[N-i-1]*=np.pi return angles """Creation of a doubly controlled phase gate""" def ccphase(circuit, angle, ctl1, ctl2, tgt): circuit.cu1(angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(-angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(angle/2,ctl2,tgt) """Creation of the circuit that performs addition by a in Fourier Space""" """Can also be used for subtraction by setting the parameter inv to a value different from 0""" def phiADD(circuit, q, a, N, inv): angle=getAngles(a,N) for i in range(0,N): if inv==0: circuit.u1(angle[i],q[i]) """addition""" else: circuit.u1(-angle[i],q[i]) """subtraction""" """Single controlled version of the phiADD circuit""" def cphiADD(circuit, q, ctl, a, n, inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: circuit.cu1(angle[i],ctl,q[i]) else: circuit.cu1(-angle[i],ctl,q[i]) """Doubly controlled version of the phiADD circuit""" def ccphiADD(circuit,q,ctl1,ctl2,a,n,inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: ccphase(circuit,angle[i],ctl1,ctl2,q[i]) else: ccphase(circuit,-angle[i],ctl1,ctl2,q[i]) """Circuit that implements doubly controlled modular addition by a""" def ccphiADDmodN(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) phiADD(circuit, q, N, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1],aux) create_QFT(circuit,q,n,0) cphiADD(circuit, q, aux, N, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1], aux) circuit.x(q[n-1]) create_QFT(circuit,q,n,0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) """Circuit that implements the inverse of doubly controlled modular addition by a""" def ccphiADDmodN_inv(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1],aux) circuit.x(q[n-1]) create_QFT(circuit, q, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) cphiADD(circuit, q, aux, N, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1], aux) create_QFT(circuit, q, n, 0) phiADD(circuit, q, N, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) """Circuit that implements single controlled modular multiplication by a""" def cMULTmodN(circuit, ctl, q, aux, a, N, n): create_QFT(circuit,aux,n+1,0) for i in range(0, n): ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1) create_inverse_QFT(circuit, aux, n+1, 0) for i in range(0, n): circuit.cswap(ctl,q[i],aux[i]) a_inv = modinv(a, N) create_QFT(circuit, aux, n+1, 0) i = n-1 while i >= 0: ccphiADDmodN_inv(circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1) i -= 1 create_inverse_QFT(circuit, aux, n+1, 0)
6,248
31.378238
112
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/Test_Mult.py
""" This file allows to test the Multiplication blocks Ua. This blocks, when put together as explain in the report, do the exponentiation. The user can change N, n, a and the input state, to create the circuit: up_reg |+> ---------------------|----------------------- |+> | | | -------|--------- ------------ | | ------------ down_reg |x> ------------ | Mult | ------------ |(x*a) mod N> ------------ | | ------------ ----------------- Where |x> has n qubits and is the input state, the user can change it to whatever he wants This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import math import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Function to properly get the final state, it prints it to user """ """ This is only possible in this way because the program uses the statevector_simulator """ def get_final(results, number_aux, number_up, number_down): i=0 """ Get total number of qubits to go through all possibilities """ total_number = number_aux + number_up + number_down max = pow(2,total_number) print('|aux>|top_register>|bottom_register>\n') while i<max: binary = bin(i)[2:].zfill(total_number) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ If the respective state is not zero, then print it and store the state of the register where the result we are looking for is. This works because that state is the same for every case where number !=0 """ if number!=0: print('|{0}>|{1}>|{2}>'.format(binary[0:number_aux],binary[number_aux:(number_aux+number_up)],binary[(number_aux+number_up):(total_number)]),number) if binary[number_aux:(number_aux+number_up)]=='1': store = binary[(number_aux+number_up):(total_number)] i=i+1 print(' ') return int(store, 2) """ Main program """ if __name__ == '__main__': """ Select number N to do modN""" N = int(input('Please insert integer number N: ')) print(' ') """ Get n value used in QFT, to know how many qubits are used """ n = math.ceil(math.log(N,2)) """ Select the value for 'a' """ a = int(input('Please insert integer number a: ')) print(' ') """ Please make sure the a and N are coprime""" if math.gcd(a,N)!=1: print('Please make sure the a and N are coprime. Exiting program.') exit() print('Total number of qubits used: {0}\n'.format(2*n+3)) print('Please check source file to change input quantum state. By default is |2>.\n') ts = time.time() """ Create quantum and classical registers """ aux = QuantumRegister(n+2) up_reg = QuantumRegister(1) down_reg = QuantumRegister(n) aux_classic = ClassicalRegister(n+2) up_classic = ClassicalRegister(1) down_classic = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, down_classic, up_classic, aux_classic) """ Initialize with |+> to also check if the control is working""" circuit.h(up_reg[0]) """ Put the desired input state in the down quantum register. By default we put |2> """ circuit.x(down_reg[1]) """ Apply multiplication""" cMULTmodN(circuit, up_reg[0], down_reg, aux, int(a), N, n) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ Show the final state after the multiplication """ after_exp = get_final(outputstate, n+2, 1, n) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('When control=1, value after exponentiation is in bottom quantum register: |{0}>'.format(after_exp))
5,125
38.736434
160
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/cfunctions.py
""" This file contains classical code in support of Shor's Algorithm """ """ Imports to Python functions """ import math import array import fractions import numpy as np import sys """ ******** Pre-Quantum *** """ """ Function to check if N is of type q^p""" def check_if_power(N): """ Check if N is a perfect power in O(n^3) time, n=ceil(logN) """ b=2 while (2**b) <= N: a = 1 c = N while (c-a) >= 2: m = int( (a+c)/2 ) if (m**b) < (N+1): p = int( (m**b) ) else: p = int(N+1) if int(p) == int(N): print('N is {0}^{1}'.format(int(m),int(b)) ) return True if p<N: a = int(m) else: c = int(m) b=b+1 return False """ ******** Post-Quantum *** """ """ Function to get the value a ( 1<a<N ), such that a and N are coprime. Starts by getting the smallest a possible This normally can be done fully randomly, it is done like this for the user to have control over the a value that gets selected """ def get_value_a(N): """ ok defines if user wants to used the suggested a (if ok!='0') or not (if ok=='0') """ ok='0' """ Starting with a=2 """ a=2 """ Get the smallest a such that a and N are coprime""" while math.gcd(a,N)!=1: a=a+1 """ Store it as the smallest a possible """ smallest_a = a """ Ask user if the a found is ok, if not, then increment and find the next possibility """ ok = input('Is the number {0} ok for a? Press 0 if not, other number if yes: '.format(a)) if ok=='0': if(N==3): print('Number {0} is the only one you can use. Using {1} as value for a\n'.format(a,a)) return a a=a+1 """ Cycle to find all possibilities for a not counting the smallest one, until user says one of them is ok """ while ok=='0': """ Get a coprime with N """ while math.gcd(a,N)!=1: a=a+1 """ Ask user if ok """ ok = input('Is the number {0} ok for a? Press 0 if not, other number if yes: '.format(a)) """ If user says it is ok, then exit cycle, a has been found """ if ok!='0': break """ If user says it is not ok, increment a and check if are all possibilites checked. """ a=a+1 """ If all possibilities for a are rejected, put a as the smallest possible value and exit cycle """ if a>(N-1): print('You rejected all options for value a, selecting the smallest one\n') a=smallest_a break """ Print the value that is used as a """ print('Using {0} as value for a\n'.format(a)) return a """ Function to apply the continued fractions to find r and the gcd to find the desired factors""" def get_factors(x_value,t_upper,N,a): if x_value<=0: print('x_value is <= 0, there are no continued fractions\n') return False print('Running continued fractions for this case\n') """ Calculate T and x/T """ T = pow(2,t_upper) x_over_T = x_value/T """ Cycle in which each iteration corresponds to putting one more term in the calculation of the Continued Fraction (CF) of x/T """ """ Initialize the first values according to CF rule """ i=0 b = array.array('i') t = array.array('f') b.append(math.floor(x_over_T)) t.append(x_over_T - b[i]) while i>=0: """From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests""" if i>0: b.append( math.floor( 1 / (t[i-1]) ) ) t.append( ( 1 / (t[i-1]) ) - b[i] ) """ Calculate the CF using the known terms """ aux = 0 j=i while j>0: aux = 1 / ( b[j] + aux ) j = j-1 aux = aux + b[0] """Get the denominator from the value obtained""" frac = fractions.Fraction(aux).limit_denominator() den=frac.denominator print('Approximation number {0} of continued fractions:'.format(i+1)) print("Numerator:{0} \t\t Denominator: {1}\n".format(frac.numerator,frac.denominator)) """ Increment i for next iteration """ i=i+1 if (den%2) == 1: if i>=15: print('Returning because have already done too much tries') return False print('Odd denominator, will try next iteration of continued fractions\n') continue """ If denominator even, try to get factors of N """ """ Get the exponential a^(r/2) """ exponential = 0 if den<1000: exponential=pow(a , (den/2)) """ Check if the value is too big or not """ if math.isinf(exponential)==1 or exponential>1000000000: print('Denominator of continued fraction is too big!\n') aux_out = input('Input number 1 if you want to continue searching, other if you do not: ') if aux_out != '1': return False else: continue """If the value is not to big (infinity), then get the right values and do the proper gcd()""" putting_plus = int(exponential + 1) putting_minus = int(exponential - 1) one_factor = math.gcd(putting_plus,N) other_factor = math.gcd(putting_minus,N) """ Check if the factors found are trivial factors or are the desired factors """ if one_factor==1 or one_factor==N or other_factor==1 or other_factor==N: print('Found just trivial factors, not good enough\n') """ Check if the number has already been found, use i-1 because i was already incremented """ if t[i-1]==0: print('The continued fractions found exactly x_final/(2^(2n)) , leaving funtion\n') return False if i<15: aux_out = input('Input number 1 if you want to continue searching, other if you do not: ') if aux_out != '1': return False else: """ Return if already too much tries and numbers are huge """ print('Returning because have already done too many tries\n') return False else: print('The factors of {0} are {1} and {2}\n'.format(N,one_factor,other_factor)) print('Found the desired factors!\n') return True
6,652
30.680952
115
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/Shor_Normal_QFT.py
""" This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the first simplification introduced by the base paper used. As the circuit is completely general, it is a rather long circuit, with a lot of QASM instructions in the generated Assembly code, which makes that for high values of N the code is not able to run in IBM Q Experience because IBM has a very low restriction on the number os QASM instructions it can run. For N=15, it can run on IBM. But, for example, for N=21 it already may not, because it exceeds the restriction of QASM instructions. The user can try to use n qubits on top register instead of 2n to get more cases working on IBM. This will, however and naturally, diminish the probabilty of success. For a small number of qubits (about until 20), the code can be run on a local simulator. This makes it to be a little slow even for the factorization of small numbers N. Because of this, although all is general and we ask the user to introduce the number N and if he agrees with the 'a' value selected or not, we after doing that force N=15 and a=4, because that is a case where the simulation, although slow, can be run in local simulator and does not last 'forever' to end. If the user wants he can just remove the 2 lines of code where that is done, and put bigger N (that will be slow) or can try to run on the ibm simulator (for that, the user should introduce its IBM Q Experience Token and be aware that for high values of N it will just receive a message saying the size of the circuit is too big) """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ from qiskit import BasicAer import sys """ Imports to Python functions """ import math import array import fractions import numpy as np import time """ Local Imports """ from cfunctions import check_if_power, get_value_a from cfunctions import get_factors from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') """ To login to IBM Q experience the following functions should be called """ """ IBMQ.delete_accounts() IBMQ.save_account('insert token here') IBMQ.load_accounts() """ """ Get an integer a that is coprime with N """ a = get_value_a(N) """ If user wants to force some values, he can do that here, please make sure to update the print and that N and a are coprime""" print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info') N=15 a=4 """ Get n value used in Shor's algorithm, to know how many qubits are used """ n = math.ceil(math.log(N,2)) print('Total number of qubits used: {0}\n'.format(4*n+2)) ts = time.time() """ Create quantum and classical registers """ """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(n+2) """quantum register where the sequential QFT is performed""" up_reg = QuantumRegister(2*n) """quantum register where the multiplications are made""" down_reg = QuantumRegister(n) """classical register where the measured values of the QFT are stored""" up_classic = ClassicalRegister(2*n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic) """ Initialize down register to 1 and create maximal superposition in top register """ circuit.h(up_reg) circuit.x(down_reg[0]) """ Apply the multiplication gates as showed in the report in order to create the exponentiation """ for i in range(0, 2*n): cMULTmodN(circuit, up_reg[i], down_reg, aux, int(pow(a, pow(2, i))), N, n) """ Apply inverse QFT """ create_inverse_QFT(circuit, up_reg, 2*n ,1) """ Measure the top qubits, to get x value""" circuit.measure(up_reg,up_classic) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) #if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Select how many times the circuit runs""" number_shots=int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() if number_shots > 1: print('\nIf the circuit takes too long to run, consider running it less times\n') """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a)) """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result=simulation.result() counts_result = sim_result.get_counts(circuit) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots)) i=0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots)) i=i+1 """ An empty print just to have a good display in terminal """ print(' ') """ Initialize this variable """ prob_success=0 """ For each simulation result, print proper info to user and try to calculate the factors of N""" i=0 while i < len(counts_result): """ Get the x_value from the final state qubits """ output_desired = list(sim_result.get_counts().keys())[i] x_value = int(output_desired, 2) prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots) print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result)) """ Print the final x_value to user """ print('In decimal, x_final value for this result is: {0}\n'.format(x_value)) """ Get the factors using the x value obtained """ success=get_factors(int(x_value),int(2*n),int(N),int(a)) if success==True: prob_success = prob_success + prob_this_result i=i+1 print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
7,486
39.912568
166
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/Test_QFT.py
""" This file allows to test the various QFT implemented. The user must specify: 1) The number of qubits it wants the QFT to be implemented on 2) The kind of QFT want to implement, among the options: -> Normal QFT with SWAP gates at the end -> Normal QFT without SWAP gates at the end -> Inverse QFT with SWAP gates at the end -> Inverse QFT without SWAP gates at the end The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT """ Function to properly print the final state of the simulation """ """ This is only possible in this way because the program uses the statevector_simulator """ def show_good_coef(results, n): i=0 max = pow(2,n) if max > 100: max = 100 """ Iterate to all possible states """ while i<max: binary = bin(i)[2:].zfill(n) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ Print the respective component of the state if it has a non-zero coefficient """ if number!=0: print('|{}>'.format(binary),number) i=i+1 """ Main program """ if __name__ == '__main__': """ Select how many qubits want to apply the QFT on """ n = int(input('\nPlease select how many qubits want to apply the QFT on: ')) """ Select the kind of QFT to apply using the variable what_to_test: what_to_test = 0: Apply normal QFT with the SWAP gates at the end what_to_test = 1: Apply normal QFT without the SWAP gates at the end what_to_test = 2: Apply inverse QFT with the SWAP gates at the end what_to_test = 3: Apply inverse QFT without the SWAP gates at the end """ print('\nSelect the kind of QFT to apply:') print('Select 0 to apply normal QFT with the SWAP gates at the end') print('Select 1 to apply normal QFT without the SWAP gates at the end') print('Select 2 to apply inverse QFT with the SWAP gates at the end') print('Select 3 to apply inverse QFT without the SWAP gates at the end\n') what_to_test = int(input('Select your option: ')) if what_to_test<0 or what_to_test>3: print('Please select one of the options') exit() print('\nTotal number of qubits used: {0}\n'.format(n)) print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n') ts = time.time() """ Create quantum and classical registers """ quantum_reg = QuantumRegister(n) classic_reg = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(quantum_reg, classic_reg) """ Create the input state desired Please change this as you like, by default we put H gates in every qubit, initializing with a maximimal superposition state """ #circuit.h(quantum_reg) """ Test the right QFT according to the variable specified before""" if what_to_test == 0: create_QFT(circuit,quantum_reg,n,1) elif what_to_test == 1: create_QFT(circuit,quantum_reg,n,0) elif what_to_test == 2: create_inverse_QFT(circuit,quantum_reg,n,1) elif what_to_test == 3: create_inverse_QFT(circuit,quantum_reg,n,0) else: print('Noting to implement, exiting program') exit() """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('The final state after applying the QFT is:\n') show_good_coef(outputstate,n)
4,888
38.427419
139
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/Test_classical_before_quantum.py
""" This file allows to test the calculations done before creating the quantum circuit It asks the user for a number N and then: Checks if N is 1 or 0 or is an even -> these cases are simple Checks if N can be put in q^p form, q and p integers -> this can be done quicker classicaly then using the quantum circuit If it is not an easy case like the above ones, then the program gets an integer a, coprime with N, starting with the smallest one possible and asking the user if the selected a is ok, if not, going to the second smallest one, and like this until the user agrees with an a """ from cfunctions import check_if_power, get_value_a """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') a=get_value_a(N)
1,347
31.878049
128
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/qiskit/interactive_shors_factoring/Shor_Sequential_QFT.py
""" This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the second simplification introduced by the base paper used. The circuit is general, so, in a good computer that can support simulations infinite qubits, it can factorize any number N. The only limitation is the capacity of the computer when running in local simulator and the limits on the IBM simulator (in the number of qubits and in the number of QASM instructions the simulations can have when sent to IBM simulator). The user may try N=21, which is an example that runs perfectly fine even just in local simulator because, as in explained in report, this circuit, because implements the QFT sequentially, uses less qubits then when using a "normal"n QFT. """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ from qiskit import BasicAer import sys """ Imports to Python functions """ import math import array import fractions import numpy as np import time """ Local Imports """ from cfunctions import check_if_power, get_value_a from cfunctions import get_factors from qfunctions import create_QFT, create_inverse_QFT from qfunctions import getAngle, cMULTmodN """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') """ To login to IBM Q experience the following functions should be called """ """ IBMQ.delete_accounts() IBMQ.save_account('insert token here') IBMQ.load_accounts()""" """ Get an integer a that is coprime with N """ a = get_value_a(N) """ If user wants to force some values, can do that here, please make sure to update print and that N and a are coprime""" """print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info') N=15 a=2""" """ Get n value used in Shor's algorithm, to know how many qubits are used """ n = math.ceil(math.log(N,2)) print('Total number of qubits used: {0}\n'.format(2*n+3)) ts = time.time() """ Create quantum and classical registers """ """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(n+2) """single qubit where the sequential QFT is performed""" up_reg = QuantumRegister(1) """quantum register where the multiplications are made""" down_reg = QuantumRegister(n) """classical register where the measured values of the sequential QFT are stored""" up_classic = ClassicalRegister(2*n) """classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1""" c_aux = ClassicalRegister(1) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic, c_aux) """ Initialize down register to 1""" circuit.x(down_reg[0]) """ Cycle to create the Sequential QFT, measuring qubits and applying the right gates according to measurements """ for i in range(0, 2*n): """reset the top qubit to 0 if the previous measurement was 1""" circuit.x(up_reg).c_if(c_aux, 1) circuit.h(up_reg) cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n) """cycle through all possible values of the classical register and apply the corresponding conditional phase shift""" for j in range(0, 2**i): """the phase shift is applied if the value of the classical register matches j exactly""" circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j) circuit.h(up_reg) circuit.measure(up_reg[0], up_classic[i]) circuit.measure(up_reg[0], c_aux[0]) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) #if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Select how many times the circuit runs""" number_shots=int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a)) """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result=simulation.result() counts_result = sim_result.get_counts(circuit) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots)) i=0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots)) i=i+1 """ An empty print just to have a good display in terminal """ print(' ') """ Initialize this variable """ prob_success=0 """ For each simulation result, print proper info to user and try to calculate the factors of N""" i=0 while i < len(counts_result): """ Get the x_value from the final state qubits """ all_registers_output = list(sim_result.get_counts().keys())[i] output_desired = all_registers_output.split(" ")[1] x_value = int(output_desired, 2) prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots) print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result)) """ Print the final x_value to user """ print('In decimal, x_final value for this result is: {0}\n'.format(x_value)) """ Get the factors using the x value obtained """ success = get_factors(int(x_value),int(2*n),int(N),int(a)) if success==True: prob_success = prob_success + prob_this_result i=i+1 print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
7,141
38.458564
164
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/shors/cirq/shors_benchmark.py
""" Shor's Order Finding Algorithm Benchmark - Cirq """ from collections import defaultdict import math import sys import time import cirq import numpy as np sys.path[1:1] = ["_common", "_common/cirq", "shors/_common", "quantum-fourier-transform/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq", "../../shors/_common", "../../quantum-fourier-transform/cirq"] import cirq_utils as cirq_utils import execute as ex import metrics as metrics from shors_utils import getAngles, getAngle, modinv, generate_base, verify_order from qft_benchmark import inv_qft_gate from qft_benchmark import qft_gate np.random.seed(0) verbose = False QC_ = None PHIADD_ = None CCPHIADDMODN_ = None CMULTAMODN_ = None CUA_ = None QFT_ = None ############### Circuit Definition # Creation of the circuit that performs addition by a in Fourier Space # Can also be used for subtraction by setting the parameter inv to a value different from 0 def phiADD(num_qubits, a): # allocate qubits qr = cirq.GridQubit.rect(1,num_qubits,0) qc = cirq.Circuit() angle = getAngles(a, num_qubits) for i in range(0, num_qubits): # addition qc.append(cirq.rz(angle[i]).on(qr[i])) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="\u03C6ADD") # Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a) cphiadd_gate = cirq.ops.ControlledGate(phiadd_gate, num_controls=1) return cphiadd_gate # Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a) ccphiadd_gate = cirq.ops.ControlledGate(phiadd_gate, num_controls=2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = cirq.GridQubit.rect(1,2,0) qr_main = cirq.GridQubit.rect(1,num_qubits + 1, 1) qr_ancilla = cirq.GridQubit.rect(1,1,2) qc = cirq.Circuit() # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits + 1, a) ccphiadda_inv_gate = cirq.inverse(ccphiADD(num_qubits + 1, a)) phiaddN_inv_gate = cirq.inverse(phiADD(num_qubits + 1, N)) cphiaddN_gate = cphiADD(num_qubits + 1, N) # Create circuit qc.append(ccphiadda_gate.on(*qr_ctl, *qr_main)) qc.append(phiaddN_inv_gate.on(*qr_main)) qc.append(inv_qft_gate(num_qubits + 1).on(*qr_main)) qc.append(cirq.CNOT(qr_main[-1], qr_ancilla[0])) qc.append(qft_gate(num_qubits + 1).on(*qr_main)) qc.append(cphiaddN_gate.on(*qr_ancilla, *qr_main)) qc.append(ccphiadda_inv_gate.on(*qr_ctl, *qr_main)) qc.append(inv_qft_gate(num_qubits + 1).on(*qr_main)) qc.append(cirq.X(qr_main[-1])) qc.append(cirq.CNOT(qr_main[-1], qr_ancilla[0])) qc.append(cirq.X(qr_main[-1])) qc.append(qft_gate(num_qubits + 1).on(*qr_main)) qc.append(ccphiadda_gate.on(*qr_ctl, *qr_main)) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return cirq_utils.to_gate(num_qubits=num_qubits + 4, circ=qc, name="cc\u03C6ADDmodN") # Circuit that implements the inverse of doubly controlled modular addition by a def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_gate = cirq.inverse(cchpiAddmodN_circ) return cchpiAddmodN_inv_gate # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = cirq.GridQubit.rect(1,1,0) qr_x = cirq.GridQubit.rect(1,n,1) qr_main_ancilla = cirq.GridQubit.rect(1, n+2,2) qc = cirq.Circuit() # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n + 1).on(*qr_main_ancilla[:n+1])) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2 ** i) * a % N, N) qc.append(ccphiADDmodN_gate.on(*qr_ctl, qr_x[i], *qr_main_ancilla)) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n + 1).on(*qr_main_ancilla[:n+1])) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return cirq_utils.to_gate(num_qubits=2*n+3, circ=qc, name="cMULTamodN") # Creates circuit that implements single controlled Ua gate. n represents the number of bits # needed to represent the integer number N def controlled_Ua(n, a, exponent, N): qr_ctl = cirq.GridQubit.rect(1,1,0) qr_x = cirq.GridQubit.rect(1,n,1) qr_main = cirq.GridQubit.rect(1,n,2) qr_ancilla = cirq.GridQubit.rect(1, 2,3) qc = cirq.Circuit() # Generate Gates a_inv = modinv(a ** exponent, N) cMULTamodN_gate = cMULTamodN(n, a ** exponent, N) cMULTamodN_inv_gate = cirq.inverse(cMULTamodN(n, a_inv, N)) qc.append(cMULTamodN_gate.on(*qr_ctl,*qr_x,*qr_main,*qr_ancilla)) for i in range(n): qc.append(cirq.CSWAP(*qr_ctl, qr_x[i], qr_main[i])) qc.append(cMULTamodN_inv_gate.on(*qr_ctl,*qr_x,*qr_main,*qr_ancilla)) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return cirq_utils.to_gate(num_qubits=2*n+3, circ=qc, name=f"C-U^{a ** exponent}") # Execute Shor's Order Finding Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' def ShorsAlgorithm(number, base, method, verbose=verbose): # Create count of qubits to use to represent the number to factor # NOTE: this should match the number of bits required to represent (number) n = int(math.ceil(math.log(number, 2))) # Standard Shors Algorithm if method == 1: num_qubits = 4 * n + 2 if verbose: print( f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") # Create a circuit and allocate necessary qubits qr_counting = cirq.GridQubit.rect(1,2*n,0) # Register for sequential QFT qr_mult = cirq.GridQubit.rect(1,n,1) # Register for multiplications qr_aux = cirq.GridQubit.rect(1,n+2,2) # Register for addition and multiplication qc = cirq.Circuit() # Initialize multiplication register to 1 and counting register to superposition state qc.append(cirq.H.on_each(*qr_counting)) qc.append(cirq.X(qr_mult[0])) # Apply Multiplication Gates for exponentiation for i in reversed(range(2 * n)): cUa_gate = controlled_Ua(n, int(base), 2 ** (2 * n - 1 - i), number) qc.append(cUa_gate.on(qr_counting[i],*qr_mult,*qr_aux)) qc.append(inv_qft_gate(2 * n).on(*qr_counting)) # measure counting register qc.append(cirq.measure(*[qr_counting[i_qubit] for i_qubit in range(2*n)], key='result')) # Method 2 requires mid circuit measurement currently unavailable on cirq hardware ''' elif method == 2: # Create a circuit and allocate necessary qubits num_qubits = 2 * n + 3 if verbose: print( f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") qr_counting = QuantumRegister(1) # Single qubit for sequential QFT qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT cr_aux = ClassicalRegister( 1) # Register to reset the state of the counting register based on previous measurements qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, cr_aux, name="main") # Initialize multiplication register to 1 qc.x(qr_mult[0]) # perform modular exponentiation 2*n times for k in range(2 * n): # Reset the top qubit to 0 if the previous measurement was 1 qc.x(qr_counting).c_if(cr_aux, 1) qc.h(qr_counting) cUa_gate = controlled_Ua(n, base, 2 ** (2 * n - 1 - k), number) # Create relevant temporary qubit list qubits = [qr_counting[0]]; qubits.extend([i for i in qr_mult]); qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2 ** k): qc.p(getAngle(i, k), qr_counting[0]).c_if(cr_data, i) qc.h(qr_counting) qc.measure(qr_counting[0], cr_data[k]) qc.measure(qr_counting[0], cr_aux[0]) ''' global QC_, QFT_ if QC_ == None or n <= 2: if n < 3: QC_ = qc if QFT_ == None or n <= 2: if n < 3: QFT_ = qft_gate(n + 1) return qc ############### Circuit end def expected_shor_dist(num_bits, order, num_shots): # num_bits represent the number of bits to represent the number N in question # Qubits measureed always 2 * num_bits for the three methods implemented in this benchmark qubits_measured = 2 * num_bits dist = {} # Conver float to int r = int(order) # Generate expected distribution q = int(2 ** (qubits_measured)) for i in range(r): key = bin(int(q * (i / r)))[2:].zfill(qubits_measured) dist[key] = num_shots / r ''' for c in range(2 ** qubits_measured): key = bin(c)[2:].zfill(qubits_measured) amp = 0 for i in range(int(q/r) - 1): amp += np.exp(2*math.pi* 1j * i * (r * c % q)/q ) amp = amp * np.sqrt(r) / q dist[key] = abs(amp) ** 2 ''' return dist # Print analyzed results # Analyze and print measured results # Expected result is always the order r, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method): if method == 1: num_bits = int((num_qubits - 2) / 4) elif method == 2: num_bits = int((num_qubits - 3) / 2) elif method == 3: num_bits = int((num_qubits - 2) / 2) # get measurement array measurements = result.measurements['result'] counts = defaultdict(lambda: 0) for row in measurements: counts["".join([str(x) for x in reversed(row)])] += 1 ''' # Only classical data qubits are important and removing first auxiliary qubit from count if method == 2: temp_counts = {} for key, item in counts.items(): temp_counts[key[2:]] = item counts = temp_counts ''' # generate correct distribution correct_dist = expected_shor_dist(num_bits, order, num_shots) if verbose: print(f"For order value {order}, measured: {counts}") print(f"For order value {order}, correct_dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity #################### Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_circuits=1, max_qubits=18, num_shots=100, method=1, verbose=verbose, backend_id='simulator', provider_backend=None): print("Shor's Order Finding Algorithm Benchmark - Cirq") print(f"... using circuit method {method}") # Each method has a different minimum amount of qubits to run and a certain multiple of qubits that can be run qubit_multiple = 2 # Standard for Method 2 and 3 max_qubits = max(max_qubits, min_qubits) # max must be >= min if method == 1: min_qubits = max(min_qubits, 10) # need min of 10 qubit_multiple = 4 elif method == 2: min_qubits = max(min_qubits, 7) # need min of 7 elif method == 3: min_qubits = max(min_qubits, 6) # need min of 6 if max_qubits < min_qubits: print( f"Max number of qubits {max_qubits} is too low to run method {method} of Shor's Order Finding") return # Initialize metrics module metrics.init_metrics() # Define custom result handler # number_order contains an array of length 2 with the number and order def execution_handler(qc, result, num_qubits, number_order, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) # Must convert number_order from string to array order = eval(number_order)[1] counts, fidelity = analyze_and_print_result(qc, result, num_qubits, order, num_shots, method) metrics.store_metric(num_qubits, number_order, 'fidelity', fidelity) # Initialize execution module with the result handler ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, qubit_multiple): input_size = num_qubits - 1 if method == 1: num_bits = int((num_qubits - 2) / 4) elif method == 2: num_bits = int((num_qubits - 3) / 2) elif method == 3: num_bits = int((num_qubits - 2) / 2) # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") for _ in range(num_circuits): base = 1 while base == 1: # Ensure N is a number using the greatest bit number = np.random.randint(2 ** (num_bits - 1) + 1, 2 ** num_bits) order = np.random.randint(2, number) base = generate_base(number, order) # Checking if generated order can be reduced. Can also run through prime list in shors utils if order % 2 == 0: order = 2 if order % 3 == 0: order = 3 number_order = (number, order) if verbose: print(f"Generated {number=}, {base=}, {order=}") # create the circuit for given qubit size and order, store time metric ts = time.time() qc = ShorsAlgorithm(number, base, method=method, verbose=verbose) metrics.store_metric(num_qubits, number_order, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, number_order, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # print the last circuit created print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Ua Operator 'cUa' ="); print(CUA_ if CUA_ != None else " ... too large!") print("\nControlled Multiplier Operator 'cMULTamodN' ="); print(CMULTAMODN_ if CMULTAMODN_ != None else " ... too large!") print("\nControlled Modular Adder Operator 'ccphiamodN' ="); print(CCPHIADDMODN_ if CCPHIADDMODN_ != None else " ... too large!") print("\nPhi Adder Operator '\u03C6ADD' ="); print(PHIADD_ if PHIADD_ != None else " ... too large!") qr_state = cirq.GridQubit.rect(1, QFT_.num_qubits,0) # we need to create registers to print circuits in cirq print("\nQFT Circuit ="); print(cirq.Circuit(cirq.decompose(QFT_.on(*qr_state))) if QFT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Shor's Order Finding ({method}) - Cirq") # if main, execute method if __name__ == '__main__': run() # max_qubits = 6, max_circuits = 5, num_shots=100)
16,134
35.8379
153
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/quantum-fourier-transform/braket/qft_benchmark.py
""" Quantum Fourier Transform Benchmark Program - Braket """ import sys import time from braket.circuits import Circuit # AWS imports: Import Braket SDK modules import math import numpy as np sys.path[1:1] = [ "_common", "_common/braket" ] sys.path[1:1] = [ "../../_common", "../../_common/braket" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display num_gates = 0 depth = 0 QC_ = None QFT_ = None QFTI_ = None ############### Circuit Definition def QuantumFourierTransform (num_qubits, secret_int, method=1): global num_gates, depth # Size of input is one less than available qubits input_size = num_qubits num_gates = 0 depth = 0 # allocate circuit qc = Circuit() if method==1: # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(input_size)+'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size-1-i_qubit]=='1': qc.x(i_qubit) num_gates += 1 depth += 1 # perform QFT on the input qft = qft_gate(input_size) qc.add(qft) # End with Hadamard on all qubits (to measure the z rotations) ''' don't do this unless NOT doing the inverse afterwards for i_qubit in range(input_size): qc.h(i_qubit) ''' # some compilers recognize the QFT and IQFT in series and collapse them to identity; # perform a set of rotations to add one to the secret_int to avoid this collapse for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz(i_q, 1 * math.pi / divisor) num_gates+=1 # to revert back to initial state, apply inverse QFT qfti = inv_qft_gate(input_size) qc.add(qfti) elif method == 2: for i_q in range(0, num_qubits): qc.h(i_q) num_gates += 1 for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz(i_q, secret_int * math.pi / divisor) num_gates += 1 depth += 1 qfti = inv_qft_gate(input_size) qc.add(qfti) # This method is a work in progress elif method == 3: for i_q in range(0, secret_int): qc.h(i_q) num_gates += 1 for i_q in range(secret_int, num_qubits): qc.x(i_q) num_gates += 1 depth += 1 qfti = inv_qft_gate(input_size) qc.add(qfti) else: exit("Invalid QFT method") num_gates += num_qubits depth += 1 # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############### QFT Circuit def qft_gate(input_size): global QFT_, num_gates, depth qc = Circuit() # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) #qc.crz(hidx, math.pi / divisor , input_size - j - 1) crz_gate(qc, math.pi / divisor, hidx, input_size - j - 1) num_gates += 1 depth += 1 # followed by an H gate (applied to all qubits) qc.h(hidx) num_gates += 1 depth += 1 #qc.barrier() if QFT_ == None or input_size <= 5: if input_size < 9: QFT_ = qc return qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qc = Circuit() # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(hidx) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) #qc.crz( -math.pi / divisor , hidx, input_size - j - 1) crz_gate(qc, -math.pi / divisor, hidx, input_size - j - 1) num_gates += 1 depth += 1 if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc ############### CRZ shim # Implement the CRZ with RZs and CNOTs def crz_gate(qc, theta, control_qubit, target_qubit): qc.rz(target_qubit, theta/2) qc.cnot(control_qubit, target_qubit) qc.rz(target_qubit, -theta/2) qc.cnot(control_qubit, target_qubit) global num_gates, depth num_gates += 3 depth += 1 ############### Result Data Analysis # Define expected distribution calculated from applying the iqft to the prepared secret_int state def expected_dist(num_qubits, secret_int, counts): dist = {} s = num_qubits - secret_int for key in counts.keys(): key_r = key[::-1] # for braket, need to reverse the key to compare against secret int if key_r[(num_qubits-secret_int):] == ''.zfill(secret_int): dist[key] = 1/(2**s) return dist # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, method): # obtain shots from the result metadata num_shots = result.task_metadata.shots # obtain counts from the result object counts = result.measurement_counts # For method 1, expected result is always the secret_int if method==1: # add one to the secret_int to compensate for the extra rotations done between QFT and IQFT secret_int_plus_one = (secret_int + 1) % (2 ** num_qubits) # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int_plus_one, f"0{num_qubits}b") key_r = key[::-1] # correct distribution is measuring the key 100% of the time correct_dist = {key_r: 1.0} # For method 2, expected result is always the secret_int elif method==2: # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") key_r = key[::-1] # correct distribution is measuring the key 100% of the time correct_dist = {key_r: 1.0} # For method 3, correct_dist is a distribution with more than one value elif method==3: # correct_dist is from the expected dist correct_dist = expected_dist(num_qubits, secret_int, counts) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) if verbose: print(f"For secret int {secret_int} measured: {counts} fidelity: {fidelity}") return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits = 2, max_qubits = 8, max_circuits = 3, num_shots = 100, method=1, backend_id = 'simulator'): print("Quantum Fourier Transform Benchmark Program - Braket") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, input_size, s_int): # determine fidelity of result set num_qubits = int(input_size) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), method) metrics.store_metric(input_size, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1): num_qubits = input_size # determine number of circuits to execute for this group # and determine range of secret strings to loop over if method == 1 or method == 2: num_circuits = min(2 ** (input_size), max_circuits) if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) elif method == 3: num_circuits = min(input_size, max_circuits) if input_size <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(range(input_size), num_circuits, False) else: exit("Invalid QFT method") print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = QuantumFourierTransform(num_qubits, s_int, method=method) metrics.store_metric(input_size, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, input_size, s_int, shots=num_shots) print(f"... number of gates, depth = {num_gates}, {depth}") # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(input_size) metrics.report_metrics_for_group(input_size) # Alternatively, execute all circuits, aggregate and report metrics #ex.execute_circuits() #metrics.aggregate_metrics_for_group(input_size) #metrics.report_metrics_for_group(input_size) # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method==1: print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Quantum Fourier Transform ({method}) - Braket") # if main, execute method if __name__ == '__main__': run()
11,398
31.568571
99
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/quantum-fourier-transform/qiskit/qft_benchmark.py
""" Quantum Fourier Transform Benchmark Program - Qiskit """ import math import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qiskit" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display num_gates = 0 depth = 0 QC_ = None QFT_ = None QFTI_ = None ############### Circuit Definition def QuantumFourierTransform (num_qubits, secret_int, method=1): global num_gates, depth # Size of input is one less than available qubits input_size = num_qubits num_gates = 0 depth = 0 # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main") if method==1: # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(input_size)+'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size-1-i_qubit]=='1': qc.x(qr[i_qubit]) num_gates += 1 depth += 1 qc.barrier() # perform QFT on the input qc.append(qft_gate(input_size).to_instruction(), qr) # End with Hadamard on all qubits (to measure the z rotations) ''' don't do this unless NOT doing the inverse afterwards for i_qubit in range(input_size): qc.h(qr[i_qubit]) qc.barrier() ''' qc.barrier() # some compilers recognize the QFT and IQFT in series and collapse them to identity; # perform a set of rotations to add one to the secret_int to avoid this collapse for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz( 1 * math.pi / divisor , qr[i_q]) num_gates+=1 qc.barrier() # to revert back to initial state, apply inverse QFT qc.append(inv_qft_gate(input_size).to_instruction(), qr) qc.barrier() elif method == 2: for i_q in range(0, num_qubits): qc.h(qr[i_q]) num_gates += 1 for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz(secret_int * math.pi / divisor, qr[i_q]) num_gates += 1 depth += 1 qc.append(inv_qft_gate(input_size).to_instruction(), qr) # This method is a work in progress elif method==3: for i_q in range(0, secret_int): qc.h(qr[i_q]) num_gates+=1 for i_q in range(secret_int, num_qubits): qc.x(qr[i_q]) num_gates+=1 depth += 1 qc.append(inv_qft_gate(input_size).to_instruction(), qr) else: exit("Invalid QFT method") # measure all qubits qc.measure(qr, cr) num_gates += num_qubits depth += 1 # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############### QFT Circuit def qft_gate(input_size): global QFT_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 qc.barrier() if QFT_ == None or input_size <= 5: if input_size < 9: QFT_ = qc return qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc # Define expected distribution calculated from applying the iqft to the prepared secret_int state def expected_dist(num_qubits, secret_int, counts): dist = {} s = num_qubits - secret_int for key in counts.keys(): if key[(num_qubits-secret_int):] == ''.zfill(secret_int): dist[key] = 1/(2**s) return dist ############### Result Data Analysis # Analyze and print measured results def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots, method): # obtain counts from the result object counts = result.get_counts(qc) # For method 1, expected result is always the secret_int if method==1: # add one to the secret_int to compensate for the extra rotations done between QFT and IQFT secret_int_plus_one = (secret_int + 1) % (2 ** num_qubits) # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int_plus_one, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 2, expected result is always the secret_int elif method==2: # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 3, correct_dist is a distribution with more than one value elif method==3: # correct_dist is from the expected dist correct_dist = expected_dist(num_qubits, secret_int, counts) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) if verbose: print(f"For secret int {secret_int} measured: {counts} fidelity: {fidelity}") return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits = 2, max_qubits = 8, max_circuits = 3, skip_qubits=1, num_shots = 100, method=1, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Quantum Fourier Transform Benchmark Program - Qiskit") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, input_size, s_int, num_shots): # determine fidelity of result set num_qubits = int(input_size) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots, method) metrics.store_metric(input_size, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) num_qubits = input_size # determine number of circuits to execute for this group # and determine range of secret strings to loop over if method == 1 or method == 2: num_circuits = min(2 ** (input_size), max_circuits) if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) elif method == 3: num_circuits = min(input_size, max_circuits) if input_size <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(range(input_size), num_circuits, False) else: sys.exit("Invalid QFT method") print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = QuantumFourierTransform(num_qubits, s_int, method=method) metrics.store_metric(input_size, s_int, 'create_time', time.time()-ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, input_size, s_int, num_shots) print(f"... number of gates, depth = {num_gates}, {depth}") # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method==1: print("\nQFT Circuit ="); print(QFT_) print("\nInverse QFT Circuit ="); print(QFTI_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Quantum Fourier Transform ({method}) - Qiskit") # if main, execute method 1 if __name__ == '__main__': run()
11,249
31.991202
114
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/quantum-fourier-transform/cirq/qft_benchmark.py
""" Quantum Fourier Transform Benchmark Program - Cirq """ from collections import defaultdict import math import sys import time import cirq import numpy as np sys.path[1:1] = [ "_common", "_common/cirq" ] sys.path[1:1] = [ "../../_common", "../../_common/cirq" ] import cirq_utils as cirq_utils import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display num_gates = 0 depth = 0 QC_ = None QFT_ = None QFTI_ = None ############### Circuit Definition def QuantumFourierTransform (num_qubits, secret_int, method=1): global num_gates, depth # Size of input is one less than available qubits input_size = num_qubits num_gates = 0 depth = 0 # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() if method==1: # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(input_size)+'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size-1-i_qubit]=='1': qc.append(cirq.X(qr[i_qubit])) num_gates += 1 depth += 1 # perform QFT on the input qc.append(qft_gate(input_size).on(*qr)) # End with Hadamard on all qubits (to measure the z rotations) ''' don't do this unless NOT doing the inverse afterwards for i_qubit in range(input_size): qc.h(qr[i_qubit]) qc.barrier() ''' # some compilers recognize the QFT and IQFT in series and collapse them to identity; # perform a set of rotations to add one to the secret_int to avoid this collapse for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.append(cirq.rz( 1 * math.pi / divisor).on(qr[i_q])) num_gates+=1 # to revert back to initial state, apply inverse QFT qc.append(inv_qft_gate(input_size).on(*qr)) elif method == 2: for i_q in range(0, num_qubits): qc.append(cirq.H(qr[i_q])) num_gates += 1 for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.append(cirq.rz(secret_int * math.pi / divisor)(qr[i_q])) num_gates += 1 depth += 1 qc.append(inv_qft_gate(input_size).on(*qr)) # This method is a work in progress elif method==3: for i_q in range(0, secret_int): qc.append(cirq.H(qr[i_q])) num_gates+=1 for i_q in range(secret_int, num_qubits): qc.append(cirq.X(qr[i_q])) num_gates+=1 depth += 1 qc.append(inv_qft_gate(input_size).on(*qr)) else: exit("Invalid QFT method") # measure all qubits qc.append(cirq.measure(*[qr[i_qubit] for i_qubit in range(num_qubits)], key='result')) num_gates += num_qubits depth += 1 # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc def qft_gate(input_size): global QFT_, num_gates, depth # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(input_size)] qc = cirq.Circuit() # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) qc.append(cirq.CZ(qr[hidx],qr[input_size - j - 1])**(1.0/divisor)) num_gates += 1 depth += 1 # followed by an H gate (applied to all qubits) qc.append(cirq.H(qr[hidx])) num_gates += 1 depth += 1 if QFT_ == None or input_size <= 5: if input_size < 9: QFT_ = qc return cirq_utils.to_gate(num_qubits=input_size, circ=qc, name="qft") ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(input_size)] qc = cirq.Circuit() # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.append(cirq.H(qr[hidx])) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.append(cirq.CZ(qr[hidx],qr[input_size - j - 1])**(-1.0/divisor)) num_gates += 1 depth += 1 if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_ = qc return cirq_utils.to_gate(num_qubits=input_size, circ=qc, name="inv_qft") # Define expected distribution calculated from applying the iqft to the prepared secret_int state def expected_dist(num_qubits, secret_int, counts): dist = {} s = num_qubits - secret_int for key in counts.keys(): if key[(num_qubits-secret_int):] == ''.zfill(secret_int): dist[key] = 1/(2**s) return dist ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots, method): # get measurement array and shot count measurements = result.measurements['result'] num_shots = len(measurements) # create counts distribution counts = defaultdict(lambda: 0) for row in measurements: counts["".join([str(x) for x in reversed(row)])] += 1 # For method 1, expected result is always the secret_int if method==1: # add one to the secret_int to compensate for the extra rotations done between QFT and IQFT secret_int_plus_one = (secret_int + 1) % (2 ** num_qubits) # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int_plus_one, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 2, expected result is always the secret_int elif method==2: # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 3, correct_dist is a distribution with more than one value elif method==3: # correct_dist is from the expected dist correct_dist = expected_dist(num_qubits, secret_int, counts) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) if verbose: print(f"For secret int {secret_int} measured: {counts} fidelity: {fidelity}") return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits = 2, max_qubits = 8, max_circuits = 3, num_shots=100, method=1, backend_id='qasm_simulator', provider_backend=None): print("Quantum Fourier Transform Benchmark Program - Cirq") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, input_size, s_int, num_shots): # determine fidelity of result set num_qubits = int(input_size) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots, method) metrics.store_metric(input_size, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1): num_qubits = input_size # determine number of circuits to execute for this group # and determine range of secret strings to loop over if method == 1 or method == 2: num_circuits = min(2 ** (input_size), max_circuits) if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) elif method == 3: num_circuits = min(input_size, max_circuits) if input_size <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(range(input_size), num_circuits, False) else: exit("Invalid QFT method") print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = QuantumFourierTransform(num_qubits, s_int, method=method) metrics.store_metric(input_size, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, input_size, s_int, num_shots) print(f"... number of gates, depth = {num_gates}, {depth}") # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(input_size) metrics.report_metrics_for_group(input_size) # Alternatively, execute all circuits, aggregate and report metrics #ex.execute_circuits() #metrics.aggregate_metrics_for_group(input_size) #metrics.report_metrics_for_group(input_size) # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method==1: print("\nQFT Circuit ="); print(QFT_) print("\nInverse QFT Circuit ="); print(QFTI_) # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Quantum Fourier Transform - Cirq") # if main, execute method if __name__ == '__main__': run()
11,470
32.837758
106
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/phase-estimation/braket/pe_benchmark.py
""" Phase Estimation Benchmark Program - Braket """ import time import sys from braket.circuits import Circuit # AWS imports: Import Braket SDK modules import numpy as np sys.path[1:1] = ["_common", "_common/braket", "quantum-fourier-transform/braket"] sys.path[1:1] = ["../../_common", "../../_common/braket", "../../quantum-fourier-transform/braket"] import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate np.random.seed(0) verbose = False # saved circuits for display QC_ = None QFTI_ = None U_ = None ############### Circuit Definition def PhaseEstimation(num_qubits, theta): num_counting_qubits = num_qubits - 1 # only 1 state qubit qc = Circuit() # initialize counting qubits in superposition for i_qubit in range(num_counting_qubits): qc.h(i_qubit) # change to |1> in state qubit, so phase will be applied by cphase gate qc.x(num_counting_qubits) repeat = 1 for j in reversed(range(num_counting_qubits)): # controlled operation: adds phase exp(i*2*pi*theta) to the state |1> # does nothing to state |0> # needs additional factor of 2 as crz has half the phase of cphase crz_gate(qc, 2*2*np.pi*theta*repeat, j, num_counting_qubits) repeat *= 2 # inverse quantum Fourier transform only on counting qubits qfti = inv_qft_gate(num_counting_qubits) qc.add(qfti) # save smaller circuit example for display global QC_, U_, QFTI_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc #if U_ == None or num_qubits <= 5: #if num_qubits < 9: U_ = U if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # return a handle on the circuit return qc ############### CRZ shim # Implement the CRZ with RZs and CNOTs def crz_gate(qc, theta, control_qubit, target_qubit): qc.rz(target_qubit, theta/2) qc.cnot(control_qubit, target_qubit) qc.rz(target_qubit, -theta/2) qc.cnot(control_qubit, target_qubit) ############### Result Data Analysis # Analyze and print measured results def analyze_and_print_result (qc, result, num_counting_qubits, theta): # obtain shots from the result metadata num_shots = result.task_metadata.shots # obtain counts from the result object # for braket, need to reverse the key to match binary order # for braket, measures all qubits, so we have to remove data qubit measurement counts_r = result.measurement_counts counts_str = {} for measurement_r in counts_r.keys(): measurement = measurement_r[:-1][::-1] # remove data qubit and reverse order if measurement in counts_str: counts_str[measurement] += counts_r[measurement_r] else: counts_str[measurement] = counts_r[measurement_r] # get results as times a particular theta was measured counts = bitstring_to_theta(counts_str, num_counting_qubits) if verbose: print(f"For theta value {theta}, measured thetas: {counts}") # correct distribution is measuring theta 100% of the time correct_dist = {theta: 1.0} # generate thermal_dist with amplitudes instead, to be comparable to correct_dist bit_thermal_dist = metrics.uniform_dist(num_counting_qubits) thermal_dist = bitstring_to_theta(bit_thermal_dist, num_counting_qubits) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) return counts, fidelity def bitstring_to_theta(counts, num_counting_qubits): theta_counts = {} for key in counts.keys(): r = counts[key] theta = int(key,2) / (2**num_counting_qubits) if theta not in theta_counts.keys(): theta_counts[theta] = 0 theta_counts[theta] += r return theta_counts ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_qubits=8, max_circuits=3, num_shots=100, backend_id='simulator'): print("Phase Estimation Benchmark Program - Braket") num_state_qubits = 1 # default, not exposed to users, cannot be changed in current implementation # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, theta): # determine fidelity of result set num_counting_qubits = int(num_qubits) - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(theta)) metrics.store_metric(num_qubits, theta, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2**(num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # generate theta to always be a multiple of 1/2^N theta = np.random.choice(2**(num_counting_qubits)) / 2**(num_counting_qubits) # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))] else: theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)] # loop over limited # of random theta choices for theta in theta_range: # create the circuit for given qubit size and theta, store time metric ts = time.time() qc = PhaseEstimation(num_qubits, theta) metrics.store_metric(num_qubits, theta, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, theta, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics #ex.execute_circuits() #metrics.aggregate_metrics_for_group(num_qubits) #metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Phase Estimation - Braket") # if main, execute method if __name__ == '__main__': run()
7,572
35.941463
129
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/phase-estimation/qiskit/pe_benchmark.py
""" Phase Estimation Benchmark Program - Qiskit """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate np.random.seed(0) verbose = False # saved subcircuits circuits for printing QC_ = None QFTI_ = None U_ = None ############### Circuit Definition def PhaseEstimation(num_qubits, theta): qr = QuantumRegister(num_qubits) num_counting_qubits = num_qubits - 1 # only 1 state qubit cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr, cr) # initialize counting qubits in superposition for i in range(num_counting_qubits): qc.h(qr[i]) # change to |1> in state qubit, so phase will be applied by cphase gate qc.x(num_counting_qubits) qc.barrier() repeat = 1 for j in reversed(range(num_counting_qubits)): # controlled operation: adds phase exp(i*2*pi*theta*repeat) to the state |1> # does nothing to state |0> cp, _ = CPhase(2*np.pi*theta, repeat) qc.append(cp, [j, num_counting_qubits]) repeat *= 2 #Define global U operator as the phase operator _, U = CPhase(2*np.pi*theta, 1) qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr[:num_counting_qubits]) qc.barrier() # measure counting qubits qc.measure([qr[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_, U_, QFTI_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if U_ == None or num_qubits <= 5: if num_qubits < 9: U_ = U if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) return qc #Construct the phase gates and include matching gate representation as readme circuit def CPhase(angle, exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") qc.p(angle*exponent, 0) phase_gate = qc.to_gate().control(1) return phase_gate, qc # Analyze and print measured results # Expected result is always theta, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, theta, num_shots): # get results as measured counts counts = result.get_counts(qc) # calculate expected output histogram correct_dist = theta_to_bitstring(theta, num_counting_qubits) # generate thermal_dist to be comparable to correct_dist thermal_dist = metrics.uniform_dist(num_counting_qubits) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring theta correctly 100% of the time app_counts = bitstring_to_theta(counts, num_counting_qubits) app_correct_dist = {theta: 1.0} app_thermal_dist = bitstring_to_theta(thermal_dist, num_counting_qubits) if verbose: print(f"For theta {theta}, expected: {correct_dist} measured: {counts}") print(f" ... For theta {theta} thermal_dist: {thermal_dist}") print(f"For theta {theta}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For theta {theta} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) hf_fidelity = metrics.hellinger_fidelity_with_expected(counts, correct_dist) if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return counts, fidelity # Convert theta to a bitstring distribution def theta_to_bitstring(theta, num_counting_qubits): counts = {format( int(theta * (2**num_counting_qubits)), "0"+str(num_counting_qubits)+"b"): 1.0} return counts # Convert bitstring to theta representation, useful for debugging def bitstring_to_theta(counts, num_counting_qubits): theta_counts = {} for key in counts.keys(): r = counts[key] theta = int(key,2) / (2**num_counting_qubits) if theta not in theta_counts.keys(): theta_counts[theta] = 0 theta_counts[theta] += r return theta_counts ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_qubits=8, max_circuits=3, skip_qubits=1, num_shots=100, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Phase Estimation Benchmark Program - Qiskit") num_state_qubits = 1 # default, not exposed to users, cannot be changed in current implementation # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: PE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, theta, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(theta), num_shots) metrics.store_metric(num_qubits, theta, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))] else: theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)] # loop over limited # of random theta choices for theta in theta_range: # create the circuit for given qubit size and theta, store time metric ts = time.time() qc = PhaseEstimation(num_qubits, theta) metrics.store_metric(num_qubits, theta, 'create_time', time.time() - ts) # collapse the 3 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, theta, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nPhase Operator 'U' = "); print(U_ if U_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Phase Estimation - Qiskit") # if main, execute method if __name__ == '__main__': run()
8,723
37.263158
129
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/phase-estimation/cirq/pe_benchmark.py
""" Phase Estimation Benchmark Program - Cirq """ from collections import defaultdict import sys import time import cirq import numpy as np sys.path[1:1] = ["_common", "_common/cirq", "quantum-fourier-transform/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq", "../../quantum-fourier-transform/cirq"] import cirq_utils as cirq_utils import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate np.random.seed(0) verbose = False # saved circuits for display QC_ = None QFTI_ = None U_ = None ############### Circuit Definition def PhaseEstimation(num_qubits, theta): qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() num_counting_qubits = num_qubits - 1 # only 1 state qubit # initialize counting qubits in superposition qc.append(cirq.H.on_each(*qr[:num_counting_qubits])) # change to |1> in state qubit, so phase will be applied by cphase gate qc.append(cirq.X(qr[num_counting_qubits])) repeat = 1 for j in reversed(range(num_counting_qubits)): # controlled operation: adds phase exp(i*2*pi*theta) to the state |1> # does nothing to state |0> cp, _ = CPhase(2*np.pi*theta, repeat) qc.append(cp.on(qr[j], qr[num_counting_qubits])) repeat *= 2 #Define global U operator as the phase operator _, U = CPhase(2*np.pi*theta, 1) # inverse quantum Fourier transform only on counting qubits QFT_inv_gate = inv_qft_gate(num_counting_qubits) qc.append(QFT_inv_gate.on(*qr[:num_counting_qubits])) # measure counting qubits qc.append(cirq.measure(*qr[:num_counting_qubits], key='result')) # save smaller circuit example for display global QC_, U_, QFTI_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if U_ == None or num_qubits <= 5: if num_qubits < 9: U_ = U if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # return a handle on the circuit return qc #Construct the phase gates and include matching gate representation as readme circuit def CPhase(angle, exponent): qr = cirq.GridQubit.rect(1,1,0) qc = cirq.Circuit() qc.append(cirq.ZPowGate(exponent=angle*exponent/np.pi).on(qr[0])) U_gate = cirq_utils.to_gate(num_qubits=1, circ=qc, name=f"U^{exponent}") phase_gate = cirq.ops.ControlledGate(U_gate, num_controls=1) return phase_gate, qc # Analyze and print measured results def analyze_and_print_result(qc, result, num_counting_qubits, theta, num_shots): measurements = result.measurements['result'] counts_str = defaultdict(lambda: 0) for row in measurements: counts_str["".join([str(x) for x in reversed(row)])] += 1 # get results as times a particular theta was measured counts = bitstring_to_theta(counts_str, num_counting_qubits) if verbose: print(f"For theta value {theta}, measured: {counts}") # correct distribution is measuring theta 100% of the time correct_dist = {theta: 1.0} # generate thermal_dist with amplitudes instead, to be comparable to correct_dist bit_thermal_dist = metrics.uniform_dist(num_counting_qubits) thermal_dist = bitstring_to_theta(bit_thermal_dist, num_counting_qubits) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) return counts, fidelity def bitstring_to_theta(counts, num_counting_qubits): theta_counts = {} for key in counts.keys(): r = counts[key] theta = int(key,2) / (2**num_counting_qubits) if theta not in theta_counts.keys(): theta_counts[theta] = 0 theta_counts[theta] += r return theta_counts ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_qubits=8, max_circuits=3, num_shots=100, backend_id='simulator', provider_backend=None): print("Phase Estimation Benchmark Program - Cirq") num_state_qubits = 1 # default, not exposed to users, cannot be changed in current implementation # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, theta, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(theta), num_shots) metrics.store_metric(num_qubits, theta, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # ex.set_noise_model() # ex.set_noise_model(noise_model = "DEFAULT") # depolarizing noise # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # generate theta to always be a multiple of 1/2^N theta = np.random.choice(2**(num_counting_qubits)) / 2**(num_counting_qubits) # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))] else: theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)] # loop over limited # of random theta choices for theta in theta_range: # create the circuit for given qubit size and theta, store time metric ts = time.time() qc = PhaseEstimation(num_qubits, theta) metrics.store_metric(num_qubits, theta, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, theta, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(input_size) # metrics.report_metrics_for_group(input_size) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nPhase Operator 'U' = "); print(U_ if U_ != None else " ... too large!") qr_state = [cirq.GridQubit(i, 0) for i in range(QFTI_.num_qubits)] # we need to create registers to print circuits in cirq print("\nInverse QFT Circuit ="); print(cirq.Circuit(cirq.decompose(QFTI_.on(*qr_state))) if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Phase Estimation - Cirq") # if main, execute method if __name__ == '__main__': run()
8,006
36.947867
135
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/bernstein-vazirani/braket/bv_benchmark.py
""" Bernstein-Vazirani Benchmark Program - Braket """ import sys import time from braket.circuits import Circuit # AWS imports: Import Braket SDK modules import numpy as np sys.path[1:1] = [ "_common", "_common/braket" ] sys.path[1:1] = [ "../../_common", "../../_common/braket" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition def create_oracle(input_size, secret_int): qc = Circuit() # perform CX for each qubit that matches a bit in secret string s = ('{0:0'+str(input_size)+'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size-1-i_qubit]=='1': qc.cnot(i_qubit, input_size) #qc = braket_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") return qc def BersteinVazirani (num_qubits, secret_int): # size of input is one less than available qubits input_size = num_qubits - 1 qc = Circuit() # put ancilla in superposition qc.x(num_qubits-1) # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(i_qubit) Uf = create_oracle(input_size, secret_int) qc.add(Uf) # end with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(i_qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) # save smaller circuit example for display global QC_, Uf_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int): # size of input is one less than available qubits input_size = num_qubits - 1 # obtain shots from the result metadata num_shots = result.task_metadata.shots # obtain counts from the result object # for braket, need to reverse the key to match binary order # for braket, measures all qubits, so we have to remove data qubit measurement counts_r = result.measurement_counts counts = {} for measurement_r in counts_r.keys(): measurement = measurement_r[:-1][::-1] # remove data qubit and reverse order if measurement in counts: counts[measurement] += counts_r[measurement_r] else: counts[measurement] = counts_r[measurement_r] if verbose: print(f"For secret int {secret_int} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{input_size}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=6, max_circuits=3, num_shots=100, backend_id='simulator'): print("Bernstein-Vazirani Benchmark Program - Braket") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int)) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2**(input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = BersteinVazirani(num_qubits, s_int) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics #ex.execute_circuits() #metrics.aggregate_metrics_for_group(num_qubits) #metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Bernstein-Vazirani - Braket") # if main, execute method if __name__ == '__main__': run()
6,356
32.81383
99
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/bernstein-vazirani/qiskit/bv_benchmark.py
""" Bernstein-Vazirani Benchmark Program - Qiskit """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qiskit" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition def create_oracle(num_qubits, input_size, secret_int): # Initialize first n qubits and single ancilla qubit qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size - 1 - i_qubit] == '1': qc.cx(qr[i_qubit], qr[input_size]) return qc def BersteinVazirani (num_qubits, secret_int, method = 1): # size of input is one less than available qubits input_size = num_qubits - 1 if method == 1: # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main") # put ancilla in |1> state qc.x(qr[input_size]) # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() #generate Uf oracle Uf = create_oracle(num_qubits, input_size, secret_int) qc.append(Uf,qr) qc.barrier() # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # uncompute ancilla qubit, not necessary for algorithm qc.x(qr[input_size]) qc.barrier() # measure all data qubits for i in range(input_size): qc.measure(i, i) global Uf_ if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf elif method == 2: # allocate qubits qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main") # put ancilla in |-> state qc.x(qr[1]) qc.h(qr[1]) qc.barrier() # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i in range(input_size): if s[input_size - 1 - i] == '1': qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[i]) # Perform num_resets reset operations qc.reset([0]*num_resets) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): # size of input is one less than available qubits input_size = num_qubits - 1 # obtain counts from the result object counts = result.get_counts(qc) if verbose: print(f"For secret int {secret_int} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{input_size}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=6, max_circuits=3, num_shots=100, backend_id='qasm_simulator', method = 1, provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Bernstein-Vazirani Benchmark Program - Qiskit") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = True if method ==2 else False # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2**(input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits if method == 2: mid_circuit_qubit_group.append(2) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = BersteinVazirani(num_qubits, s_int, method) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Bernstein-Vazirani ({method}) - Qiskit", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()
7,840
33.69469
118
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/bernstein-vazirani/cirq/bv_benchmark.py
""" Bernstein-Vazirani Benchmark Program - Cirq """ from collections import defaultdict import sys import time import cirq import numpy as np sys.path[1:1] = [ "_common", "_common/cirq" ] sys.path[1:1] = [ "../../_common", "../../_common/cirq" ] import cirq_utils as cirq_utils import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition def create_oracle(num_qubits, input_size, secret_int): # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() # perform CX for each qubit that matches a bit in secret string CNOT_exist = False s = ('{0:0'+str(input_size)+'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size-1-i_qubit]=='1': qc.append(cirq.CNOT(qr[i_qubit], qr[input_size])) CNOT_exist = True else: qc.append(cirq.I(qr[i_qubit])) # Add identity to target qubit if no CNOT gate added if not CNOT_exist: qc.append(cirq.I(qr[input_size])) return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") def BersteinVazirani (num_qubits, secret_int): # size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() # put ancilla in superposition qc.append(cirq.X(qr[num_qubits-1])) # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.append(cirq.H(qr[i_qubit])) #generate Uf oracle Uf = create_oracle(num_qubits, input_size, secret_int) qc.append(Uf.on(*qr)) # end with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.append(cirq.H(qr[i_qubit])) # uncompute ancilla qubit, not necessary for algorithm qc.append(cirq.X(qr[input_size])) # measure all data qubits qc.append(cirq.measure(*[qr[i_qubit] for i_qubit in range(input_size)], key='result')) # save smaller circuit example for display global QC_, Uf_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): # size of input is one less than available qubits input_size = num_qubits - 1 # get measurement array measurements = result.measurements['result'] # create counts distribution counts = defaultdict(lambda: 0) for row in measurements: counts["".join([str(x) for x in reversed(row)])] += 1 if verbose: print(f"For secret int {secret_int} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{input_size}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=6, max_circuits=3, num_shots=100, backend_id='simulator', provider_backend=None): print("Bernstein-Vazirani Benchmark Program - Cirq") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module with the result handler ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2**(input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = BersteinVazirani(num_qubits, s_int) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics #ex.execute_circuits() #metrics.aggregate_metrics_for_group(num_qubits) #metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") qr_state = [cirq.GridQubit(i, 0) for i in range(Uf_.num_qubits)] # we need to create registers to print circuits in cirq print("\nQuantum Oracle 'Uf' ="); print(cirq.Circuit(cirq.decompose(Uf_.on(*qr_state))) if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Bernstein-Vazirani - Cirq") # if main, execute method if __name__ == '__main__': run()
6,711
33.244898
130
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/monte-carlo/_common/mc_utils.py
from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit from collections.abc import Iterable import functools import math import random import numpy as np import copy ########## Classical math functions def gaussian_dist(num_state_qubits, mu, sigma=0.3): if mu > 1: mu = 1 if mu < 0: mu = 0 if sigma < 1e-3: sigma = 1e-3 dist = {} normalization = 0.5 * (math.erf((1-mu)/(np.sqrt(2)*sigma)) - math.erf((0-mu)/(np.sqrt(2)*sigma))) for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) a = (i)/(2**num_state_qubits) b = (i+1)/(2**num_state_qubits) dist[key] = 0.5/normalization * (math.erf((b-mu)/(np.sqrt(2)*sigma)) - math.erf((a-mu)/(np.sqrt(2)*sigma))) return dist def linear_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = (2*i+1)/(2**(2*num_state_qubits)) return dist def power_f(i, num_state_qubits, power): if isinstance(i, Iterable): out = [] for val in i: out.append((val / ((2**num_state_qubits) - 1))**power) return np.array(out) else: return (i / ((2**num_state_qubits) - 1))**power def estimated_value(target_dist, f): avg = 0 for key in target_dist.keys(): x = int(key,2) avg += target_dist[key]*f(x) return avg def zeta_from_f(i, func, epsilon, degree, c): """ Intermediate polynomial derived from f to serve as angle for controlled Ry gates. """ rad = np.sqrt(c*(func(i) - 0.5) + 0.5) return np.arcsin(rad) def simplex(n, k): """ Get all ordered combinations of n integers (zero inclusive) which add up to k; the n-dimensional k simplex. """ if k == 0: z = [0]*n return [z] l = [] for p in simplex(n,k-1): for i in range(n): a = p[i]+1 ns = copy.copy(p) ns[i] = a if ns not in l: l.append(ns) return l def binary_expansion(num_state_qubits, poly): """ Convert a polynomial into expression replacing x with its binary decomposition x_0 + 2 x_1 + 4 x_2 + ... Simplify using (x_i)^p = x_i for all integer p > 0 and collect coefficients of equivalent expression """ n = num_state_qubits if isinstance(poly, Polynomial): poly_c = poly.coef else: poly_c = poly out_front = {} out_front[()] = poly_c[0] for k in range(1,len(poly_c)): for pow_list in simplex(n,k): two_exp, denom, t = 0, 1, 0 for power in pow_list: two_exp += t*power denom *= np.math.factorial(power) t+=1 nz = np.nonzero(pow_list)[0] key = tuple(nz) if key not in out_front.keys(): out_front[key] = 0 out_front[key] += poly_c[k]*((np.math.factorial(k) / denom) * (2**(two_exp))) return out_front def starting_regions(num_state_qubits): """ For use in bisection search for state preparation subroutine. Fill out the necessary region labels for num_state_qubits. """ sub_regions = [] sub_regions.append(['1']) for d in range(1,num_state_qubits): region = [] for i in range(2**d): key = bin(i)[2:].zfill(d) + '1' region.append(key) sub_regions.append(region) return sub_regions def region_probs(target_dist, num_state_qubits): """ Fetch bisected region probabilities for the desired probability distribution {[p1], [p01, p11], [p001, p011, p101, p111], ...}. """ regions = starting_regions(num_state_qubits) probs = {} n = len(regions) for k in range(n): for string in regions[k]: p = 0 b = n-k-1 for i in range(2**b): subkey = bin(i)[2:].zfill(b) if b == 0: subkey = '' try: p += target_dist[string+subkey] except KeyError: pass probs[string] = p return probs def mc_dist(num_counting_qubits, exact, c_star, method): """ Creates the probabilities of measurements we should get from the phase estimation routine Taken from Eq. (5.25) in Nielsen and Chuang """ # shift exact value into phase phi which the phase estimation approximates if method == 1: unshifted_exact = ((exact - 0.5)*c_star) + 0.5 elif method == 2: unshifted_exact = exact phi = np.arcsin(np.sqrt(unshifted_exact))/np.pi dist = {} precision = int(num_counting_qubits / (np.log2(10))) + 2 for b in range(2**num_counting_qubits): # Eq. (5.25), gives probability for measuring an integer (b) after phase estimation routine # if phi is too close to b, results in 0/0, but acutally should be 1 if abs(phi-b/(2**num_counting_qubits)) > 1e-6: prob = np.abs(((1/2)**num_counting_qubits) * (1-np.exp(2j*np.pi*(2**num_counting_qubits*phi-b))) / (1-np.exp(2j*np.pi*(phi-b/(2**num_counting_qubits)))))**2 else: prob = 1.0 # calculates the predicted expectation value if measure b in the counting qubits a_meas = pow(np.sin(np.pi*b/pow(2,num_counting_qubits)),2) if method == 1: a = ((a_meas - 0.5)/c_star) + 0.5 elif method == 2: a = a_meas a = round(a, precision) # generates distribution of expectation values and their relative probabilities if a not in dist.keys(): dist[a] = 0 dist[a] += prob return dist def value_and_max_prob_from_dist(dist): """ Returns the max probability and value from a distribution: Ex: From: {0.0: 0.1, 0.33: 0.4, 0.66: 0.2, 1.0: 0.3} Returns: (0.33, 0.4) """ value = max(dist, key = dist.get) max_prob = dist[value] return value, max_prob
6,152
28.581731
168
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/monte-carlo/qiskit/mc_benchmark.py
""" Monte Carlo Sampling Benchmark Program via Amplitude Estimation- Qiskit """ import copy import functools import sys import time import numpy as np from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library.standard_gates.ry import RYGate sys.path[1:1] = ["_common", "_common/qiskit", "monte-carlo/_common", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../monte-carlo/_common", "../../quantum-fourier-transform/qiskit"] import execute as ex import mc_utils as mc_utils import metrics as metrics from qft_benchmark import inv_qft_gate np.random.seed(0) # default function is f(x) = x^2 f_of_X = functools.partial(mc_utils.power_f, power=2) # default distribution is gaussian distribution p_distribution = mc_utils.gaussian_dist verbose = False # saved circuits and subcircuits for display A_ = None Q_ = None cQ_ = None QC_ = None R_ = None F_ = None QFTI_ = None ############### Circuit Definition def MonteCarloSampling(target_dist, f, num_state_qubits, num_counting_qubits, epsilon=0.05, degree=2, method=2): A_qr = QuantumRegister(num_state_qubits+1) A = QuantumCircuit(A_qr, name=f"A") num_qubits = num_state_qubits + 1 + num_counting_qubits # initialize R and F circuits R_qr = QuantumRegister(num_state_qubits+1) F_qr = QuantumRegister(num_state_qubits+1) R = QuantumCircuit(R_qr, name=f"R") F = QuantumCircuit(F_qr, name=f"F") # method 1 takes in the abitrary function f and arbitrary dist if method == 1: state_prep(R, R_qr, target_dist, num_state_qubits) f_on_objective(F, F_qr, f, epsilon=epsilon, degree=degree) # method 2 chooses to have lower circuit depth by choosing specific f and dist elif method == 2: uniform_prep(R, R_qr, num_state_qubits) square_on_objective(F, F_qr) # append R and F circuits to A A.append(R.to_gate(), A_qr) A.append(F.to_gate(), A_qr) # run AE subroutine given our A composed of R and F qc = AE_Subroutine(num_state_qubits, num_counting_qubits, A) # save smaller circuit example for display global QC_, R_, F_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if (R_ and F_) == None or num_state_qubits <= 3: if num_state_qubits < 5: R_ = R; F_ = F return qc ############### def f_on_objective(qc, qr, f, epsilon=0.05, degree=2): """ Assume last qubit is the objective. Function f is evaluated on first n-1 qubits """ num_state_qubits = qc.num_qubits - 1 c_star = (2*epsilon)**(1/(degree+1)) f_ = functools.partial(f, num_state_qubits=num_state_qubits) zeta_ = functools.partial(mc_utils.zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1) poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree)) b_exp = mc_utils.binary_expansion(num_state_qubits, poly) for controls in b_exp.keys(): theta = 2*b_exp[controls] controls = list(controls) if len(controls)==0: qc.ry(-theta, qr[num_state_qubits]) else: # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(len(controls)) qc.append(MCRY, [*(qr[i] for i in controls), qr[num_state_qubits]]) def square_on_objective(qc, qr): """ Assume last qubit is the objective. Shifted square wave function: if x is even, f(x) = 0; if x i s odd, f(x) = 1 """ num_state_qubits = qc.num_qubits - 1 for control in range(num_state_qubits): qc.cx(control, num_state_qubits) def state_prep(qc, qr, target_dist, num_state_qubits): """ Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i> """ r_probs = mc_utils.region_probs(target_dist, num_state_qubits) regions = r_probs.keys() r_norm = {} for r in regions: num_controls = len(r) - 1 super_key = r[:num_controls] if super_key=='': r_norm[super_key] = 1 elif super_key == '1': r_norm[super_key] = r_probs[super_key] r_norm['0'] = 1-r_probs[super_key] else: try: r_norm[super_key] = r_probs[super_key] except KeyError: r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1'] norm = r_norm[super_key] p = 0 if norm != 0: p = r_probs[r] / norm theta = 2*np.arcsin(np.sqrt(p)) if r == '1': qc.ry(-theta, num_state_qubits-1) else: controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)] # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(num_controls, ctrl_state=r[:-1]) qc.append(MCRY, [*controls, qr[num_state_qubits-1 - num_controls]]) def uniform_prep(qc, qr, num_state_qubits): """ Generates a uniform distribution over all states """ for i in range(num_state_qubits): qc.h(i) def AE_Subroutine(num_state_qubits, num_counting_qubits, A_circuit): qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_state, qr_counting, cr) A = A_circuit cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q if A_ == None or num_state_qubits <= 3: if num_state_qubits < 5: A_ = A if QFTI_ == None or num_counting_qubits <= 3: if num_counting_qubits < 4: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, qr_state) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) return qc ############################### # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc ######################################### # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, mu, num_shots, method, num_state_qubits): # generate exact value for the expectation value given our function and dist target_dist = p_distribution(num_state_qubits, mu) f = functools.partial(f_of_X, num_state_qubits=num_state_qubits) if method == 1: exact = mc_utils.estimated_value(target_dist, f) elif method == 2: exact = 0.5 # hard coded exact value from uniform dist and square function # obtain counts from the result object counts = result.get_counts(qc) # calculate the expected output histogram correct_dist = a_to_bitstring(exact, num_counting_qubits) # generate thermal_dist with amplitudes instead, to be comparable to correct_dist thermal_dist = metrics.uniform_dist(num_counting_qubits) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring the input a 100% of the time # convert bit_counts into expectation values counts according to Quantum Risk Analysis paper app_counts = expectation_from_bits(counts, num_counting_qubits, num_shots, method) app_correct_dist = mc_utils.mc_dist(num_counting_qubits, exact, c_star, method) app_thermal_dist = expectation_from_bits(thermal_dist, num_counting_qubits, num_shots, method) if verbose: print(f"For expected value {exact}, expected: {correct_dist} measured: {counts}") print(f" ... For expected value {exact} thermal_dist: {thermal_dist}") print(f"For expected value {exact}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For expected value {exact} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) hf_fidelity = metrics.hellinger_fidelity_with_expected(counts, correct_dist) ########################################################################### # NOTE: in this benchmark, we are testing how well the amplitude estimation routine # works according to theory, and we do not measure the difference between # the reported answer and the correct answer; the below code just helps # demonstrate that we do approximate the expectation value accurately. # the max in the counts is what the algorithm would report as the correct answer a, _ = mc_utils.value_and_max_prob_from_dist(counts) if verbose: print(f"For expected value {exact} measured: {a}") ########################################################################### if verbose: print(f"Solution counts: {counts}") if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return counts, fidelity def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def expectation_from_bits(bits, num_qubits, num_shots, method): amplitudes = {} for b in bits.keys(): precision = int(num_qubits / (np.log2(10))) + 2 r = bits[b] a_meas = pow(np.sin(np.pi*int(b,2)/pow(2,num_qubits)),2) if method == 1: a = ((a_meas - 0.5)/c_star) + 0.5 if method == 2: a = a_meas a = round(a, precision) if a not in amplitudes.keys(): amplitudes[a] = 0 amplitudes[a] += r return amplitudes ################ Benchmark Loop MIN_QUBITS = 4 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS = 1 # set minimums for method 1 MIN_QUBITS_M1 = 5 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS_M1 = 2 # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=10 # Execute program with default parameters def run(min_qubits=MIN_QUBITS, max_qubits=10, max_circuits=1, num_shots=100, epsilon=0.05, degree=2, num_state_qubits=MIN_STATE_QUBITS, method = 2, # default, not exposed to users backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Monte Carlo Sampling Benchmark Program - Qiskit") print(f"... using circuit method {method}") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: Monte Carlo Sampling benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS if (method == 2): if max_qubits < MIN_QUBITS: print(f"INFO: Monte Carlo Simulation benchmark method ({method}) requires a minimum of {MIN_QUBITS} qubits.") return if min_qubits < MIN_QUBITS: min_qubits = MIN_QUBITS elif (method == 1): if max_qubits < MIN_QUBITS_M1: print(f"INFO: Monte Carlo Simulation benchmark method ({method}) requires a minimum of {MIN_QUBITS_M1} qubits.") return if min_qubits < MIN_QUBITS_M1: min_qubits = MIN_QUBITS_M1 if (method == 1) and (num_state_qubits == MIN_STATE_QUBITS): num_state_qubits = MIN_STATE_QUBITS_M1 ### TODO: need to do more validation of arguments, e.g. min_state_qubits and min_qubits # Initialize metrics module metrics.init_metrics() global c_star c_star = (2*epsilon)**(1/(degree+1)) # Define custom result handler def execution_handler(qc, result, num_qubits, mu, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits -1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(mu), num_shots, method=method, num_state_qubits=num_state_qubits) metrics.store_metric(num_qubits, mu, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # reset random seed np.random.seed(0) input_size = num_qubits - 1 # TODO: keep using inputsize? only used in num_circuits # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) #print(num_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of circuits to loop over for method 1 if 2**(input_size) <= max_circuits: mu_range = [i/2**(input_size) for i in range(num_circuits)] else: mu_range = [i/2**(input_size) for i in np.random.choice(2**(input_size), num_circuits, False)] #print(mu_range) # loop over limited # of mu values for this for mu in mu_range: target_dist = p_distribution(num_state_qubits, mu) f_to_estimate = functools.partial(f_of_X, num_state_qubits=num_state_qubits) #print(mu) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = MonteCarloSampling(target_dist, f_to_estimate, num_state_qubits, num_counting_qubits, epsilon, degree, method=method) metrics.store_metric(num_qubits, mu, 'create_time', time.time() - ts) # collapse the 4 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, mu, num_shots) # if method is 2, we only have one type of circuit, so break out of loop #if method == 2: # break # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nDistribution Generator 'R' ="); print(R_ if R_ != None else " ... too large!") print("\nFunction Generator 'F' ="); print(F_ if F_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Monte Carlo Sampling ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run()
18,202
37.08159
156
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/monte-carlo/cirq/mc_benchmark.py
""" Monte Carlo Sampling Benchmark Program via Amplitude Estimation- Cirq """ from collections import defaultdict import copy import functools import sys import time import cirq import numpy as np from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit sys.path[1:1] = ["_common", "_common/cirq", "monte-carlo/_common", "quantum-fourier-transform/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq", "../../monte-carlo/_common", "../../quantum-fourier-transform/cirq"] import cirq_utils as cirq_utils import execute as ex import mc_utils as mc_utils import metrics as metrics from qft_benchmark import inv_qft_gate np.random.seed(0) # default function is f(x) = x^2 f_of_X = functools.partial(mc_utils.power_f, power=2) # default distribution is gaussian distribution p_distribution = mc_utils.gaussian_dist verbose = False # saved subcircuits circuits for printing A_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def MonteCarloSampling(target_dist, f, num_state_qubits, num_counting_qubits, epsilon=0.05, degree=2, method=2): A_qr = [cirq.GridQubit(i, 0) for i in range(num_state_qubits+1)] A = cirq.Circuit() num_qubits = num_state_qubits + 1 + num_counting_qubits # method 1 takes in the abitrary function f and arbitrary dist if method == 1: state_prep(A, A_qr, target_dist, num_state_qubits) f_on_objective(A, A_qr, f, epsilon=epsilon, degree=degree) # method 2 chooses to have lower circuit depth by choosing specific f and dist elif method == 2: uniform_prep(A, A_qr, num_state_qubits) square_on_objective(A, A_qr) qc = AE_Subroutine(num_state_qubits, num_counting_qubits, A) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc return qc ############### def f_on_objective(qc, qr, f, epsilon=0.05, degree=3): """ Assume last qubit is the objective. Function f is evaluated on first n-1 qubits """ num_state_qubits = len(qr) - 1 c_star = (2*epsilon)**(1/(degree+1)) f_ = functools.partial(f, num_state_qubits=num_state_qubits) zeta_ = functools.partial(mc_utils.zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1) poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree)) b_exp = mc_utils.binary_expansion(num_state_qubits, poly) for controls in b_exp.keys(): theta = 2*b_exp[controls] controls = list(controls) if len(controls)==0: qc.append(cirq.ry(-theta).on(qr[num_state_qubits])) else: qc.append(cirq.ry(-theta).controlled(num_controls=len(controls)).on(*[qr[i] for i in controls]+[qr[num_state_qubits]])) def square_on_objective(qc, qr): """ Assume last qubit is the objective. Shifted square wave function: if x is even, f(x) = 0; if x i s odd, f(x) = 1 """ num_state_qubits = len(qr) - 1 for control in range(num_state_qubits): qc.append(cirq.CX.on(qr[control], qr[num_state_qubits])) def state_prep(qc, qr, target_dist, num_state_qubits): """ Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i> """ r_probs = mc_utils.region_probs(target_dist, num_state_qubits) regions = r_probs.keys() r_norm = {} for r in regions: num_controls = len(r) - 1 super_key = r[:num_controls] if super_key=='': r_norm[super_key] = 1 elif super_key == '1': r_norm[super_key] = r_probs[super_key] r_norm['0'] = 1-r_probs[super_key] else: try: r_norm[super_key] = r_probs[super_key] except KeyError: r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1'] norm = r_norm[super_key] p = 0 if norm != 0: p = r_probs[r] / norm theta = -2*np.arcsin(np.sqrt(p)) if r == '1': qc.append(cirq.ry(theta).on(qr[num_state_qubits-1])) else: for k in range(num_controls): if r[k] == '0': qc.append(cirq.X.on(qr[num_state_qubits-1 - k])) controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)] qc.append(cirq.ry(theta).controlled(num_controls=num_controls).on(*controls+[qr[num_state_qubits-1-num_controls]])) for k in range(num_controls): if r[k] == '0': qc.append(cirq.X.on(qr[num_state_qubits-1 - k])) def uniform_prep(qc, qr, num_state_qubits): """ Generates a uniform distribution over all states """ for i in range(num_state_qubits): qc.append(cirq.H.on(qr[i])) def AE_Subroutine(num_state_qubits, num_counting_qubits, A_circuit): qr_state = cirq.GridQubit.rect(1,num_state_qubits+1,0) qr_counting = cirq.GridQubit.rect(1,num_counting_qubits,1) qc_full = cirq.Circuit() A = cirq_utils.to_gate(num_state_qubits+1, A_circuit, name="A") cQ, Q = Ctrl_Q(num_state_qubits, A_circuit) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if cQ_ == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ if (Q_ or A_) == None or num_state_qubits <= 3: if num_state_qubits < 5: A_ = A; Q_ = Q if QFTI_ == None or num_counting_qubits <= 3: if num_counting_qubits < 4: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc_full.append(A.on(*qr_state)) for i in range(num_counting_qubits): qc_full.append(cirq.H.on(qr_counting[i])) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc_full.append(cQ.on(*[qr_counting[j]]+qr_state)) repeat *= 2 # inverse quantum Fourier transform only on counting qubits QFT_inv_gate = inv_qft_gate(num_counting_qubits) qc_full.append(QFT_inv_gate.on(*qr_counting)) qc_full.append(cirq.measure(*qr_counting, key='result')) return qc_full ############################### # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qr_Q = cirq.GridQubit.rect(1,num_state_qubits+1,0) qc_Q = cirq.Circuit() A_gate = cirq_utils.to_gate(num_state_qubits+1, A_circ, name="A") A_gate_inv = cirq.inverse(copy.copy(A_gate)) ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc_Q.append(cirq.X(qr_Q[num_state_qubits])) qc_Q.append(cirq.Z(qr_Q[num_state_qubits])) qc_Q.append(cirq.X(qr_Q[num_state_qubits])) # A_circ_inverse qc_Q.append(A_gate_inv.on(*qr_Q)) # S_0 for i in range(num_state_qubits+1): qc_Q.append(cirq.X.on(qr_Q[i])) qc_Q.append(cirq.H(qr_Q[num_state_qubits])) qc_Q.append(cirq.X.controlled(num_controls=num_state_qubits).on(*qr_Q)) qc_Q.append(cirq.H(qr_Q[num_state_qubits])) for i in range(num_state_qubits+1): qc_Q.append(cirq.X.on(qr_Q[i])) # A_circ qc_Q.append(A_gate.on(*qr_Q)) # Create a gate out of the Q operator Q_ = cirq_utils.to_gate(num_qubits=num_state_qubits+1, circ=qc_Q, name="Q") # and also a controlled version of it Ctrl_Q_ = cirq.ops.ControlledGate(Q_, num_controls=1) # and return both return Ctrl_Q_, Q_ ######################################### # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, mu, num_shots, method, num_state_qubits): # generate exact value for the expectation value given our function and dist target_dist = p_distribution(num_state_qubits, mu) f = functools.partial(f_of_X, num_state_qubits=num_state_qubits) if method == 1: exact = mc_utils.estimated_value(target_dist, f) elif method == 2: exact = 0.5 # hard coded exact value from uniform dist and square function # obtain bit_counts from the result object measurements = result.measurements['result'] bit_counts = defaultdict(lambda: 0) for row in measurements: bit_counts["".join([str(x) for x in reversed(row)])] += 1 # convert bit_counts into expectation values counts according to Quantum Risk Analysis paper counts = expectation_from_bits(bit_counts, num_counting_qubits, num_shots, method) # calculate the distribution we should expect from the amplitude estimation routine correct_dist = mc_utils.mc_dist(num_counting_qubits, exact, c_star, method) # generate thermal_dist with amplitudes instead, to be comparable to correct_dist bit_thermal_dist = metrics.uniform_dist(num_counting_qubits) thermal_dist = expectation_from_bits(bit_thermal_dist, num_counting_qubits, num_shots, method) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) ########################################################################### # NOTE: in this benchmark, we are testing how well the amplitude estimation routine # works according to theory, and we do not measure the difference between # the reported answer and the correct answer; the below code just helps # demonstrate that we do approximate the expectation value accurately. # the max in the counts is what the algorithm would report as the correct answer a, _ = mc_utils.value_and_max_prob_from_dist(counts) if verbose: print(f"For expected value {exact} measured: {a}") ########################################################################### if verbose: print(f"Solution counts: {counts}") return counts, fidelity def expectation_from_bits(bits, num_qubits, num_shots, method): amplitudes = {} for b in bits.keys(): precision = int(num_qubits / (np.log2(10))) + 2 r = bits[b] a_meas = pow(np.sin(np.pi*int(b,2)/pow(2,num_qubits)),2) if method == 1: a = ((a_meas - 0.5)/c_star) + 0.5 if method == 2: a = a_meas a = round(a, precision) if a not in amplitudes.keys(): amplitudes[a] = 0 amplitudes[a] += r return amplitudes ################ Benchmark Loop MIN_QUBITS = 4 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS = 1 # set minimums for method 1 MIN_QUBITS_M1 = 5 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS_M1 = 2 # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=10 # Execute program with default parameters def run(min_qubits=MIN_QUBITS, max_qubits=10, max_circuits=1, num_shots=100, epsilon=0.05, degree=2, num_state_qubits=MIN_STATE_QUBITS, method=2, # default, not exposed to users backend_id='simulator', provider_backend=None): print("Monte Carlo Sampling Benchmark Program - Cirq") print(f"... using circuit method {method}") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: Monte Carlo Sampling benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS if (method == 2): if max_qubits < MIN_QUBITS: print(f"INFO: Monte Carlo Simulation benchmark method ({method}) requires a minimum of {MIN_QUBITS} qubits.") return if min_qubits < MIN_QUBITS: min_qubits = MIN_QUBITS elif (method == 1): if max_qubits < MIN_QUBITS_M1: print(f"INFO: Monte Carlo Simulation benchmark method ({method}) requires a minimum of {MIN_QUBITS_M1} qubits.") return if min_qubits < MIN_QUBITS_M1: min_qubits = MIN_QUBITS_M1 if (method == 1) and (num_state_qubits == MIN_STATE_QUBITS): num_state_qubits = MIN_STATE_QUBITS_M1 ### TODO: need to do more validation of arguments, e.g. min_state_qubits and min_qubits # Initialize metrics module metrics.init_metrics() global c_star c_star = (2*epsilon)**(1/(degree+1)) # Define custom result handler def execution_handler(qc, result, num_qubits, mu, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits -1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(mu), num_shots, method=method, num_state_qubits=num_state_qubits) metrics.store_metric(num_qubits, mu, 'fidelity', fidelity) # Initialize execution module with the result handler ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # TODO: keep using inputsize? only used in num_circuits # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of circuits to loop over for method 1 if 2**(input_size) <= max_circuits: mu_range = [i/2**(input_size) for i in range(num_circuits)] else: mu_range = [i/2**(input_size) for i in np.random.choice(2**(input_size), num_circuits, False)] # loop over limited # of mu values for this for mu in mu_range: target_dist = p_distribution(num_state_qubits, mu) f_to_estimate = functools.partial(f_of_X, num_state_qubits=num_state_qubits) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = MonteCarloSampling(target_dist, f_to_estimate, num_state_qubits, num_counting_qubits, epsilon, degree, method=method) metrics.store_metric(num_qubits, mu, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, mu, num_shots) # if method is 2, we only have one type of circuit, so break out of loop if method == 2: break # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") qr_state = cirq.GridQubit.rect(1,num_state_qubits+1,0) # we need to create registers to print circuits in cirq qr_control = cirq.GridQubit.rect(1,1,1) print("\nControlled Quantum Operator 'cQ' ="); print(cirq.Circuit(cQ_.on(qr_control[0], *qr_state)) if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(cirq.Circuit(cirq.decompose(Q_.on(*qr_state))) if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(cirq.Circuit(cirq.decompose(A_.on(*qr_state))) if A_ != None else " ... too large!") qr_state = cirq.GridQubit.rect(1,QFTI_.num_qubits,0) # we need to create registers to print circuits in cirq print("\nInverse QFT Circuit ="); print(cirq.Circuit(cirq.decompose(QFTI_.on(*qr_state))) if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Monte Carlo Sampling ({method}) - Cirq") # if main, execute method if __name__ == '__main__': run()
16,763
37.986047
156
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/deutsch-jozsa/braket/dj_benchmark.py
""" Deutsch-Jozsa Benchmark Program - Braket """ import sys import time from braket.circuits import Circuit # AWS imports: Import Braket SDK modules import numpy as np sys.path[1:1] = [ "_common", "_common/braket" ] sys.path[1:1] = [ "../../_common", "../../_common/braket" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle (input_size): qc = Circuit() output = np.random.randint(2) if output == 1: qc.x(input_size) #qc = braket_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") return qc # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle (input_size): qc = Circuit() b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) for qubit in range(input_size): qc.cnot(qubit, input_size) for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) #qc = braket_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") return qc # Create benchmark circuit def DeutschJozsa (num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qc = Circuit() for qubit in range(input_size): qc.h(qubit) qc.x(input_size) qc.h(input_size) #qc.barrier() # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size) else: Uf = balanced_oracle(input_size) qc.add(Uf) #qc.barrier() for qubit in range(num_qubits): qc.h(qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) # save smaller circuit example for display global QC_, Uf_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf # return a handle to the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the type, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # obtain shots from the result metadata num_shots = result.task_metadata.shots # obtain counts from the result object # for braket, need to reverse the key to match binary order # for braket, measures all qubits, so we have to remove data qubit measurement counts_r = result.measurement_counts counts = {} for measurement_r in counts_r.keys(): measurement = measurement_r[:-1][::-1] # remove data qubit and reverse order if measurement in counts: counts[measurement] += counts_r[measurement_r] else: counts[measurement] = counts_r[measurement_r] if verbose: print(f"For type {type} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=8, max_circuits=3, num_shots=100, backend_id='simulator'): print("Deutsch-Jozsa Benchmark Program - Braket") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type)) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over only 2 circuits for type in range( num_circuits ): # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type) metrics.store_metric(num_qubits, type, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, type, shots=num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics #ex.execute_circuits() #metrics.aggregate_metrics_for_group(num_qubits) #metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Deutsch-Jozsa - Braket") # if main, execute method if __name__ == '__main__': run()
6,511
30.765854
99
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/deutsch-jozsa/qiskit/dj_benchmark.py
""" Deutsch-Jozsa Benchmark Program - Qiskit """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qiskit" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None C_ORACLE_ = None B_ORACLE_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") output = np.random.randint(2) if output == 1: qc.x(input_size) global C_ORACLE_ if C_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: C_ORACLE_ = qc return qc # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) qc.barrier() for qubit in range(input_size): qc.cx(qubit, input_size) qc.barrier() for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) global B_ORACLE_ if B_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: B_ORACLE_ = qc return qc # Create benchmark circuit def DeutschJozsa (num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main") for qubit in range(input_size): qc.h(qubit) qc.x(input_size) qc.h(input_size) qc.barrier() # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size, num_qubits) else: Uf = balanced_oracle(input_size, num_qubits) qc.append(Uf, qr) qc.barrier() for qubit in range(num_qubits): qc.h(qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) qc.barrier() for i in range(input_size): qc.measure(i, i) # save smaller circuit and oracle subcircuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle to the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the type, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, type, num_shots): # Size of input is one less than available qubits input_size = num_qubits - 1 # obtain counts from the result object counts = result.get_counts(qc) if verbose: print(f"For type {type} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=8, max_circuits=3, num_shots=100, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Deutsch-Jozsa Benchmark Program - Qiskit") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over only 2 circuits for type in range( num_circuits ): # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type) metrics.store_metric(num_qubits, type, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, type, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nConstant Oracle 'Uf' ="); print(C_ORACLE_ if C_ORACLE_ != None else " ... too large or not used!") print("\nBalanced Oracle 'Uf' ="); print(B_ORACLE_ if B_ORACLE_ != None else " ... too large or not used!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Deutsch-Jozsa - Qiskit") # if main, execute method if __name__ == '__main__': run()
6,790
31.649038
114
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/deutsch-jozsa/cirq/dj_benchmark.py
""" Deutsch-Jozsa Benchmark Program - Cirq """ from collections import defaultdict import sys import time import cirq import numpy as np sys.path[1:1] = ["_common", "_common/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq"] import cirq_utils as cirq_utils import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle(input_size, num_qubits): #Initialize Quantum Circuit qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() #Added identities because cirq requires gates on each qubit for qubit in range(input_size): qc.append(cirq.I(qr[qubit])) #Add X Gate or Identity at random on last qubit for constant oracle output = np.random.randint(2) if output == 1: qc.append(cirq.X(qr[input_size])) else: qc.append(cirq.I(qr[input_size])) return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle(input_size, num_qubits): #Initialize Quantum Circuit qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.append(cirq.X(qr[qubit])) for qubit in range(input_size): qc.append(cirq.CX(qr[qubit], qr[input_size])) for qubit in range(input_size): if b_str[qubit] == '1': qc.append(cirq.X(qr[qubit])) return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") # Create benchmark circuit def DeutschJozsa(num_qubits, type): # size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() # start with flipping the ancilla to 1 qc.append(cirq.X(qr[input_size])) # Add Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.append(cirq.H(qr[i_qubit])) # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size, num_qubits) else: Uf = balanced_oracle(input_size, num_qubits) qc.append(Uf.on(*qr)) # end with Hadamard on all qubits, excluding ancilla for i_qubit in range(input_size): qc.append(cirq.H(qr[i_qubit])) # uncompute ancilla qubit, not necessary for algorithm qc.append(cirq.X(qr[input_size])) # measure all qubits, excluding ancilla qc.append(cirq.measure(*[qr[i_qubit] for i_qubit in range(input_size)], key='result')) # save smaller circuit example for display global QC_, Uf_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, type, num_shots): # Size of input is one less than available qubits input_size = num_qubits - 1 # get measurement array measurements = result.measurements['result'] # create counts distribution counts = defaultdict(lambda: 0) for row in measurements: counts["".join([str(x) for x in reversed(row)])] += 1 if verbose: print(f"For type {type} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_qubits=8, max_circuits=3, num_shots=100, backend_id='simulator', provider_backend=None): print("Deutsch-Jozsa Benchmark Program - Cirq") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module with the result handler ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over only 2 circuits for type in range( num_circuits ): # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type) metrics.store_metric(num_qubits, type, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, type, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(input_size) # metrics.report_metrics_for_group(input_size) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") qr_state = [cirq.GridQubit(i, 0) for i in range(Uf_.num_qubits)] # we need to create registers to print circuits in cirq print("\nQuantum Oracle 'Uf' ="); print(cirq.Circuit(cirq.decompose(Uf_.on(*qr_state))) if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Deutsch-Jozsa - Cirq") # if main, execute method if __name__ == '__main__': run()
7,283
32.412844
130
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hidden-shift/braket/hs_benchmark.py
""" Hidden Shift Benchmark Program - Braket """ import sys import time from braket.circuits import Circuit # AWS imports: Import Braket SDK modules import numpy as np sys.path[1:1] = [ "_common", "_common/braket" ] sys.path[1:1] = [ "../../_common", "../../_common/braket" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None Ug_ = None ############### Circuit Definition def Uf_oracle(num_qubits, secret_int): # allocate qubits qc = Circuit() # Perform X on each qubit that matches a bit in secret string s = ('{0:0' + str(num_qubits) + 'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits - 1 - i_qubit] == '1': qc.x(i_qubit) for i_qubit in range(0, num_qubits - 1, 2): qc.cz(i_qubit, i_qubit + 1) # Perform X on each qubit that matches a bit in secret string s = ('{0:0' + str(num_qubits) + 'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits - 1 - i_qubit] == '1': qc.x(i_qubit) #qc = cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") return qc def Ug_oracle(num_qubits): # allocate qubits qc = Circuit() for i_qubit in range(0,num_qubits-1,2): qc.cz(i_qubit, i_qubit+1) #qc = cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Ug") return qc def HiddenShift (num_qubits, secret_int): # allocate qubits qc = Circuit() # Start with Hadamard on all input qubits for i_qubit in range(num_qubits): qc.h(i_qubit) Uf = Uf_oracle(num_qubits, secret_int) qc.add(Uf) # Again do Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(i_qubit) Ug = Ug_oracle(num_qubits) qc.add(Ug) # End with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(i_qubit) # save smaller circuit example for display global QC_, Uf_, Ug_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf if Ug_ == None or num_qubits <= 6: if num_qubits < 9: Ug_ = Ug # return a handle on the circuit return qc ############### Circuit end # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int): # obtain shots from the result metadata num_shots = result.task_metadata.shots # obtain counts from the result object # for braket, need to reverse the key to match binary order # for braket, measures all qubits, so we have to remove data qubit measurement counts_r = result.measurement_counts counts = {} for measurement_r in counts_r.keys(): measurement = measurement_r[::-1] # reverse order counts[measurement] = counts_r[measurement_r] if verbose: print(f"For secret int {secret_int} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=2, max_qubits=6, max_circuits=3, num_shots=100, backend_id='simulator'): print("Hidden Shift Benchmark Program - Braket") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int)) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = HiddenShift(num_qubits, s_int) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics #ex.execute_circuits() #metrics.aggregate_metrics_for_group(num_qubits) #metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nQuantum Oracle 'Ug' ="); print(Ug_ if Ug_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Hidden Shift - Braket") # if main, execute method if __name__ == '__main__': run()
6,641
32.21
99
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hidden-shift/qiskit/hs_benchmark.py
""" Hidden Shift Benchmark Program - Qiskit """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qiskit" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None Ug_ = None ############### Circuit Definition # Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} def Uf_oracle(num_qubits, secret_int): # Initialize qubits qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) return qc # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) def Ug_oracle(num_qubits): # Initialize first n qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Ug") for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) return qc def HiddenShift (num_qubits, secret_int): # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main") # Start with Hadamard on all input qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} Uf = Uf_oracle(num_qubits, secret_int) qc.append(Uf,qr) qc.barrier() # Again do Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) Ug = Ug_oracle(num_qubits) qc.append(Ug,qr) qc.barrier() # End with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # measure all qubits qc.measure(qr, cr) # save smaller circuit example for display global QC_, Uf_, Ug_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf if Ug_ == None or num_qubits <= 6: if num_qubits < 9: Ug_ = Ug # return a handle on the circuit return qc ############### Circuit end # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): # obtain counts from the result object counts = result.get_counts(qc) if verbose: print(f"For secret int {secret_int} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=2, max_qubits=6, max_circuits=3, num_shots=100, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Hidden Shift Benchmark Program - Qiskit") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = HiddenShift(num_qubits, s_int) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nQuantum Oracle 'Ug' ="); print(Ug_ if Ug_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Hidden Shift - Qiskit") # if main, execute method if __name__ == '__main__': run()
6,927
32.468599
114
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hidden-shift/cirq/hs_benchmark.py
""" Hidden-Shift Benchmark Program - Cirq """ from collections import defaultdict import sys import time import cirq import numpy as np sys.path[1:1] = ["_common", "_common/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq"] import cirq_utils as cirq_utils import execute as ex import metrics as metrics np.random.seed() verbose = False # saved circuits for display QC_ = None Uf_ = None Ug_ = None ############### Circuit Definition def Uf_oracle(num_qubits, secret_int): # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.append(cirq.X(qr[i_qubit])) for i_qubit in range(0,num_qubits-1,2): qc.append(cirq.CZ(qr[i_qubit], qr[i_qubit+1])) # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.append(cirq.X(qr[i_qubit])) return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Uf") def Ug_oracle(num_qubits): # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() for i_qubit in range(0, num_qubits - 1, 2): qc.append(cirq.CZ(qr[i_qubit], qr[i_qubit + 1])) return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc,name="Ug") def HiddenShift (num_qubits, secret_int): # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() # Add Hadamard on all qubits for i_qubit in range(num_qubits): qc.append(cirq.H(qr[i_qubit])) # Generate Uf oracle Uf = Uf_oracle(num_qubits, secret_int) qc.append(Uf.on(*qr)) # Again do Hadamard on all qubits for i_qubit in range(num_qubits): qc.append(cirq.H(qr[i_qubit])) # Generate Ug oracle Ug = Ug_oracle(num_qubits) qc.append(Ug.on(*qr)) # End with Hadamard on all qubits for i_qubit in range(num_qubits): qc.append(cirq.H(qr[i_qubit])) # measure all qubits qc.append(cirq.measure(*[qr[i_qubit] for i_qubit in range(num_qubits)], key='result')) # save smaller circuit example for display global QC_, Uf_, Ug_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf if Ug_ == None or num_qubits <= 6: if num_qubits < 9: Ug_ = Ug # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, secret_int, num_shots): # get measurement array measurements = result.measurements['result'] # create counts distribution counts = defaultdict(lambda: 0) for row in measurements: counts["".join([str(x) for x in reversed(row)])] += 1 if verbose: print(f"For secret int {secret_int} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=3, num_shots=1000, backend_id='simulator', provider_backend=None): print("Hidden-Shift Benchmark Program - Cirq") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module with the result handler ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = HiddenShift(num_qubits, s_int) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") qr_state = [cirq.GridQubit(i, 0) for i in range(Uf_.num_qubits)] # we need to create registers to print circuits in cirq print("\nQuantum Oracle 'Uf' ="); print(cirq.Circuit(cirq.decompose(Uf_.on(*qr_state))) if Uf_ != None else " ... too large!") print("\nQuantum Oracle 'Ug' ="); print(cirq.Circuit(cirq.decompose(Ug_.on(*qr_state))) if Ug_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Hidden Shift - Cirq") # if main, execute method if __name__ == '__main__': run()
7,075
33.349515
130
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hhl/qiskit/uniform_controlled_rotation.py
""" Uniformly controlled rotation from arXiv:0407010 """ import numpy as np from sympy.combinatorics.graycode import GrayCode from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute def dot_product(str1, str2): """ dot product between 2 binary string """ prod = 0 for j in range(len(str1)): if str1[j] == '1' and str2[j] == '1': prod = (prod + 1)%2 return prod def conversion_matrix(N): M = np.zeros((N,N)) n = int(np.log2(N)) gc_list = list(GrayCode(n).generate_gray()) # list of gray code strings for i in range(N): g_i = gc_list[i] for j in range(N): b_j = np.binary_repr(j, width=n)[::-1] M[i,j] = (-1)**dot_product(g_i, b_j)/(2**n) return M def alpha2theta(alpha): """ alpha : list of angles that get applied controlled on 0,...,2^n-1 theta : list of angles occuring in circuit construction """ N = len(alpha) M = conversion_matrix(N) theta = M @ np.array(alpha) return theta def uni_con_rot_recursive_step(qc, qubits, anc, theta): """ qc : qiskit QuantumCircuit object qubits : qiskit QuantumRegister object anc : ancilla qubit register on which rotation acts theta : list of angles specifying rotations for 0, ..., 2^(n-1) """ if type(qubits) == list: n = len(qubits) else: n = qubits.size # lowest level of recursion if n == 1: qc.ry(theta[0], anc[0]) qc.cx(qubits[0], anc[0]) qc.ry(theta[1], anc[0]) elif n > 1: qc = uni_con_rot_recursive_step(qc, qubits[1:], anc, theta[0:int(len(theta)/2)]) qc.cx(qubits[0], anc[0]) qc = uni_con_rot_recursive_step(qc, qubits[1:], anc, theta[int(len(theta)/2):]) return qc def uniformly_controlled_rot(n, theta): qubits = QuantumRegister(n) anc_reg = QuantumRegister(1) qc = QuantumCircuit(qubits, anc_reg, name = 'INV_ROT') qc = uni_con_rot_recursive_step(qc, qubits, anc_reg, theta) qc.cx(qubits[0], anc_reg[0]) return qc # def uniformly_controlled_rot(qc, qubits, anc, theta): # """ # qc : qiskit QuantumCircuit object # qubits : qiskit QuantumRegister object # anc : ancilla qubit register on which rotation acts # theta : list of angles specifying rotations for 0, ..., 2^(n-1) # """ # qc = uni_con_rot_recursive_step(qc, qubits, anc, theta) # qc.cx(qubits[0], anc[0]) # return qc def test_circuit(n): shots = 10000 C = 0.25 N = 2**n # make list of rotation angles alpha = [2*np.arcsin(C)] for j in range(1,N): j_rev = int(np.binary_repr(j, width=n)[::-1],2) alpha.append(2*np.arcsin(C*N/j_rev)) theta = alpha2theta(alpha) for x in range(N): # state prep #x_bin = np.binary_repr(x, width=n) qubits = QuantumRegister(n) anc = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qubits, anc, cr) # state prep x_bin = np.binary_repr(x, width=n) for q in range(n): if x_bin[n-1-q] == '1': qc.x(q) qc.barrier() qc = uniformly_controlled_rot(qc, qubits, anc, theta) qc.barrier() qc.measure(anc[0], cr[0]) outcomes = sim_circuit(qc, shots) print(round(outcomes['1']/shots, 4)) def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes
3,751
23.051282
88
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hhl/qiskit/sparse_Ham_sim.py
# -*- coding: utf-8 -*- """ sparse Hamiltonian simulation """ from math import pi import numpy as np from scipy.linalg import expm from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute def Ham_sim(H, t): """ H : sparse matrix t : time parameter returns : QuantumCircuit for e^(-i*H*t) """ # read in number of qubits N = len(H) n = int(np.log2(N)) # read in matrix elements #diag_el = H[0,0] for j in range(1,N): if H[0,j] != 0: off_diag_el = H[0,j] break j_bin = np.binary_repr(j, width=n) sign = (-1)**((j_bin.count('1'))%2) # create registers qreg_a = QuantumRegister(n, name='q_a') creg = ClassicalRegister(n, name='c') qreg_b = QuantumRegister(n, name='q_b') # ancilla register anc_reg = QuantumRegister(1, name='q_anc') qc = QuantumCircuit(qreg_a, qreg_b, anc_reg, creg) # apply sparse H oracle gate qc = V_gate(qc, H, qreg_a, qreg_b) # apply W gate that diagonalizes SWAP operator and Toffoli for q in range(n): qc = W_gate(qc, qreg_a[q], qreg_b[q]) qc.x(qreg_b[q]) qc.ccx(qreg_a[q], qreg_b[q], anc_reg[0]) # phase qc.p(sign*2*t*off_diag_el, anc_reg[0]) # uncompute for q in range(n): j = n-1-q qc.ccx(qreg_a[j], qreg_b[j], anc_reg[0]) qc.x(qreg_b[j]) qc = W_gate(qc, qreg_a[j], qreg_b[j]) # sparse H oracle gate is its own inverse qc = V_gate(qc, H, qreg_a, qreg_b) # measure #qc.barrier() #qc.measure(qreg_a[0:], creg[0:]) return qc def control_Ham_sim(n, H, t): """ H : sparse matrix t : time parameter returns : QuantumCircuit for control-e^(-i*H*t) """ qreg = QuantumRegister(n) qreg_b = QuantumRegister(n) control_reg = QuantumRegister(1) anc_reg = QuantumRegister(1) qc = QuantumCircuit(qreg, qreg_b, control_reg, anc_reg) control = control_reg[0] anc = anc_reg[0] # read in number of qubits N = len(H) n = int(np.log2(N)) # read in matrix elements diag_el = H[0,0] for j in range(1,N): if H[0,j] != 0: off_diag_el = H[0,j] break j_bin = np.binary_repr(j, width=n) sign = (-1)**((j_bin.count('1'))%2) # use ancilla for phase kickback to simulate diagonal part of H qc.x(anc) qc.cp(-t*(diag_el+sign*off_diag_el), control, anc) qc.x(anc) # apply sparse H oracle gate qc = V_gate(qc, H, qreg, qreg_b) # apply W gate that diagonalizes SWAP operator and Toffoli for q in range(n): qc = W_gate(qc, qreg[q], qreg_b[q]) qc.x(qreg_b[q]) qc.ccx(qreg[q], qreg_b[q], anc) # phase qc.cp((sign*2*t*off_diag_el), control, anc) # uncompute for q in range(n): j = n-1-q qc.ccx(qreg[j], qreg_b[j], anc) qc.x(qreg_b[j]) qc = W_gate(qc, qreg[j], qreg_b[j]) # sparse H oracle gate is its own inverse qc = V_gate(qc, H, qreg, qreg_b) return qc def V_gate(qc, H, qreg_a, qreg_b): """ Hamiltonian oracle V|a,b> = |a,b+v(a)> """ # index of non-zero off diagonal in first row of H n = qreg_a.size N = len(H) for i in range(1,N): if H[0,i] != 0: break i_bin = np.binary_repr(i, width=n) for q in range(n): a, b = qreg_a[q], qreg_b[q] if i_bin[n-1-q] == '1': qc.x(a) qc.cx(a,b) qc.x(a) else: qc.cx(a,b) return qc def W_gate(qc, q0, q1): """ W : |00> -> |00> |01> -> |01> + |10> |10> -> |01> - |10> |11> -> |11> """ qc.rz(-pi,q1) qc.rz(-3*pi/2,q0) qc.ry(-pi/2,q1) qc.ry(-pi/2,q0) qc.rz(-pi,q1) qc.rz(-3*pi/2,q0) qc.cx(q0,q1) qc.rz(-7*pi/4,q1) qc.rx(-pi/2,q0) qc.rx(-pi,q1) qc.rz(-3*pi/2,q0) qc.cx(q0,q1) qc.ry(-pi/2,q1) qc.rx(-pi/4,q1) qc.cx(q1,q0) qc.rz(-3*pi/2,q0) return qc def qc_unitary(qc): simulator = Aer.get_backend('unitary_simulator') result = execute(qc, simulator).result() U = np.array(result.get_unitary(qc)) return U def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes def true_distr(H, t, psi0=0): N = len(H) n = int(np.log2(N)) U = expm(-1j*H*t) psi = U[:,psi0] probs = np.array([np.abs(amp)**2 for amp in psi]) probs_bin = {} for j, p in enumerate(probs): if p > 0: j_bin = np.binary_repr(j, width=n) probs_bin[j_bin] = p return probs_bin def generate_sparse_H(n, k, diag_el=0.75, off_diag_el=-0.25): """ n (int) : number of qubits. H will be 2^n by 2^n k (int) : between 1,...,2^n-1. determines which H will be generated in class of matrices generates 2-sparse H with 1.5 on diagonal and 0.5 on off diagonal """ N = 2**n k_bin = np.binary_repr(k, width=n) # initialize H H = np.diag(diag_el*np.ones(N)) pairs = [] tot_indices = [] for i in range(N): i_bin = np.binary_repr(i, width=n) j_bin = '' for q in range(n): if i_bin[q] == k_bin[q]: j_bin += '0' else: j_bin += '1' j = int(j_bin,2) if i not in tot_indices and j not in tot_indices: pairs.append([i,j]) tot_indices.append(i) tot_indices.append(j) # fill in H for pair in pairs: i, j = pair[0], pair[1] H[i,j] = off_diag_el H[j,i] = off_diag_el return H def condition_number(A): evals = np.linalg.eigh(A)[0] abs_evals = [abs(e) for e in evals] if min(abs_evals) == 0.0: return 'inf' else: k = max(abs_evals)/min(abs_evals) return k
6,309
21.140351
69
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hhl/qiskit/hhl_benchmark_km.py
""" HHL Benchmark Program - Qiskit (KM initial version 220402) TODO: - switch from total variation distance to Hellinger fidelity """ import sys import time import numpy as np pi = np.pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute import sparse_Ham_sim as shs import uniform_controlled_rotation as ucr # include QFT in this list, so we can refer to the QFT sub-circuit definition #sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] #sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] # cannot use the QFT common yet, as HHL seems to use reverse bit order sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] #from qft_benchmark import qft_gate, inv_qft_gate import execute as ex import metrics as metrics np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None ############### Circuit Definitions ''' replaced with code below ... def qft_dagger(qc, clock, n): qc.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(-np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[0]); def qft(qc, clock, n): qc.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[1]); ''' ''' DEVNOTE: the QFT and IQFT are defined here as they are in the QFT benchmark - almost; Here, the sign of the angles is reversed and the QFT is actually used as the inverse QFT. This is an inconsistency that needs to be resolved later. The QPE part of the algorithm should be using the inverse QFT, but the qubit order is not correct. The QFT as defined in the QFT benchmark operates on qubits in the opposite order from the HHL pattern. ''' def initialize_state(qc, qreg, b): """ b (int): initial basis state |b> """ n = qreg.size b_bin = np.binary_repr(b, width=n) for q in range(n): if b_bin[n-1-q] == '1': qc.x(qreg[q]) return qc def IQFT(qc, qreg): """ inverse QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of the circuit """ n = int(qreg.size) for i in reversed(range(n)): for j in range(i+1,n): phase = -pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) qc.h(qreg[i]) return qc def QFT(qc, qreg): """ QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of circuit """ n = int(qreg.size) for i in range(n): qc.h(qreg[i]) for j in reversed(range(i+1,n)): phase = pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) return qc def inv_qft_gate(input_size, method=1): #def qft_gate(input_size): #global QFT_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="qft") qc = QuantumCircuit(qr, name="QFT†") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) #qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( -np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cu1(-np.pi / divisor, qr[hidx], qr[input_size - j - 1]); # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) elif method == 2: # apply IQFT to register for i in range(input_size)[::-1]: for j in range(i+1,input_size): phase = -np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.h(qr[i]) qc.barrier() return qc ############### Inverse QFT Circuit def qft_gate(input_size, method=1): #def inv_qft_gate(input_size): #global QFTI_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="inv_qft") qc = QuantumCircuit(qr, name="QFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) #qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cu1( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) elif method == 2: # apply QFT to register for i in range(input_size): qc.h(qr[i]) for j in range(i+1, input_size): phase = np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.barrier() return qc ############# Controlled U Gate #Construct the U gates for A def ctrl_u(exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, -np.pi/2, np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc #Construct the U^-1 gates for reversing A def ctrl_ui(exponent): qc = QuantumCircuit(1, name=f"U^-{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, np.pi/2, -np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc ############# Quantum Phase Estimation # DEVNOTE: The QPE and IQPE methods below mirror the mechanism in Hector_Wong # Need to investigate whether the clock qubits are in the correct, as this implementation # seems to require the QFT be implemented in reverse also. TODO # Append a series of Quantum Phase Estimation gates to the circuit def qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): qc.barrier() ''' original code from Hector_Wong # e^{i*A*t} #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*np.pi/4, clock[0]); qc.cu3(np.pi/2, -np.pi/2, np.pi/2, clock[0], target); # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); qc.barrier(); ''' # apply series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now if method == 1: repeat = 1 #for j in reversed(range(len(clock))): for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_u(1) qc.append(cp, [clock[j], target]) repeat *= 2 qc.barrier(); #Define global U operator as the phase operator (for printing later) _, U_ = ctrl_u(1) if method == 2: for j in range(len(clock)): control = clock[j] phase = -(2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) # Perform an inverse QFT on the register holding the eigenvalues qc.append(inv_qft_gate(len(clock), method), clock) # Append a series of Inverse Quantum Phase Estimation gates to the circuit def inv_qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): # Perform a QFT on the register holding the eigenvalues qc.append(qft_gate(len(clock), method), clock) qc.barrier() if method == 1: ''' original code from Hector_Wong # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); # e^{i*A*t} #qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(-3*np.pi/4, clock[0]); qc.cu3(np.pi/2, np.pi/2, -np.pi/2, clock[0], target); qc.barrier() ''' # apply inverse series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now repeat = 2 ** (len(clock) - 1) for j in reversed(range(len(clock))): #for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(-3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_ui(1) qc.append(cp, [clock[j], target]) repeat = int(repeat / 2) qc.barrier(); #Define global U operator as the phase operator (for printing later) _, UI_ = ctrl_ui(1) if method == 2: for j in reversed(range(len(clock))): control = clock[j] phase = (2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) def hhl_routine(qc, ancilla, clock, input_qubits, measurement, extra_qubits=None, A=None, method=1): qpe(qc, clock, input_qubits, extra_qubits, ancilla, A, method) qc.reset(ancilla) qc.barrier() if method == 1: # This section is to test and implement C = 1 # since we are not swapping after the QFT, reverse order of qubits from what is in papers qc.cry(np.pi, clock[1], ancilla) qc.cry(np.pi/3, clock[0], ancilla) # uniformly-controlled rotation elif method == 2: n_clock = clock.size C = 1/2**n_clock # constant in rotation (lower bound on eigenvalues A) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_clock): x_bin_rev = np.binary_repr(x, width=n_clock)[::-1] lam = int(x_bin_rev,2)/(2**n_clock) alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step qc = ucr.uniformly_controlled_rot(qc, clock, ancilla, theta) qc.barrier() qc.measure(ancilla, measurement[0]) qc.reset(ancilla) qc.barrier() inv_qpe(qc, clock, input_qubits, extra_qubits, ancilla, A, method) def HHL(num_qubits, num_input_qubits, num_clock_qubits, beta, A=None, method=1): if method == 1: # Create the various registers needed clock = QuantumRegister(num_clock_qubits, name='clock') input_qubits = QuantumRegister(num_input_qubits, name='b') ancilla = QuantumRegister(1, name='ancilla') measurement = ClassicalRegister(2, name='c') # Create an empty circuit with the specified registers qc = QuantumCircuit(ancilla, clock, input_qubits, measurement) # State preparation. (various initial values, done with initialize method) # intial_state = [0,1] # intial_state = [1,0] # intial_state = [1/np.sqrt(2),1/np.sqrt(2)] # intial_state = [np.sqrt(0.9),np.sqrt(0.1)] ##intial_state = [np.sqrt(1 - beta), np.sqrt(beta)] ##qc.initialize(intial_state, 3) # use an RY rotation to initialize the input state between 0 and 1 qc.ry(2 * np.arcsin(beta), input_qubits) # Put clock qubits into uniform superposition qc.h(clock) # Perform the HHL routine hhl_routine(qc, ancilla, clock, input_qubits, measurement) # Perform a Hadamard Transform on the clock qubits qc.h(clock) qc.barrier() # measure the input, which now contains the answer qc.measure(input_qubits, measurement[1]) # return a handle on the circuit return qc # Make the HHL circuit (this is the one aactually used right now) def make_circuit(A, b, num_clock_qubits): """ circuit for HHL algo A|x>=|b> A : sparse Hermitian matrix b (int): between 0,...,2^n-1. Initial basis state |b> """ # read in number of qubits N = len(A) n = int(np.log2(N)) n_t = num_clock_qubits # number of qubits in clock register # lower bound on eigenvalues of A. Fixed for now C = 1/4 # create quantum registers qr = QuantumRegister(n) qr_b = QuantumRegister(n) # ancillas for Hamiltonian simulation cr = ClassicalRegister(n) qr_t = QuantumRegister(n_t) # for phase estimation qr_a = QuantumRegister(1) # ancilla qubit cr_a = ClassicalRegister(1) qc = QuantumCircuit(qr, qr_b, qr_t, qr_a, cr, cr_a) # initialize the |b> state qc = initialize_state(qc, qr, b) # Hadamard phase estimation register for q in range(n_t): qc.h(qr_t[q]) # perform controlled e^(i*A*t) for q in range(n_t): control = qr_t[q] phase = -(2*pi)*2**q qc = shs.control_Ham_sim(qc, A, phase, control, qr, qr_b, qr_a[0]) # inverse QFT qc = IQFT(qc, qr_t) # reset ancilla qc.reset(qr_a[0]) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_t): x_bin_rev = np.binary_repr(x, width=n_t)[::-1] lam = int(x_bin_rev,2)/(2**n_t) if lam < C: alpha.append(0) elif lam >= C: alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step and measure ancilla qc = ucr.uniformly_controlled_rot(qc, qr_t, qr_a, theta) qc.measure(qr_a[0], cr_a[0]) qc.reset(qr_a[0]) # QFT qc = QFT(qc, qr_t) # uncompute phase estimation # perform controlled e^(-i*A*t) for q in reversed(range(n_t)): control = qr_t[q] phase = (2*pi)*2**q qc = shs.control_Ham_sim(qc, A, phase, control, qr, qr_b, qr_a[0]) # Hadamard phase estimation register for q in range(n_t): qc.h(qr_t[q]) # measure ancilla and main register qc.barrier() qc.measure(qr[0:], cr[0:]) return qc def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes def postselect(outcomes, return_probs=True): mar_out = {} for b_str in outcomes: if b_str[0] == '1': counts = outcomes[b_str] mar_out[b_str[2:]] = counts # compute postselection rate ps_shots = sum(mar_out.values()) shots = sum(outcomes.values()) rate = ps_shots/shots # convert to probability distribution if return_probs == True: mar_out = {b_str:round(mar_out[b_str]/ps_shots, 4) for b_str in mar_out} return mar_out, rate ############### Result Data Analysis saved_result = None def true_distr(A, b=0): N = len(A) n = int(np.log2(N)) b_vec = np.zeros(N); b_vec[b] = 1.0 #b = np.array([1,1])/np.sqrt(2) x = np.linalg.inv(A) @ b_vec # normalize x x_n = x/np.linalg.norm(x) probs = np.array([np.abs(xj)**2 for xj in x_n]) distr = {} for j, prob in enumerate(probs): if prob > 1e-8: j_bin = np.binary_repr(j, width=n) distr[j_bin] = prob distr = {out:distr[out]/sum(distr.values()) for out in distr} return distr def TVD(distr1, distr2): """ compute total variation distance between distr1 and distr2 which are represented as dictionaries of bitstrings and probabilities """ tvd = 0.0 for out1 in distr1: if out1 in distr2: p1, p2 = distr1[out1], distr2[out1] tvd += np.abs(p1-p2)/2 else: p1 = distr1[out1] tvd += p1/2 for out2 in distr2: if out2 not in distr1: p2 = distr2[out2] tvd += p2/2 return tvd def analyze_and_print_result (qc, result, num_qubits, s_int, num_shots): global saved_result saved_result = result # obtain counts from the result object counts = result.get_counts(qc) # post-select counts where ancilla was measured as |1> post_counts, rate = postselect(counts) num_input_qubits = len(list(post_counts.keys())[0]) if verbose: print(f'Ratio of counts with ancilla measured |1> : {round(rate, 4)}') # compute true distribution from secret int off_diag_index = 0 b = 0 s_int_o = int(s_int) s_int_b = int(s_int) while (s_int_o % 2) == 0: s_int_o = int(s_int_o/2) off_diag_index += 1 while (s_int_b % 3) == 0: s_int_b = int(s_int_b/3) b += 1 # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) ideal_distr = true_distr(A, b) # compute total variation distance tvd = TVD(ideal_distr, post_counts) # use TVD as infidelity fidelity = 1 - tvd return post_counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_input_qubits=1, max_input_qubits=3, min_clock_qubits=2, max_clock_qubits=3, max_circuits=3, num_shots=100, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("HHL Benchmark Program - Qiskit") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #counts, fidelity = analyze_and_print_result(qc, result, num_qubits, ideal_distr) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = False # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # for noiseless simulation, set noise model to be None #ex.set_noise_model(None) # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete #for num_input_qubits in range(min_input_qubits, max_input_qubits+1): for num_input_qubits in range(min_input_qubits, max_input_qubits+1): N = 2**num_input_qubits # matrix size for num_clock_qubits in range(min_clock_qubits, max_clock_qubits+1): num_qubits = 2*num_input_qubits + num_clock_qubits + 1 # determine number of circuits to execute for this group num_circuits = max_circuits print(f"************\nExecuting {num_circuits} circuits with {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") # loop over randomly generated problem instances for i in range(num_circuits): b = np.random.choice(range(N)) off_diag_index = np.random.choice(range(1,N)) A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) # define secret_int s_int = (2**off_diag_index)*(3**b) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = make_circuit(A, b, num_clock_qubits) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit #print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") #if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") #print("\nU Circuit ="); print(U_ if U_ != None else " ... too large!") #print("\nU^-1 Circuit ="); print(UI_ if UI_ != None else " ... too large!") #print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") #print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - HHL - Qiskit", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()
24,218
31.12069
142
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hhl/qiskit/hhl_benchmark.py
""" HHL Benchmark Program - Qiskit TODO: - switch from total variation distance to Hellinger fidelity """ import sys import time import numpy as np pi = np.pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute import sparse_Ham_sim as shs import uniform_controlled_rotation as ucr # include QFT in this list, so we can refer to the QFT sub-circuit definition #sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] #sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] # cannot use the QFT common yet, as HHL seems to use reverse bit order sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] #from qft_benchmark import qft_gate, inv_qft_gate import execute as ex import metrics as metrics np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None HP_ = None INVROT_ = None ############### Circuit Definitions ''' replaced with code below ... def qft_dagger(qc, clock, n): qc.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(-np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[0]); def qft(qc, clock, n): qc.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[1]); ''' ''' DEVNOTE: the QFT and IQFT are defined here as they are in the QFT benchmark - almost; Here, the sign of the angles is reversed and the QFT is actually used as the inverse QFT. This is an inconsistency that needs to be resolved later. The QPE part of the algorithm should be using the inverse QFT, but the qubit order is not correct. The QFT as defined in the QFT benchmark operates on qubits in the opposite order from the HHL pattern. ''' def initialize_state(qc, qreg, b): """ b (int): initial basis state |b> """ n = qreg.size b_bin = np.binary_repr(b, width=n) if verbose: print(f"... initializing |b> to {b}, binary repr = {b_bin}") for q in range(n): if b_bin[n-1-q] == '1': qc.x(qreg[q]) return qc def IQFT(qc, qreg): """ inverse QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of the circuit """ n = int(qreg.size) for i in reversed(range(n)): for j in range(i+1,n): phase = -pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) qc.h(qreg[i]) return qc def QFT(qc, qreg): """ QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of circuit """ n = int(qreg.size) for i in range(n): qc.h(qreg[i]) for j in reversed(range(i+1,n)): phase = pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) return qc def inv_qft_gate(input_size, method=1): #def qft_gate(input_size): #global QFT_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="qft") qc = QuantumCircuit(qr, name="IQFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) #qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( -np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cp(-np.pi / divisor, qr[hidx], qr[input_size - j - 1]); # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) elif method == 2: # apply IQFT to register for i in range(input_size)[::-1]: for j in range(i+1,input_size): phase = -np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.h(qr[i]) qc.barrier() return qc ############### Inverse QFT Circuit def qft_gate(input_size, method=1): #def inv_qft_gate(input_size): #global QFTI_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="inv_qft") qc = QuantumCircuit(qr, name="QFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) #qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cp( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) elif method == 2: # apply QFT to register for i in range(input_size): qc.h(qr[i]) for j in range(i+1, input_size): phase = np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.barrier() return qc ############# Controlled U Gate #Construct the U gates for A def ctrl_u(exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, -np.pi/2, np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc #Construct the U^-1 gates for reversing A def ctrl_ui(exponent): qc = QuantumCircuit(1, name=f"U^-{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, np.pi/2, -np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc ####### DEVNOTE: The following functions (up until the make_circuit) are from the first inccarnation # of this benchmark and are not used here. Should be removed, but kept here for reference for now ############# Quantum Phase Estimation # DEVNOTE: The QPE and IQPE methods below mirror the mechanism in Hector_Wong # Need to investigate whether the clock qubits are in the correct, as this implementation # seems to require the QFT be implemented in reverse also. TODO # Append a series of Quantum Phase Estimation gates to the circuit def qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): qc.barrier() ''' original code from Hector_Wong # e^{i*A*t} #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*np.pi/4, clock[0]); qc.cu3(np.pi/2, -np.pi/2, np.pi/2, clock[0], target); # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); qc.barrier(); ''' # apply series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now if method == 1: repeat = 1 #for j in reversed(range(len(clock))): for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_u(1) qc.append(cp, [clock[j], target]) repeat *= 2 qc.barrier(); #Define global U operator as the phase operator (for printing later) _, U_ = ctrl_u(1) if method == 2: for j in range(len(clock)): control = clock[j] phase = -(2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) # Perform an inverse QFT on the register holding the eigenvalues qc.append(inv_qft_gate(len(clock), method), clock) # Append a series of Inverse Quantum Phase Estimation gates to the circuit def inv_qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): # Perform a QFT on the register holding the eigenvalues qc.append(qft_gate(len(clock), method), clock) qc.barrier() if method == 1: ''' original code from Hector_Wong # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); # e^{i*A*t} #qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(-3*np.pi/4, clock[0]); qc.cu3(np.pi/2, np.pi/2, -np.pi/2, clock[0], target); qc.barrier() ''' # apply inverse series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now repeat = 2 ** (len(clock) - 1) for j in reversed(range(len(clock))): #for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(-3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_ui(1) qc.append(cp, [clock[j], target]) repeat = int(repeat / 2) qc.barrier(); #Define global U operator as the phase operator (for printing later) _, UI_ = ctrl_ui(1) if method == 2: for j in reversed(range(len(clock))): control = clock[j] phase = (2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) ''' def hhl_routine(qc, ancilla, clock, input_qubits, measurement, extra_qubits=None, A=None, method=1): qpe(qc, clock, input_qubits, extra_qubits, ancilla, A, method) qc.reset(ancilla) qc.barrier() if method == 1: # This section is to test and implement C = 1 # since we are not swapping after the QFT, reverse order of qubits from what is in papers qc.cry(np.pi, clock[1], ancilla) qc.cry(np.pi/3, clock[0], ancilla) # uniformly-controlled rotation elif method == 2: n_clock = clock.size C = 1/2**n_clock # constant in rotation (lower bound on eigenvalues A) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_clock): x_bin_rev = np.binary_repr(x, width=n_clock)[::-1] lam = int(x_bin_rev,2)/(2**n_clock) alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step qc = ucr.uniformly_controlled_rot(qc, clock, ancilla, theta) qc.barrier() qc.measure(ancilla, measurement[0]) qc.reset(ancilla) qc.barrier() inv_qpe(qc, clock, input_qubits, extra_qubits, ancilla, A, method) def HHL(num_qubits, num_input_qubits, num_clock_qubits, beta, A=None, method=1): if method == 1: print(num_clock_qubits) print(num_input_qubits) # Create the various registers needed clock = QuantumRegister(num_clock_qubits, name='clock') input_qubits = QuantumRegister(num_input_qubits, name='b') ancilla = QuantumRegister(1, name='ancilla') measurement = ClassicalRegister(2, name='c') # Create an empty circuit with the specified registers qc = QuantumCircuit(ancilla, clock, input_qubits, measurement) # State preparation. (various initial values, done with initialize method) # intial_state = [0,1] # intial_state = [1,0] # intial_state = [1/np.sqrt(2),1/np.sqrt(2)] # intial_state = [np.sqrt(0.9),np.sqrt(0.1)] ##intial_state = [np.sqrt(1 - beta), np.sqrt(beta)] ##qc.initialize(intial_state, 3) # use an RY rotation to initialize the input state between 0 and 1 qc.ry(2 * np.arcsin(beta), input_qubits) # Put clock qubits into uniform superposition qc.h(clock) # Perform the HHL routine hhl_routine(qc, ancilla, clock, input_qubits, measurement) # Perform a Hadamard Transform on the clock qubits qc.h(clock) qc.barrier() # measure the input, which now contains the answer qc.measure(input_qubits, measurement[1]) # # save smaller circuit example for display # global QC_, U_, UI_, QFT_, QFTI_ # if QC_ == None or num_qubits <= 6: # if num_qubits < 9: # QC_ = qc # if U_ == None or num_qubits <= 6: # _, U_ = ctrl_u(1) # #U_ = ctrl_u(np.pi/2, 2, 0, 1) # if UI_ == None or num_qubits <= 6: # _, UI_ = ctrl_ui(1) # #UI_ = ctrl_ui(np.pi/2, 2, 0, 1) # if QFT_ == None or num_qubits <= 5: # if num_qubits < 9: QFT_ = qft_gate(len(clock)) # if QFTI_ == None or num_qubits <= 5: # if num_qubits < 9: QFTI_ = inv_qft_gate(len(clock)) # return a handle on the circuit return qc def hamiltonian_phase(n_t): qr_t = QuantumRegister(n_t) qc = QuantumCircuit(qr_t, name = 'H⊗n' ) # Hadamard phase estimation register for q in range(n_t): qc.h(qr_t[q]) return qc ''' # Make the HHL circuit (this is the one aactually used right now) def make_circuit(A, b, num_clock_qubits): """ circuit for HHL algo A|x>=|b> A : sparse Hermitian matrix b (int): between 0,...,2^n-1. Initial basis state |b> """ # save smaller circuit example for display global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_ # read in number of qubits N = len(A) n = int(np.log2(N)) n_t = num_clock_qubits # number of qubits in clock register # lower bound on eigenvalues of A. Fixed for now C = 1/4 ''' Define sets of qubits for this algorithm ''' # create 'input' quantum and classical measurement register qr = QuantumRegister(n, name='input') qr_b = QuantumRegister(n, name='in_anc') # ancillas for Hamiltonian simulation (?) cr = ClassicalRegister(n) # create 'clock' quantum register qr_t = QuantumRegister(n_t, name='clock') # for phase estimation # create 'ancilla' quantum and classical measurement register qr_a = QuantumRegister(1, name='ancilla') # ancilla qubit cr_a = ClassicalRegister(1) # create the top-level HHL circuit, with all the registers qc = QuantumCircuit(qr, qr_b, qr_t, qr_a, cr, cr_a) ''' Initialize the input and clock qubits ''' # initialize the |b> state - the 'input' qc = initialize_state(qc, qr, b) #qc.barrier() # Hadamard the phase estimation register - the 'clock' for q in range(n_t): qc.h(qr_t[q]) qc.barrier() ''' Perform Quantum Phase Estimation on input (b), clock, and ancilla ''' # perform controlled e^(i*A*t) for q in range(n_t): control = qr_t[q] anc = qr_a[0] phase = -(2*pi)*2**q qc_u = shs.control_Ham_sim(n, A, phase) if phase <= 0: qc_u.name = "e^{" + str(q) + "iAt}" else: qc_u.name = "e^{-" + str(q) + "iAt}" if U_ == None: U_ = qc_u qc.append(qc_u, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc]) qc.barrier() ''' Perform Inverse Quantum Fourier Transform on clock qubits ''' #qc = IQFT(qc, qr_t) qc_qfti = inv_qft_gate(n_t, method=2) qc.append(qc_qfti, qr_t) if QFTI_ == None: QFTI_ = qc_qfti qc.barrier() ''' Perform inverse rotation with ancilla ''' # reset ancilla qc.reset(qr_a[0]) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_t): x_bin_rev = np.binary_repr(x, width=n_t)[::-1] lam = int(x_bin_rev,2)/(2**n_t) if lam < C: alpha.append(0) elif lam >= C: alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step qc_invrot = ucr.uniformly_controlled_rot(n_t, theta) qc.append(qc_invrot, qr_t[0:len(qr_t)] + [qr_a[0]]) if INVROT_ == None: INVROT_ = qc_invrot # and measure ancilla qc.measure(qr_a[0], cr_a[0]) qc.reset(qr_a[0]) qc.barrier() ''' Perform Quantum Fourier Transform on clock qubits ''' #qc = QFT(qc, qr_t) qc_qft = qft_gate(n_t, method=2) qc.append(qc_qft, qr_t) if QFT_ == None: QFT_ = qc_qft qc.barrier() ''' Perform Inverse Quantum Phase Estimation on input (b), clock, and ancilla ''' # uncompute phase estimation # perform controlled e^(-i*A*t) for q in reversed(range(n_t)): control = qr_t[q] phase = (2*pi)*2**q qc_ui = shs.control_Ham_sim(n, A, phase) if phase <= 0: qc_ui.name = "e^{" + str(q) + "iAt}" else: qc_ui.name = "e^{-" + str(q) + "iAt}" if UI_ == None: UI_ = qc_ui qc.append(qc_ui, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc]) qc.barrier() # Hadamard (again) the phase estimation register - the 'clock' for q in range(n_t): qc.h(qr_t[q]) qc.barrier() ''' Perform final measurements ''' # measure ancilla and main register qc.measure(qr[0:], cr[0:]) if QC_ == None: QC_ = qc #print(f"... made circuit = \n{QC_}") return qc def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes def postselect(outcomes, return_probs=True): mar_out = {} for b_str in outcomes: if b_str[0] == '1': counts = outcomes[b_str] mar_out[b_str[2:]] = counts # compute postselection rate ps_shots = sum(mar_out.values()) shots = sum(outcomes.values()) rate = ps_shots/shots # convert to probability distribution if return_probs == True: mar_out = {b_str:round(mar_out[b_str]/ps_shots, 4) for b_str in mar_out} return mar_out, rate ############### Result Data Analysis saved_result = None def true_distr(A, b=0): N = len(A) n = int(np.log2(N)) b_vec = np.zeros(N); b_vec[b] = 1.0 #b = np.array([1,1])/np.sqrt(2) x = np.linalg.inv(A) @ b_vec # normalize x x_n = x/np.linalg.norm(x) probs = np.array([np.abs(xj)**2 for xj in x_n]) distr = {} for j, prob in enumerate(probs): if prob > 1e-8: j_bin = np.binary_repr(j, width=n) distr[j_bin] = prob distr = {out:distr[out]/sum(distr.values()) for out in distr} return distr # DEVNOTE: This is not used any more and possibly should be removed ''' def TVD(distr1, distr2): """ compute total variation distance between distr1 and distr2 which are represented as dictionaries of bitstrings and probabilities """ tvd = 0.0 for out1 in distr1: if out1 in distr2: p1, p2 = distr1[out1], distr2[out1] tvd += np.abs(p1-p2)/2 else: p1 = distr1[out1] tvd += p1/2 for out2 in distr2: if out2 not in distr1: p2 = distr2[out2] tvd += p2/2 return tvd ''' def analyze_and_print_result (qc, result, num_qubits, s_int, num_shots): global saved_result saved_result = result # obtain counts from the result object counts = result.get_counts(qc) if verbose: print(f"... for circuit = {num_qubits} {s_int}, counts = {counts}") # post-select counts where ancilla was measured as |1> post_counts, rate = postselect(counts) num_input_qubits = len(list(post_counts.keys())[0]) if verbose: print(f'... ratio of counts with ancilla measured |1> : {round(rate, 4)}') # compute true distribution from secret int off_diag_index = 0 b = 0 # remove instance index from s_int s_int = s_int - 1000 * int(s_int/1000) # get off_diag_index and b s_int_o = int(s_int) s_int_b = int(s_int) while (s_int_o % 2) == 0: s_int_o = int(s_int_o/2) off_diag_index += 1 while (s_int_b % 3) == 0: s_int_b = int(s_int_b/3) b += 1 if verbose: print(f"... rem(s_int) = {s_int}, b = {b}, odi = {off_diag_index}") # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) ideal_distr = true_distr(A, b) # # compute total variation distance # tvd = TVD(ideal_distr, post_counts) # # use TVD as infidelity # fidelity = 1 - tvd # #fidelity = metrics.polarization_fidelity(post_counts, ideal_distr) fidelity = metrics.polarization_fidelity(post_counts, ideal_distr) return post_counts, fidelity ################ Benchmark Loop # Execute program with default parameters (based on min and max_qubits) # This routine computes a reasonable min and max input and clock qubit range to sweep # from the given min and max qubit sizes using the formula below and making the # assumption that num_input_qubits ~= num_clock_qubits and num_input_qubits < num_clock_qubits: # num_qubits = 2 * num_input_qubits + num_clock_qubits + 1 (the ancilla) def run (min_qubits=3, max_qubits=6, max_circuits=3, num_shots=100, method = 1, use_best_widths=True, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): # we must have at least 4 qubits and min must be less than max max_qubits = max(4, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) #print(f"... using min_qubits = {min_qubits} and max_qubits = {max_qubits}") ''' first attempt .. min_input_qubits = min_qubits//2 if min_qubits%2 == 1: min_clock_qubits = min_qubits//2 + 1 else: min_clock_qubits = min_qubits//2 max_input_qubits = max_qubits//2 if max_qubits%2 == 1: max_clock_qubits = max_qubits//2 + 1 else: max_clock_qubits = max_qubits//2 ''' # the calculation below is based on the formula described above, where I = input, C = clock: # I = int((N - 1) / 3) min_input_qubits = int((min_qubits - 1) / 3) max_input_qubits = int((max_qubits - 1) / 3) # C = N - 1 - 2 * I min_clock_qubits = min_qubits - 1 - 2 * min_input_qubits max_clock_qubits = max_qubits - 1 - 2 * max_input_qubits #print(f"... input, clock qubit width range: {min_input_qubits} : {max_input_qubits}, {min_clock_qubits} : {max_clock_qubits}") return run2(min_input_qubits=min_input_qubits,max_input_qubits= max_input_qubits, min_clock_qubits=min_clock_qubits, max_clock_qubits=max_clock_qubits, max_circuits=max_circuits, num_shots=num_shots, method=method, use_best_widths=use_best_widths, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute program with default parameters and permitting the user to specify an # arbitrary range of input and clock qubit widths # The benchmark sweeps over all input widths and clock widths in the range specified def run2 (min_input_qubits=1, max_input_qubits=3, min_clock_qubits=1, max_clock_qubits=3, max_circuits=3, num_shots=100, method=2, use_best_widths=False, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("HHL Benchmark Program - Qiskit") # ensure valid input an clock qubit widths min_input_qubits = min(max(1, min_input_qubits), max_input_qubits) max_input_qubits = max(min_input_qubits, max_input_qubits) min_clock_qubits = min(max(1, min_clock_qubits), max_clock_qubits) max_clock_qubits = max(min_clock_qubits, max_clock_qubits) #print(f"... in, clock: {min_input_qubits}, {max_input_qubits}, {min_clock_qubits}, {max_clock_qubits}") # initialize saved circuits for display global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_ QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None HP_ = None INVROT_ = None # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #counts, fidelity = analyze_and_print_result(qc, result, num_qubits, ideal_distr) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = False # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # for noiseless simulation, set noise model to be None #ex.set_noise_model(None) # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete #for num_input_qubits in range(min_input_qubits, max_input_qubits+1): for num_input_qubits in range(min_input_qubits, max_input_qubits+1): N = 2**num_input_qubits # matrix size for num_clock_qubits in range(min_clock_qubits, max_clock_qubits+1): num_qubits = 2*num_input_qubits + num_clock_qubits + 1 # determine number of circuits to execute for this group num_circuits = max_circuits # if flagged to use best input and clock for specific num_qubits, check against formula if use_best_widths: if num_input_qubits != int((num_qubits - 1) / 3) or num_clock_qubits != (num_qubits - 1 - 2 * num_input_qubits): if verbose: print(f"... SKIPPING {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") continue print(f"************\nExecuting {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") # loop over randomly generated problem instances for i in range(num_circuits): # generate a non-zero value < N #b = np.random.choice(range(N)) # orig code, gens 0 sometimes b = np.random.choice(range(1, N)) # and a non-zero index off_diag_index = np.random.choice(range(1, N)) # define secret_int (include 'i' since b and off_diag_index don't need to be unique) s_int = 1000 * (i+1) + (2**off_diag_index)*(3**b) #s_int = (2**off_diag_index)*(3**b) if verbose: print(f"... create A for b = {b}, off_diag_index = {off_diag_index}, s_int = {s_int}") A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = make_circuit(A, b, num_clock_qubits) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) #print(qc) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") #if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nU Circuit ="); print(U_ if U_ != None else " ... too large!") print("\nU^-1 Circuit ="); print(UI_ if UI_ != None else " ... too large!") print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") print("\nHamiltonian Phase Estimation Circuit ="); print(HP_ if HP_ != None else " ... too large!") print("\nControlled Rotation Circuit ="); print(INVROT_ if INVROT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - HHL - Qiskit", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()
32,496
32.433128
170
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/grovers/braket/grovers_benchmark.py
""" Grover's Search Benchmark Program - Braket """ import sys import time from braket.circuits import Circuit # AWS imports: Import Braket SDK modules import numpy as np sys.path[1:1] = [ "_common", "_common/braket" ] sys.path[1:1] = [ "../../_common", "../../_common/braket" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None grover_oracle = None diffusion_operator = None # On Braket some devices don't support cu1 (cphaseshift) _use_cu1_shim = False ############### Circuit Definition def GroversSearch(num_qubits, marked_item, n_iterations): # allocate qubits num_qubits = num_qubits # allocate circuit qc = Circuit() # Start with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(i_qubit) # loop over the estimated number of iterations for _ in range(n_iterations): #qc.barrier() # add the grover oracle grover_oracle =create_grover_oracle(num_qubits, marked_item) qc.add(grover_oracle) # add the diffusion operator diffusion_operator =create_diffusion_operator(num_qubits) qc.add(diffusion_operator) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############## Grover Oracle def create_grover_oracle(num_qubits, marked_item): global grover_oracle marked_item_bits = format(marked_item, f"0{num_qubits}b")[::-1] qc = Circuit() for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) qc.h(num_qubits - 1) #qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) if grover_oracle == None or num_qubits <= 5: if num_qubits < 9: grover_oracle = qc # qc = braket_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Grover") return qc ############## Grover Diffusion Operator def create_diffusion_operator(num_qubits): global diffusion_operator qc = Circuit() for i_qubit in range(num_qubits): qc.h(i_qubit) for i_qubit in range(num_qubits): qc.x(i_qubit) qc.h(num_qubits - 1) #qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) for i_qubit in range(num_qubits): qc.x(i_qubit) for i_qubit in range(num_qubits): qc.h(i_qubit) if diffusion_operator == None or num_qubits <= 5: if num_qubits < 9: diffusion_operator = qc #qc = braket_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Diffuser") return qc ############### MCX shim # single cx / cu1 unit for mcx implementation def add_cx_unit(qc, cxcu1_unit, controls, target): num_controls = len(controls) i_qubit = cxcu1_unit[1] j_qubit = cxcu1_unit[0] theta = cxcu1_unit[2] if j_qubit != None: qc.cnot(controls[j_qubit], controls[i_qubit]) #qc.cu1(theta, controls[i_qubit], target) if _use_cu1_shim: add_cphaseshift(qc, controls[i_qubit], target, theta) else: qc.cphaseshift(controls[i_qubit], target, theta) i_qubit = i_qubit - 1 if j_qubit == None: j_qubit = i_qubit + 1 else: j_qubit = j_qubit - 1 if theta < 0: theta = -theta new_units = [] if i_qubit >= 0: new_units += [ [ j_qubit, i_qubit, -theta ] ] new_units += [ [ num_controls - 1, i_qubit, theta ] ] return new_units # mcx recursion loop def add_cxcu1_units(qc, cxcu1_units, controls, target): new_units = [] for cxcu1_unit in cxcu1_units: new_units += add_cx_unit(qc, cxcu1_unit, controls, target) cxcu1_units.clear() return new_units # mcx gate implementation: brute force and inefficient # start with a single CU1 on last control and target # and recursively expand for each additional control def add_mcx(qc, controls, target): num_controls = len(controls) theta = np.pi / 2**num_controls qc.h(target) cxcu1_units = [ [ None, num_controls - 1, theta] ] while len(cxcu1_units) > 0: cxcu1_units += add_cxcu1_units(qc, cxcu1_units, controls, target) qc.h(target) ############### CPHASESHIFT shim # a CU1 or CPHASESHIFT equivalent def add_cphaseshift(qc, control, target, theta): qc.rz(control, theta/2) qc.cnot(control, target) qc.rz(target, -theta/2) qc.cnot(control, target) qc.rz(target, theta/2) ############### Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, marked_item): # obtain shots from the result metadata num_shots = result.task_metadata.shots # obtain counts from the result object counts_r = result.measurement_counts # obtain counts from the result object # for braket, need to reverse the key to match binary order # for braket, measures all qubits, so we have to remove data qubit measurement counts_r = result.measurement_counts counts = {} for measurement_r in counts_r.keys(): measurement = measurement_r[::-1] # reverse order counts[measurement] = counts_r[measurement_r] if verbose: print(f"For type {marked_item} measured: {counts}") # we compare counts to analytical correct distribution correct_dist = grovers_dist(num_qubits, marked_item) if verbose: print(f"Marked item: {marked_item}, Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity def grovers_dist(num_qubits, marked_item): n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) dist = {} for i in range(2**num_qubits): key = bin(i)[2:].zfill(num_qubits) theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == int(marked_item): dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=2, max_qubits = 6, max_circuits = 3, num_shots = 100, backend_id = 'simulator', use_cu1_shim=False): print("Grover's Search Benchmark Program - Braket") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # set the flag to use a cu1 (cphaseshift) shim if given, or for devices that don't support it global _use_cu1_shim if "ionq/" in backend_id: use_cu1_shim=True _use_cu1_shim = use_cu1_shim if _use_cu1_shim: print("... using CPHASESHIFT shim") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int)) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) qc = GroversSearch(num_qubits, s_int, n_iterations) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nOracle ="); print(grover_oracle) print("\nDiffuser ="); print(diffusion_operator) # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Grover's Search - Braket") # if main, execute method if __name__ == '__main__': run()
9,980
30.386792
99
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/grovers/qiskit/grovers_benchmark.py
""" Grover's Search Benchmark Program - Qiskit """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None grover_oracle = None diffusion_operator = None # for validating the implementation of an mcx shim _use_mcx_shim = False ############### Circuit Definition def GroversSearch(num_qubits, marked_item, n_iterations): # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main") # Start with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # loop over the estimated number of iterations for _ in range(n_iterations): qc.barrier() # add the grover oracle qc.append(add_grover_oracle(num_qubits, marked_item).to_instruction(), qr) # add the diffusion operator qc.append(add_diffusion_operator(num_qubits).to_instruction(), qr) qc.barrier() # measure all qubits qc.measure(qr, cr) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############## Grover Oracle def add_grover_oracle(num_qubits, marked_item): global grover_oracle marked_item_bits = format(marked_item, f"0{num_qubits}b")[::-1] qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="oracle") for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) qc.h(num_qubits - 1) if _use_mcx_shim: add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) else: qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) qc.barrier() for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) if grover_oracle == None or num_qubits <= 5: if num_qubits < 9: grover_oracle = qc return qc ############## Grover Diffusion Operator def add_diffusion_operator(num_qubits): global diffusion_operator qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="diffuser") for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) for i_qubit in range(num_qubits): qc.x(qr[i_qubit]) qc.h(num_qubits - 1) if _use_mcx_shim: add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) else: qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) qc.barrier() for i_qubit in range(num_qubits): qc.x(qr[i_qubit]) for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) if diffusion_operator == None or num_qubits <= 5: if num_qubits < 9: diffusion_operator = qc return qc ############### MCX shim # single cx / cu1 unit for mcx implementation def add_cx_unit(qc, cxcu1_unit, controls, target): num_controls = len(controls) i_qubit = cxcu1_unit[1] j_qubit = cxcu1_unit[0] theta = cxcu1_unit[2] if j_qubit != None: qc.cx(controls[j_qubit], controls[i_qubit]) qc.cu1(theta, controls[i_qubit], target) i_qubit = i_qubit - 1 if j_qubit == None: j_qubit = i_qubit + 1 else: j_qubit = j_qubit - 1 if theta < 0: theta = -theta new_units = [] if i_qubit >= 0: new_units += [ [ j_qubit, i_qubit, -theta ] ] new_units += [ [ num_controls - 1, i_qubit, theta ] ] return new_units # mcx recursion loop def add_cxcu1_units(qc, cxcu1_units, controls, target): new_units = [] for cxcu1_unit in cxcu1_units: new_units += add_cx_unit(qc, cxcu1_unit, controls, target) cxcu1_units.clear() return new_units # mcx gate implementation: brute force and inefficent # start with a single CU1 on last control and target # and recursively expand for each additional control def add_mcx(qc, controls, target): num_controls = len(controls) theta = np.pi / 2**num_controls qc.h(target) cxcu1_units = [ [ None, num_controls - 1, theta] ] while len(cxcu1_units) > 0: cxcu1_units += add_cxcu1_units(qc, cxcu1_units, controls, target) qc.h(target) ################ Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots): counts = result.get_counts(qc) if verbose: print(f"For type {marked_item} measured: {counts}") # we compare counts to analytical correct distribution correct_dist = grovers_dist(num_qubits, marked_item) if verbose: print(f"Marked item: {marked_item}, Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity def grovers_dist(num_qubits, marked_item): n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) dist = {} for i in range(2**num_qubits): key = bin(i)[2:].zfill(num_qubits) theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == int(marked_item): dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist ################ Benchmark Loop # Because this circuit size grows significantly with num_qubits (due to the mcx gate) # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=2, max_qubits=6, max_circuits=3, num_shots=100, use_mcx_shim=False, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Grover's Search Benchmark Program - Qiskit") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: Grover's Search benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # set the flag to use an mcx shim if given global _use_mcx_shim _use_mcx_shim = use_mcx_shim if _use_mcx_shim: print("... using MCX shim") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) qc = GroversSearch(num_qubits, s_int, n_iterations) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nOracle ="); print(grover_oracle if grover_oracle!= None else " ... too large!") print("\nDiffuser ="); print(diffusion_operator ) # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Grover's Search - Qiskit") # if main, execute method if __name__ == '__main__': run()
9,694
30.477273
99
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/grovers/cirq/grovers_benchmark.py
""" Grover's Search Benchmark Program - Cirq """ from collections import defaultdict import sys import time import cirq import numpy as np sys.path[1:1] = ["_common", "_common/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq"] import cirq_utils as cirq_utils import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits for display QC_ = None grover_oracle = None diffusion_operator = None ############### Circuit Definition def GroversSearch(num_qubits, marked_item, n_iterations): qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() # start with Hadamard on all qubits qc.append(cirq.H.on_each(*qr)) # loop over the estimated number of iterations for _ in range(n_iterations): # add the oracle grover_oracle = create_grover_oracle(num_qubits, marked_item) qc.append(grover_oracle.on(*qr)) # add the diffusion operator diffusion_operator =create_diffusion_operator(num_qubits) qc.append(diffusion_operator.on(*qr)) # measure all qubits qc.append(cirq.measure(*[qr[i_qubit] for i_qubit in range(num_qubits)], key='result')) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############## Grover Oracle def create_grover_oracle(num_qubits, marked_item): global grover_oracle qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() marked_item_bits = format(marked_item, f"0{num_qubits}b")[::-1] qc.append([cirq.X(q) for (q, bit) in zip(qr, marked_item_bits) if not int(bit)]) qc.append(cirq.Z(qr[-1]).controlled_by(*qr[0:-1])) qc.append([cirq.X(q) for (q, bit) in zip(qr, marked_item_bits) if not int(bit)]) if grover_oracle == None or num_qubits <= 5: if num_qubits < 9: grover_oracle = qc return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Oracle") ############## Grover Diffusion Operator def create_diffusion_operator(num_qubits): global diffusion_operator qr = [cirq.GridQubit(i, 0) for i in range(num_qubits)] qc = cirq.Circuit() qc.append(cirq.H.on_each(*qr)) qc.append(cirq.X.on_each(*qr)) qc.append(cirq.Z(qr[-1]).controlled_by(*qr[0:-1])) qc.append(cirq.X.on_each(*qr)) qc.append(cirq.H.on_each(*qr)) if diffusion_operator == None or num_qubits <= 5: if num_qubits < 9: diffusion_operator = qc return cirq_utils.to_gate(num_qubits=num_qubits, circ=qc, name="Diffusor") ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots): # get measurement array measurements = result.measurements['result'] # create counts distribution counts = defaultdict(lambda: 0) for row in measurements: counts["".join([str(x) for x in reversed(row)])] += 1 if verbose: print(f"For type {marked_item} measured: {counts}") # we compare counts to analytical correct distribution correct_dist = grovers_dist(num_qubits, marked_item) if verbose: print(f"Marked item: {marked_item}, Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity def grovers_dist(num_qubits, marked_item): n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) dist = {} for i in range(2**num_qubits): key = bin(i)[2:].zfill(num_qubits) theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == int(marked_item): dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=6, max_circuits=3, num_shots=100, backend_id='simulator', provider_backend=None): print("Grover's Search Benchmark Program - Cirq") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module with the result handler ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) qc = GroversSearch(num_qubits, s_int, n_iterations) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nOracle ="); print(grover_oracle if grover_oracle!= None else " ... too large!") print("\nDiffuser ="); print(diffusion_operator if diffusion_operator!= None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Grover's Search - Cirq") # if main, execute method if __name__ == '__main__': run()
7,315
33.186916
105
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/vqe/qiskit/vqe_benchmark.py
""" Variational Quantum Eigensolver Benchmark Program - Qiskit """ import json import os import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] import execute as ex import metrics as metrics verbose= False # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name = 'main') # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(os.path.dirname(__file__), f'./ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(os.path.dirname(__file__), f'./Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham ################ Result Data Analysis ## Analyze and print measured results ## Compute the quality of the result based on measured probability distribution for each state def analyze_and_print_result(qc, result, num_qubits, references, num_shots): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] # get results counts counts = result.get_counts(qc) # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] # compute fidelity fidelity = metrics.polarization_fidelity(counts, correct_dist) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity *= ( abs(float(total_name.split()[1])) / normalization ) return fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=4, max_qubits=10, max_circuits=3, num_shots=4092, method=1, backend_id="qasm_simulator", provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Variational Quantum Eigensolver Benchmark Program - Qiskit") print(f"... using circuit method {method}") # Max qubits must be 10 since the referenced files only go to 12 qubits MAX_QUBITS = 10 max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubitts) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return # Initialize the metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(os.path.dirname(__file__), f'../_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(os.path.dirname(__file__), f'../_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) fidelity = analyze_and_print_result(qc, result, num_qubits, references, num_shots) if len(qc.name.split()) == 2: metrics.store_metric(num_qubits, qc.name.split()[0], 'fidelity', fidelity) else: metrics.store_metric(num_qubits, qc.name.split()[2], 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] # record creation time metrics.store_metric(input_size, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, input_size, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when group complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - VQE Simulation ({method}) - Qiskit") # if main, execute methods if __name__ == "__main__": run()
13,422
30.143852
104
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/vqe/qiskit/vqe_utils.py
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock as HF from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.transformers import ActiveSpaceTransformer from qiskit_nature.operators.second_quantization import FermionicOp # Function that converts a list of single and double excitation operators to Pauli operators def convertExcitationToPauli(singles, doubles, norb, t1_amp, t2_amp): # initialize Pauli list pauli_list = [] # qubit converter qubit_converter = QubitConverter(JordanWignerMapper()) # loop over singles for index, single in enumerate(singles): t1 = t1_amp[index] * 1j * (FermionicOp(f"-_{single[0]} +_{single[1]}", norb) \ - FermionicOp(f"-_{single[0]} +_{single[1]}", norb).adjoint()) #print(t1) qubit_op = qubit_converter.convert(t1) for p in qubit_op: pauli_list.append(p) #pauli_list.append(qubit_op[0]) # loop over doubles for index, double in enumerate(doubles): t2 = t2_amp[index] * 1j * (FermionicOp(f"-_{double[0]} +_{double[1]} -_{double[2]} +_{double[3]}", norb) \ - FermionicOp(f"-_{double[0]} +_{double[1]} -_{double[2]} +_{double[3]}", norb).adjoint()) qubit_op = qubit_converter.convert(t2) #print(qubit_op) for p in qubit_op: pauli_list.append(p) #pauli_list.append(qubit_op[0]) # return Pauli list return pauli_list # Get the inactive energy and the Hamiltonian operator in an active space def GetHamiltonians(mol, n_orbs, na, nb): # construct the driver driver = PySCFDriver(molecule=mol, unit=UnitsType.ANGSTROM, basis='sto6g') # the active space transformer (use a (2, 2) active space) transformer = ActiveSpaceTransformer(num_electrons=(na+nb), num_molecular_orbitals=int(n_orbs/2)) # the electronic structure problem problem = ElectronicStructureProblem(driver, [transformer]) # get quantum molecule q_molecule = driver.run() # reduce the molecule to active space q_molecule_reduced = transformer.transform(q_molecule) # compute inactive energy core_energy = q_molecule_reduced.energy_shift["ActiveSpaceTransformer"] # add nuclear repulsion energy core_energy += q_molecule_reduced.nuclear_repulsion_energy # generate the second-quantized operators second_q_ops = problem.second_q_ops() # construct a qubit converter qubit_converter = QubitConverter(JordanWignerMapper()) # qubit Operations qubit_op = qubit_converter.convert(second_q_ops[0]) # return the qubit operations return qubit_op, core_energy
2,896
35.670886
114
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hamiltonian-simulation/braket/hamiltonian_simulation_benchmark.py
""" Hamiltonian-Simulation Benchmark Program - Braket """ import json import os import sys import time import numpy as np from braket.circuits import Circuit # AWS imports: Import Braket SDK modules sys.path[1:1] = [ "_common", "_common/braket" ] sys.path[1:1] = [ "../../_common", "../../_common/braket" ] import execute as ex import metrics as metrics np.random.seed(0) verbose = False qcs = [None, None, None] # saved subcircuits for printing (not used yet in braket) # save main circuit to display QC_ = None # for validating the implementation of XXYYZZ operation _use_XX_YY_ZZ_gates = False # import precalculated data to compare against filename = os.path.join(os.path.dirname(__file__), os.path.pardir, "_common", "precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Braket circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a braket circuit for this Hamiltonian ''' # allocate circuit qc = Circuit() tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(k) # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(i, 2 * tau * w * h_x[i]) for i in range(n_spins)] [qc.rz(i, 2 * tau * w * h_z[i]) for i in range(n_spins)] # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qcs[0] = qc_xx = xx_gate(qc, tau, [i, (i + 1) % n_spins]) #qc.append(qc_xx.to_instruction(), [i, (i + 1) % n_spins]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qcs[1] = qc_yy = yy_gate(qc, tau, [i, (i + 1) % n_spins]) #qc.append(qc_yy.to_instruction(), [i, (i + 1) % n_spins]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qcs[2] = qc_zz = zz_gate(qc, tau, [i, (i + 1) % n_spins]) #qc.append(qc_zz.to_instruction(), [i, (i + 1) % n_spins]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qcs[0] = qc_xxyyzz = xxyyzz_opt_gate(qc, tau, [i, (i + 1) % n_spins]) #qc.append(qc_xxyyzz.to_instruction(), [i, (i + 1) % n_spins]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(qc, tau, qr): qc.h(qr[0]) qc.h(qr[1]) qc.cnot(qr[0], qr[1]) qc.rz(qr[1], 3.1416*tau) qc.cnot(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(qc, tau, qr): qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cnot(qr[0], qr[1]) qc.rz(qr[1], 3.1416*tau) qc.cnot(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.si(qr[0]) qc.si(qr[1]) return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(qc, tau, qr): qc.cnot(qr[0], qr[1]) qc.rz(qr[1], 3.1416*tau) qc.cnot(qr[0], qr[1]) return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(qc, tau, qr): alpha = tau; beta = tau; gamma = tau qc.rz(qr[1], 3.1416/2) qc.cnot(qr[1], qr[0]) qc.rz(qr[0], 3.1416*gamma - 3.1416/2) qc.ry(qr[1], 3.1416/2 - 3.1416*alpha) qc.cnot(qr[0], qr[1]) qc.ry(qr[1], 3.1416*beta - 3.1416/2) qc.cnot(qr[1], qr[0]) qc.rz(qr[0], -3.1416/2) return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type): # obtain shots from the result metadata num_shots = result.task_metadata.shots # obtain counts from the result object counts_r = result.measurement_counts # obtain counts from the result object # for braket, need to reverse the key to match binary order # for braket, measures all qubits, so we have to remove data qubit measurement counts_r = result.measurement_counts counts = {} for measurement_r in counts_r.keys(): measurement = measurement_r[::-1] # reverse order counts[measurement] = counts_r[measurement_r] if verbose: print(f"For type {type} measured: {counts}") # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] if verbose: print(f"Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=3, num_shots=100, use_XX_YY_ZZ_gates = False, backend_id='simulator'): print("Hamiltonian-Simulation Benchmark Program - Braket") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # set the flag to use an XX YY ZZ shim if given global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # determine number of circuits to execute for this group num_circuits = min(1, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### # loop over only 1 circuit for circuit_id in range(num_circuits): # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, circuit_id, shots=num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") ''' if _use_XX_YY_ZZ_gates: print("\n********\nXX, YY, ZZ =") print(qcs[0]); print(qcs[1]); print(qcs[2]) else: print("\n********\nXXYYZZ =") print(qcs[0]) ''' # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Hamiltonian Simulation - Braket") # if main, execute method if __name__ == '__main__': run()
9,872
34.901818
104
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hamiltonian-simulation/qiskit/hamiltonian_simulation_benchmark.py
""" Hamiltonian-Simulation Benchmark Program - Qiskit """ import json import os import sys import time import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # for validating the implementation of XXYYZZ operation _use_XX_YY_ZZ_gates = False # import precalculated data to compare against filename = os.path.join(os.path.dirname(__file__), os.path.pardir, "_common", "precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name="main") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): counts = result.get_counts(qc) if verbose: print(f"For type {type} measured: {counts}") # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] if verbose: print(f"Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=3, skip_qubits=1, num_shots=100, use_XX_YY_ZZ_gates = False, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Hamiltonian-Simulation Benchmark Program - Qiskit") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # set the flag to use an XX YY ZZ shim if given global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### # loop over only 1 circuit for circuit_id in range(num_circuits): #print(circuit_id) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Hamiltonian Simulation - Qiskit") # if main, execute method if __name__ == '__main__': run()
10,162
32.989967
108
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hamiltonian-simulation/qiskit/WIP_benchmarks/tfim_benchmark.py
""" Hamiltonian-Simulation (Transverse Field Ising Model) Benchmark Program - Qiskit """ import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict verbose = False # saved circuits and subcircuits for display QC_ = None ZZ_ = None ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, method): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :param method: whether the circuit simulates the TFIM in paramagnetic or ferromagnetic phase :return: return a Qiskit circuit for this Hamiltonian ''' # strength of transverse field if method == 1: g = 20.0 # g >> 1 -> paramagnetic phase else: g = 0.1 # g << 1 -> ferromagnetic phase # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name="main") # define timestep based on total runtime and number of Trotter steps tau = t / K # initialize state to approximate eigenstate when deep into phases of TFIM if abs(g) > 1: # paramagnetic phase # start with initial state of |++...> (eigenstate in x-basis) for k in range(n_spins): qc.h(qr[k]) if abs(g) < 1: # ferromagnetic phase # state with initial state of GHZ state: 1/sqrt(2) ( |00...> + |11...> ) qc.h(qr[0]) for k in range(1, n_spins): qc.cnot(qr[k-1], qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the Hamiltonian for k in range(K): # the Pauli spin vector product for i in range(n_spins): qc.rx(2 * tau * g, qr[i]) qc.barrier() # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # transform state back to computational basis |00000> if abs(g) > 1: # paramagnetic phase # reverse transformation from |++...> (eigenstate in x-basis) for k in range(n_spins): qc.h(qr[k]) if abs(g) < 1: # ferromagnetic phase # reversed tranformation from GHZ state for k in reversed(range(1, n_spins)): qc.cnot(qr[k-1], qr[k]) qc.h(qr[0]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 4: if n_spins < 9: QC_ = qc return qc ############### exp(ZZ) Gate Implementations # Simple exp(ZZ) gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(np.pi*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): counts = result.get_counts(qc) if verbose: print(f"For type {type} measured: {counts}") correct_state = '0'*num_qubits fidelity = 0 if correct_state in counts.keys(): fidelity = counts[correct_state] / num_shots return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=3, num_shots=100, method=1, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main"): print("Hamiltonian-Simulation (Transverse Field Ising Model) Benchmark Program - Qiskit") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = max_circuits num_qubits = input_size print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation t = 1 # time of simulation, 1 is chosen so that the dynamics are not completely trivial k = int(5*num_qubits*t) # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. for circuit_id in range(num_circuits): # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = 2 * np.random.random(num_qubits) - 1 # random numbers between [-1, 1] h_z = 2 * np.random.random(num_qubits) - 1 qc = HamiltonianSimulation(num_qubits, K=k, t=t, method=method) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\n********\nZZ ="); print(ZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Hamiltonian Simulation ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run()
7,616
34.593458
108
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hamiltonian-simulation/qiskit/WIP_benchmarks/mbl_benchmark.py
""" Many Body Localization Benchmark Program - Qiskit """ import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z, method=2): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :param method: the method used to generate hamiltonian circuit :return: return a Qiskit circuit for this Hamiltonian ''' # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name="main") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() ''' Method 1: Basic implementation of exp(i * t * (XX + YY + ZZ)) ''' if method == 1: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) ''' Method 2: Use an optimal XXYYZZ combined operator See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf ''' if method == 2: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): counts = result.get_counts(qc) if verbose: print(f"For type {type} measured: {counts}") ################### IMBALANCE CALCULATION ONE ####################### expectation_a = 0 for key in counts.keys(): # compute the operator expectation for this state lambda_a = sum([((-1) ** i) * ((-1) ** int(bit)) for i, bit in enumerate(key)])/num_qubits prob = counts[key] / num_shots # probability of this state expectation_a += lambda_a * prob ##################################################################### ################### IMBALANCE CALCULATION TWO ####################### # this is the imbalance calculation explicitely defined in Sonika's notes prob_one = {} for i in range(num_qubits): prob_one[i] = 0 for key in counts.keys(): for i in range(num_qubits): if key[::-1][i] == '1': prob_one[i] += counts[key] / num_shots I_numer = 0 I_denom = 0 for i in prob_one.keys(): I_numer += (-1)**i * prob_one[i] I_denom += prob_one[i] I = I_numer/I_denom ##################################################################### if verbose: print(f"\tMeasured Imbalance: {I}, measured expectation_a: {expectation_a}") # rescaled fideltiy fidelity = I/0.4 # rescaled expectation_a expectation_a = expectation_a/0.4 # We expect expecation_a to give 1. We would like to plot the deviation from the true expectation. return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=300, num_shots=100, method=2, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main"): print("Many Body Localization Benchmark Program - Qiskit") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project) ex.set_noise_model() # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = max_circuits num_qubits = input_size print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation w = 20 # strength of disorder k = 100 # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = 1.2 # time of simulation for circuit_id in range(num_circuits): # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = 2 * np.random.random(num_qubits) - 1 # random numbers between [-1, 1] h_z = 2 * np.random.random(num_qubits) - 1 qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z, method=method) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\n********\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\n********\nXXYYZZ =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Hamiltonian Simulation ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run()
10,466
32.334395
108
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/hamiltonian-simulation/cirq/hamiltonian_simulation_benchmark.py
""" Hamiltonian-Simulation Benchmark Program - Cirq """ import json import os import sys import time from collections import defaultdict import numpy as np import cirq sys.path[1:1] = ["_common", "_common/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq"] import cirq_utils as cirq_utils import execute as ex import metrics as metrics np.random.seed(0) verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # for validating the implementation of XXYYZZ operation _use_XX_YY_ZZ_gates = False # import precalculated data to compare against filename = os.path.join(os.path.dirname(__file__), os.path.pardir, "_common", "precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Cirq circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a cirq circuit for this Hamiltonian ''' # allocate qubits qr = [cirq.GridQubit(i, 0) for i in range(n_spins)] qc = cirq.Circuit() tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.append(cirq.X(qr[k])) # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product qc.append([cirq.rx(2 * tau * w * h_x[i])(qr[i]) for i in range(n_spins)]) qc.append([cirq.rz(2 * tau * w * h_z[i])(qr[i]) for i in range(n_spins)]) # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in a loop for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).on(qr[i], qr[(i+1) % n_spins])) # YY operator on each pair of qubits in a loop for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).on(qr[i], qr[(i+1) % n_spins])) # ZZ operation on each pair of qubits in a loop for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).on(qr[i], qr[(i+1) % n_spins])) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in a loop for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).on(qr[i], qr[(i+1) % n_spins])) # measure all the qubits used in the circuit qc.append(cirq.measure(*[qr[i_qubit] for i_qubit in range(n_spins)], key='result')) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on qidx1 and qidx2 with angle 'tau' def xx_gate(tau): qr = [cirq.GridQubit(i, 0) for i in range(2)] qc = cirq.Circuit() qc.append([ cirq.H(qr[0]), cirq.H(qr[1]), cirq.CNOT(qr[0], qr[1]), cirq.rz(2 * tau)(qr[1]), cirq.CNOT(qr[0], qr[1]), cirq.H(qr[0]), cirq.H(qr[1]) ]) global XX_ XX_ = qc return cirq_utils.to_gate(num_qubits=2, circ=qc, name="XX") # Simple YY gate on qidx1 and qidx2 with angle 'tau' def yy_gate(tau): qr = [cirq.GridQubit(i, 0) for i in range(2)] qc = cirq.Circuit() qc.append([ cirq.S(qr[0]), cirq.S(qr[1]), cirq.H(qr[0]), cirq.H(qr[1]), cirq.CNOT(qr[0], qr[1]), cirq.rz(2 * tau)(qr[1]), cirq.CNOT(qr[0], qr[1]), cirq.H(qr[0]), cirq.H(qr[1]), cirq.ZPowGate(exponent=-0.5)(qr[0]), # the s dagger gate, not built-in to cirq cirq.ZPowGate(exponent=-0.5)(qr[1]) ]) global YY_ YY_ = qc return cirq_utils.to_gate(num_qubits=2, circ=qc, name="YY") # Simple YY gate on qidx1 and qidx2 with angle 'tau' def zz_gate(tau): qr = [cirq.GridQubit(i, 0) for i in range(2)] qc = cirq.Circuit() qc.append([ cirq.CNOT(qr[0], qr[1]), cirq.rz(2 * tau)(qr[1]), cirq.CNOT(qr[0], qr[1]), ]) global ZZ_ ZZ_ = qc return cirq_utils.to_gate(num_qubits=2, circ=qc, name="ZZ") # Optimal XXYYZZ gate on qidx1 and qidx2 with angle 'tau' def xxyyzz_opt_gate(tau): qr = [cirq.GridQubit(i, 0) for i in range(2)] qc = cirq.Circuit() qc.append([ cirq.rz(-np.pi / 2)(qr[1]), cirq.CNOT(qr[1], qr[0]), cirq.rz(-tau + np.pi / 2)(qr[0]), cirq.ry(-np.pi / 2 + tau)(qr[1]), cirq.CNOT(qr[0], qr[1]), cirq.ry(-tau + np.pi / 2)(qr[1]), cirq.CNOT(qr[1], qr[0]), cirq.rz(np.pi / 2)(qr[0]) ]) global XXYYZZ_ XXYYZZ_ = qc return cirq_utils.to_gate(num_qubits=2, circ=qc, name="XXYYZZ") ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): # get measurement array measurements = result.measurements['result'] # create counts distribution counts = defaultdict(lambda: 0) for row in measurements: counts["".join([str(x) for x in reversed(row)])] += 1 if verbose: print(f"For type {type} measured: {counts}") # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] if verbose: print(f"Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist) return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=3, num_shots=100, use_XX_YY_ZZ_gates = False, backend_id='simulator', provider_backend=None): print("Hamiltonian-Simulation Benchmark Program - Cirq") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # set the flag to use an XX YY ZZ shim if given global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module with the result handler ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # determine number of circuits to execute for this group num_circuits = min(1, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### # loop over only 1 circuit for circuit_id in range(num_circuits): # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, circuit_id, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Hamiltonian Simulation - Cirq") # if main, execute method if __name__ == '__main__': run()
10,425
33.753333
104
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/amplitude-estimation/qiskit/ae_benchmark.py
""" Amplitude Estimation Benchmark Program via Phase Estimation - Qiskit """ import copy import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate np.random.seed(0) verbose = False # saved subcircuits circuits for printing A_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None): qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_counting, qr_state, cr) num_qubits = num_state_qubits + 1 + num_counting_qubits # create the Amplitude Generator circuit A = A_gen(num_state_qubits, a, psi_zero, psi_one) # create the Quantum Operator circuit and a controlled version of it cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, [qr_state[i] for i in range(num_state_qubits+1)]) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() # measure counting qubits qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc return qc # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qc_A = QuantumCircuit(num_state_qubits+1, name=f"A") # takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>) qc_A.ry(theta, num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1> qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.cnot(num_state_qubits,i) qc_A.x(num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.cnot(num_state_qubits,i) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc # Analyze and print measured results # Expected result is always the secret_int (which encodes alpha), so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, s_int, num_shots): # get results as measured counts counts = result.get_counts(qc) # calculate expected output histogram a = a_from_s_int(s_int, num_counting_qubits) correct_dist = a_to_bitstring(a, num_counting_qubits) # generate thermal_dist for polarization calculation thermal_dist = metrics.uniform_dist(num_counting_qubits) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring amplitude a 100% of the time app_counts = bitstring_to_a(counts, num_counting_qubits) app_correct_dist = {a: 1.0} app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits) if verbose: print(f"For amplitude {a}, expected: {correct_dist} measured: {counts}") print(f" ... For amplitude {a} thermal_dist: {thermal_dist}") print(f"For amplitude {a}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For amplitude {a} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) hf_fidelity = metrics.hellinger_fidelity_with_expected(counts, correct_dist) if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return counts, fidelity def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def bitstring_to_a(counts, num_counting_qubits): est_counts = {} m = num_counting_qubits precision = int(num_counting_qubits / (np.log2(10))) + 2 for key in counts.keys(): r = counts[key] num = int(key,2) / (2**m) a_est = round((np.sin(np.pi * num) )** 2, precision) if a_est not in est_counts.keys(): est_counts[a_est] = 0 est_counts[a_est] += r return est_counts def a_from_s_int(s_int, num_counting_qubits): theta = s_int * np.pi / (2**num_counting_qubits) precision = int(num_counting_qubits / (np.log2(10))) + 2 a = round(np.sin(theta)**2, precision) return a ################ Benchmark Loop # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=3, max_qubits=8, max_circuits=3, num_shots=100, num_state_qubits=1, # default, not exposed to users backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("Amplitude Estimation Benchmark Program - Qiskit") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: Amplitude Estimation benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") if verbose: print(f" with num_state_qubits = {num_state_qubits} num_counting_qubits = {num_counting_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() a_ = a_from_s_int(s_int, num_counting_qubits) qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # collapse the 3 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QC_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Amplitude Estimation - Qiskit") # if main, execute method if __name__ == '__main__': run()
11,928
36.394984
123
py
QC-App-Oriented-Benchmarks
QC-App-Oriented-Benchmarks-master/amplitude-estimation/cirq/ae_benchmark.py
""" Amplitude Estimation Benchmark Program via Phase Estimation - Cirq """ from collections import defaultdict import copy import sys import time import cirq import numpy as np sys.path[1:1] = ["_common", "_common/cirq", "quantum-fourier-transform/cirq"] sys.path[1:1] = ["../../_common", "../../_common/cirq", "../../quantum-fourier-transform/cirq"] import cirq_utils as cirq_utils import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate np.random.seed(0) verbose = False # saved circuits for display QC_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None): qr_state = cirq.GridQubit.rect(1,num_state_qubits+1,0) qr_counting = cirq.GridQubit.rect(1,num_counting_qubits,1) qc = cirq.Circuit() num_qubits = num_state_qubits + 1 + num_counting_qubits # create the Amplitude Generator circuit A_circuit = A_gen(num_state_qubits, a, psi_zero, psi_one) A = cirq_utils.to_gate(num_state_qubits+1, A_circuit, name="A") # create the Quantum Operator circuit and a controlled version of it cQ, Q = Ctrl_Q(num_state_qubits, A_circuit) # save small example subcircuits for visualization global A_, Q_, cQ_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A # Prepare state from A, and counting qubits with H transform qc.append(A.on(*qr_state)) for i in range(num_counting_qubits): qc.append(cirq.H.on(qr_counting[i])) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ.on(qr_counting[j], *qr_state)) repeat *= 2 # inverse quantum Fourier transform only on counting qubits QFT_inv_gate = inv_qft_gate(num_counting_qubits) qc.append(QFT_inv_gate.on(*qr_counting)) # measure counting qubits qc.append(cirq.measure(*[qr_counting[i_qubit] for i_qubit in range(num_counting_qubits)], key='result')) # save smaller circuit example for display global QC_,QFTI_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = QFT_inv_gate # return a handle on the circuit return qc # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qr_A = cirq.GridQubit.rect(1,num_state_qubits+1,0) qc_A = cirq.Circuit() # takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>) qc_A.append(cirq.ry(theta).on(qr_A[num_state_qubits])) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1> qc_A.append(cirq.X(qr_A[num_state_qubits])) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.append(cirq.CNOT(qr_A[num_state_qubits],qr_A[i])) qc_A.append(cirq.X(qr_A[num_state_qubits])) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.append(cirq.CNOT(qr_A[num_state_qubits],qr_A[i])) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qr_Q = cirq.GridQubit.rect(1,num_state_qubits+1,0) qc_Q = cirq.Circuit() A_gate = cirq_utils.to_gate(num_state_qubits+1, A_circ, name="A") A_gate_inv = cirq.inverse(copy.copy(A_gate)) ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc_Q.append(cirq.X(qr_Q[num_state_qubits])) qc_Q.append(cirq.Z(qr_Q[num_state_qubits])) qc_Q.append(cirq.X(qr_Q[num_state_qubits])) # A_circ_inverse qc_Q.append(A_gate_inv.on(*qr_Q)) # S_0 for i in range(num_state_qubits+1): qc_Q.append(cirq.X.on(qr_Q[i])) qc_Q.append(cirq.H(qr_Q[num_state_qubits])) qc_Q.append(cirq.X.controlled(num_controls=num_state_qubits).on(*qr_Q)) qc_Q.append(cirq.H(qr_Q[num_state_qubits])) for i in range(num_state_qubits+1): qc_Q.append(cirq.X.on(qr_Q[i])) # A_circ qc_Q.append(A_gate.on(*qr_Q)) # Create a gate out of the Q operator Q_ = cirq_utils.to_gate(num_qubits=num_state_qubits+1, circ=qc_Q, name="Q") # and also a controlled version of it Ctrl_Q_ = cirq.ops.ControlledGate(Q_, num_controls=1) # and return both return Ctrl_Q_, Q_ # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, s_int, num_shots): measurements = result.measurements['result'] counts_str = defaultdict(lambda: 0) for row in measurements: counts_str["".join([str(x) for x in reversed(row)])] += 1 counts = bitstring_to_a(counts_str, num_counting_qubits) a = a_from_s_int(s_int, num_counting_qubits) if verbose: print(f"For amplitude {a} measured: {counts}") # correct distribution is measuring amplitude a 100% of the time correct_dist = {a: 1.0} # generate thermal_dist with amplitudes instead, to be comparable to correct_dist bit_thermal_dist = metrics.uniform_dist(num_counting_qubits) thermal_dist = bitstring_to_a(bit_thermal_dist, num_counting_qubits) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) return counts, fidelity def bitstring_to_a(counts, num_counting_qubits): est_counts = {} m = num_counting_qubits precision = int(num_counting_qubits / (np.log2(10))) + 2 for key in counts.keys(): r = counts[key] num = int(key,2) / (2**m) a_est = round((np.sin(np.pi * num) )** 2, precision) if a_est not in est_counts.keys(): est_counts[a_est] = 0 est_counts[a_est] += r return est_counts def a_from_s_int(s_int, num_counting_qubits): theta = s_int * np.pi / (2**num_counting_qubits) precision = int(num_counting_qubits / (np.log2(10))) + 2 a = round(np.sin(theta)**2, precision) return a ################ Benchmark Loop # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=3, max_qubits=8, max_circuits=3, num_shots=100, num_state_qubits=1, # default, not exposed to users backend_id='simulator', provider_backend=None): print("Amplitude Estimation Benchmark Program - Cirq") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: Amplitude Estimation benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() a_ = a_from_s_int(s_int, num_counting_qubits) qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, num_shots) # execute all circuits for this group, aggregate and report metrics when complete ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(input_size) # metrics.report_metrics_for_group(input_size) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") qr_state = cirq.GridQubit.rect(1,num_state_qubits+1,0) # we need to create registers to print circuits in cirq qr_control = cirq.GridQubit.rect(1,1,1) print("\nControlled Quantum Operator 'cQ' ="); print(cirq.Circuit(cQ_.on(qr_control[0], *qr_state)) if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(cirq.Circuit(cirq.decompose(Q_.on(*qr_state))) if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(cirq.Circuit(cirq.decompose(A_.on(*qr_state))) if A_ != None else " ... too large!") qr_state = cirq.GridQubit.rect(1,QFTI_.num_qubits,0) # we need to create registers to print circuits in cirq print("\nInverse QFT Circuit ="); print(cirq.Circuit(cirq.decompose(QFTI_.on(*qr_state))) if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Amplitude Estimation - Cirq") # if main, execute method if __name__ == '__main__': run()
11,316
36.97651
143
py