repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/h-rathee851/Pulse_application_qiskit
h-rathee851
from calibration import * IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main') """ Object to calibrate pulse of backend and qubit of interest. """ # Importing required python packages from warnings import warn import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.signal import find_peaks from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis # Importing standard Qiskit libraries from qiskit import IBMQ, execute, pulse from qiskit.providers.ibmq import IBMQBackend from qiskit.pulse import DriveChannel, Schedule, Play from qiskit.pulse import library as pulse_lib from qiskit.pulse.library import Waveform, Gaussian from qiskit.tools.monitor import job_monitor from qiskit.providers.exceptions import QiskitBackendNotFoundError, BackendConfigurationError # Loading your IBM Q account(s) #IBMQ.load_account() #provider = IBMQ.get_provider() class PulseCalibration(): """Creates an object that is used for pulse calibration. Args: backend (IBMQBackend) : The IBMQBackend for which pulse calibration needs to be done. qubit (int) : The qubit for which the pulse calibration is done. qubit_freq_ground (float) : Custom frequency for 0->1 transition. qubit_freq_excited (float) : Custom frequency for 1->2 transition. pi_amp_ground (float) : Custom pi amplitude for 0->1 transition. The value should be between 0 and 1. pi_amp_excited (float) : Custom pi amplitude for 1->2 transition. The value should be between 0 and 1. pulse_dur (int) : The duration of the pi pulse to be used for calibration. pulse_sigma (int) : The standard deviation of the pi pulse to be used for calibration. """ def __init__(self, backend, qubit, qubit_freq_ground=None, qubit_freq_excited=None, pi_amp_ground=None, pi_amp_excited=None, pulse_dur=None, pulse_sigma=None): # pylint: disable=too-many-locals # pylint: disable=too-many-arguments if not isinstance(backend, IBMQBackend): raise QiskitBackendNotFoundError("Provided backend not available." + "Please provide backend after obtaining from IBMQ.") self._backend = backend self._back_config = backend.configuration() if qubit >= self._back_config.n_qubits: raise BackendConfigurationError(f"Qubit {qubit} not present in the provided backend.") self._qubit = qubit self._back_defaults = backend.defaults() self._qubit_anharmonicity = backend.properties().qubit_property(self._qubit)['anharmonicity'][0] self._dt = self._back_config.dt self._qubit_freq = self._back_defaults.qubit_freq_est[self._qubit] self._inst_sched_map = self._back_defaults.instruction_schedule_map self._drive_chan = DriveChannel(qubit) if pulse_sigma: self._pulse_sigma = pulse_sigma else: if self._backend.name() == 'ibmq_armonk': self._pulse_sigma = 80 else: self._pulse_sigma = 40 if pulse_dur: self._pulse_duration = pulse_dur else: self._pulse_duration = (4*self._pulse_sigma)-((4*self._pulse_sigma) % 16) self._qubit_freq_ground = qubit_freq_ground self._qubit_freq_excited = qubit_freq_excited self._pi_amp_ground = pi_amp_ground self._pi_amp_excited = pi_amp_excited self._state_discriminator_012 = None # Find out which measurement map index is needed for this qubit meas_map_idx = None for i, measure_group in enumerate(self._back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" # The measurement pulse for measuring the qubit of interest. self._measure = self._inst_sched_map.get('measure', qubits=self._back_config.meas_map[meas_map_idx]) def create_cal_circuit(self, amp): """Constructs and returns a schedule containing Gaussian pulse with amplitude as 'amp', sigma as 'pulse_sigma' and duration as 'pulse_duration'.""" sched = Schedule() sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=amp), self._drive_chan) sched += self._measure << sched.duration return sched def create_cal_circuit_excited(self, base_pulse, freq): """ Constructs and returns a schedule containing a pi pulse for 0->1 transition followed by a sidebanded pulse which corresponds to applying 'base_pulse' at frequency 'freq'.""" sched = Schedule() sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground), self._drive_chan) sched += Play(self.apply_sideband(base_pulse, freq), self._drive_chan) sched += self._measure << sched.duration return sched @staticmethod def _fit_function(x_values, y_values, function, init_params): """ A function fitter. Returns the fit parameters of 'function'.""" fitparams, _ = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit @staticmethod def _baseline_remove(values): """Centering data around zero.""" return np.array(values) - np.mean(values) def apply_sideband(self, pulse, frequency): """Apply a sine sideband to 'pulse' at frequency 'freq'. Args: pulse (Waveform): The pulse to which sidebanding is to be applied. frequency (float): LO frequency at which the pulse is to be applied. Returns: Waveform: The sidebanded pulse. """ t_samples = np.linspace(0, self._dt*self._pulse_duration, self._pulse_duration) sine_pulse = np.sin(2*np.pi*(frequency-self._qubit_freq_ground)*t_samples) sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse), name='sideband_pulse') return sideband_pulse def get_job_data(self, job, average): """Retrieve data from a job that has already run. Args: job (Job): The job whose data you want. average (bool): If True, gets the data assuming data is an average. If False, gets the data assuming it is for single shots. Return: list: List containing job result data. """ scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[self._qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, self._qubit]*scale_factor) return result_data # Prints out relative maxima frequencies in output_data; height gives lower bound (abs val) @staticmethod def _rel_maxima(freqs, output_data, height, distance): """Prints out relative maxima frequencies in output_data (can see peaks); height gives upper bound (abs val). Be sure to set the height properly or the peak will be ignored! Args: freqs (list): frequency list output_data (list): list of resulting signals height (float): upper bound (abs val) on a peak width (float): Returns: list: List containing relative maxima frequencies """ peaks, _ = find_peaks(x=output_data, height=height, distance=distance) return freqs[peaks] def find_freq_ground(self, verbose=False, visual=False): """Sets and returns the calibrated frequency corresponding to 0->1 transition.""" # pylint: disable=too-many-locals sched_list = [self.create_cal_circuit(0.5)]*75 freq_list = np.linspace(self._qubit_freq-(45*1e+6), self._qubit_freq+(45*1e+6), 75) sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{self._drive_chan: freq} for freq in freq_list]) jid = sweep_job.job_id() if verbose: print("Executing the Frequency sweep job for 0->1 transition.") print('Job Id : ', jid) # job_monitor(sweep_job) sweep_job = self._backend.retrieve_job(jid) sweep_result = sweep_job.result() sweep_values = [] for i in range(len(sweep_result.results)): # Get the results from the ith experiment res = sweep_result.get_memory(i)*1e-14 # Get the results for `qubit` from this experiment sweep_values.append(res[self._qubit]) freq_list_GHz = freq_list/1e+9 if visual: print("The frequency-signal plot for frequency sweep: ") plt.scatter(freq_list_GHz, np.real(sweep_values), color='black') plt.xlim([min(freq_list_GHz), max(freq_list_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() # def find_init_params(freq_list, res_values): # hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] # hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] # if hmin_index < hmax_index: # est_baseline = min(res_values) # est_slope = (res_values[hmax_index] - res_values[hmin_index])/(freq_list[hmax_index] - freq_list[hmin_index]) # else: # est_baseline = max(res_values) # est_slope = (res_values[hmin_index] - res_values[hmax_index])/(freq_list[hmin_index] - freq_list[hmax_index]) # return [est_slope, self._qubit_freq/1e9, 1, est_baseline] def find_init_params_gauss(freq_list, res_values): hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] mean_est = freq_list[hmax_index] var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2 scale_est = max(res_values)-min(res_values) shift_est = min(res_values) return [mean_est, var_est, scale_est, shift_est] def gauss(x, mean, var, scale, shift): return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift def lorentzian(xval, scale, q_freq, hwhm, shift): return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift # do fit in Hz init_params = find_init_params_gauss(freq_list_GHz, np.real(sweep_values)) # init_params = find_init_params(freq_list_GHz, np.real(sweep_values)) print('ground freq init params : ', init_params) # Obtain the optimal paramters that fit the result data. # fit_params, y_fit = self._fit_function(freq_list_GHz, # np.real(sweep_values), # lorentzian, # init_params # init parameters for curve_fit # ) fit_params, y_fit = self._fit_function(freq_list_GHz, np.real(sweep_values), gauss, init_params # init parameters for curve_fit ) if visual: print("The frequency-signal plot for frequency sweep: ") plt.scatter(freq_list_GHz, np.real(sweep_values), color='black') plt.plot(freq_list_GHz, y_fit, color='red') plt.xlim([min(freq_list_GHz), max(freq_list_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() qubit_freq_new, _, _, _ = fit_params self._qubit_freq_ground = qubit_freq_new*1e9 if verbose: print(f"The calibrate frequency for the 0->1 transition is {self._qubit_freq_ground}") return [self._qubit_freq_ground, freq_list_GHz, sweep_values] def find_pi_amp_ground(self, verbose=False, visual=False): """Sets and returns the amplitude of the pi pulse corresponding to 0->1 transition.""" # pylint: disable=too-many-locals if not self._qubit_freq_ground: warn("ground_qubit_freq not computed yet and custom qubit freq not provided." + "Computing ground_qubit_freq now.") self._qubit_freq_ground = self.find_freq_ground(verbose, visual) amp_list = np.linspace(0, 1, 75) rabi_sched_list = [self.create_cal_circuit(amp) for amp in amp_list] rabi_list_len = len(rabi_sched_list) rabi_job = execute(rabi_sched_list,backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(rabi_sched_list)) jid = rabi_job.job_id() if verbose: print("Executing the rabi oscillation job to get Pi pulse for 0->1 transition.") print('Job Id : ', jid) # job_monitor(rabi_job) rabi_job = self._backend.retrieve_job(jid) rabi_results = rabi_job.result() scale_factor = 1e-14 rabi_values = [] for i in range(75): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[self._qubit]*scale_factor) rabi_values = np.real(self._baseline_remove(rabi_values)) def find_init_params_amp(amp_list, rabi_values): min_index = np.where(rabi_values==min(rabi_values))[0][0] max_index = np.where(rabi_values==max(rabi_values))[0][0] scale_est = (max(rabi_values) - min(rabi_values))/2 shift_est = (max(rabi_values) + min(rabi_values))/2 shift_est = np.mean(rabi_values) period_est = 0.5 if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5: phi_est = np.pi/2 else: phi_est = -np.pi/2 return [scale_est, shift_est, period_est, phi_est] # Obtain the optimal paramters that fit the result data. init_params = find_init_params_amp(amp_list,rabi_values) fit_params, y_fit = self._fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), init_params) drive_period = fit_params[2] self._pi_amp_ground = drive_period/2 if verbose: print(f"The Pi amplitude of 0->1 transition is {self._pi_amp_ground}.") if visual: print("The amplitude-signal plot for rabi oscillation for 0->1 transition.") plt.figure() plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2, 0), arrowprops=dict(arrowstyle="<->", color='red')) #plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() return [self._pi_amp_ground, amp_list, rabi_values] def find_freq_excited(self, verbose=False, visual=False): """Sets and returns the frequency corresponding to 1->2 transition.""" # pylint: disable=too-many-locals if not self._qubit_freq_ground: raise ValueError("The qubit_freq_ground is not determined. Please determine" + "qubit_freq_ground first.") if not self._pi_amp_ground: raise ValueError("The pi_amp_ground is not determined.\ Please determine pi_amp_ground first.") base_pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=0.3) sched_list = [] # Here we assume that the anharmocity is about 8% for all qubits. excited_freq_list = self._qubit_freq_ground + self._qubit_anharmonicity + np.linspace(-30*1e+6, 30*1e+6, 75) for freq in excited_freq_list: sched_list.append(self.create_cal_circuit_excited(base_pulse, freq)) excited_sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(excited_freq_list) ) jid = excited_sweep_job.job_id() excited_freq_list_GHz = excited_freq_list/1e+9 if verbose: print("Executing the Frequency sweep job for 1->2 transition.") print('Job Id : ', jid) # job_monitor(excited_sweep_job) excited_sweep_job = self._backend.retrieve_job(jid) excited_sweep_data = self.get_job_data(excited_sweep_job, average=True) if visual: print("The frequency-signal plot of frequency sweep for 1->2 transition.") # Note: we are only plotting the real part of the signal plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black') plt.xlim([min(excited_freq_list_GHz), max(excited_freq_list_GHz)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep", fontsize=15) plt.show() def find_init_params_gauss(freq_list, res_values): hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] mean_est = freq_list[hmax_index] var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2 scale_est = max(res_values)-min(res_values) shift_est = min(res_values) return [mean_est, var_est, scale_est, shift_est] def gauss(x, mean, var, scale, shift): return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift def lorentzian(xval, scale, q_freq, hwhm, shift): return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift # do fit in Hz # init_params = find_init_params(excited_freq_list_GHz, np.real(excited_sweep_data)) init_params = find_init_params_gauss(excited_freq_list_GHz, np.real(excited_sweep_data)) print("Init params : ", init_params) excited_sweep_fit_params, excited_sweep_y_fit = self._fit_function(excited_freq_list_GHz, excited_sweep_data, gauss, init_params ) if visual: print("The frequency-signal plot of frequency sweep for 1->2 transition.") # Note: we are only plotting the real part of the signal plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black') plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red') plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep", fontsize=15) plt.show() qubit_freq_12, _, _, _ = excited_sweep_fit_params self._qubit_freq_excited = qubit_freq_12*1e+9 if verbose: print(f"The calibrated frequency for the 1->2 transition\ is {self._qubit_freq_excited}.") return [self._qubit_freq_excited, excited_freq_list, excited_sweep_data] def find_pi_amp_excited(self, verbose=False, visual=False): """Sets and returns the amplitude of the pi pulse corresponding to 1->2 transition.""" if not self._qubit_freq_excited: warn("ground_qubit_freq not computed yet and custom qubit freq not provided." + "Computing ground_qubit_freq now.") self._qubit_freq_ground = self.find_freq_excited(verbose, visual) amp_list = np.linspace(0, 1.0, 75) rabi_sched_list = [] for amp in amp_list: base_pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=amp) rabi_sched_list.append(self.create_cal_circuit_excited(base_pulse, self._qubit_freq_excited)) rabi_job = execute(rabi_sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*75 ) jid = rabi_job.job_id() if verbose: print("Executing the rabi oscillation job for 1->2 transition.") print('Job Id : ', jid) # job_monitor(rabi_job) rabi_job = self._backend.retrieve_job(jid) rabi_data = self.get_job_data(rabi_job, average=True) rabi_data = np.real(self._baseline_remove(rabi_data)) if visual: print("The amplitude-signal plot of rabi oscillation for 1->2 transition.") plt.figure() plt.scatter(amp_list, rabi_data, color='black') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.title('Rabi Experiment (1->2)', fontsize=20) plt.show() def find_init_params_amp(amp_list, rabi_values): min_index = np.where(rabi_values==min(rabi_values))[0][0] max_index = np.where(rabi_values==max(rabi_values))[0][0] scale_est = (max(rabi_values) - min(rabi_values))/2 shift_est = (max(rabi_values) + min(rabi_values))/2 shift_est = np.mean(rabi_values) period_est = 0.5 if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5: phi_est = np.pi/2 else: phi_est = -np.pi/2 return [scale_est, shift_est, period_est, phi_est] init_params = find_init_params_amp(amp_list, rabi_data) print('Init params for 01 amp : ', init_params) (rabi_fit_params, rabi_y_fit) = self._fit_function(amp_list, rabi_data, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), init_params) drive_period_excited = rabi_fit_params[2] pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3]) self._pi_amp_excited = pi_amp_excited if visual: print("The amplitude-signal plot of rabi oscillation for 1->2 transition.") plt.figure() plt.scatter(amp_list, rabi_data, color='black') plt.plot(amp_list, rabi_y_fit, color='red') # account for phi in computing pi amp plt.axvline(self._pi_amp_excited, color='red', linestyle='--') plt.axvline(self._pi_amp_excited+drive_period_excited/2, color='red', linestyle='--') plt.annotate("", xy=(self._pi_amp_excited+drive_period_excited/2, 0), xytext=(self._pi_amp_excited, 0), arrowprops=dict(arrowstyle="<->", color='red')) #plt.annotate("$\\pi$", xy=(self._pi_amp_excited-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.title('Rabi Experiment (1->2)', fontsize=20) plt.show() return [self._pi_amp_excited, amp_list, rabi_data] def get_pi_pulse_ground(self): """Returns a pi pulse of the 0->1 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground) return pulse def get_pi_pulse_excited(self): """Returns a pi pulse of the 1->2 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_excited) excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited) return excited_pulse def get_x90_pulse_ground(self): """Returns a pi/2 pulse of the 0->1 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground/2) return pulse def get_x90_pulse_excited(self): """Returns a pi/2 pulse of the 1->2 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_excited/2) excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited) return excited_pulse def get_zero_sched(self): """Returns a schedule that performs only a measurement.""" zero_sched = Schedule() zero_sched += self._measure return zero_sched def get_one_sched(self): """Returns a schedule that creates a |1> state from |0> by applying a pi pulse of 0->1 transition and performs a measurement.""" one_sched = Schedule() one_sched += Play(self.get_pi_pulse_ground(), self._drive_chan) one_sched += self._measure << one_sched.duration return one_sched def get_two_sched(self): """Returns a schedule that creates a |2> state from |0> by applying a pi pulse of 0->1 transition followed by applying a pi pulse of 1->2 transition and performs a measurement.""" two_sched = Schedule() two_sched += Play(self.get_pi_pulse_ground(), self._drive_chan) two_sched += Play(self.get_pi_pulse_excited(), self._drive_chan) two_sched += self._measure << two_sched.duration return two_sched @staticmethod def _create_iq_plot(zero_data, one_data, two_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') # two data plotted in green plt.scatter(np.real(two_data), np.imag(two_data), s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$') x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))-5 x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))+5 y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))-5 y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) mean_two = np.mean(two_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_two), np.imag(mean_two), s=200, cmap='viridis', c='black', alpha=1.0) # plt.xlim(x_min, x_max) # plt.ylim(y_min, y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1-2 discrimination", fontsize=15) return x_min, x_max, y_min, y_max @staticmethod def reshape_complex_vec(vec): """Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning. Args: vec (list): complex vector of data Returns: list: vector w/ entries given by (real(vec], imag(vec)) """ length = len(vec) vec_reshaped = np.zeros((length, 2)) for i, item in enumerate(vec): vec_reshaped[i] = [np.real(item), np.imag(item)] return vec_reshaped def find_three_level_discriminator(self, verbose=False, visual=False): """Returns a discriminator for discriminating 0-1-2 states.""" # pylint: disable=too-many-locals zero_sched = self.get_zero_sched() one_sched = self.get_one_sched() two_sched = self.get_two_sched() iq_job = execute([zero_sched, one_sched, two_sched], backend=self._backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*3 ) jid = iq_job.job_id() if verbose: print('Job Id : ', jid) # job_monitor(iq_job) iq_job = self._backend.retrieve_job(jid) iq_data = self.get_job_data(iq_job, average=False) zero_data = iq_data[0] one_data = iq_data[1] two_data = iq_data[2] if visual: print("The discriminator plot for 0-1-2 discrimination.") x_min, x_max, y_min, y_max = self._create_iq_plot(zero_data, one_data, two_data) # Create IQ vector (split real, imag parts) zero_data_reshaped = self.reshape_complex_vec(zero_data) one_data_reshaped = self.reshape_complex_vec(one_data) two_data_reshaped = self.reshape_complex_vec(two_data) iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped)) # construct vector w/ 0's, 1's and 2's (for testing) state_012 = np.zeros(1024) # shots gives number of experiments state_012 = np.concatenate((state_012, np.ones(1024))) state_012 = np.concatenate((state_012, 2*np.ones(1024))) # Shuffle and split data into training and test sets iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data, state_012, test_size=0.5) classifier_lda_012 = LinearDiscriminantAnalysis() classifier_lda_012.fit(iq_012_train, state_012_train) score_012 = classifier_lda_012.score(iq_012_test, state_012_test) if verbose: print('The accuracy score of the discriminator is: ', score_012) self._state_discriminator_012 = classifier_lda_012 if visual: self._separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024) return self._state_discriminator_012 @staticmethod def _separatrix_plot(lda, x_min, x_max, y_min, y_max, shots): """Returns a sepratrix plot for the classifier.""" # pylint: disable=too-many-arguments num_x, num_y = shots, shots xvals, vals = np.meshgrid(np.linspace(x_min, x_max, num_x), np.linspace(y_min, y_max, num_y)) predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()]) predict_prob = predict_prob[:, 1].reshape(xvals.shape) plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black') def get_qubit_freq_ground(self): """Returns the set 0->1 transition frequency.""" return self._qubit_freq_ground def get_qubit_freq_excited(self): """Returns the set 1->2 transition frequency.""" return self._qubit_freq_excited def get_pi_amp_ground(self): """Returns the set 0->1 transition pi pulse amplitude.""" return self._pi_amp_ground def get_pi_amp_excited(self): """Returns the set 1->2 transition pi pulse amplitude.""" return self._pi_amp_excited def get_three_level_discriminator(self): """Returns the set 0-1-2 state discriminator.""" return self._state_discriminator_012 def calibrate_all(self, verbose=False, visual=False): """Calibrates and sets both the ground and excited transition frequencies and corresponding pi pulse amplitudes. Also constructs a 0-1-2 state discriminator.""" ground_freq = self.find_freq_ground(verbose, visual) ground_amp = self.find_pi_amp_ground(verbose, visual) excited_freq = self.find_freq_excited(verbose, visual) excited_amp = self.find_pi_amp_excited(verbose, visual) state_discriminator = self.find_three_level_discriminator(verbose, visual) return ground_freq, ground_amp, excited_freq, excited_amp, state_discriminator anharmon = backend.properties().qubit_property(qubit)['anharmonicity'][0] qu_freq = backend.properties().qubit_property(qubit)['frequency'][0] print(qu_freq) print(anharmon) print(qu_freq+anharmon) backend = provider.get_backend('ibmq_casablanca') # backend = provider.get_backend('ibmq_jakarta') # backend = provider.get_backend('ibmq_rome') qubit = 0 cal_object = PulseCalibration(backend, qubit) visual = True verbose = True ground_freq_list = cal_object.find_freq_ground(verbose, visual) [ground_freq, freq_list, sweep_vals] = ground_freq_list print(ground_freq) cal_object = PulseCalibration(backend, qubit, qubit_freq_ground=ground_freq) ground_amp_list = cal_object.find_pi_amp_ground(verbose, visual) pi_amp_ground = ground_amp_list[0] amp_list = ground_amp_list[1] rabi_values = ground_amp_list[2] def find_init_params_amp(amp_list, rabi_values): min_index = np.where(rabi_values==min(rabi_values))[0][0] max_index = np.where(rabi_values==max(rabi_values))[0][0] scale_est = (max(rabi_values) - min(rabi_values))/2 shift_est = amp_list[min_index] period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index]) slope = np.sign(rabi_values[1]-rabi_values[0]) if slope < 0: phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) else: phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) return [scale_est, shift_est, period_est, phi_est] def find_init_params_amp(amp_list, rabi_values): min_index = np.where(rabi_values==min(rabi_values))[0][0] max_index = np.where(rabi_values==max(rabi_values))[0][0] scale_est = (max(rabi_values) - min(rabi_values))/2 shift_est = (max(rabi_values) + min(rabi_values))/2 shift_est = np.mean(rabi_values) # period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index]) period_est = 0.5 slope = np.sign(rabi_values[1]-rabi_values[0]) if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5: phi_est = np.pi/2 else: phi_est = -np.pi/2 # if slope >= 0: # phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) # else: # phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) return [scale_est, shift_est, period_est, phi_est] def fit_function(x_values, y_values, function, init_params): """ A function fitter. Returns the fit parameters of 'function'.""" fitparams, _ = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit # Obtain the optimal paramters that fit the result data. init_params = find_init_params_amp(amp_list,rabi_values) print(init_params) # init_params = [3.0733272e-07, 0.5, 0.25, 1.57] fit_params, y_fit = fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), init_params) drive_period = fit_params[2] pi_amp_ground = drive_period/2 print(fit_params) print("The amplitude-signal plot for rabi oscillation for 0->1 transition.") plt.figure() plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2, 0), arrowprops=dict(arrowstyle="<->", color='red')) plt.annotate("$\pi$", xy=(drive_period/2-0.04, np.mean(rabi_values)), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() fit_params cal_object._pi_amp_ground=pi_amp_ground print(ground_freq) print(pi_amp_ground) cal_object = PulseCalibration(backend, qubit, qubit_freq_ground=ground_freq, pi_amp_ground=pi_amp_ground) excited_list = cal_object.find_freq_excited(verbose, visual) excited_freq = excited_list[0] excited_freq_list = excited_list[1] excited_sweep_data = excited_list[2] excited_freq_list_GHz = excited_freq_list/1e+9 excited_freq if visual: print("The frequency-signal plot of frequency sweep for 1->2 transition.") # Note: we are only plotting the real part of the signal plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black') plt.xlim([min(excited_freq_list_GHz), max(excited_freq_list_GHz)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep", fontsize=15) plt.show() # qubit_anharmon = backend.properties().qubit_property(0)['anharmonicity'][0] # qubit_freq = backend.properties().qubit_property(0)['frequency'][0] # qubit_anharmon # qubit_freq+qubit_anharmon # def fit_function(x_values, y_values, function, init_params): # """ A function fitter. Returns the fit parameters of 'function'.""" # fitparams, _ = curve_fit(function, x_values, y_values, init_params) # y_fit = function(x_values, *fitparams) # return fitparams, y_fit # # def find_init_params(freq_list, res_values): # # hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] # # hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] # # if hmin_index < hmax_index: # # est_baseline = min(res_values) # # est_slope = (res_values[hmax_index] - res_values[hmin_index])/(freq_list[hmax_index] - freq_list[hmin_index]) # # else: # # est_baseline = max(res_values) # # est_slope = (res_values[hmin_index] - res_values[hmax_index])/(freq_list[hmin_index] - freq_list[hmax_index]) # # return [est_slope, (qubit_freq+qubit_anharmon)/1e9, 0.05*1e+9, est_baseline] # def find_init_params_gauss(freq_list, res_values): # hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] # hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] # mean_est = freq_list[hmax_index] # var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2 # scale_est = max(res_values)-min(res_values) # shift_est = min(res_values) # return [mean_est, var_est, scale_est, shift_est] # def lorentzian(xval, scale, q_freq, hwhm, shift): # return ((scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2))) + shift # def gauss(x, mean, var, scale, shift): # return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift # # do fit in Hz # # init_params = find_init_params(excited_freq_list_GHz, np.real(excited_sweep_data)) # init_params = find_init_params_gauss(excited_freq_list_GHz, np.real(excited_sweep_data)) # print("Init params : ", init_params) # # excited_sweep_fit_params, excited_sweep_y_fit = fit_function(excited_freq_list_GHz, # # excited_sweep_data, # # lorentzian, # # [1e-7, 4631077333.915148, 0.08, -2.6e-7] # # ) # excited_sweep_fit_params, excited_sweep_y_fit = fit_function(excited_freq_list_GHz, # excited_sweep_data, # gauss, # init_params # ) # # xlist = qubit_freq+qubit_anharmon + np.arange(-4,4,0.1) # # y = [lorentzian(x,0.00002,(qubit_freq+qubit_anharmon)/1e+9, 1, 0) for x in excited_freq_list_GHz] # shift = -2.6e-7 # y = [(1e-7*lor(x,(qubit_freq+qubit_anharmon)/1e+9,0.08))+shift for x in excited_freq_list_GHz] # if visual: # print("The frequency-signal plot of frequency sweep for 1->2 transition.") # # Note: we are only plotting the real part of the signal # plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black') # # plt.plot(excited_freq_list_GHz, y, color='green') # plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red') # # plt.plot(excited_freq_list_GHz, shift, color='blue') # plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)]) # plt.xlabel("Frequency [GHz]", fontsize=15) # plt.ylabel("Measured Signal [a.u.]", fontsize=15) # plt.title("1->2 Frequency Sweep", fontsize=15) # plt.show() # qubit_freq_12,_, _, _ = excited_sweep_fit_params # print('fit params : ', excited_sweep_fit_params) # qubit_freq_excited = qubit_freq_12*1e+9 # if verbose: # print(f"The calibrated frequency for the 1->2 transition is {qubit_freq_excited}.") # def gauss(x, mean, var, scale, shift): # return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift # function = gauss # x_values = excited_freq_list_GHz # y_values = excited_sweep_data # init_params = [4.63, 0.02, 1e-7, 1] # fitparams, _ = curve_fit(function, x_values, y_values, init_params) # y_fit = function(x_values, *fitparams) # plt.plot(excited_freq_list_GHz, y_fit, color='red') # plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black') cal_object = PulseCalibration(backend, qubit, qubit_freq_ground=ground_freq, pi_amp_ground=pi_amp_ground, qubit_freq_excited = excited_freq) pi_amp_excited_list = cal_object.find_pi_amp_excited(verbose, visual) [excited_amp, amp_list, rabi_data] = pi_amp_excited_list def fit_function(x_values, y_values, function, init_params): """ A function fitter. Returns the fit parameters of 'function'.""" fitparams, _ = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit def baseline_remove(values): """Centering data around zero.""" return np.array(values) - np.mean(values) # def find_init_params_amp(amp_list, rabi_values): # min_index = np.where(rabi_values==min(rabi_values))[0][0] # max_index = np.where(rabi_values==max(rabi_values))[0][0] # scale_est = (max(rabi_values) - min(rabi_values))/2 # shift_est = amp_list[min_index] # period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index]) # slope = np.sign(rabi_values[1]-rabi_values[0]) # if slope < 0: # phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) # else: # phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) # return [scale_est, shift_est, period_est, phi_est] def find_init_params_amp(amp_list, rabi_values): min_index = np.where(rabi_values==min(rabi_values))[0][0] max_index = np.where(rabi_values==max(rabi_values))[0][0] scale_est = (max(rabi_values) - min(rabi_values))/2 shift_est = (max(rabi_values) + min(rabi_values))/2 shift_est = np.mean(rabi_values) # period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index]) period_est = 0.5 slope = np.sign(rabi_values[1]-rabi_values[0]) if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5: phi_est = np.pi/2 else: phi_est = -np.pi/2 # if slope >= 0: # phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) # else: # phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi) return [scale_est, shift_est, period_est, phi_est] init_params = find_init_params_amp(amp_list, rabi_data) print('Init params for 01 amp : ', init_params) # init_params = [8.797258e-08, 0, 0.4, np.pi/2] print('Init params for 01 amp : ', init_params) (rabi_fit_params, rabi_y_fit) = fit_function(amp_list, rabi_data, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), init_params) drive_period_excited = rabi_fit_params[2] pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3]) # pi_amp_excited = pi_amp_excited if visual: print("The amplitude-signal plot of rabi oscillation for 1->2 transition.") plt.figure() plt.scatter(amp_list, rabi_data, color='black') plt.plot(amp_list, rabi_y_fit, color='red') # # account for phi in computing pi amp plt.axvline(pi_amp_excited, color='red', linestyle='--') plt.axvline(pi_amp_excited+drive_period_excited/2, color='red', linestyle='--') plt.annotate("", xy=(pi_amp_excited+drive_period_excited/2, 0), xytext=(pi_amp_excited, 0), arrowprops=dict(arrowstyle="<->", color='red')) # plt.annotate("$\\pi$", xy=(pi_amp_excited-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.title('Rabi Experiment (1->2)', fontsize=20) plt.show() pi_amp_excited rabi_fit_params print(ground_freq) print(pi_amp_ground) print(excited_freq) print(pi_amp_excited) cal_object = PulseCalibration(backend, qubit, qubit_freq_ground=ground_freq, pi_amp_ground=pi_amp_ground, qubit_freq_excited = excited_freq, pi_amp_excited=pi_amp_excited ) discrim = cal_object.find_three_level_discriminator(verbose, visual) def create_iq_plot(zero_data, one_data, two_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') # two data plotted in green plt.scatter(np.real(two_data), np.imag(two_data), s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$') x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))-5 x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))+5 y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))-5 y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) mean_two = np.mean(two_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_two), np.imag(mean_two), s=200, cmap='viridis', c='black', alpha=1.0) # plt.xlim(x_min, x_max) # plt.ylim(y_min, y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1-2 discrimination", fontsize=15) return x_min, x_max, y_min, y_max def reshape_complex_vec(vec): """Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning. Args: vec (list): complex vector of data Returns: list: vector w/ entries given by (real(vec], imag(vec)) """ length = len(vec) vec_reshaped = np.zeros((length, 2)) for i, item in enumerate(vec): vec_reshaped[i] = [np.real(item), np.imag(item)] return vec_reshaped def separatrix_plot(lda, x_min, x_max, y_min, y_max, shots): """Returns a sepratrix plot for the classifier.""" # pylint: disable=too-many-arguments num_x, num_y = shots, shots xvals, vals = np.meshgrid(np.linspace(x_min-4, x_max+4, num_x), np.linspace(y_min-4, y_max+4, num_y)) predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()]) predict_prob = predict_prob[:, 1].reshape(xvals.shape) plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black') def get_job_data(job, average): """Retrieve data from a job that has already run. Args: job (Job): The job whose data you want. average (bool): If True, gets the data assuming data is an average. If False, gets the data assuming it is for single shots. Return: list: List containing job result data. """ scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor) return result_data iq_job = backend.retrieve_job('60b46e055255f0dc9738af93') iq_data = get_job_data(iq_job, average=False) zero_data = iq_data[0] one_data = iq_data[1] two_data = iq_data[2] if visual: print("The discriminator plot for 0-1-2 discrimination.") x_min, x_max, y_min, y_max = create_iq_plot(zero_data, one_data, two_data) # Create IQ vector (split real, imag parts) zero_data_reshaped = reshape_complex_vec(zero_data) one_data_reshaped = reshape_complex_vec(one_data) two_data_reshaped = reshape_complex_vec(two_data) iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped)) # construct vector w/ 0's, 1's and 2's (for testing) state_012 = np.zeros(1024) # shots gives number of experiments state_012 = np.concatenate((state_012, np.ones(1024))) state_012 = np.concatenate((state_012, 2*np.ones(1024))) # Shuffle and split data into training and test sets iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data, state_012, test_size=0.5) classifier_lda_012 = LinearDiscriminantAnalysis() classifier_lda_012.fit(iq_012_train, state_012_train) score_012 = classifier_lda_012.score(iq_012_test, state_012_test) if verbose: print('The accuracy score of the discriminator is: ', score_012) state_discriminator_012 = classifier_lda_012 if visual: x_min, x_max, y_min, y_max = create_iq_plot(zero_data, one_data, two_data) separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024) # return self._state_discriminator_012 back_config = backend.configuration() back_defaults = backend.defaults() inst_sched_map = back_defaults.instruction_schedule_map meas_map_idx = None for i, measure_group in enumerate(back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" # The measurement pulse for measuring the qubit of interest. measure = inst_sched_map.get('measure', qubits=back_config.meas_map[meas_map_idx]) sigma = 40 duration = 4*40 chan = DriveChannel(0) with pulse.build(backend) as test_0: pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan) pulse.set_frequency(excited_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited), chan) test_0 += measure << test_0.duration test_0.draw() test0_job = execute(test_0, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test0 = test0_job.job_id() print(jid_test0) test0_job = backend.retrieve_job(jid_test0) res = get_job_data(test0_job, average=False) res[0] reshaped_res = reshape_complex_vec(res[0]) plt.scatter(np.real(res[0]), np.imag(res[0])) plt.show() output = discrim.predict(reshaped_res) arr = [0,0,0] for i in output: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) with pulse.build(backend) as test_00: pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan) test_00 += measure << test_00.duration test_00.draw() test00_job = execute(test_00, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test00 = test00_job.job_id() print(jid_test00) test00_job = backend.retrieve_job(jid_test00) res00 = get_job_data(test00_job, average=False) res[0] reshaped_res00 = reshape_complex_vec(res00[0]) plt.scatter(np.real(res[0]), np.imag(res00[0])) plt.show() output00 = discrim.predict(reshaped_res00) arr = [0,0,0] for i in output00: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H then Z then H gate on 0-1 # Should get |1> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_1: # Setting 0-1 frequency for channel and applying H gate pulse.set_frequency(ground_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Applying a Z pulse pulse.shift_phase(np.pi, chan) # Applying H gate on 0-1 pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_1 += measure << test_pulse_1.duration test_pulse_1.draw() test1_job = execute(test_pulse_1, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test1 = test1_job.job_id() print(jid_test1) test1_job = backend.retrieve_job(jid_test1) res1 = get_job_data(test1_job, average=False) reshaped_res1 = reshape_complex_vec(res1[0]) plt.scatter(np.real(res1[0]), np.imag(res1[0])) plt.show() output1 = discrim.predict(reshaped_res1) arr = [0,0,0] for i in output1: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H then Z then H gate on 1-2 # Should get |2> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_2: # Exciting the qubit to |1> state pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) # Setting 1-2 frequency for channel and applying H gate pulse.set_frequency(excited_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Applying a Z pulse pulse.shift_phase(np.pi, chan) # Applying H gate on 1-2 pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_2 += measure << test_pulse_2.duration test_pulse_2.draw() test2_job = execute(test_pulse_2, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test2 = test2_job.job_id() print(jid_test2) test2_job = backend.retrieve_job(jid_test2) res2 = get_job_data(test2_job, average=False) reshaped_res2 = reshape_complex_vec(res2[0]) plt.scatter(np.real(res2[0]), np.imag(res2[0])) plt.show() output2 = discrim.predict(reshaped_res2) arr = [0,0,0] for i in output2: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H on 0-1, then H on 1-2 # then Z on 1-2 followed by H on 1-2 # Should get |0>/sqrt(2) + |2>/sqrt(2) chan = DriveChannel(0) with pulse.build(backend) as test_pulse_3: # Setting 0-1 frequency for channel and applying H gate pulse.set_frequency(ground_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Undoing phase appied during 0-1 transitions pulse.shift_phase(np.pi, chan) # Setting 1-2 frequency for channel and applying H gate pulse.set_frequency(excited_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Applying a Z pulse pulse.shift_phase(np.pi, chan) # Applying H gate on 1-2 pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_3 += measure << test_pulse_3.duration test_pulse_3.draw() test3_job = execute(test_pulse_3, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test3 = test3_job.job_id() print(jid_test3) test3_job = backend.retrieve_job(jid_test3) res3 = get_job_data(test3_job, average=False) reshaped_res3 = reshape_complex_vec(res3[0]) plt.scatter(np.real(res3[0]), np.imag(res3[0])) plt.show() output3 = discrim.predict(reshaped_res3) arr = [0,0,0] for i in output3: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H on 1-2 # Should get |1>/sqrt(2) + |2>/sqrt(2) ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_4: # Exciting the qubit to |1> state pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) # Setting 1-2 frequency for channel and applying H gate pulse.set_frequency(excited_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_4 += measure << test_pulse_4.duration test_pulse_4.draw() test4_job = execute(test_pulse_4, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test4 = test4_job.job_id() print(jid_test4) test4_job = backend.retrieve_job(jid_test4) res4 = get_job_data(test4_job, average=False) reshaped_res4 = reshape_complex_vec(res4[0]) plt.scatter(np.real(res4[0]), np.imag(res4[0])) plt.show() output4 = discrim.predict(reshaped_res4) arr = [0,0,0] for i in output4: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H on 0-1 # Should get |0>/sqrt(2) + |1>/sqrt(2) ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_5: # Setting 0-1 frequency for channel and applying H gate pulse.set_frequency(ground_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_5 += measure << test_pulse_5.duration test_pulse_5.draw() test5_job = execute(test_pulse_5, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test5 = test5_job.job_id() print(jid_test5) test5_job = backend.retrieve_job(jid_test5) res5 = get_job_data(test5_job, average=False) reshaped_res5 = reshape_complex_vec(res5[0]) plt.scatter(np.real(res5[0]), np.imag(res5[0])) plt.show() output5 = discrim.predict(reshaped_res5) arr = [0,0,0] for i in output5: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a X on 0-1 # Should get |1> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_6: # Setting 0-1 frequency for channel and applying X gate pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) test_pulse_6 += measure << test_pulse_6.duration test_pulse_6.draw() test6_job = execute(test_pulse_6, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test6 = test6_job.job_id() print(jid_test6) test6_job = backend.retrieve_job(jid_test6) res6 = get_job_data(test6_job, average=False) reshaped_res6 = reshape_complex_vec(res6[0]) plt.scatter(np.real(res6[0]), np.imag(res6[0])) plt.show() output6 = discrim.predict(reshaped_res6) arr = [0,0,0] for i in output6: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a X on 1-2 # Should get |2> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_7: # Setting 0-1 frequency for channel and applying 0-1 pi pulse pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) # Setting 1-2 frequency for channel and applying 1-2 pi pulse pulse.set_frequency(excited_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited, name='X(pi)'), chan) test_pulse_7 += measure << test_pulse_7.duration test_pulse_7.draw() test7_job = execute(test_pulse_7, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test7 = test7_job.job_id() print(jid_test7) test7_job = backend.retrieve_job(jid_test7) res7 = get_job_data(test7_job, average=False) reshaped_res7 = reshape_complex_vec(res7[0]) plt.scatter(np.real(res7[0]), np.imag(res7[0])) plt.show() output7 = discrim.predict(reshaped_res7) arr = [0,0,0] for i in output7: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr)
https://github.com/h-rathee851/Pulse_application_qiskit
h-rathee851
from calibration import * IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main') """ Object to calibrate pulse of backend and qubit of interest. """ # Importing required python packages from warnings import warn import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.signal import find_peaks from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis # Importing standard Qiskit libraries from qiskit import IBMQ, execute, pulse from qiskit.providers.ibmq import IBMQBackend from qiskit.pulse import DriveChannel, Schedule, Play from qiskit.pulse import library as pulse_lib from qiskit.pulse.library import Waveform, Gaussian from qiskit.tools.monitor import job_monitor from qiskit.providers.exceptions import QiskitBackendNotFoundError, BackendConfigurationError # Loading your IBM Q account(s) #IBMQ.load_account() #provider = IBMQ.get_provider() class PulseCalibration(): """Creates an object that is used for pulse calibration. Args: backend (IBMQBackend) : The IBMQBackend for which pulse calibration needs to be done. qubit (int) : The qubit for which the pulse calibration is done. qubit_freq_ground (float) : Custom frequency for 0->1 transition. qubit_freq_excited (float) : Custom frequency for 1->2 transition. pi_amp_ground (float) : Custom pi amplitude for 0->1 transition. The value should be between 0 and 1. pi_amp_excited (float) : Custom pi amplitude for 1->2 transition. The value should be between 0 and 1. pulse_dur (int) : The duration of the pi pulse to be used for calibration. pulse_sigma (int) : The standard deviation of the pi pulse to be used for calibration. """ def __init__(self, backend, qubit, qubit_freq_ground=None, qubit_freq_excited=None, pi_amp_ground=None, pi_amp_excited=None, pulse_dur=None, pulse_sigma=None): # pylint: disable=too-many-locals # pylint: disable=too-many-arguments if not isinstance(backend, IBMQBackend): raise QiskitBackendNotFoundError("Provided backend not available." + "Please provide backend after obtaining from IBMQ.") self._backend = backend self._back_config = backend.configuration() if qubit >= self._back_config.n_qubits: raise BackendConfigurationError(f"Qubit {qubit} not present in the provided backend.") self._qubit = qubit self._back_defaults = backend.defaults() self._qubit_anharmonicity = backend.properties().qubit_property(self._qubit)['anharmonicity'][0] self._dt = self._back_config.dt self._qubit_freq = self._back_defaults.qubit_freq_est[self._qubit] self._inst_sched_map = self._back_defaults.instruction_schedule_map self._drive_chan = DriveChannel(qubit) if pulse_sigma: self._pulse_sigma = pulse_sigma else: if self._backend.name() == 'ibmq_armonk': self._pulse_sigma = 80 else: self._pulse_sigma = 40 if pulse_dur: self._pulse_duration = pulse_dur else: self._pulse_duration = (4*self._pulse_sigma)-((4*self._pulse_sigma) % 16) self._qubit_freq_ground = qubit_freq_ground self._qubit_freq_excited = qubit_freq_excited self._pi_amp_ground = pi_amp_ground self._pi_amp_excited = pi_amp_excited self._state_discriminator_012 = None # Find out which measurement map index is needed for this qubit meas_map_idx = None for i, measure_group in enumerate(self._back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" # The measurement pulse for measuring the qubit of interest. self._measure = self._inst_sched_map.get('measure', qubits=self._back_config.meas_map[meas_map_idx]) def create_cal_circuit(self, amp): """Constructs and returns a schedule containing Gaussian pulse with amplitude as 'amp', sigma as 'pulse_sigma' and duration as 'pulse_duration'.""" sched = Schedule() sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=amp), self._drive_chan) sched += self._measure << sched.duration return sched def create_cal_circuit_excited(self, base_pulse, freq): """ Constructs and returns a schedule containing a pi pulse for 0->1 transition followed by a sidebanded pulse which corresponds to applying 'base_pulse' at frequency 'freq'.""" sched = Schedule() sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground), self._drive_chan) sched += Play(self.apply_sideband(base_pulse, freq), self._drive_chan) sched += self._measure << sched.duration return sched @staticmethod def _fit_function(x_values, y_values, function, init_params): """ A function fitter. Returns the fit parameters of 'function'.""" fitparams, _ = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit @staticmethod def _baseline_remove(values): """Centering data around zero.""" return np.array(values) - np.mean(values) def apply_sideband(self, pulse, frequency): """Apply a sine sideband to 'pulse' at frequency 'freq'. Args: pulse (Waveform): The pulse to which sidebanding is to be applied. frequency (float): LO frequency at which the pulse is to be applied. Returns: Waveform: The sidebanded pulse. """ t_samples = np.linspace(0, self._dt*self._pulse_duration, self._pulse_duration) sine_pulse = np.sin(2*np.pi*(frequency-self._qubit_freq_ground)*t_samples) sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse), name='sideband_pulse') return sideband_pulse def get_job_data(self, job, average): """Retrieve data from a job that has already run. Args: job (Job): The job whose data you want. average (bool): If True, gets the data assuming data is an average. If False, gets the data assuming it is for single shots. Return: list: List containing job result data. """ scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[self._qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, self._qubit]*scale_factor) return result_data # Prints out relative maxima frequencies in output_data; height gives lower bound (abs val) @staticmethod def _rel_maxima(freqs, output_data, height, distance): """Prints out relative maxima frequencies in output_data (can see peaks); height gives upper bound (abs val). Be sure to set the height properly or the peak will be ignored! Args: freqs (list): frequency list output_data (list): list of resulting signals height (float): upper bound (abs val) on a peak width (float): Returns: list: List containing relative maxima frequencies """ peaks, _ = find_peaks(x=output_data, height=height, distance=distance) return freqs[peaks] def find_freq_ground(self, verbose=False, visual=False): """Sets and returns the calibrated frequency corresponding to 0->1 transition.""" # pylint: disable=too-many-locals sched_list = [self.create_cal_circuit(0.5)]*75 freq_list = np.linspace(self._qubit_freq-(45*1e+6), self._qubit_freq+(45*1e+6), 75) sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{self._drive_chan: freq} for freq in freq_list]) jid = sweep_job.job_id() if verbose: print("Executing the Frequency sweep job for 0->1 transition.") print('Job Id : ', jid) # job_monitor(sweep_job) sweep_job = self._backend.retrieve_job(jid) sweep_result = sweep_job.result() sweep_values = [] for i in range(len(sweep_result.results)): # Get the results from the ith experiment res = sweep_result.get_memory(i)*1e-14 # Get the results for `qubit` from this experiment sweep_values.append(res[self._qubit]) freq_list_GHz = freq_list/1e+9 if visual: print("The frequency-signal plot for frequency sweep: ") plt.scatter(freq_list_GHz, np.real(sweep_values), color='black') plt.xlim([min(freq_list_GHz), max(freq_list_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() # def find_init_params(freq_list, res_values): # hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] # hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] # if hmin_index < hmax_index: # est_baseline = min(res_values) # est_slope = (res_values[hmax_index] - res_values[hmin_index])/(freq_list[hmax_index] - freq_list[hmin_index]) # else: # est_baseline = max(res_values) # est_slope = (res_values[hmin_index] - res_values[hmax_index])/(freq_list[hmin_index] - freq_list[hmax_index]) # return [est_slope, self._qubit_freq/1e9, 1, est_baseline] def find_init_params_gauss(freq_list, res_values): hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] mean_est = freq_list[hmax_index] var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2 scale_est = max(res_values)-min(res_values) shift_est = min(res_values) return [mean_est, var_est, scale_est, shift_est] def gauss(x, mean, var, scale, shift): return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift def lorentzian(xval, scale, q_freq, hwhm, shift): return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift # do fit in Hz init_params = find_init_params_gauss(freq_list_GHz, np.real(sweep_values)) # init_params = find_init_params(freq_list_GHz, np.real(sweep_values)) print('ground freq init params : ', init_params) # Obtain the optimal paramters that fit the result data. # fit_params, y_fit = self._fit_function(freq_list_GHz, # np.real(sweep_values), # lorentzian, # init_params # init parameters for curve_fit # ) fit_params, y_fit = self._fit_function(freq_list_GHz, np.real(sweep_values), gauss, init_params # init parameters for curve_fit ) if visual: print("The frequency-signal plot for frequency sweep: ") plt.scatter(freq_list_GHz, np.real(sweep_values), color='black') plt.plot(freq_list_GHz, y_fit, color='red') plt.xlim([min(freq_list_GHz), max(freq_list_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() qubit_freq_new, _, _, _ = fit_params self._qubit_freq_ground = qubit_freq_new*1e9 if verbose: print(f"The calibrate frequency for the 0->1 transition is {self._qubit_freq_ground}") return [self._qubit_freq_ground, freq_list_GHz, sweep_values] def find_pi_amp_ground(self, verbose=False, visual=False): """Sets and returns the amplitude of the pi pulse corresponding to 0->1 transition.""" # pylint: disable=too-many-locals if not self._qubit_freq_ground: warn("ground_qubit_freq not computed yet and custom qubit freq not provided." + "Computing ground_qubit_freq now.") self._qubit_freq_ground = self.find_freq_ground(verbose, visual) amp_list = np.linspace(0, 1, 75) rabi_sched_list = [self.create_cal_circuit(amp) for amp in amp_list] rabi_list_len = len(rabi_sched_list) rabi_job = execute(rabi_sched_list,backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(rabi_sched_list)) jid = rabi_job.job_id() if verbose: print("Executing the rabi oscillation job to get Pi pulse for 0->1 transition.") print('Job Id : ', jid) # job_monitor(rabi_job) rabi_job = self._backend.retrieve_job(jid) rabi_results = rabi_job.result() scale_factor = 1e-14 rabi_values = [] for i in range(75): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[self._qubit]*scale_factor) rabi_values = np.real(self._baseline_remove(rabi_values)) def find_init_params_amp(amp_list, rabi_values): min_index = np.where(rabi_values==min(rabi_values))[0][0] max_index = np.where(rabi_values==max(rabi_values))[0][0] scale_est = (max(rabi_values) - min(rabi_values))/2 shift_est = (max(rabi_values) + min(rabi_values))/2 shift_est = np.mean(rabi_values) period_est = 0.5 if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5: phi_est = np.pi/2 else: phi_est = -np.pi/2 return [scale_est, shift_est, period_est, phi_est] # Obtain the optimal paramters that fit the result data. init_params = find_init_params_amp(amp_list,rabi_values) fit_params, y_fit = self._fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), init_params) drive_period = fit_params[2] self._pi_amp_ground = drive_period/2 if verbose: print(f"The Pi amplitude of 0->1 transition is {self._pi_amp_ground}.") if visual: print("The amplitude-signal plot for rabi oscillation for 0->1 transition.") plt.figure() plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2, 0), arrowprops=dict(arrowstyle="<->", color='red')) #plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() return [self._pi_amp_ground, amp_list, rabi_values] def find_freq_excited(self, verbose=False, visual=False): """Sets and returns the frequency corresponding to 1->2 transition.""" # pylint: disable=too-many-locals if not self._qubit_freq_ground: raise ValueError("The qubit_freq_ground is not determined. Please determine" + "qubit_freq_ground first.") if not self._pi_amp_ground: raise ValueError("The pi_amp_ground is not determined.\ Please determine pi_amp_ground first.") base_pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=0.3) sched_list = [] # Here we assume that the anharmocity is about 8% for all qubits. excited_freq_list = self._qubit_freq_ground + self._qubit_anharmonicity + np.linspace(-30*1e+6, 30*1e+6, 75) for freq in excited_freq_list: sched_list.append(self.create_cal_circuit_excited(base_pulse, freq)) excited_sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(excited_freq_list) ) jid = excited_sweep_job.job_id() excited_freq_list_GHz = excited_freq_list/1e+9 if verbose: print("Executing the Frequency sweep job for 1->2 transition.") print('Job Id : ', jid) # job_monitor(excited_sweep_job) excited_sweep_job = self._backend.retrieve_job(jid) excited_sweep_data = self.get_job_data(excited_sweep_job, average=True) if visual: print("The frequency-signal plot of frequency sweep for 1->2 transition.") # Note: we are only plotting the real part of the signal plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black') plt.xlim([min(excited_freq_list_GHz), max(excited_freq_list_GHz)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep", fontsize=15) plt.show() def find_init_params_gauss(freq_list, res_values): hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0] hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0] mean_est = freq_list[hmax_index] var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2 scale_est = max(res_values)-min(res_values) shift_est = min(res_values) return [mean_est, var_est, scale_est, shift_est] def gauss(x, mean, var, scale, shift): return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift def lorentzian(xval, scale, q_freq, hwhm, shift): return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift # do fit in Hz # init_params = find_init_params(excited_freq_list_GHz, np.real(excited_sweep_data)) init_params = find_init_params_gauss(excited_freq_list_GHz, np.real(excited_sweep_data)) print("Init params : ", init_params) excited_sweep_fit_params, excited_sweep_y_fit = self._fit_function(excited_freq_list_GHz, excited_sweep_data, gauss, init_params ) if visual: print("The frequency-signal plot of frequency sweep for 1->2 transition.") # Note: we are only plotting the real part of the signal plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black') plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red') plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep", fontsize=15) plt.show() qubit_freq_12, _, _, _ = excited_sweep_fit_params self._qubit_freq_excited = qubit_freq_12*1e+9 if verbose: print(f"The calibrated frequency for the 1->2 transition\ is {self._qubit_freq_excited}.") return [self._qubit_freq_excited, excited_freq_list, excited_sweep_data] def find_pi_amp_excited(self, verbose=False, visual=False): """Sets and returns the amplitude of the pi pulse corresponding to 1->2 transition.""" if not self._qubit_freq_excited: warn("ground_qubit_freq not computed yet and custom qubit freq not provided." + "Computing ground_qubit_freq now.") self._qubit_freq_ground = self.find_freq_excited(verbose, visual) amp_list = np.linspace(0, 1.0, 75) rabi_sched_list = [] for amp in amp_list: base_pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=amp) rabi_sched_list.append(self.create_cal_circuit_excited(base_pulse, self._qubit_freq_excited)) rabi_job = execute(rabi_sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*75 ) jid = rabi_job.job_id() if verbose: print("Executing the rabi oscillation job for 1->2 transition.") print('Job Id : ', jid) # job_monitor(rabi_job) rabi_job = self._backend.retrieve_job(jid) rabi_data = self.get_job_data(rabi_job, average=True) rabi_data = np.real(self._baseline_remove(rabi_data)) if visual: print("The amplitude-signal plot of rabi oscillation for 1->2 transition.") plt.figure() plt.scatter(amp_list, rabi_data, color='black') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.title('Rabi Experiment (1->2)', fontsize=20) plt.show() def find_init_params_amp(amp_list, rabi_values): min_index = np.where(rabi_values==min(rabi_values))[0][0] max_index = np.where(rabi_values==max(rabi_values))[0][0] scale_est = (max(rabi_values) - min(rabi_values))/2 shift_est = (max(rabi_values) + min(rabi_values))/2 shift_est = np.mean(rabi_values) period_est = 0.5 if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5: phi_est = np.pi/2 else: phi_est = -np.pi/2 return [scale_est, shift_est, period_est, phi_est] init_params = find_init_params_amp(amp_list, rabi_data) print('Init params for 01 amp : ', init_params) (rabi_fit_params, rabi_y_fit) = self._fit_function(amp_list, rabi_data, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), init_params) drive_period_excited = rabi_fit_params[2] pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3]) self._pi_amp_excited = pi_amp_excited if visual: print("The amplitude-signal plot of rabi oscillation for 1->2 transition.") plt.figure() plt.scatter(amp_list, rabi_data, color='black') plt.plot(amp_list, rabi_y_fit, color='red') # account for phi in computing pi amp plt.axvline(self._pi_amp_excited, color='red', linestyle='--') plt.axvline(self._pi_amp_excited+drive_period_excited/2, color='red', linestyle='--') plt.annotate("", xy=(self._pi_amp_excited+drive_period_excited/2, 0), xytext=(self._pi_amp_excited, 0), arrowprops=dict(arrowstyle="<->", color='red')) #plt.annotate("$\\pi$", xy=(self._pi_amp_excited-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.title('Rabi Experiment (1->2)', fontsize=20) plt.show() return [self._pi_amp_excited, amp_list, rabi_data] def get_pi_pulse_ground(self): """Returns a pi pulse of the 0->1 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground) return pulse def get_pi_pulse_excited(self): """Returns a pi pulse of the 1->2 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_excited) excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited) return excited_pulse def get_x90_pulse_ground(self): """Returns a pi/2 pulse of the 0->1 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground/2) return pulse def get_x90_pulse_excited(self): """Returns a pi/2 pulse of the 1->2 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_excited/2) excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited) return excited_pulse def get_zero_sched(self): """Returns a schedule that performs only a measurement.""" zero_sched = Schedule() zero_sched += self._measure return zero_sched def get_one_sched(self): """Returns a schedule that creates a |1> state from |0> by applying a pi pulse of 0->1 transition and performs a measurement.""" one_sched = Schedule() one_sched += Play(self.get_pi_pulse_ground(), self._drive_chan) one_sched += self._measure << one_sched.duration return one_sched def get_two_sched(self): """Returns a schedule that creates a |2> state from |0> by applying a pi pulse of 0->1 transition followed by applying a pi pulse of 1->2 transition and performs a measurement.""" two_sched = Schedule() two_sched += Play(self.get_pi_pulse_ground(), self._drive_chan) two_sched += Play(self.get_pi_pulse_excited(), self._drive_chan) two_sched += self._measure << two_sched.duration return two_sched @staticmethod def _create_iq_plot(zero_data, one_data, two_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') # two data plotted in green plt.scatter(np.real(two_data), np.imag(two_data), s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$') x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))-5 x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))+5 y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))-5 y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) mean_two = np.mean(two_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_two), np.imag(mean_two), s=200, cmap='viridis', c='black', alpha=1.0) # plt.xlim(x_min, x_max) # plt.ylim(y_min, y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1-2 discrimination", fontsize=15) return x_min, x_max, y_min, y_max @staticmethod def reshape_complex_vec(vec): """Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning. Args: vec (list): complex vector of data Returns: list: vector w/ entries given by (real(vec], imag(vec)) """ length = len(vec) vec_reshaped = np.zeros((length, 2)) for i, item in enumerate(vec): vec_reshaped[i] = [np.real(item), np.imag(item)] return vec_reshaped def find_three_level_discriminator(self, verbose=False, visual=False): """Returns a discriminator for discriminating 0-1-2 states.""" # pylint: disable=too-many-locals zero_sched = self.get_zero_sched() one_sched = self.get_one_sched() two_sched = self.get_two_sched() iq_job = execute([zero_sched, one_sched, two_sched], backend=self._backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*3 ) jid = iq_job.job_id() if verbose: print('Job Id : ', jid) # job_monitor(iq_job) iq_job = self._backend.retrieve_job(jid) iq_data = self.get_job_data(iq_job, average=False) zero_data = iq_data[0] one_data = iq_data[1] two_data = iq_data[2] if visual: print("The discriminator plot for 0-1-2 discrimination.") x_min, x_max, y_min, y_max = self._create_iq_plot(zero_data, one_data, two_data) # Create IQ vector (split real, imag parts) zero_data_reshaped = self.reshape_complex_vec(zero_data) one_data_reshaped = self.reshape_complex_vec(one_data) two_data_reshaped = self.reshape_complex_vec(two_data) iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped)) # construct vector w/ 0's, 1's and 2's (for testing) state_012 = np.zeros(1024) # shots gives number of experiments state_012 = np.concatenate((state_012, np.ones(1024))) state_012 = np.concatenate((state_012, 2*np.ones(1024))) # Shuffle and split data into training and test sets iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data, state_012, test_size=0.5) classifier_lda_012 = LinearDiscriminantAnalysis() classifier_lda_012.fit(iq_012_train, state_012_train) score_012 = classifier_lda_012.score(iq_012_test, state_012_test) if verbose: print('The accuracy score of the discriminator is: ', score_012) self._state_discriminator_012 = classifier_lda_012 if visual: self._separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024) return self._state_discriminator_012 @staticmethod def _separatrix_plot(lda, x_min, x_max, y_min, y_max, shots): """Returns a sepratrix plot for the classifier.""" # pylint: disable=too-many-arguments num_x, num_y = shots, shots xvals, vals = np.meshgrid(np.linspace(x_min, x_max, num_x), np.linspace(y_min, y_max, num_y)) predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()]) predict_prob = predict_prob[:, 1].reshape(xvals.shape) plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black') def get_qubit_freq_ground(self): """Returns the set 0->1 transition frequency.""" return self._qubit_freq_ground def get_qubit_freq_excited(self): """Returns the set 1->2 transition frequency.""" return self._qubit_freq_excited def get_pi_amp_ground(self): """Returns the set 0->1 transition pi pulse amplitude.""" return self._pi_amp_ground def get_pi_amp_excited(self): """Returns the set 1->2 transition pi pulse amplitude.""" return self._pi_amp_excited def get_three_level_discriminator(self): """Returns the set 0-1-2 state discriminator.""" return self._state_discriminator_012 def calibrate_all(self, verbose=False, visual=False): """Calibrates and sets both the ground and excited transition frequencies and corresponding pi pulse amplitudes. Also constructs a 0-1-2 state discriminator.""" ground_freq = self.find_freq_ground(verbose, visual) ground_amp = self.find_pi_amp_ground(verbose, visual) excited_freq = self.find_freq_excited(verbose, visual) excited_amp = self.find_pi_amp_excited(verbose, visual) state_discriminator = self.find_three_level_discriminator(verbose, visual) return ground_freq, ground_amp, excited_freq, excited_amp, state_discriminator anharmon = backend.properties().qubit_property(qubit)['anharmonicity'][0] qu_freq = backend.properties().qubit_property(qubit)['frequency'][0] print(qu_freq) print(anharmon) print(qu_freq+anharmon) # backend = provider.get_backend('ibmq_casablanca') # backend = provider.get_backend('ibmq_jakarta') backend = provider.get_backend('ibmq_rome') qubit = 0 cal_object = PulseCalibration(backend, qubit) visual = True verbose = True ground_freq_list = cal_object.find_freq_ground(verbose, visual) [ground_freq, freq_list, sweep_vals] = ground_freq_list print(ground_freq) ground_amp_list = cal_object.find_pi_amp_ground(verbose, visual) pi_amp_ground = ground_amp_list[0] amp_list = ground_amp_list[1] rabi_values = ground_amp_list[2] print(ground_freq) print(pi_amp_ground) excited_list = cal_object.find_freq_excited(verbose, visual) excited_freq = excited_list[0] excited_freq_list = excited_list[1] excited_sweep_data = excited_list[2] excited_freq_list_GHz = excited_freq_list/1e+9 excited_freq pi_amp_excited_list = cal_object.find_pi_amp_excited(verbose, visual) [excited_amp, amp_list, rabi_data] = pi_amp_excited_list pi_amp_excited = excited_amp pi_amp_excited print(ground_freq) print(pi_amp_ground) print(excited_freq) print(pi_amp_excited) discrim = cal_object.find_three_level_discriminator(verbose, visual) def create_iq_plot(zero_data, one_data, two_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') # two data plotted in green plt.scatter(np.real(two_data), np.imag(two_data), s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$') x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))-5 x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))+5 y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))-5 y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) mean_two = np.mean(two_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_two), np.imag(mean_two), s=200, cmap='viridis', c='black', alpha=1.0) # plt.xlim(x_min, x_max) # plt.ylim(y_min, y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1-2 discrimination", fontsize=15) return x_min, x_max, y_min, y_max def reshape_complex_vec(vec): """Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning. Args: vec (list): complex vector of data Returns: list: vector w/ entries given by (real(vec], imag(vec)) """ length = len(vec) vec_reshaped = np.zeros((length, 2)) for i, item in enumerate(vec): vec_reshaped[i] = [np.real(item), np.imag(item)] return vec_reshaped def separatrix_plot(lda, x_min, x_max, y_min, y_max, shots): """Returns a sepratrix plot for the classifier.""" # pylint: disable=too-many-arguments num_x, num_y = shots, shots xvals, vals = np.meshgrid(np.linspace(x_min-4, x_max+4, num_x), np.linspace(y_min-4, y_max+4, num_y)) predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()]) predict_prob = predict_prob[:, 1].reshape(xvals.shape) plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black') def get_job_data(job, average): """Retrieve data from a job that has already run. Args: job (Job): The job whose data you want. average (bool): If True, gets the data assuming data is an average. If False, gets the data assuming it is for single shots. Return: list: List containing job result data. """ scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor) return result_data iq_job = backend.retrieve_job('60b501ab4a088c8310c55ebd') iq_data = get_job_data(iq_job, average=False) zero_data = iq_data[0] one_data = iq_data[1] two_data = iq_data[2] if visual: print("The discriminator plot for 0-1-2 discrimination.") x_min, x_max, y_min, y_max = create_iq_plot(zero_data, one_data, two_data) newcalobject = PulseCalibration(backend, qubit) output_list = newcalobject.calibrate_all(verbose, visual) [new_ground_freq, new_pi_amp_ground, new_excited_freq, new_pi_amp_excited, new_discrim] = output_list print(new_ground_freq[0]) print(new_pi_amp_ground[0]) print(new_excited_freq[0]) print(new_pi_amp_excited[0]) back_config = backend.configuration() back_defaults = backend.defaults() inst_sched_map = back_defaults.instruction_schedule_map meas_map_idx = None for i, measure_group in enumerate(back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" # The measurement pulse for measuring the qubit of interest. measure = inst_sched_map.get('measure', qubits=back_config.meas_map[meas_map_idx]) # Should be getting |2> ideally. sigma = 40 duration = 4*40 chan = DriveChannel(0) with pulse.build(backend) as test_0: pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan) pulse.set_frequency(excited_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited), chan) test_0 += measure << test_0.duration test_0.draw() test0_job = execute(test_0, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test0 = test0_job.job_id() print(jid_test0) test0_job = backend.retrieve_job(jid_test0) res = get_job_data(test0_job, average=False) res[0] reshaped_res = reshape_complex_vec(res[0]) plt.scatter(np.real(res[0]), np.imag(res[0])) plt.show() output = discrim.predict(reshaped_res) arr = [0,0,0] for i in output: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a 0-1 pi pulse. # Should be ideally getting |1> with pulse.build(backend) as test_00: pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan) test_00 += measure << test_00.duration test_00.draw() test00_job = execute(test_00, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test00 = test00_job.job_id() print(jid_test00) test00_job = backend.retrieve_job(jid_test00) res00 = get_job_data(test00_job, average=False) res00[0] reshaped_res00 = reshape_complex_vec(res00[0]) plt.scatter(np.real(res00[0]), np.imag(res00[0])) plt.show() output00 = discrim.predict(reshaped_res00) arr = [0,0,0] for i in output00: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H then Z then H gate on 0-1 # Should get |1> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_1: # Setting 0-1 frequency for channel and applying H gate pulse.set_frequency(ground_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Applying a Z pulse pulse.shift_phase(np.pi, chan) # Applying H gate on 0-1 pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_1 += measure << test_pulse_1.duration test_pulse_1.draw() test1_job = execute(test_pulse_1, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test1 = test1_job.job_id() print(jid_test1) test1_job = backend.retrieve_job(jid_test1) res1 = get_job_data(test1_job, average=False) reshaped_res1 = reshape_complex_vec(res1[0]) plt.scatter(np.real(res1[0]), np.imag(res1[0])) plt.show() output1 = discrim.predict(reshaped_res1) arr = [0,0,0] for i in output1: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H then Z then H gate on 1-2 # Should get |2> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_2: # Exciting the qubit to |1> state pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) # Setting 1-2 frequency for channel and applying H gate pulse.set_frequency(excited_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Applying a Z pulse pulse.shift_phase(np.pi, chan) # Applying H gate on 1-2 pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_2 += measure << test_pulse_2.duration test_pulse_2.draw() test2_job = execute(test_pulse_2, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test2 = test2_job.job_id() print(jid_test2) test2_job = backend.retrieve_job(jid_test2) res2 = get_job_data(test2_job, average=False) reshaped_res2 = reshape_complex_vec(res2[0]) plt.scatter(np.real(res2[0]), np.imag(res2[0])) plt.show() output2 = discrim.predict(reshaped_res2) arr = [0,0,0] for i in output2: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H on 0-1, then H on 1-2 # then Z on 1-2 followed by H on 1-2 # Should get |0>/sqrt(2) + |2>/sqrt(2) chan = DriveChannel(0) with pulse.build(backend) as test_pulse_3: # Setting 0-1 frequency for channel and applying H gate pulse.set_frequency(ground_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Undoing phase appied during 0-1 transitions pulse.shift_phase(np.pi, chan) # Setting 1-2 frequency for channel and applying H gate pulse.set_frequency(excited_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) # Applying a Z pulse pulse.shift_phase(np.pi, chan) # Applying H gate on 1-2 pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_3 += measure << test_pulse_3.duration test_pulse_3.draw() test3_job = execute(test_pulse_3, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test3 = test3_job.job_id() print(jid_test3) test3_job = backend.retrieve_job(jid_test3) res3 = get_job_data(test3_job, average=False) reshaped_res3 = reshape_complex_vec(res3[0]) plt.scatter(np.real(res3[0]), np.imag(res3[0])) plt.show() output3 = discrim.predict(reshaped_res3) arr = [0,0,0] for i in output3: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H on 1-2 # Should get |1>/sqrt(2) + |2>/sqrt(2) ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_4: # Exciting the qubit to |1> state pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) # Setting 1-2 frequency for channel and applying H gate pulse.set_frequency(excited_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_4 += measure << test_pulse_4.duration test_pulse_4.draw() test4_job = execute(test_pulse_4, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test4 = test4_job.job_id() print(jid_test4) test4_job = backend.retrieve_job(jid_test4) res4 = get_job_data(test4_job, average=False) reshaped_res4 = reshape_complex_vec(res4[0]) plt.scatter(np.real(res4[0]), np.imag(res4[0])) plt.show() output4 = discrim.predict(reshaped_res4) arr = [0,0,0] for i in output4: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a H on 0-1 # Should get |0>/sqrt(2) + |1>/sqrt(2) ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_5: # Setting 0-1 frequency for channel and applying H gate pulse.set_frequency(ground_freq, chan) pulse.shift_phase(-np.pi/2, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan) pulse.shift_phase(-np.pi/2, chan) test_pulse_5 += measure << test_pulse_5.duration test_pulse_5.draw() test5_job = execute(test_pulse_5, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test5 = test5_job.job_id() print(jid_test5) test5_job = backend.retrieve_job(jid_test5) res5 = get_job_data(test5_job, average=False) reshaped_res5 = reshape_complex_vec(res5[0]) plt.scatter(np.real(res5[0]), np.imag(res5[0])) plt.show() output5 = discrim.predict(reshaped_res5) arr = [0,0,0] for i in output5: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a X on 0-1 # Should get |1> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_6: # Setting 0-1 frequency for channel and applying X gate pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) test_pulse_6 += measure << test_pulse_6.duration test_pulse_6.draw() test6_job = execute(test_pulse_6, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test6 = test6_job.job_id() print(jid_test6) test6_job = backend.retrieve_job(jid_test6) res6 = get_job_data(test6_job, average=False) reshaped_res6 = reshape_complex_vec(res6[0]) plt.scatter(np.real(res6[0]), np.imag(res6[0])) plt.show() output6 = discrim.predict(reshaped_res6) arr = [0,0,0] for i in output6: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) # Performing a X on 1-2 # Should get |2> ideally. chan = DriveChannel(0) with pulse.build(backend) as test_pulse_7: # Setting 0-1 frequency for channel and applying 0-1 pi pulse pulse.set_frequency(ground_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan) # Setting 1-2 frequency for channel and applying 1-2 pi pulse pulse.set_frequency(excited_freq, chan) pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited, name='X(pi)'), chan) test_pulse_7 += measure << test_pulse_7.duration test_pulse_7.draw() test7_job = execute(test_pulse_7, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_test7 = test7_job.job_id() print(jid_test7) test7_job = backend.retrieve_job(jid_test7) res7 = get_job_data(test7_job, average=False) reshaped_res7 = reshape_complex_vec(res7[0]) plt.scatter(np.real(res7[0]), np.imag(res7[0])) plt.show() output7 = discrim.predict(reshaped_res7) arr = [0,0,0] for i in output7: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) back_config = backend.configuration() print("Supported kernels: ", back_config.meas_kernels) print("Supported discriminators: ", back_config.discriminators) qc = QuantumCircuit(2) qc.cx(0,1) with pulse.build(backend) as cnot_pulse: pulse.call(qc) cnot_pulse += measure << cnot_pulse.duration cnot_pulse.draw() cnot_job = execute(cnot_pulse, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{chan: ground_freq}] ) jid_cnot = cnot_job.job_id() print(jid_cnot) cnot_job = backend.retrieve_job(jid_cnot) cnot_job.result().to_dict() cnot_res = get_job_data(cnot_job, average=False) reshaped_cnot_res = reshape_complex_vec(cnot_res[0]) plt.scatter(np.real(cnot_res[0]), np.imag(cnot_res[0])) plt.show() cnot_output = discrim.predict(reshaped_cnot_res) arr = [0,0,0] for i in cnot_output: if i==0: arr[0]+=1 elif i==1: arr[1]+=1 else: arr[2]+=1 print(arr) qc = QuantumCircuit(1) qc.y(0) with pulse.build(backend) as ypulse: pulse.call(qc) ypulse += measure << ypulse.duration ypulse.draw()
https://github.com/h-rathee851/Pulse_application_qiskit
h-rathee851
def speak(text): from IPython.display import Javascript as js, clear_output # Escape single quotes text = text.replace("'", r"\'") display(js(f''' if(window.speechSynthesis) {{ var synth = window.speechSynthesis; synth.speak(new window.SpeechSynthesisUtterance('{text}')); }} ''')) # Clear the JS so that the notebook doesn't speak again when reopened/refreshed clear_output(False) import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main') import sys np.set_printoptions(threshold=sys.maxsize) from qiskit import * from matplotlib import pyplot as plt # backend = provider.get_backend('ibmq_armonk') backend = provider.get_backend('ibmq_casablanca') from qiskit import * from qiskit.pulse import * from qiskit.tools.monitor import job_monitor qubit = 0 back_config = backend.configuration() inst_sched_map = backend.defaults().instruction_schedule_map meas_map_idx = None for i, measure_group in enumerate(back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" measure = inst_sched_map.get('measure', qubits=back_config.meas_map[qubit]) pulse_sigma = 40 pulse_duration = (4*pulse_sigma)-((4*pulse_sigma)%16) drive_chan = DriveChannel(0) def create_cal_circuits(amp): sched = Schedule() sched+=Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=amp), drive_chan) measure = inst_sched_map.get('measure', qubits=[qubit]) sched+=measure << sched.duration return sched default_qubit_freq = backend.defaults().qubit_freq_est[0] freq_list = np.linspace(default_qubit_freq-(20*1e+6), default_qubit_freq+(20*1e+6), 75) sched_list = [create_cal_circuits(0.4)]*75 # sweep_exp = assemble(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list]) # sweep_job = backend.run(sweep_exp) sweep_job = execute(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list]) job_monitor(sweep_job) sweep_result = sweep_job.result() sweep_values = [] for i in range(len(sweep_result.results)): res = sweep_result.get_memory(i)*1e-14 sweep_values.append(res[qubit]) scale_factor = 1e+9 freq_list_scaled = freq_list/scale_factor from scipy.optimize import curve_fit def find_init_params(res_values): est_baseline = np.mean(res_values) est_slope = -5 if est_baseline-np.min(res_values) > 2 else 5 return [est_slope, 4.975, 1, est_baseline] def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit init_params = find_init_params(np.real(sweep_values)) # initial parameters for curve_fit # init_params = [5, ] fit_params, y_fit = fit_function(freq_list_scaled, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, init_params ) plt.scatter(freq_list_scaled, np.real(sweep_values), color='black') plt.plot(freq_list_scaled, y_fit, color='red') plt.xlim([min(freq_list_scaled), max(freq_list_scaled)]) # plt.ylim([-7,0]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() _, qubit_freq_new, _, _ = fit_params qubit_freq_ground = qubit_freq_new*scale_factor speak("The test program is done.") print(f"The new qubit frequency is : {qubit_freq_ground} Hz") #### Moving on to the Rabi experiments for 0->1 transition. amp_list = np.linspace(0, 1.0, 75) rabi_sched_list = [create_cal_circuits(amp) for amp in amp_list] # rabi_exp = assemble(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list)) # rabi_job = backend.run(rabi_exp) rabi_job = execute(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list)) job_monitor(rabi_job) rabi_results = rabi_job.result() scale_factor = 1e-14 rabi_values = [] for i in range(75): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = np.real(baseline_remove(rabi_values)) fit_params, y_fit = fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), [3*1e-7, 0, 0.3, 0]) drive_period = fit_params[2] pi_amp_ground = drive_period/2 plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) # plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print(f"The calibrated pi amp is : {pi_amp_ground}") speak("The test program is over. Have a look at it.") from qiskit.pulse import library as pulse_lib def get_pi_pulse_ground(): pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground) return pulse def get_zero_sched(): zero_sched = Schedule() zero_sched += measure return zero_sched def get_one_sched(): one_sched = Schedule() one_sched += Play(get_pi_pulse_ground(), drive_chan) one_sched += measure << one_sched.duration return one_sched def IQ_plot(zero_data, one_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') x_min = np.min(np.append(np.real(zero_data), np.real(one_data)))-5 x_max = np.max(np.append(np.real(zero_data), np.real(one_data)))+5 y_min = np.min(np.append(np.imag(zero_data), np.imag(one_data)))-5 y_max = np.max(np.append(np.imag(zero_data), np.imag(one_data)))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=50, cmap='viridis', c='black',alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=50, cmap='viridis', c='black',alpha=1.0) # plt.xlim(x_min, x_max) # plt.ylim(y_min,y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1 discrimination", fontsize=15) return x_min, x_max, y_min, y_max def get_job_data(job, average): scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor) return result_data discrim_01_sched_list = [get_zero_sched(), get_one_sched()] discrim_job = execute(discrim_01_sched_list, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2) job_monitor(discrim_job) discrim_data = get_job_data(discrim_job, average=False) zero_data = discrim_data[0] one_data = discrim_data[1] x_min, x_max, y_min, y_max = IQ_plot(zero_data, one_data) discrim_job_0 = execute(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) # discrim_job_0 = execute(zero_pulse_with_gap(350), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(discrim_job_0) discrim_job_1 = execute(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(discrim_job_1) zero_data_sep = get_job_data(discrim_job_0, average=False) one_data_sep = get_job_data(discrim_job_1, average=False) x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep, one_data_sep) discrim_01_sched_list_assemble = [get_zero_sched(), get_one_sched()] discrim_exp = assemble(discrim_01_sched_list_assemble, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2) discrim_job_assemble = backend.run(discrim_exp) job_monitor(discrim_job_assemble) discrim_data_assemble = get_job_data(discrim_job_assemble, average=False) zero_data_asmbl = discrim_data_assemble[0] one_data_asmbl = discrim_data_assemble[1] x_min, x_max, y_min, y_max = IQ_plot(zero_data_asmbl, one_data_asmbl) discrim_exp_0 = assemble(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) discrim_job_0_asmbl = backend.run(discrim_exp_0) job_monitor(discrim_job_0_asmbl) discrim_exp_1 = assemble(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) discrim_job_1_asmbl = backend.run(discrim_exp_1) job_monitor(discrim_job_1_asmbl) zero_data_sep_asmbl = get_job_data(discrim_job_0_asmbl, average=False) one_data_sep_asmbl = get_job_data(discrim_job_1_asmbl, average=False) x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep_asmbl, one_data_sep_asmbl) def zero_pulse_with_gap(gap): gapped_sched = Schedule() gapped_sched += measure << gap return gapped_sched gap_list = range(0,720,100) gap_sched_list = [zero_pulse_with_gap(gap) for gap in gap_list] print('Gap list : ', [*gap_list]) out_file = open("temp_01_scheds_sep_result_casablanca.txt", "w") for idx, sched in enumerate(gap_sched_list): gap_job = execute(sched, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) if idx%1==0: print("Running job number %d" % idx) job_monitor(gap_job) gap_data = get_job_data(gap_job, average=False) print('0', idx*10, gap_data[0].tolist(), file=out_file) gap_job = execute(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(gap_job) gap_data = get_job_data(gap_job, average=False) print('1', '0', gap_data[0].tolist(), file=out_file) out_file.close() import ast res_file = open("temp_01_scheds_sep_result_casablanca.txt",'r') res_array =[] res = res_file.readline() iter=1 while res: res_array.append(ast.literal_eval(res[res.find('['):])) res = res_file.readline() iter += 1 res_file.close() plt.figure() print(len(res_array)) for idx, dat in enumerate(res_array[:9]): plt.scatter(np.real(dat), np.imag(dat), s=5, alpha=0.5) plt.show() for idx, sched in enumerate(gap_sched_list): gap_job = execute(sched, backend=backend, meas_level=2, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) if idx%1==0: print("Running job number %d" % idx) job_monitor(gap_job) result_counts = gap_job.result().get_counts() print('0 : ','Gap : ', idx*10, result_counts) gap_job = execute(get_one_sched(), backend=backend, meas_level=2, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(gap_job) result_counts = gap_job.result().get_counts() print('1 : ','Gap : 0', result_counts) speak("The complete program is over. Check it out.")
https://github.com/h-rathee851/Pulse_application_qiskit
h-rathee851
def speak(text): from IPython.display import Javascript as js, clear_output # Escape single quotes text = text.replace("'", r"\'") display(js(f''' if(window.speechSynthesis) {{ var synth = window.speechSynthesis; synth.speak(new window.SpeechSynthesisUtterance('{text}')); }} ''')) # Clear the JS so that the notebook doesn't speak again when reopened/refreshed clear_output(False) import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main') import sys np.set_printoptions(threshold=sys.maxsize) from qiskit import * from matplotlib import pyplot as plt backend = provider.get_backend('ibmq_armonk') from qiskit import * from qiskit.pulse import * from qiskit.tools.monitor import job_monitor qubit = 0 back_config = backend.configuration() inst_sched_map = backend.defaults().instruction_schedule_map meas_map_idx = None for i, measure_group in enumerate(back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" measure = inst_sched_map.get('measure', qubits=back_config.meas_map[qubit]) pulse_sigma = 80 pulse_duration = (4*pulse_sigma)-((4*pulse_sigma)%16) drive_chan = DriveChannel(0) def create_cal_circuits(amp): sched = Schedule() sched+=Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=amp), drive_chan) measure = inst_sched_map.get('measure', qubits=[qubit]) sched+=measure << sched.duration return sched default_qubit_freq = backend.defaults().qubit_freq_est[0] freq_list = np.linspace(default_qubit_freq-(20*1e+6), default_qubit_freq+(20*1e+6), 75) sched_list = [create_cal_circuits(0.4)]*75 # sweep_exp = assemble(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list]) # sweep_job = backend.run(sweep_exp) sweep_job = execute(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list]) job_monitor(sweep_job) sweep_result = sweep_job.result() sweep_values = [] for i in range(len(sweep_result.results)): res = sweep_result.get_memory(i)*1e-14 sweep_values.append(res[qubit]) scale_factor = 1e+9 freq_list_scaled = freq_list/scale_factor from scipy.optimize import curve_fit def find_init_params(res_values): est_baseline = np.mean(res_values) est_slope = -5 if est_baseline-np.min(res_values) > 2 else 5 return [est_slope, 4.975, 1, est_baseline] def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit init_params = find_init_params(np.real(sweep_values)) # initial parameters for curve_fit fit_params, y_fit = fit_function(freq_list_scaled, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, init_params ) plt.scatter(freq_list_scaled, np.real(sweep_values), color='black') plt.plot(freq_list_scaled, y_fit, color='red') plt.xlim([min(freq_list_scaled), max(freq_list_scaled)]) # plt.ylim([-7,0]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() _, qubit_freq_new, _, _ = fit_params qubit_freq_ground = qubit_freq_new*scale_factor speak("The test program is done.") print(f"The new qubit frequency is : {qubit_freq_ground} Hz") #### Moving on to the Rabi experiments for 0->1 transition. amp_list = np.linspace(0, 1.0, 75) rabi_sched_list = [create_cal_circuits(amp) for amp in amp_list] # rabi_exp = assemble(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list)) # rabi_job = backend.run(rabi_exp) rabi_job = execute(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list)) job_monitor(rabi_job) rabi_results = rabi_job.result() scale_factor = 1e-14 rabi_values = [] for i in range(75): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = np.real(baseline_remove(rabi_values)) fit_params, y_fit = fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), [5, 1, 1, -3]) drive_period = fit_params[2] pi_amp_ground = drive_period/2 plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print(f"The calibrated pi amp is : {pi_amp_ground}") speak("The test program is over. Have a look at it.") from qiskit.pulse import library as pulse_lib def get_pi_pulse_ground(): pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground) return pulse def get_zero_sched(): zero_sched = Schedule() zero_sched += measure return zero_sched def get_one_sched(): one_sched = Schedule() one_sched += Play(get_pi_pulse_ground(), drive_chan) one_sched += measure << one_sched.duration return one_sched def IQ_plot(zero_data, one_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') x_min = np.min(np.append(np.real(zero_data), np.real(one_data)))-5 x_max = np.max(np.append(np.real(zero_data), np.real(one_data)))+5 y_min = np.min(np.append(np.imag(zero_data), np.imag(one_data)))-5 y_max = np.max(np.append(np.imag(zero_data), np.imag(one_data)))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=200, cmap='viridis', c='black',alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=200, cmap='viridis', c='black',alpha=1.0) plt.xlim(x_min, x_max) plt.ylim(y_min,y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1 discrimination", fontsize=15) return x_min, x_max, y_min, y_max def get_job_data(job, average): scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor) return result_data discrim_01_sched_list = [get_zero_sched(), get_one_sched()] discrim_job = execute(discrim_01_sched_list, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2) job_monitor(discrim_job) discrim_data = get_job_data(discrim_job, average=False) zero_data = discrim_data[0] one_data = discrim_data[1] x_min, x_max, y_min, y_max = IQ_plot(zero_data, one_data) discrim_job_0 = execute(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(discrim_job_0) discrim_job_1 = execute(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(discrim_job_1) zero_data_sep = get_job_data(discrim_job_0, average=False) one_data_sep = get_job_data(discrim_job_1, average=False) x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep, one_data_sep) discrim_01_sched_list_assemble = [get_zero_sched(), get_one_sched()] discrim_exp = assemble(discrim_01_sched_list_assemble, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2) discrim_job_assemble = backend.run(discrim_exp) job_monitor(discrim_job_assemble) discrim_data_assemble = get_job_data(discrim_job_assemble, average=False) zero_data_asmbl = discrim_data_assemble[0] one_data_asmbl = discrim_data_assemble[1] x_min, x_max, y_min, y_max = IQ_plot(zero_data_asmbl, one_data_asmbl) def zero_pulse_with_gap(gap): gapped_sched = Schedule() gapped_sched += measure << gap return gapped_sched discrim_exp_0 = assemble(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) # discrim_exp_0 = assemble(zero_pulse_with_gap(350), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) discrim_job_0_asmbl = backend.run(discrim_exp_0) job_monitor(discrim_job_0_asmbl) discrim_exp_1 = assemble(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) discrim_job_1_asmbl = backend.run(discrim_exp_1) job_monitor(discrim_job_1_asmbl) zero_data_sep_asmbl = get_job_data(discrim_job_0_asmbl, average=False) one_data_sep_asmbl = get_job_data(discrim_job_1_asmbl, average=False) x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep_asmbl, one_data_sep_asmbl)
https://github.com/h-rathee851/Pulse_application_qiskit
h-rathee851
def speak(text): from IPython.display import Javascript as js, clear_output # Escape single quotes text = text.replace("'", r"\'") display(js(f''' if(window.speechSynthesis) {{ var synth = window.speechSynthesis; synth.speak(new window.SpeechSynthesisUtterance('{text}')); }} ''')) # Clear the JS so that the notebook doesn't speak again when reopened/refreshed clear_output(False) import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main') from qiskit import * from matplotlib import pyplot as plt backend = provider.get_backend('ibmq_armonk') from qiskit import * from qiskit.pulse import * from qiskit.tools.monitor import job_monitor qubit = 0 back_config = backend.configuration() inst_sched_map = backend.defaults().instruction_schedule_map meas_map_idx = None for i, measure_group in enumerate(back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" measure = inst_sched_map.get('measure', qubits=back_config.meas_map[qubit]) pulse_sigma = 80 pulse_duration = (4*pulse_sigma)-((4*pulse_sigma)%16) drive_chan = DriveChannel(0) def create_cal_circuits(amp): sched = Schedule() sched+=Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=amp), drive_chan) measure = inst_sched_map.get('measure', qubits=[qubit]) sched+=measure << sched.duration return sched default_qubit_freq = backend.defaults().qubit_freq_est[0] freq_list = np.linspace(default_qubit_freq-(20*1e+6), default_qubit_freq+(20*1e+6), 75) sched_list = [create_cal_circuits(0.4)]*75 sweep_exp = assemble(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list]) sweep_job = backend.run(sweep_exp) job_monitor(sweep_job) sweep_result = sweep_job.result() sweep_values = [] for i in range(len(sweep_result.results)): res = sweep_result.get_memory(i)*1e-14 sweep_values.append(res[qubit]) scale_factor = 1e+9 freq_list_scaled = freq_list/scale_factor from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(freq_list_scaled, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [5, 4.975, 1, 19] # initial parameters for curve_fit ) plt.scatter(freq_list_scaled, np.real(sweep_values), color='black') plt.plot(freq_list_scaled, y_fit, color='red') plt.xlim([min(freq_list_scaled), max(freq_list_scaled)]) # plt.ylim([-7,0]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() _, qubit_freq_new, _, _ = fit_params qubit_freq_ground = qubit_freq_new*scale_factor speak("The test program is done.") print(f"The new qubit frequency is : {qubit_freq_ground} Hz") #### Moving on to the Rabi experiments for 0->1 transition. amp_list = np.linspace(0, 1.0, 75) rabi_sched_list = [create_cal_circuits(amp) for amp in amp_list] rabi_exp = assemble(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list)) rabi_job = backend.run(rabi_exp) job_monitor(rabi_job) rabi_results = rabi_job.result() scale_factor = 1e-14 rabi_values = [] for i in range(75): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = np.real(baseline_remove(rabi_values)) fit_params, y_fit = fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), [0.6, 0.1, 1.6, 0]) drive_period = fit_params[2] pi_amp_ground = drive_period/2 plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print(f"The calibrated pi amp is : {pi_amp_ground}") def get_pi_pulse_ground(): try: pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground) except ValueError: raise ValueError("pi_amp_ground not defined. Please compute pi_amp_ground first") except Exception as err: traceback.print_exc() return pulse def get_zero_sched(): zero_sched = Schedule() zero_sched += measure return zero_sched def get_one_sched(): one_sched = Schedule() one_sched += Play(get_pi_pulse_ground(), drive_chan) one_sched += measure << one_sched.duration return one_sched def IQ_plot( zero_data, one_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') x_min = np.min(np.append(np.real(zero_data), np.real(one_data)))-5 x_max = np.max(np.append(np.real(zero_data), np.real(one_data)))+5 y_min = np.min(np.append(np.imag(zero_data), np.imag(one_data)))-5 y_max = np.max(np.append(np.imag(zero_data), np.imag(one_data)))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=200, cmap='viridis', c='black',alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=200, cmap='viridis', c='black',alpha=1.0) plt.xlim(x_min, x_max) plt.ylim(y_min,y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1 discrimination", fontsize=15) return x_min, x_max, y_min, y_max def reshape_complex_vec( vec): """Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning. Args: vec (list): complex vector of data Returns: list: vector w/ entries given by (real(vec], imag(vec)) """ length = len(vec) vec_reshaped = np.zeros((length, 2)) for i in range(len(vec)): vec_reshaped[i]=[np.real(vec[i]), np.imag(vec[i])] return vec_reshaped def separatrixPlot( lda, x_min, x_max, y_min, y_max, shots): nx, ny = shots, shots xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx), np.linspace(y_min, y_max, ny)) Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()]) Z = Z[:, 1].reshape(xx.shape) plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='black') measure = inst_sched_map.get('measure', qubits=[qubit]) one_sched = get_one_sched() exp = assemble(one_sched, backend=backend, meas_level=2, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) qjob = backend.run(exp) job_monitor(qjob) print(qjob.result().get_counts()) # zero_sched = get_zero_sched() # one_sched = get_one_sched() # IQ_exp = assemble([zero_sched, one_sched], backend=backend, # meas_level=1, meas_return='single', shots=1024, # schedule_los=[{drive_chan: qubit_freq_ground}]*2 # ) IQ_exp_0 = assemble([zero_sched], backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}] ) IQ_job_0 = backend.run(IQ_exp_0) print('Running job 1') job_monitor(IQ_job_0) IQ_exp_1 = assemble([one_sched], backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}] ) IQ_job_1 = backend.run(IQ_exp_1) print('Running job 2') job_monitor(IQ_job_1) new_one_sched = Schedule() new_one_sched += measure << pulse_duration IQ_exp_11 = assemble([new_one_sched], backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}] ) IQ_job_11 = backend.run(IQ_exp_11) print('Running job 3') job_monitor(IQ_job_11) new_one_sched_2 = Schedule() new_one_sched_2 += measure << 2*pulse_duration IQ_exp_12 = assemble([new_one_sched_2], backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}] ) IQ_job_12 = backend.run(IQ_exp_12) print('Running job 4') job_monitor(IQ_job_12) data_0 = get_job_data(IQ_job_0, average=False) data_1 = get_job_data(IQ_job_1, average=False) data_11 = get_job_data(IQ_job_11, average=False) data_12 = get_job_data(IQ_job_12, average=False) plt.scatter(np.real(data_0[0]), np.imag(data_0[0]), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'0') plt.scatter(np.real(data_1[0]), np.imag(data_1[0]), s=5, cmap='viridis', c='red', alpha=0.5, label=r'1') plt.scatter(np.real(data_11[0]), np.imag(data_11[0]), s=5, cmap='viridis', c='yellow', alpha=0.5, label=r'11') plt.scatter(np.real(data_12[0]), np.imag(data_12[0]), s=5, cmap='viridis', c='green', alpha=0.5, label=r'12') mean_0 = np.mean(data_0[0]) mean_1 = np.mean(data_1[0]) mean_11 = np.mean(data_11[0]) mean_12 = np.mean(data_12[0]) plt.scatter(np.real(mean_0), np.imag(mean_0), s=200, cmap='viridis', c='black',alpha=1.0) plt.scatter(np.real(mean_1), np.imag(mean_1), s=200, cmap='viridis', c='black',alpha=1.0) plt.scatter(np.real(mean_11), np.imag(mean_11), s=200, cmap='viridis', c='black',alpha=1.0) plt.scatter(np.real(mean_12), np.imag(mean_12), s=200, cmap='viridis', c='black',alpha=1.0) plt.legend() zero_sched.draw() # 0 one_sched.draw() # 1 new_one_sched.draw() # 11 new_one_sched_2.draw() # 12 def get_job_data(job, average): scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor) return result_data IQ_data = get_job_data(IQ_job, average=False) zero_data = IQ_data[0] one_data = IQ_data[1] # zero_data = get_job_data(IQ_job_0, average=False) # one_data = get_job_data(IQ_job_1, average=False) from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis print("The discriminator plot for 0-1-2 discrimination.") x_min, x_max, y_min, y_max = IQ_plot(zero_data, one_data) # Create IQ vector (split real, imag parts) zero_data_reshaped = reshape_complex_vec(zero_data) one_data_reshaped = reshape_complex_vec(one_data) IQ_data = np.concatenate((zero_data_reshaped, one_data_reshaped)) # construct vector w/ 0's, 1's and 2's (for testing) state_012 = np.zeros(1024) # shots gives number of experiments state_012 = np.concatenate((state_012, np.ones(1024))) # state_012 = np.concatenate((state_012, 2*np.ones(1024))) # Shuffle and split data into training and test sets IQ_012_train, IQ_012_test, state_012_train, state_012_test = train_test_split(IQ_data, state_012, test_size=0.5) LDA_012 = LinearDiscriminantAnalysis() LDA_012.fit(IQ_012_train, state_012_train) score_012 = LDA_012.score(IQ_012_test, state_012_test) print('The accuracy score of the discriminator is: ', score_012) # # _state_discriminator_012 = LDA_012 # if visual: # IQ_plot(zero_data, one_data, two_data) separatrixPlot(LDA_012, x_min, x_max, y_min, y_max, 1024) new_exp_1 = assemble([new_one_sched], backend=backend, meas_level=2, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}] ) new_job_1 = backend.run(new_exp_1) job_monitor(new_job_1) new_one_sched.draw() print(new_job_1.result().get_counts()) IQ_plot(new_data_0[0], new_data_1[0]) new_results = new_job.result() new_data = get_job_data(new_job, average=False) new_0_data = new_data[0] new_1_data = new_data[1] IQ_plot(new_0_data, new_1_data) diff_one_sched = Schedule() diff_one_sched += Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=0), drive_chan) diff_one_sched += measure print(*np.around(zero_data[:10],2), sep='\n') from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis print("The discriminator plot for 0-1-2 discrimination.") x_min, x_max, y_min, y_max = IQ_plot(zero_data[0], one_data[0]) # Create IQ vector (split real, imag parts) zero_data_reshaped = reshape_complex_vec(zero_data[0]) one_data_reshaped = reshape_complex_vec(one_data[0]) IQ_data = np.concatenate((zero_data_reshaped, one_data_reshaped)) # construct vector w/ 0's, 1's and 2's (for testing) state_012 = np.zeros(1024) # shots gives number of experiments state_012 = np.concatenate((state_012, np.ones(1024))) # state_012 = np.concatenate((state_012, 2*np.ones(1024))) # Shuffle and split data into training and test sets IQ_012_train, IQ_012_test, state_012_train, state_012_test = train_test_split(IQ_data, state_012, test_size=0.5) LDA_012 = LinearDiscriminantAnalysis() LDA_012.fit(IQ_012_train, state_012_train) score_012 = LDA_012.score(IQ_012_test, state_012_test) print('The accuracy score of the discriminator is: ', score_012) # _state_discriminator_012 = LDA_012 # if visual: # IQ_plot(zero_data, one_data, two_data) separatrixPlot(LDA_012, x_min, x_max, y_min, y_max, 1024) speak('The test is over. Check it out.') from qiskit.pulse import * import qiskit.pulse.library as pulse_lib from scipy.signal import find_peaks ### Next, going on to test the function to calibrate the 1->2 transition frequency def apply_sideband(pulse, frequency): t_samples = np.linspace(0, dt*pulse_duration, pulse_duration) sine_pulse = np.sin(2*np.pi*(frequency-qubit_freq_ground)*t_samples) sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse), name='sideband_pulse') return sideband_pulse def get_job_data(job, average): scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: result_data.append(job_results.get_memory(i)[qubit]*scale_factor) else: result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor) return result_data def rel_maxima(freqs, output_data, height): peaks, _ = find_peaks(output_data, height) return freqs[peaks] def create_cal_circuit_excited(base_pulse, freq): sched = Schedule() sched += Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground), drive_chan) sched += Play(apply_sideband(base_pulse, freq), drive_chan) measure = inst_sched_map.get('measure', qubits=[qubit]) sched += measure << sched.duration return sched dt = backend.configuration().dt base_pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=0.3) sched_list = [] freq_list = qubit_freq_ground + np.linspace(-400*1e+6, 30*1e+6, 75) for freq in freq_list: sched_list.append(create_cal_circuit_excited(base_pulse, freq)) excited_sweep_exp = assemble(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*75 ) excited_sweep_job = backend.run(excited_sweep_exp) job_monitor(excited_sweep_job) excited_sweep_data = get_job_data(excited_sweep_job, average=True) excited_sweep_freqs = freq_list plt.scatter(excited_sweep_freqs/1e+9, excited_sweep_data, color='black') # plt.xlim([min(excited_sweep_freqs/1e+9)+0.01, max(excited_sweep_freqs/1e+9)]) # ignore min point (is off) # plt.ylim(-21,-20.5) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep (first pass)", fontsize=15) plt.show() approx_12_freq = rel_maxima(freq_list, np.real(excited_sweep_data), 10) speak("The test program is done.") approx_12_freq = rel_maxima(freq_list, np.real(excited_sweep_data), 10) #### This is to find the refined frequency of the second excited state. refined_freq_list = approx_12_freq + np.linspace(-20*1e+6, 20*1e+6, 75) refined_sched_list = [] for freq in refine_freq_list: sched_list.append(create_cal_circuit_excited(base_pulse, freq)) refined_sweep_exp = assemble(refined_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*75 ) refined_sweep_job = backend.run(refined_sweep_exp) refined_sweep_data = get_job_data(refined_sweep_job, average=True) # do fit in Hz (refined_sweep_fit_params, refined_sweep_y_fit) = fit_function(refined_freq_list, refined_sweep_data, lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [-12, 4.625*1e+9, 0.05*1e+9, 3*1e+9] # initial parameters for curve_fit ) plt.scatter(refined_excited_sweep_freqs/1e+9, refined_excited_freq_sweep_data, color='black') plt.plot(refined_excited_sweep_freqs/1e+9, refined_excited_sweep_y_fit, color='red') plt.xlim([min(refined_excited_sweep_freqs/1e+9), max(refined_excited_sweep_freqs/1e+9)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep (refined pass)", fontsize=15) plt.show() _, qubit_freq_12, _, _ = refined_sweep_fit_params qubit_freq_excited = qubit_freq_12
https://github.com/Sidx369/Qiskit-Developer-Exam-C1000-112-Prep
Sidx369
import qiskit qiskit.__version__ qiskit.__qiskit_version__ import qiskit.tools.jupyter %qiskit_version_table from qiskit import QuantumCircuit qc = QuantumCircuit(2,2) # (qbit, classicalbit) qc.measure_all() qc.draw() qc.draw('mpl') qc.draw('latex') qc = QuantumCircuit(3,2) # (qbit, classicalbit) qc.measure([0,1], [0,1]) qc.draw('mpl') from qiskit import QuantumRegister, ClassicalRegister from qiskit import Aer, execute q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.measure([0, 1], [0, 1]) qc.draw('mpl') from qiskit.visualization import plot_histogram sim = Aer.get_backend('statevector_simulator') job = execute(qc, sim, shots=1024) result = job.result() counts = result.get_counts() plot_histogram(counts) from qiskit.visualization import plot_state_qsphere from qiskit.quantum_info import Statevector qc=QuantumCircuit(1) qc.x(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) from qiskit.visualization import array_to_latex sim = Aer.get_backend('unitary_simulator') job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) #array_to_latex(result.get_statevector(qc)) # for statevector_simulator qc=QuantumCircuit(1) qc.y(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.y(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.z(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.z(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.s(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.s(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.sdg(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.s(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.t(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.t(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.tdg(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.tdg(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw('latex') plot_state_qsphere(state) job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) from math import pi qc=QuantumCircuit(1) qc.p(pi,0) qc.draw(output="mpl") job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi/2,0) qc.draw(output="mpl") job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi/4,0) qc.draw(output="mpl") job = execute(qc, sim) result = job.result() array_to_latex(result.get_unitary(qc, decimals=3))
https://github.com/kardashin/E91_protocol
kardashin
import numpy as np import pandas as pd import re import random import math # Importing QISKit from qiskit import QuantumProgram import Qconfig # Quantum program setup Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url ## Input parameters measurementChoicesLength = 1000 # length of the strings that cointain measurement choices evePresence = False # Presence of an eavesdropper in the channel evePresencePercentage = 1 # Percentage of Eve's interference backend = 'local_qasm_simulator' ## Creating registers qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 4) ## Creating a shared entangled state entangledState = Q_program.create_circuit('entangledState', [qr], [cr]) # bell_11 (singlet) stete for the ibmqx2 backend #entangledState.x(qr[0]) #entangledState.x(qr[1]) #entangledState.h(qr[0]) #entangledState.cx(qr[0],qr[1]) # bell_11 (singlet) stete for the ibmqx4 backend entangledState.x(qr[0]) entangledState.x(qr[1]) entangledState.h(qr[1]) entangledState.cx(qr[1],qr[0]) ### Creating measurement circuits ## Alice's measurement circuits # measurement of the spin projection onto the A1 = (1; 0; 0) direction # projection onto the eigenvectors of the matrix X measureA1 = Q_program.create_circuit('measureA1', [qr], [cr]) measureA1.h(qr[0]) measureA1.measure(qr[0],cr[0]) # measurement of the spin projection onto A2 = (1/sqt(2); 0; 1/(sqrt(2)) direction # projection onto the eigenvectors of the matrix W = (Z+X)/sqrt(2) measureA2 = Q_program.create_circuit('measureA2', [qr], [cr]) measureA2.s(qr[0]) measureA2.h(qr[0]) measureA2.t(qr[0]) measureA2.h(qr[0]) measureA2.measure(qr[0],cr[0]) # measurement of the spin projection onto the A3 = (0; 0; 1) vector # standard Z-measurement measureA3 = Q_program.create_circuit('measureA3', [qr], [cr]) measureA3.measure(qr[0],cr[0]) ## Bob's measurement circuits # measurement of the spin projection onto the B1 = (1/sqt(2); 0; 1/(sqrt(2)) direction # projection onto the eigenvectors of the matrix W = (Z+X)/sqrt(2) measureB1 = Q_program.create_circuit('measureB1', [qr], [cr]) measureB1.s(qr[1]) measureB1.h(qr[1]) measureB1.t(qr[1]) measureB1.h(qr[1]) measureB1.measure(qr[1],cr[1]) # measurement of the spin projection onto the B2 = (0; 0; 1) direction # standard Z measurement measureB2 = Q_program.create_circuit('measureB2', [qr], [cr]) measureB2.measure(qr[1],cr[1]) # measurement of the spin projection onto the B3 = (-1/sqt(2); 0; 1/(sqrt(2)) direction # projection onto the eigenvectors of the matrix V = (Z-X)/sqrt(2) measureB3 = Q_program.create_circuit('measureB3', [qr], [cr]) measureB3.s(qr[1]) measureB3.h(qr[1]) measureB3.tdg(qr[1]) measureB3.h(qr[1]) measureB3.measure(qr[1],cr[1]) ## Eve's measuremets # identity gate for Alice's qubit ident0 = Q_program.create_circuit('ident0', [qr], [cr]) ident0.iden(qr[0]) # identity gate for Bob's qubit ident1 = Q_program.create_circuit('ident1', [qr], [cr]) ident1.iden(qr[1]) # measurement of the spin projection of Alice's qubit onto the (1; 0; 0) direction (observable X) measureEA1 = Q_program.create_circuit('measureEA1', [qr], [cr]) measureEA1.h(qr[0]) measureEA1.measure(qr[0],cr[2]) # measurement of the spin projection of Alice's qubit onto the (1/sqt(2); 0; 1/(sqrt(2)) direction (observable W) measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr]) measureEA2.s(qr[0]) measureEA2.h(qr[0]) measureEA2.t(qr[0]) measureEA2.h(qr[0]) measureEA2.measure(qr[0],cr[2]) # measurement of the spin projection of Alice's qubit onto the (0; 0; 1) direction (observable Z) measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr]) measureEA3.measure(qr[0],cr[2]) # measurement of the spin projection of Bob's qubit onto the (1/sqt(2); 0; 1/(sqrt(2)) direction (observable W) measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr]) measureEB1.s(qr[1]) measureEB1.h(qr[1]) measureEB1.t(qr[1]) measureEB1.h(qr[1]) measureEB1.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the (0; 0; 1) direction (observable Z) measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr]) measureEB2.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the (-1/sqt(2); 0; 1/(sqrt(2)) direction (observable V) measureEB3 = Q_program.create_circuit('measureEB3', [qr], [cr]) measureEB3.s(qr[1]) measureEB3.h(qr[1]) measureEB3.tdg(qr[1]) measureEB3.h(qr[1]) measureEB3.measure(qr[1],cr[3]) ## Lists of Alice's, Bob's and Eve's measurement circuits aliceMeasurements = [measureA1, measureA2, measureA3] bobMeasurements = [measureB1, measureB2, measureB3] eveMeasurements = [ident0, ident1, measureEA1, measureEA2, measureEA3, measureEB1, measureEB2, measureEB3] ## Alice's and Bob's measurement choice strings aliceMeasurementChoices = [] bobMeasurementChoices = [] # random strings generation for i in range(measurementChoicesLength): aliceMeasurementChoices.append(random.randint(1, 3)) bobMeasurementChoices.append(random.randint(1, 3)) ## Eve's optimal measurement choices array # it is efficient for Eve to measure the spin projections of Alice's and Bob's qubits onto the same direction (A2B1 and A3B2) # list of Eve's measurement choices # the first and the second element of each row represents the measurement of Alice's and Bob's qubit, respectively # default values of the list are 1 and 2 (applying identity gate) eveMeasurementChoices = [[1,2] for j in range(measurementChoicesLength)] eveMersurementPerformed = [0] * measurementChoicesLength if evePresence == True: for j in range(measurementChoicesLength): if random.uniform(0, 1) <= evePresencePercentage: eveMersurementPerformed[j] = 1 if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the A2_B1 measurement (observable WW) eveMeasurementChoices[j] = [4, 6] else: # in 50% of cases perform the A3_B2 measurement (observable ZZ) eveMeasurementChoices[j] = [5, 7] circuits = [] # the list in which the created circuits will be stored for k in range(measurementChoicesLength): # create the name of the k-th circuit depending on Alice's, Bob's and Eve's choices of measurement circuitName = str(k) + ':A' + str(aliceMeasurementChoices[k]) + '_B' + str(bobMeasurementChoices[k]) + '_E' + str(eveMeasurementChoices[k][0]) + str(eveMeasurementChoices[k][1]) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, entangledState + # singlet state circuit eveMeasurements[eveMeasurementChoices[k][0]-1] + # Eve's measurement circuit for Alice's qubit eveMeasurements[eveMeasurementChoices[k][1]-1] + # Eve's measurement circuit for Bob's qubit aliceMeasurements[aliceMeasurementChoices[k]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[k]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) ## Execute circuits result = Q_program.execute(circuits, backend=backend, shots=1, timeout=180) print(result) ## Recording the measurement results aliceResults = [] # Alice's results bobResults = [] # Bob's results eveResults = [[0, 0] for j in range(measurementChoicesLength)] # list of zeros by default; if the element is 0, then Eve did not perform a measurement # Alice's and Bob's search patterns abPatterns = [ re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1) re.compile('..01$'), # search for the '..01' output re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1) re.compile('..11$') # search for the '..11' output ] # Eve's search patterns ePatterns = [ re.compile('00..$'), # search for the '00..' result re.compile('01..$'), re.compile('10..$'), re.compile('11..$') ] # Recording results for k in range(measurementChoicesLength): res = list(result.get_counts(circuits[k]).keys())[0] # extract a key from the dict and transform it to str; execution result of the k-th circuit # Alice and Bob if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): aliceResults.append(-1) bobResults.append(1) if abPatterns[3].search(res): # check if the key is '..11' (if the measurement results are 1,1) aliceResults.append(1) bobResults.append(1) # Eve if eveMersurementPerformed[k] == True: # if Eve has performed a measurement in the k-th circuit if ePatterns[0].search(res): # check if the key is '00..' eveResults[k][0] = -1 # result of the measurement of Alice's qubit eveResults[k][1] = -1 # result of the measurement of Bob's qubit if ePatterns[1].search(res): eveResults[k][0] = 1 eveResults[k][1] = -1 if ePatterns[2].search(res): eveResults[k][0] = -1 eveResults[k][1] = 1 if ePatterns[3].search(res): eveResults[k][0] = 1 eveResults[k][1] = 1 ## Measurement choises check stage # Alice and Bob compare their strings with basis choices # If in the k-th measurement A and B used the same basis, then they record the result of the k-th measurement as the bit of the secret key aliceKey = [] # Alice's key string bobKey = [] # Bob's key string eveKeys = [] # Eve's keys; the 1-st column is the Alice's key, the 2-nd is Bob's # the key consists of the results obtained after projecting the spin onto the same directions (A2_B1 and A3_B2 measurements) for k in range(measurementChoicesLength): # if Alice and Bob measured the WW or ZZ observable if (aliceMeasurementChoices[k] == 2 and bobMeasurementChoices[k] == 1) or (aliceMeasurementChoices[k] == 3 and bobMeasurementChoices[k] == 2): aliceKey.append(aliceResults[k]) # record Alice's k-th result as a key bit bobKey.append(-bobResults[k]) # write Bob's k-th result as a key bit; must be inversed for the singlet state eveKeys.append([eveResults[k][0], -eveResults[k][1]]) keyLength = len(aliceKey) # length of the secret keys ## Comparing the bits of the keys abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's secret keys eaKeyMismatches = 0 # number of mismatching bits in Alice's and Eve's secret keys ebKeyMismatches = 0 eeKeyMismatches = 0 for k in range(keyLength): if aliceKey[k] != bobKey[k]: abKeyMismatches += 1 if eveKeys[k][0] != aliceKey[k]: eaKeyMismatches += 1 if eveKeys[k][1] != bobKey[k]: ebKeyMismatches += 1 if eveKeys[k][0] != eveKeys[k][1]: eeKeyMismatches += 1 # Eve's knowledge of the keys eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Alice's key ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Bob's key averageEveKnowledge = (eaKnowledge + ebKnowledge)/2 # average Eve's knowledge # Quantum bit error rate qber = abKeyMismatches/keyLength ## CHSH inequality test # lists with the counts of measurement results # each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively countA1B1 = [0, 0, 0, 0] countA1B3 = [0, 0, 0, 0] countA3B1 = [0, 0, 0, 0] countA3B3 = [0, 0, 0, 0] for k in range(measurementChoicesLength): res = list(result.get_counts(circuits[k]).keys())[0] # observable XW if (aliceMeasurementChoices[k] == 1 and bobMeasurementChoices[k] == 1): for j in range(4): if abPatterns[j].search(res): countA1B1[j] += 1 # observable XV if (aliceMeasurementChoices[k] == 1 and bobMeasurementChoices[k] == 3): for j in range(4): if abPatterns[j].search(res): countA1B3[j] += 1 # observable ZW if (aliceMeasurementChoices[k] == 3 and bobMeasurementChoices[k] == 1): for j in range(4): if abPatterns[j].search(res): countA3B1[j] += 1 # observable ZV if (aliceMeasurementChoices[k] == 3 and bobMeasurementChoices[k] == 3): for j in range(4): if abPatterns[j].search(res): countA3B3[j] += 1 # number of results obtained from measurements in a particular basis total11 = sum(countA1B1) total13 = sum(countA1B3) total31 = sum(countA3B1) total33 = sum(countA3B3) # expected values of the spin projections onto the A1_B1, A1_B3, A3_B1 and A3_B3 directions expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # observable XW expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total31 # observable XV expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total13 # observable ZW expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # observable ZV # CHSH correlation value # must be equal to -2*sqrt(2) in the case of the absence of noise and eavesdropping corr = expect11 - expect13 + expect31 + expect33 diff = abs(abs(corr) - 2*math.sqrt(2)) ## Print results # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3))) print('Difference from -2*sqrt(2): ' + str(round(diff, 3)) + '\n') # Secret keys print('Length of the secret key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') print('QBER: ' + str(round(qber * 100, 2)) + ' %') print('Eve\'s average knowledge: ' + str(round(averageEveKnowledge * 100, 2)) + ' %\n') ## Check measurement errors # Theoretically, the measurement in the A2_B1 and A3_B2 basises gives only the (-1,1) and (1,-1) results # This block counts how many (-1,-1) and (1,1) results obtained after the measurements of the WW and ZZ observables # actual for the execution on the real quantum devices mismatchesList = [] for k in range(measurementChoicesLength): res = list(result.get_counts(circuits[k]).keys())[0] result01 = False # by default result10 = False if abPatterns[1].search(res): result01 = True if abPatterns[2].search(res): result10 = True condition1 = ('A2_B1' in circuits[k] or 'A3_B2' in circuits[k]) and not result01 # if result is not (-1,1) condition2 = ('A2_B1' in circuits[k] or 'A3_B2' in circuits[k]) and not result10 # if result is not (1,-1) if condition1 and condition2 == True: mismatchesList.append([str(circuits[k]), res]) pd.DataFrame(mismatchesList,columns = ['Measurement', 'Result'])
https://github.com/kardashin/E91_protocol
kardashin
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # useful additional packages import numpy as np import random import math import re # regular expressions module # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram import Qconfig # Quantum program setup Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # Creating registers qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 4) singlet = Q_program.create_circuit('singlet', [qr], [cr]) singlet.x(qr[0]) singlet.x(qr[1]) singlet.h(qr[0]) singlet.cx(qr[0],qr[1]) ## Alice's measurement circuits # measure the spin projection of Alice's qubit onto the a_1 direction (X basis) measureA1 = Q_program.create_circuit('measureA1', [qr], [cr]) measureA1.h(qr[0]) measureA1.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_2 direction (W basis) measureA2 = Q_program.create_circuit('measureA2', [qr], [cr]) measureA2.s(qr[0]) measureA2.h(qr[0]) measureA2.t(qr[0]) measureA2.h(qr[0]) measureA2.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis) measureA3 = Q_program.create_circuit('measureA3', [qr], [cr]) measureA3.measure(qr[0],cr[0]) ## Bob's measurement circuits # measure the spin projection of Bob's qubit onto the b_1 direction (W basis) measureB1 = Q_program.create_circuit('measureB1', [qr], [cr]) measureB1.s(qr[1]) measureB1.h(qr[1]) measureB1.t(qr[1]) measureB1.h(qr[1]) measureB1.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis) measureB2 = Q_program.create_circuit('measureB2', [qr], [cr]) measureB2.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_3 direction (V basis) measureB3 = Q_program.create_circuit('measureB3', [qr], [cr]) measureB3.s(qr[1]) measureB3.h(qr[1]) measureB3.tdg(qr[1]) measureB3.h(qr[1]) measureB3.measure(qr[1],cr[1]) ## Lists of measurement circuits aliceMeasurements = [measureA1, measureA2, measureA3] bobMeasurements = [measureB1, measureB2, measureB3] # Define the number of singlets N numberOfSinglets = 500 aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob circuits = [] # the list in which the created circuits will be stored for i in range(numberOfSinglets): # create the name of the i-th circuit depending on Alice's and Bob's measurement choices circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i]) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) print(circuits[0]) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) result.get_counts(circuits[0]) abPatterns = [ re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1) re.compile('..01$'), # search for the '..01' output re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1) re.compile('..11$') # search for the '..11' output ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) aliceKey = [] # Alice's key string k bobKey = [] # Bob's key string k' # comparing the stings with measurement choices for i in range(numberOfSinglets): # if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2): aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' keyLength = len(aliceKey) # length of the secret key abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 # function that calculates CHSH correlation value def chsh_corr(result): # lists with the counts of measurement results # each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively countA1B1 = [0, 0, 0, 0] # XW observable countA1B3 = [0, 0, 0, 0] # XV observable countA3B1 = [0, 0, 0, 0] # ZW observable countA3B3 = [0, 0, 0, 0] # ZV observable for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA1B1[j] += 1 if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA1B3[j] += 1 if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA3B1[j] += 1 # if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA3B3[j] += 1 # number of the results obtained from the measurements in a particular basis total11 = sum(countA1B1) total13 = sum(countA1B3) total31 = sum(countA3B1) total33 = sum(countA3B3) # expectation values of XW, XV, ZW and ZV observables (2) expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2) expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2) expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2) expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2) corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3) return corr corr = chsh_corr(result) # CHSH correlation value # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3))) # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') # measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis) measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr]) measureEA2.s(qr[0]) measureEA2.h(qr[0]) measureEA2.t(qr[0]) measureEA2.h(qr[0]) measureEA2.measure(qr[0],cr[2]) # measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis) measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr]) measureEA3.measure(qr[0],cr[2]) # measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis) measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr]) measureEB1.s(qr[1]) measureEB1.h(qr[1]) measureEB1.t(qr[1]) measureEB1.h(qr[1]) measureEB1.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement) measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr]) measureEB2.measure(qr[1],cr[3]) # lists of measurement circuits eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2] # list of Eve's measurement choices # the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively eveMeasurementChoices = [] for j in range(numberOfSinglets): if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement eveMeasurementChoices.append([0, 2]) else: # in 50% of cases perform the ZZ measurement eveMeasurementChoices.append([1, 3]) circuits = [] # the list in which the created circuits will be stored for j in range(numberOfSinglets): # create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0]))) ePatterns = [ re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits) re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits) re.compile('10..$'), re.compile('11..$') ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') # list of Eve's measurement results # the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits # the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits eveResults = [] # recording the measurement results for j in range(numberOfSinglets): res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str # Alice and Bob if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) # Eve if ePatterns[0].search(res): # check if the key is '00..' eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1 if ePatterns[1].search(res): eveResults.append([1, -1]) if ePatterns[2].search(res): eveResults.append([-1, 1]) if ePatterns[3].search(res): eveResults.append([1, 1]) aliceKey = [] # Alice's key string a bobKey = [] # Bob's key string a' eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob # comparing the strings with measurement choices (b and b') for j in range(numberOfSinglets): # if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2): aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve keyLength = len(aliceKey) # length of the secret skey abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 if eveKeys[j][0] != aliceKey[j]: eaKeyMismatches += 1 if eveKeys[j][1] != bobKey[j]: ebKeyMismatches += 1 eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key corr = chsh_corr(result) # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3)) + '\n') # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %') print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
https://github.com/kardashin/E91_protocol
kardashin
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # useful additional packages import numpy as np import random import math import re # regular expressions module # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram import Qconfig # Quantum program setup Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # Creating registers qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 4) singlet = Q_program.create_circuit('singlet', [qr], [cr]) singlet.x(qr[0]) singlet.x(qr[1]) singlet.h(qr[0]) singlet.cx(qr[0],qr[1]) ## Alice's measurement circuits # measure the spin projection of Alice's qubit onto the a_1 direction (X basis) measureA1 = Q_program.create_circuit('measureA1', [qr], [cr]) measureA1.h(qr[0]) measureA1.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_2 direction (W basis) measureA2 = Q_program.create_circuit('measureA2', [qr], [cr]) measureA2.s(qr[0]) measureA2.h(qr[0]) measureA2.t(qr[0]) measureA2.h(qr[0]) measureA2.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis) measureA3 = Q_program.create_circuit('measureA3', [qr], [cr]) measureA3.measure(qr[0],cr[0]) ## Bob's measurement circuits # measure the spin projection of Bob's qubit onto the b_1 direction (W basis) measureB1 = Q_program.create_circuit('measureB1', [qr], [cr]) measureB1.s(qr[1]) measureB1.h(qr[1]) measureB1.t(qr[1]) measureB1.h(qr[1]) measureB1.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis) measureB2 = Q_program.create_circuit('measureB2', [qr], [cr]) measureB2.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_3 direction (V basis) measureB3 = Q_program.create_circuit('measureB3', [qr], [cr]) measureB3.s(qr[1]) measureB3.h(qr[1]) measureB3.tdg(qr[1]) measureB3.h(qr[1]) measureB3.measure(qr[1],cr[1]) ## Lists of measurement circuits aliceMeasurements = [measureA1, measureA2, measureA3] bobMeasurements = [measureB1, measureB2, measureB3] # Define the number of singlets N numberOfSinglets = 500 aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob circuits = [] # the list in which the created circuits will be stored for i in range(numberOfSinglets): # create the name of the i-th circuit depending on Alice's and Bob's measurement choices circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i]) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) print(circuits[0]) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) result.get_counts(circuits[0]) abPatterns = [ re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1) re.compile('..01$'), # search for the '..01' output re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1) re.compile('..11$') # search for the '..11' output ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) aliceKey = [] # Alice's key string k bobKey = [] # Bob's key string k' # comparing the stings with measurement choices for i in range(numberOfSinglets): # if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2): aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' keyLength = len(aliceKey) # length of the secret key abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 # function that calculates CHSH correlation value def chsh_corr(result): # lists with the counts of measurement results # each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively countA1B1 = [0, 0, 0, 0] # XW observable countA1B3 = [0, 0, 0, 0] # XV observable countA3B1 = [0, 0, 0, 0] # ZW observable countA3B3 = [0, 0, 0, 0] # ZV observable for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA1B1[j] += 1 if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA1B3[j] += 1 if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA3B1[j] += 1 # if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA3B3[j] += 1 # number of the results obtained from the measurements in a particular basis total11 = sum(countA1B1) total13 = sum(countA1B3) total31 = sum(countA3B1) total33 = sum(countA3B3) # expectation values of XW, XV, ZW and ZV observables (2) expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2) expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2) expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2) expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2) corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3) return corr corr = chsh_corr(result) # CHSH correlation value # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3))) # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') # measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis) measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr]) measureEA2.s(qr[0]) measureEA2.h(qr[0]) measureEA2.t(qr[0]) measureEA2.h(qr[0]) measureEA2.measure(qr[0],cr[2]) # measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis) measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr]) measureEA3.measure(qr[0],cr[2]) # measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis) measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr]) measureEB1.s(qr[1]) measureEB1.h(qr[1]) measureEB1.t(qr[1]) measureEB1.h(qr[1]) measureEB1.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement) measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr]) measureEB2.measure(qr[1],cr[3]) # lists of measurement circuits eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2] # list of Eve's measurement choices # the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively eveMeasurementChoices = [] for j in range(numberOfSinglets): if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement eveMeasurementChoices.append([0, 2]) else: # in 50% of cases perform the ZZ measurement eveMeasurementChoices.append([1, 3]) circuits = [] # the list in which the created circuits will be stored for j in range(numberOfSinglets): # create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0]))) ePatterns = [ re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits) re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits) re.compile('10..$'), re.compile('11..$') ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') # list of Eve's measurement results # the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits # the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits eveResults = [] # recording the measurement results for j in range(numberOfSinglets): res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str # Alice and Bob if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) # Eve if ePatterns[0].search(res): # check if the key is '00..' eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1 if ePatterns[1].search(res): eveResults.append([1, -1]) if ePatterns[2].search(res): eveResults.append([-1, 1]) if ePatterns[3].search(res): eveResults.append([1, 1]) aliceKey = [] # Alice's key string a bobKey = [] # Bob's key string a' eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob # comparing the strings with measurement choices (b and b') for j in range(numberOfSinglets): # if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2): aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve keyLength = len(aliceKey) # length of the secret skey abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 if eveKeys[j][0] != aliceKey[j]: eaKeyMismatches += 1 if eveKeys[j][1] != bobKey[j]: ebKeyMismatches += 1 eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key corr = chsh_corr(result) # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3)) + '\n') # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %') print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
https://github.com/Chibikuri/qwopt
Chibikuri
import sys import numpy as np import matplotlib.pyplot as plt import seaborn as sns import copy sys.path.append('../') from qwopt.compiler import composer from qwopt.benchmark import fidelity as fid from numpy import pi from qiskit import transpile from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import depolarizing_error from tqdm import tqdm, trange from mpl_toolkits.mplot3d import Axes3D import warnings warnings.simplefilter('ignore') alpha = 0.85 target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) E = np.array([[1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0], [1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4)) init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) # Circuit def four_node(opt, step): rotation = np.radians(31.788) cq = QuantumRegister(2, 'control') tq = QuantumRegister(2, 'target') c = ClassicalRegister(2, 'classical') if opt: anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, c) else: qc = QuantumCircuit(cq, tq, c) # initialize with probability distribution matrix initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # Kdg operation if opt: qc.x(cq) qc.rccx(cq[0], cq[1], anc[0]) qc.barrier() qc.ch(anc[0], tq[0]) qc.ch(anc[0], tq[1]) qc.x(anc[0]) qc.cry(-rotation, anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.barrier() else: qc.x(cq) qc.mcry(-pi/2, cq, tq[0], None) qc.mcry(-pi/2, cq, tq[1], None) qc.x(cq) qc.barrier() # qc.x(cq[1]) # qc.mcry(-pi/2, cq, tq[0], None) # qc.mcry(-rotation, cq, tq[1], None) # qc.x(cq[1]) # qc.barrier() qc.x(cq[0]) qc.mcry(-pi/2, cq, tq[0], None) qc.mcry(-rotation, cq, tq[1], None) qc.x(cq[0]) qc.barrier() qc.cry(-pi/2, cq[0], tq[0]) qc.cry(-rotation, cq[0], tq[1]) qc.barrier() # qc.mcry(-pi/2, cq, tq[0], None) # qc.mcry(-rotation, cq, tq[1], None) # qc.barrier() # D operation qc.x(tq) qc.cz(tq[0], tq[1]) qc.x(tq) qc.barrier() # K operation if opt: qc.ch(anc[0], tq[0]) qc.cry(rotation, anc[0], tq[1]) qc.x(anc[0]) qc.ch(anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.rccx(cq[0], cq[1], anc[0]) qc.x(cq) qc.barrier() else: # previous, and naive imple # qc.mcry(pi/2, cq, tq[0], None) # qc.mcry(rotation, cq, tq[1], None) # qc.barrier() qc.cry(pi/2, cq[0], tq[0]) qc.cry(rotation, cq[0], tq[1]) qc.barrier() qc.x(cq[0]) qc.mcry(pi/2, cq, tq[0], None) qc.mcry(rotation, cq, tq[1], None) qc.x(cq[0]) qc.barrier() # qc.x(cq[1]) # qc.mcry(pi/2, cq, tq[0], None) # qc.mcry(rotation, cq, tq[1], None) # qc.x(cq[1]) # qc.barrier() qc.x(cq) qc.mcry(pi/2, cq, tq[0], None) qc.mcry(pi/2, cq, tq[1], None) qc.x(cq) qc.barrier() # Tidg operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # swap qc.swap(tq[0], cq[0]) qc.swap(tq[1], cq[1]) qc.measure(tq, c) return qc qc = four_node(True, 1) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=10000) count = job.result().get_counts(qc) print(count) qc.draw(output='mpl') ex1_cx = [] ex1_u3 = [] ex2_cx = [] ex2_u3 = [] ex3_cx = [] ex3_u3 = [] ex4_cx = [] ex4_u3 = [] for step in trange(1, 11): opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex1_cx.append(ncx) ex1_u3.append(nu3) # ex2 opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex2_cx.append(ncx) ex2_u3.append(nu3) # ex3 opt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex3_cx.append(ncx) ex3_u3.append(nu3) # ex4 nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0) ncx = nopt_qc.count_ops().get('cx', 0) nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0) ex4_cx.append(ncx) ex4_u3.append(nu3) cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] # color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] # labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.xticks([i for i in range(11)]) plt.ylabel('the number of operations', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) plt.plot(steps, ex4_cx, color='#3EBA2B', label='# of CX without optimizations', linewidth=3) plt.plot(steps, ex4_u3, color='#6BBED5', label='# of single qubit operations without optimizations', linewidth=3) plt.legend(fontsize=25) cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.xticks([i for i in range(11)]) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) print(list(steps)) for cs, col, lab in zip(cx, color, labels): plt.plot(steps, cs, color=col, label=lab, linewidth=3) plt.legend(fontsize=25) import warnings warnings.simplefilter('ignore') qasm_sim = Aer.get_backend('qasm_simulator') def KL_divergence(p, q, torelance=10e-9): ''' p: np.array or list q: np.array or list ''' parray = np.array(p) + torelance qarray = np.array(q) + torelance divergence = np.sum(parray*np.log(parray/qarray)) return divergence def get_error(qc, ideal, err_model, nq, type='KL', shots=10000): bins = [format(i, '0%db'%nq) for i in range(2**nq)] job = execute(qc, backend=qasm_sim, shots=shots, noise_model=err_model) counts = job.result().get_counts(qc) prob = np.array([counts.get(b, 0)/shots for b in bins]) id_prob = np.array(ideal) # l2_error = np.sum([(i-j)**2 for i, j in zip(id_prob, prob)]) KL_error = KL_divergence(id_prob, prob) return KL_error def theoretical_prob(initial, step, ptran, nq): Pi_op = Pi_operator(ptran) swap = swap_operator(nq) operator = (2*Pi_op) - np.identity(len(Pi_op)) Szegedy = np.dot(operator, swap) Szegedy_n = copy.deepcopy(Szegedy) if step == 0: init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float) return init_prob elif step == 1: prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)], dtype=np.float) return prob else: for n in range(step-1): Szegedy_n = np.dot(Szegedy_n, Szegedy) probs = np.array([abs(i)**2 for i in np.dot(Szegedy_n, initial)], dtype=np.float) return probs def swap_operator(n_qubit): q1 = QuantumRegister(n_qubit//2) q2 = QuantumRegister(n_qubit//2) qc = QuantumCircuit(q1, q2) for c, t in zip(q1, q2): qc.swap(c, t) # FIXME backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend=backend) swap = job.result().get_unitary(qc) return swap def Pi_operator(ptran): ''' This is not a quantum operation, just returning matrix ''' lg = len(ptran) psi_op = [] count = 0 for i in range(lg): psi_vec = [0 for _ in range(lg**2)] for j in range(lg): psi_vec[count] = np.sqrt(ptran[j][i]) count += 1 psi_op.append(np.kron(np.array(psi_vec).T, np.conjugate(psi_vec)).reshape((lg**2, lg**2))) Pi = psi_op[0] for i in psi_op[1:]: Pi = np.add(Pi, i) return Pi # circuit verifications # for step in range(1, 11): # opt_qc1 = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0) # opt_qc2 = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3) # opt_qc3 = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3) # nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0) # job1 = execute(opt_qc1, backend=qasm_sim, shots=10000) # job2 = execute(opt_qc2, backend=qasm_sim, shots=10000) # job3 = execute(opt_qc3, backend=qasm_sim, shots=10000) # job4 = execute(nopt_qc, backend=qasm_sim, shots=10000) # count1 = job1.result().get_counts() # count2 = job2.result().get_counts() # count3 = job3.result().get_counts() # count4 = job4.result().get_counts() # print(count1.get('00'), count2.get('00'), count3.get('00'), count4.get('00')) ex1_mean = [] ex1_std = [] ex2_mean = [] ex2_std = [] ex3_mean = [] ex3_std = [] ex4_mean = [] ex4_std = [] extime = 10 u3_error = depolarizing_error(0.001, 1) qw_step = range(1, 11) gate_error = np.arange(0, 0.03, 0.001) # errors, steps= np.meshgrid(gate_error, qw_step) bins = [format(i, '02b') for i in range(2**2)] step = 5 opt_qc = four_node(True, step) job = execute(opt_qc, backend=qasm_sim, shots=100000) count = job.result().get_counts(opt_qc) ideal_prob = [count.get(i, 0)/100000 for i in bins] for cxerr in tqdm(gate_error): # noise model error_model = NoiseModel() cx_error = depolarizing_error(cxerr, 2) error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # ex1 errors = [] for i in range(extime): opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0) error = get_error(opt_qc, ideal_prob, error_model, 2) errors.append(error) ex1_mean.append(np.mean(errors)) ex1_std.append(np.std(errors)) # ex2 errors = [] for i in range(extime): opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3) error = get_error(opt_qc, ideal_prob, error_model, 2) errors.append(error) ex2_mean.append(np.mean(errors)) ex2_std.append(np.std(errors)) # ex3 errors = [] for i in range(extime): opt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3) error = get_error(opt_qc, ideal_prob, error_model, 2) errors.append(error) ex3_mean.append(np.mean(errors)) ex3_std.append(np.std(errors)) # ex4 errors=[] for i in range(extime): nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0) error = get_error(nopt_qc, ideal_prob, error_model, 2) errors.append(error) ex4_mean.append(np.mean(errors)) ex4_std.append(np.std(errors)) fig = plt.figure(figsize=(20, 10)) # plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations') # # plt.errorbar(gate_error, ex2_mean, yerr=ex2_std, label='With my and qiskit optimizations') # # plt.errorbar(gate_error, ex3_mean, yerr=ex3_std, label='With qiskit optimizations') plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations') plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30) plt.xlabel('cx error rate', fontsize=30) plt.ylabel('KL divergence', fontsize=30) plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() # ex1_mean = [] # ex1_std = [] # ex2_mean = [] # ex2_std = [] # ex3_mean = [] # ex3_std = [] # ex4_mean = [] # ex4_std = [] # extime = 10 # u3_error = depolarizing_error(0, 1) # qw_step = range(1,6) # gate_error = np.arange(0, 0.1, 0.01) # errors, steps= np.meshgrid(gate_error, qw_step) # bins = [format(i, '02b') for i in range(2**2)] # for ce, st in tqdm(zip(errors, steps)): # opt_qc = four_node(True, st[0]) # job = execute(opt_qc, backend=qasm_sim, shots=100000) # count = job.result().get_counts(opt_qc) # ideal_prob = [count.get(i, 0)/100000 for i in bins] # for cxerr, step in zip(ce, st): # # noise model # error_model = NoiseModel() # cx_error = depolarizing_error(cxerr, 2) # error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) # error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # # ex1 # qcs1 = [four_node(True, step) for i in range(extime)] # opt_qc1 = transpile(qcs1, basis_gates=['cx', 'u3'], optimization_level=0) # errors = get_error(opt_qc1, ideal_prob, error_model, 2) # ex1_mean.append(np.mean(errors)) # ex1_std.append(np.std(errors)) # # ex2 # qcs2 = [four_node(True, step) for i in range(extime)] # opt_qc2 = transpile(qcs2, basis_gates=['cx', 'u3'], optimization_level=3) # errors = get_error(opt_qc2, ideal_prob, error_model, 2) # ex2_mean.append(np.mean(errors)) # ex2_std.append(np.std(errors)) # # ex3 # qcs3 = [four_node(False, step) for i in range(extime)] # opt_qc3 = transpile(qcs3, basis_gates=['cx', 'u3'], optimization_level=3) # errors = get_error(opt_qc, ideal_prob, error_model, 2) # ex3_mean.append(np.mean(errors)) # ex3_std.append(np.std(errors)) # # ex4 # qcs4 = [four_node(False, step) for i in range(extime)] # nopt_qc = transpile(qcs4, basis_gates=['cx', 'u3'], optimization_level=0) # error = get_error(nopt_qc, ideal_prob, error_model, 2) # ex4_mean.append(np.mean(errors)) # ex4_std.append(np.std(errors)) res1 = np.array(ex1_mean).reshape(10, 10) res2 = np.array(ex2_mean).reshape(10, 10) res3 = np.array(ex3_mean).reshape(10, 10) res4 = np.array(ex4_mean).reshape(10, 10) # fig = plt.figure(figsize=(20, 10)) # ax = Axes3D(fig) # ax.plot_wireframe(errors, steps, res1, color='#E6855E', linewidth=2, label='With my optimization') # ax.plot_wireframe(errors, steps, res2, color='#F9DB57', linewidth=2, label='With my and qiskit optimizations') # ax.plot_wireframe(errors, steps, res3, color='#3DB680', linewidth=2, label='With qiskit optimizations') # ax.plot_wireframe(errors, steps, res4, color='#6A8CC7', linewidth=2, label='Without optimizations') # ax.set_xlabel('Cx error rate', labelpad=30, fontsize=30) # ax.set_ylabel('The number of steps', labelpad=30, fontsize=30) # ax.set_zlabel('Error', labelpad=30, fontsize=30) # plt.tick_params(labelsize=20) # plt.legend(fontsize=20) # plt.show() # In this case, we're gonna investigate matrix that has just one partition alpha = 0.85 target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) E = np.array([[1/8, 1/2, 0, 0, 0, 0, 0, 1/2], [1/8, 0, 1/2, 0, 0, 0, 0, 0], [1/8, 1/2, 0, 1/2, 0, 0, 0, 0], [1/8, 0, 1/2, 0, 1/2, 0, 0, 0], [1/8, 0, 0, 1/2, 0, 1/2, 0, 0], [1/8, 0, 0, 0, 1/2, 0, 1/2, 0], [1/8, 0, 0, 0, 0, 1/2, 0, 1/2], [1/8, 0, 0, 0, 0, 0, 1/2, 0]]) # use google matrix lt = len(target_graph) prob_dist = alpha*E + ((1-alpha)/lt)*np.ones((lt, lt)) init_state_eight = 1/np.sqrt(8)*np.array([np.sqrt(prob_dist[j][i]) for i in range(lt) for j in range(lt)]) # Circuit def eight_node(opt, step, initial, hardopt=False): rotation1 = np.radians(31.788) rotation2 = np.radians(90) rotation3 = np.radians(23.232) cq = QuantumRegister(3, 'control') tq = QuantumRegister(3, 'target') # ancilla for mct gates anc = QuantumRegister(3, 'mct anc') c = ClassicalRegister(3, 'classical') if opt: opt_anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, opt_anc, c) else: qc = QuantumCircuit(cq, tq, anc, c) # initialize with probability distribution matrix if initial is not None: qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation # T1 qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[2], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # T2 qc.x(cq[0]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.barrier() # T3 qc.x(cq[1:]) qc.mct(cq, tq[1], anc) qc.mct(cq, tq[2], anc) qc.x(cq[1:]) qc.barrier() # T4 qc.x(cq[1]) qc.mct(cq, tq[0], anc) qc.x(cq[1]) qc.barrier() # T5 qc.x(cq[2]) qc.mct(cq, tq[0], anc) qc.mct(cq, tq[2], anc) qc.x(cq[2]) qc.barrier() # T6 qc.x(tq[2]) qc.mct([*cq, *tq[1:]], tq[0], anc) qc.x(tq[2]) qc.barrier() # # Kdg operation if opt: qc.x(cq[:]) # qc.rcccx(cq[0], cq[1], cq[2], opt_anc[0]) qc.mct(cq, opt_anc[0], anc) qc.x(cq[:]) for ryq in tq: qc.cry(-pi/2, opt_anc[0], ryq) if hardopt: raise Exception('under_construction') else: qc.x(opt_anc[0]) qc.x(tq[0]) qc.mcry(-rotation3, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[1], anc) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(-rotation2, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) qc.cry(-rotation1, opt_anc[0], tq[0]) qc.x(opt_anc[0]) else: qc.x(cq[:]) for ryq in tq: qc.mcry(-pi/2, cq, ryq, anc) qc.barrier() qc.x(cq[:]) for i in range(1, 8): bins = list(format(i, '03b')) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) qc.x(tq[0]) qc.mcry(-rotation3, [*cq, tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [*cq, tq[0]], tq[1], anc) qc.mcry(3/2*pi, [*cq, tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(-rotation2, [*cq, tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(-rotation1, cq, tq[0], anc) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) # D operation qc.x(tq) qc.h(tq[2]) qc.ccx(tq[0], tq[1], tq[2]) qc.h(tq[2]) qc.x(tq) qc.barrier() # # K operation if opt: if hardopt: raise Exception('under...') else: qc.x(opt_anc[0]) qc.cry(rotation1, opt_anc[0], tq[0]) qc.x(tq[0]) qc.mcry(rotation2, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[1], anc) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(rotation3, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.x(opt_anc[0]) for anq in tq: qc.cry(pi/2, opt_anc[0], anq) qc.barrier() qc.x(cq[:]) qc.mct(cq, opt_anc[0], anc) qc.x(cq[:]) else: for i in range(1, 8): bins = list(format(i, '03b')) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) qc.mcry(rotation1, cq, tq[0], anc) qc.x(tq[0]) qc.mcry(rotation2, [*cq, tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [*cq, tq[0]], tq[2], anc) qc.mcry(3/2*pi, [*cq, tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(rotation3, [*cq, tq[0]], tq[2], anc) qc.x(tq[0]) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) qc.x(cq[:]) for anq in tq: qc.mcry(pi/2, cq, anq, anc) qc.x(cq[:]) # # Tidg operation # T6 qc.x(tq[2]) qc.mct([*cq, *tq[1:]], tq[0], anc) qc.x(tq[2]) qc.barrier() # T5 qc.x(cq[2]) qc.mct(cq, tq[0], anc) qc.mct(cq, tq[2], anc) qc.x(cq[2]) qc.barrier() # T4 qc.x(cq[1]) qc.mct(cq, tq[0], anc) qc.x(cq[1]) qc.barrier() # T3 qc.x(cq[1:]) qc.mct(cq, tq[1], anc) qc.mct(cq, tq[2], anc) qc.x(cq[1:]) qc.barrier() # T2 qc.x(cq[0]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.barrier() # T1 qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[2], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # swap for cont, targ in zip(cq, tq): qc.swap(cont, targ) qc.measure(cq, c) return qc # circuit verifications qasm_sim = Aer.get_backend("qasm_simulator") for step in range(1, 11): opt_qc1 = transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) opt_qc2 = transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3) opt_qc3 = transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3) nopt_qc = transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) job1 = execute(opt_qc1, backend=qasm_sim, shots=10000) job2 = execute(opt_qc2, backend=qasm_sim, shots=10000) job3 = execute(opt_qc3, backend=qasm_sim, shots=10000) job4 = execute(nopt_qc, backend=qasm_sim, shots=10000) count1 = job1.result().get_counts() count2 = job2.result().get_counts() count3 = job3.result().get_counts() count4 = job4.result().get_counts() print(count1.get('000'), count2.get('000'), count3.get('000'), count4.get('000')) ex1_cx = [] ex1_u3 = [] ex2_cx = [] ex2_u3 = [] ex3_cx = [] ex3_u3 = [] ex4_cx = [] ex4_u3 = [] for step in trange(1, 11): opt_qc = transpile(eight_node(True, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex1_cx.append(ncx) ex1_u3.append(nu3) # ex2 opt_qc = transpile(eight_node(True, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex2_cx.append(ncx) ex2_u3.append(nu3) # ex3 opt_qc = transpile(eight_node(False, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex3_cx.append(ncx) ex3_u3.append(nu3) # ex4 nopt_qc = transpile(eight_node(False, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = nopt_qc.count_ops().get('cx', 0) nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0) ex4_cx.append(ncx) ex4_u3.append(nu3) steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) plt.xticks([i for i in range(11)]) # for cs, col, lab in zip(cx, color, labels): plt.plot(steps, ex4_cx, color= '#3EBA2B', label= '# of CX without optimizations', linewidth=3) plt.plot(steps, ex4_u3, color= '#6BBED5', label= '# of single qubit operations without optimizations', linewidth=3) plt.legend(fontsize=25) cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) for cs, col, lab in zip(cx, color, labels): plt.plot(steps, cs, color=col, label=lab, linewidth=3) plt.legend(fontsize=25) ex1_mean = [] ex1_std = [] ex2_mean = [] ex2_std = [] ex3_mean = [] ex3_std = [] ex4_mean = [] ex4_std = [] extime = 100 u3_error = depolarizing_error(0, 1) qw_step = range(1, 11) gate_error = np.arange(0, 0.03, 0.001) # errors, steps= np.meshgrid(gate_error, qw_step) bins = [format(i, '03b') for i in range(2**3)] step = 3 opt_qc = eight_node(True, step, init_state_eight) job = execute(opt_qc, backend=qasm_sim, shots=100000) count = job.result().get_counts(opt_qc) ideal_prob = [count.get(i, 0)/100000 for i in bins] for cxerr in tqdm(gate_error, desc="error"): # noise model error_model = NoiseModel() cx_error = depolarizing_error(cxerr, 2) error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # ex1 # opt_qc = [transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime)] # errors = [] # for eqc in opt_qc: # errors.append(get_error(eqc, ideal_prob, error_model, 3)) # ex1_mean.append(np.mean(errors)) # ex1_std.append(np.std(errors)) # # ex2 # errors = [] # opt_qc = [transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3) for i in range(extime)] # for eqc in opt_qc: # errors.append(get_error(eqc, ideal_prob, error_model, 3)) # ex2_mean.append(np.mean(errors)) # ex2_std.append(np.std(errors)) # # ex3 # errors = [] # opt_qc = [transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3)for i in range(extime)] # for eqc in opt_qc: # errors.append(get_error(eqc, ideal_prob, error_model, 3)) # ex3_mean.append(np.mean(errors)) # ex3_std.append(np.std(errors)) # ex4 errors = [] nopt_qc = [transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime)] for eqc in nopt_qc: errors.append(get_error(eqc, ideal_prob, error_model, 3)) ex4_mean.append(np.mean(errors)) ex4_std.append(np.std(errors)) fig = plt.figure(figsize=(20, 10)) sns.set() # plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations') # # plt.errorbar(gate_error, ex2_mean, yerr=ex2_std, label='With my and qiskit optimizations') # # plt.errorbar(gate_error, ex3_mean, yerr=ex3_std, label='With qiskit optimizations') plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations') plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30) plt.xlabel('cx error rate', fontsize=30) plt.ylabel('KL divergence', fontsize=30) plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() # 1step fig = plt.figure(figsize=(20, 10)) plt.plot(gate_error, ex1_mean, label='ex1') plt.plot(gate_error, ex2_mean, label='ex2') plt.plot(gate_error, ex3_mean, label='ex3') plt.plot(gate_error, ex4_mean, label='ex4') plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() # res1 = np.array(ex1_mean).reshape(10, 10) # res2 = np.array(ex2_mean).reshape(10, 10) # res3 = np.array(ex3_mean).reshape(10, 10) # res4 = np.array(ex4_mean).reshape(10, 10) # fig = plt.figure(figsize=(20, 10)) # ax = Axes3D(fig) # ax.plot_wireframe(errors, steps, res1, color='#E6855E', linewidth=2, label='With my optimization') # ax.plot_wireframe(errors, steps, res2, color='#F9DB57', linewidth=2, label='With my and qiskit optimizations') # ax.plot_wireframe(errors, steps, res3, color='#3DB680', linewidth=2, label='With qiskit optimizations') # ax.plot_wireframe(errors, steps, res4, color='#6A8CC7', linewidth=2, label='Without optimizations') # ax.set_xlabel('Cx error rate', labelpad=30, fontsize=30) # ax.set_ylabel('The number of steps', labelpad=30, fontsize=30) # ax.set_zlabel('Error', labelpad=30, fontsize=30) # plt.tick_params(labelsize=20) # plt.legend(fontsize=20) # plt.show() alpha = 0.85 target_graph = np.array([[0, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1]]) E = np.array([[0, 0, 0, 1, 1/2, 0, 0, 0], [1, 0, 0, 0, 1/2, 0, 0, 0], [0, 1, 0, 0, 0, 1/2, 0, 0], [0, 0, 1, 0, 0, 1/2, 0, 0], [0, 0, 0, 0, 0, 0, 1/4, 1/4], [0, 0, 0, 0, 0, 0, 1/4, 1/4], [0, 0, 0, 0, 0, 0, 1/4, 1/4], [0, 0, 0, 0, 0, 0, 1/4, 1/4]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/8)*np.ones((8, 8)) init_state_eight = 1/np.sqrt(8)*np.array([np.sqrt(prob_dist[j][i]) for i in range(8) for j in range(8)]) def mch(qc, controls, target, anc, tganc): # multi control hadamard gate if len(controls) == 1: qc.ch(*controls, target) elif len(controls) == 2: qc.ccx(controls[0], controls[1], tganc[0]) qc.ch(tganc[0], target) qc.ccx(controls[0], controls[1], tganc[0]) elif len(controls) > 2: qc.mct(controls, tganc[0], anc) for tg in target: qc.ch(tganc[0], tg) qc.mct(controls, tganc[0], anc) return qc qasm_sim = Aer.get_backend("qasm_simulator") q = QuantumRegister(6) anc = QuantumRegister(3) tganc = QuantumRegister(1) c = ClassicalRegister(10) qc = QuantumCircuit(q, anc, tganc, c) mch(qc, [q[0], q[3]], [q[4], q[5]], anc, tganc) qc.barrier() qc.draw(output='mpl') qc.measure(q, c[:6]) qc.measure(anc, c[6:9]) qc.measure(tganc, c[9]) job = execute(qc, backend=qasm_sim, shots=1024) count = job.result().get_counts(qc) print(count) qc.draw(output='mpl') # Circuit def eight_node_multi(opt, step, initial, hardopt=False): rotation11 = np.radians(31.788) rotation12 = np.radians(23.231) rotation13 = np.radians(163.285) rotation21 = np.radians(31.788) rotation22 = np.radians(23.231) rotation31 = np.radians(148.212) # for multi qubit hadamrd gate hs = QuantumCircuit.ch cq = QuantumRegister(3, 'control') tq = QuantumRegister(3, 'target') # ancilla for mct gates anc = QuantumRegister(3, 'mct anc') tganc = QuantumRegister(1, 'tgancila') c = ClassicalRegister(3, 'classical') if opt: opt_anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, opt_anc, tganc, c) else: qc = QuantumCircuit(cq, tq, anc,tganc, c) # initialize with probability distribution matrix if initial is not None: qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation(opt) # T11 qc.x(cq[1]) qc.ccx(cq[1], cq[2], tq[1]) qc.x(cq[1]) qc.barrier() # T12 qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # T21 qc.x(cq[0]) qc.ccx(cq[0], cq[2], tq[2]) qc.x(cq[0]) qc.barrier() # # Kdg operation if opt: if hardopt: raise Exception('under const') else: # K1dg qc.x(cq[0]) # s1 qc.x(tq[0]) # s2 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[1]) # s3 qc.mcry(-rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) qc.x(tq[1]) # e3 qc.x(tq[0]) # e2 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # s4 qc.mcry(-rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e4 qc.cry(-rotation11, cq[0], tq[0]) qc.x(cq[0]) # e1 qc.barrier # K2dg # map qc.x(cq[1]) qc.ccx(cq[1], cq[0], opt_anc[0]) qc.x(cq[1]) # op qc.ch(opt_anc[0], tq[2]) mch(qc, [opt_anc[0], tq[0]], tq[1], anc, tganc) qc.x(tq[0])# s1 qc.mcry(-rotation22, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e1 qc.cry(-rotation21, opt_anc[0], tq[0]) qc.barrier # K3dg #map qc.ccx(cq[1], cq[0], opt_anc[1]) # op qc.ch(opt_anc[1], tq[2]) qc.ch(opt_anc[1], tq[1]) qc.cry(-rotation31, opt_anc[1], tq[0]) qc.barrier else: # K1dg qc.x(cq[0]) # s1 qc.x(tq[0]) # s2 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[1]) # s3 qc.mcry(-rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) # rotation 3 dg qc.x(tq[1]) # e3 qc.x(tq[0]) # e2 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # s4 qc.mcry(-rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e4 qc.cry(-rotation11, cq[0], tq[0]) qc.x(cq[0]) # e1 # K2dg qc.x(cq[1]) # s1 qc.x(tq[0]) # s2 mch(qc, [cq[0], cq[1], tq[0]], [tq[2]], anc, tganc) qc.x(tq[0]) # e2 mch(qc, [cq[0], cq[1], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # s3 qc.mcry(-rotation22, [cq[0], cq[1], tq[0]], tq[1], anc) qc.x(tq[0]) # e3 qc.mcry(-rotation21, [cq[0], cq[1]], tq[0], anc) qc.x(cq[1]) # K3dg mch(qc, [cq[0], cq[1]], [tq[1], tq[2]], anc, tganc) qc.mcry(-rotation31, [cq[0], cq[1]], tq[0], anc) # D operation qc.x(tq) qc.h(tq[2]) qc.ccx(tq[0], tq[1], tq[2]) qc.h(tq[2]) qc.x(tq) qc.barrier() # # K operation if opt: if hardopt: raise Exception('under') else: # K3 qc.cry(rotation31, opt_anc[1], tq[0]) qc.ch(opt_anc[1], tq[1]) qc.ch(opt_anc[1], tq[2]) #unmap qc.ccx(cq[1], cq[0], opt_anc[1]) qc.barrier() # K2 qc.cry(rotation21, opt_anc[0], tq[0]) qc.x(tq[0]) # s1 qc.mcry(rotation22, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) mch(qc, [opt_anc[0], tq[0]], tq[1], anc, tganc) qc.ch(opt_anc[0], tq[2]) # unmap qc.x(cq[1]) qc.ccx(cq[1], cq[0], opt_anc[0]) qc.x(cq[1]) # op qc.barrier # K1 qc.x(cq[0]) # s1 qc.cry(rotation11, cq[0], tq[0]) qc.x(tq[0]) # s2 qc.mcry(rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e2 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) #s3 qc.x(tq[1]) # s4 qc.mcry(rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) qc.x(tq[1]) # 4 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[0]) # e3 qc.x(cq[0]) # e1 qc.barrier else: # K3 qc.mcry(rotation31, [cq[0], cq[1]], tq[0], anc) mch(qc, [cq[0], cq[1]], [tq[1], tq[2]], anc, tganc) # K2 qc.x(cq[1]) qc.mcry(rotation21, [cq[0], cq[1]], tq[0], anc) qc.x(tq[0]) # e3 qc.mcry(rotation22, [cq[0], cq[1], tq[0]], tq[1], anc) qc.x(tq[0]) # s3 mch(qc, [cq[0], cq[1], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # e2 mch(qc, [cq[0], cq[1], tq[0]], [tq[2]], anc, tganc) qc.x(tq[0]) # s2 qc.x(cq[0]) qc.x(cq[1]) # s1 # K1 qc.cry(rotation11, cq[0], tq[0]) qc.x(tq[0]) # e4 qc.mcry(rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # s4 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # e2 qc.x(tq[1]) # e3 qc.mcry(rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) # rotation 3 dg qc.x(tq[1]) # s3 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[0]) # s2 qc.x(cq[0]) # s1 # T21 dg qc.x(cq[0]) qc.ccx(cq[0], cq[2], tq[2]) qc.x(cq[0]) qc.barrier() # T12dg qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # T11 dg qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) # swap for cont, targ in zip(cq, tq): qc.swap(cont, targ) qc.measure(cq, c) return qc qc = eight_node_multi(True, 1, None) qc.draw(output='mpl') # circuit verifications qasm_sim = Aer.get_backend('qasm_simulator') init_state = [np.sqrt(1/64) for i in range(64)] for step in range(1, 11): opt_qc1 = transpile(eight_node_multi(True, step, init_state), basis_gates=['cx', 'u3'], optimization_level=0) opt_qc2 = transpile(eight_node_multi(True, step, init_state), basis_gates=['cx', 'u3'], optimization_level=3) opt_qc3 = transpile(eight_node_multi(False, step, init_state), basis_gates=['cx', 'u3'], optimization_level=3) nopt_qc = transpile(eight_node_multi(False, step, init_state), basis_gates=['cx', 'u3'], optimization_level=0) job1 = execute(opt_qc1, backend=qasm_sim, shots=10000) job2 = execute(opt_qc2, backend=qasm_sim, shots=10000) job3 = execute(opt_qc3, backend=qasm_sim, shots=10000) job4 = execute(nopt_qc, backend=qasm_sim, shots=10000) count1 = job1.result().get_counts() count2 = job2.result().get_counts() count3 = job3.result().get_counts() count4 = job4.result().get_counts() print(count1.get('000'), count2.get('000'), count3.get('000'), count4.get('000')) ex1_cx = [] ex1_u3 = [] ex2_cx = [] ex2_u3 = [] ex3_cx = [] ex3_u3 = [] ex4_cx = [] ex4_u3 = [] for step in trange(1, 11): opt_qc = transpile(eight_node_multi(True, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex1_cx.append(ncx) ex1_u3.append(nu3) # ex2 opt_qc = transpile(eight_node_multi(True, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex2_cx.append(ncx) ex2_u3.append(nu3) # ex3 opt_qc = transpile(eight_node_multi(False, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex3_cx.append(ncx) ex3_u3.append(nu3) # ex4 nopt_qc = transpile(eight_node_multi(False, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = nopt_qc.count_ops().get('cx', 0) nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0) ex4_cx.append(ncx) ex4_u3.append(nu3) qc = eight_node_multi(False, 1, None) print(qc.depth()) qc = eight_node_multi(False, 2, None) print(qc.depth()) cx = [ex1_cx, ex4_cx] u3 = [ex1_u3, ex4_u3] color = ['#C23685', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'related works[6]'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.yticks(range(0, 9000, 500)) plt.xticks(range(0, 11, 1)) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) plt.plot(steps, ex4_cx, color= '#3EBA2B', label="# of CX paper circuit", linewidth=3) plt.plot(steps, ex4_u3, color= '#6BBED5', label="# of single qubit gates of paper circuit", linewidth=3) plt.legend(fontsize=25) cx = [ex1_cx, ex4_cx] u3 = [ex1_u3, ex4_u3] color = ['#C23685', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'related works[6]'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.yticks(range(0, 4600, 200)) plt.xticks(range(0, 11, 1)) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) for cs, col, lab in zip(cx, color, labels): plt.plot(steps, cs, color=col, label=lab, linewidth=3) plt.legend(fontsize=25) ex1_mean = [] ex1_std = [] ex4_mean = [] ex4_std = [] extime = 10 u3_error = depolarizing_error(0, 1) gate_error = np.arange(0, 0.03, 0.001) # errors, steps= np.meshgrid(gate_error, qw_step) bins = [format(i, '03b') for i in range(2**3)] step = 5 opt_qc = eight_node_multi(False, step, init_state_eight) job = execute(opt_qc, backend=qasm_sim, shots=100000) count = job.result().get_counts(opt_qc) ideal_prob = [count.get(i, 0)/100000 for i in bins] for cxerr in tqdm(gate_error): # noise model error_model = NoiseModel() cx_error = depolarizing_error(cxerr, 2) error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # ex1 opt_qc = transpile(eight_node_multi(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) errors = [] for i in range(extime): error = get_error(opt_qc, ideal_prob, error_model, 3) errors.append(error) ex1_mean.append(np.mean(errors)) ex1_std.append(np.std(errors)) # ex4 nopt_qc = transpile(eight_node_multi(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime): error = get_error(nopt_qc, ideal_prob, error_model, 3) errors.append(error) ex4_mean.append(np.mean(errors)) ex4_std.append(np.std(errors)) fig = plt.figure(figsize=(20, 10)) sns.set() # plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations') plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations') plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30) plt.xlabel('cx error rate', fontsize=30) plt.ylabel('KL divergence', fontsize=30) plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() q = QuantumRegister(1) qc = QuantumCircuit(q) rotation12 = np.radians(23.231) qc.u3(pi/2+rotation12, 0, pi, q[0]) unit = Aer.get_backend('unitary_simulator') job = execute(qc, backend=unit) uni = job.result().get_unitary() print(uni) q = QuantumRegister(1) qc = QuantumCircuit(q) rotation12 = np.radians(23.231) qc.u3(pi/2, 0, pi, q[0]) qc.ry(rotation12, q[0]) unit = Aer.get_backend('unitary_simulator') job = execute(qc, backend=unit) uni = job.result().get_unitary() print(uni) q = QuantumRegister(3,'qr') anc = QuantumRegister(2, 'anc') qc = QuantumCircuit(q, anc) qc.mcmt([q[0], q[1]], anc, QuantumCircuit.ch, [q[2]]) qc.draw(output='mpl') q = QuantumRegister(6) qc = QuantumCircuit(q) qc.initialize(init_state, q) nqc = transpile(qc, basis_gates=['cx', 'h', 'x', 'u3']) nqc.draw(output='mpl')
https://github.com/Chibikuri/qwopt
Chibikuri
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Optimization benchmarking # Plotting benchmark result. # + import sys import numpy as np import matplotlib.pyplot as plt import seaborn as sns import copy sys.path.append('../') from qwopt.compiler import composer from qwopt.benchmark import fidelity as fid from numpy import pi from qiskit import transpile from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import depolarizing_error from tqdm import tqdm, trange from mpl_toolkits.mplot3d import Axes3D import warnings warnings.simplefilter('ignore') # - # ## 1. Multi step of 4 node graph with one partition # ## Target graph and probability transition matrix # + alpha = 0.85 target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) E = np.array([[1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0], [1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4)) init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) # - # ### Check points # - How to decrease the fidelity over the number of steps # - The number of operations # ### Count operations # #### Without any optimizations # + # Circuit def four_node(opt, step): rotation = np.radians(31.788) cq = QuantumRegister(2, 'control') tq = QuantumRegister(2, 'target') c = ClassicalRegister(2, 'classical') if opt: anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, c) else: qc = QuantumCircuit(cq, tq, c) # initialize with probability distribution matrix initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # Kdg operation if opt: qc.x(cq) qc.rccx(cq[0], cq[1], anc[0]) qc.barrier() qc.ch(anc[0], tq[0]) qc.ch(anc[0], tq[1]) qc.x(anc[0]) qc.cry(-rotation, anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.barrier() else: qc.x(cq) qc.mcry(-pi/2, cq, tq[0], None) qc.mcry(-pi/2, cq, tq[1], None) qc.x(cq) qc.barrier() # qc.x(cq[1]) # qc.mcry(-pi/2, cq, tq[0], None) # qc.mcry(-rotation, cq, tq[1], None) # qc.x(cq[1]) # qc.barrier() qc.x(cq[0]) qc.mcry(-pi/2, cq, tq[0], None) qc.mcry(-rotation, cq, tq[1], None) qc.x(cq[0]) qc.barrier() qc.cry(-pi/2, cq[0], tq[0]) qc.cry(-rotation, cq[0], tq[1]) qc.barrier() # qc.mcry(-pi/2, cq, tq[0], None) # qc.mcry(-rotation, cq, tq[1], None) # qc.barrier() # D operation qc.x(tq) qc.cz(tq[0], tq[1]) qc.x(tq) qc.barrier() # K operation if opt: qc.ch(anc[0], tq[0]) qc.cry(rotation, anc[0], tq[1]) qc.x(anc[0]) qc.ch(anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.rccx(cq[0], cq[1], anc[0]) qc.x(cq) qc.barrier() else: # previous, and naive imple # qc.mcry(pi/2, cq, tq[0], None) # qc.mcry(rotation, cq, tq[1], None) # qc.barrier() qc.cry(pi/2, cq[0], tq[0]) qc.cry(rotation, cq[0], tq[1]) qc.barrier() qc.x(cq[0]) qc.mcry(pi/2, cq, tq[0], None) qc.mcry(rotation, cq, tq[1], None) qc.x(cq[0]) qc.barrier() # qc.x(cq[1]) # qc.mcry(pi/2, cq, tq[0], None) # qc.mcry(rotation, cq, tq[1], None) # qc.x(cq[1]) # qc.barrier() qc.x(cq) qc.mcry(pi/2, cq, tq[0], None) qc.mcry(pi/2, cq, tq[1], None) qc.x(cq) qc.barrier() # Tidg operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # swap qc.swap(tq[0], cq[0]) qc.swap(tq[1], cq[1]) qc.measure(tq, c) return qc # - qc = four_node(True, 1) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=10000) count = job.result().get_counts(qc) print(count) qc.draw(output='mpl') # ### The number of operations in steps # + ex1_cx = [] ex1_u3 = [] ex2_cx = [] ex2_u3 = [] ex3_cx = [] ex3_u3 = [] ex4_cx = [] ex4_u3 = [] for step in trange(1, 11): opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex1_cx.append(ncx) ex1_u3.append(nu3) # ex2 opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex2_cx.append(ncx) ex2_u3.append(nu3) # ex3 opt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex3_cx.append(ncx) ex3_u3.append(nu3) # ex4 nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0) ncx = nopt_qc.count_ops().get('cx', 0) nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0) ex4_cx.append(ncx) ex4_u3.append(nu3) # - cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] # color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] # labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.xticks([i for i in range(11)]) plt.ylabel('the number of operations', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) plt.plot(steps, ex4_cx, color='#3EBA2B', label='# of CX without optimizations', linewidth=3) plt.plot(steps, ex4_u3, color='#6BBED5', label='# of single qubit operations without optimizations', linewidth=3) plt.legend(fontsize=25) cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.xticks([i for i in range(11)]) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) print(list(steps)) for cs, col, lab in zip(cx, color, labels): plt.plot(steps, cs, color=col, label=lab, linewidth=3) plt.legend(fontsize=25) # ## Error rate transition import warnings warnings.simplefilter('ignore') # + qasm_sim = Aer.get_backend('qasm_simulator') def KL_divergence(p, q, torelance=10e-9): ''' p: np.array or list q: np.array or list ''' parray = np.array(p) + torelance qarray = np.array(q) + torelance divergence = np.sum(parray*np.log(parray/qarray)) return divergence def get_error(qc, ideal, err_model, nq, type='KL', shots=10000): bins = [format(i, '0%db'%nq) for i in range(2**nq)] job = execute(qc, backend=qasm_sim, shots=shots, noise_model=err_model) counts = job.result().get_counts(qc) prob = np.array([counts.get(b, 0)/shots for b in bins]) id_prob = np.array(ideal) # l2_error = np.sum([(i-j)**2 for i, j in zip(id_prob, prob)]) KL_error = KL_divergence(id_prob, prob) return KL_error def theoretical_prob(initial, step, ptran, nq): Pi_op = Pi_operator(ptran) swap = swap_operator(nq) operator = (2*Pi_op) - np.identity(len(Pi_op)) Szegedy = np.dot(operator, swap) Szegedy_n = copy.deepcopy(Szegedy) if step == 0: init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float) return init_prob elif step == 1: prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)], dtype=np.float) return prob else: for n in range(step-1): Szegedy_n = np.dot(Szegedy_n, Szegedy) probs = np.array([abs(i)**2 for i in np.dot(Szegedy_n, initial)], dtype=np.float) return probs def swap_operator(n_qubit): q1 = QuantumRegister(n_qubit//2) q2 = QuantumRegister(n_qubit//2) qc = QuantumCircuit(q1, q2) for c, t in zip(q1, q2): qc.swap(c, t) # FIXME backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend=backend) swap = job.result().get_unitary(qc) return swap def Pi_operator(ptran): ''' This is not a quantum operation, just returning matrix ''' lg = len(ptran) psi_op = [] count = 0 for i in range(lg): psi_vec = [0 for _ in range(lg**2)] for j in range(lg): psi_vec[count] = np.sqrt(ptran[j][i]) count += 1 psi_op.append(np.kron(np.array(psi_vec).T, np.conjugate(psi_vec)).reshape((lg**2, lg**2))) Pi = psi_op[0] for i in psi_op[1:]: Pi = np.add(Pi, i) return Pi # + # circuit verifications # for step in range(1, 11): # opt_qc1 = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0) # opt_qc2 = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3) # opt_qc3 = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3) # nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0) # job1 = execute(opt_qc1, backend=qasm_sim, shots=10000) # job2 = execute(opt_qc2, backend=qasm_sim, shots=10000) # job3 = execute(opt_qc3, backend=qasm_sim, shots=10000) # job4 = execute(nopt_qc, backend=qasm_sim, shots=10000) # count1 = job1.result().get_counts() # count2 = job2.result().get_counts() # count3 = job3.result().get_counts() # count4 = job4.result().get_counts() # print(count1.get('00'), count2.get('00'), count3.get('00'), count4.get('00')) # + ex1_mean = [] ex1_std = [] ex2_mean = [] ex2_std = [] ex3_mean = [] ex3_std = [] ex4_mean = [] ex4_std = [] extime = 10 u3_error = depolarizing_error(0.001, 1) qw_step = range(1, 11) gate_error = np.arange(0, 0.03, 0.001) # errors, steps= np.meshgrid(gate_error, qw_step) bins = [format(i, '02b') for i in range(2**2)] step = 5 opt_qc = four_node(True, step) job = execute(opt_qc, backend=qasm_sim, shots=100000) count = job.result().get_counts(opt_qc) ideal_prob = [count.get(i, 0)/100000 for i in bins] for cxerr in tqdm(gate_error): # noise model error_model = NoiseModel() cx_error = depolarizing_error(cxerr, 2) error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # ex1 errors = [] for i in range(extime): opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0) error = get_error(opt_qc, ideal_prob, error_model, 2) errors.append(error) ex1_mean.append(np.mean(errors)) ex1_std.append(np.std(errors)) # ex2 errors = [] for i in range(extime): opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3) error = get_error(opt_qc, ideal_prob, error_model, 2) errors.append(error) ex2_mean.append(np.mean(errors)) ex2_std.append(np.std(errors)) # ex3 errors = [] for i in range(extime): opt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3) error = get_error(opt_qc, ideal_prob, error_model, 2) errors.append(error) ex3_mean.append(np.mean(errors)) ex3_std.append(np.std(errors)) # ex4 errors=[] for i in range(extime): nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0) error = get_error(nopt_qc, ideal_prob, error_model, 2) errors.append(error) ex4_mean.append(np.mean(errors)) ex4_std.append(np.std(errors)) # + fig = plt.figure(figsize=(20, 10)) # plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations') # # plt.errorbar(gate_error, ex2_mean, yerr=ex2_std, label='With my and qiskit optimizations') # # plt.errorbar(gate_error, ex3_mean, yerr=ex3_std, label='With qiskit optimizations') plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations') plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30) plt.xlabel('cx error rate', fontsize=30) plt.ylabel('KL divergence', fontsize=30) plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() # + # ex1_mean = [] # ex1_std = [] # ex2_mean = [] # ex2_std = [] # ex3_mean = [] # ex3_std = [] # ex4_mean = [] # ex4_std = [] # extime = 10 # u3_error = depolarizing_error(0, 1) # qw_step = range(1,6) # gate_error = np.arange(0, 0.1, 0.01) # errors, steps= np.meshgrid(gate_error, qw_step) # bins = [format(i, '02b') for i in range(2**2)] # for ce, st in tqdm(zip(errors, steps)): # opt_qc = four_node(True, st[0]) # job = execute(opt_qc, backend=qasm_sim, shots=100000) # count = job.result().get_counts(opt_qc) # ideal_prob = [count.get(i, 0)/100000 for i in bins] # for cxerr, step in zip(ce, st): # # noise model # error_model = NoiseModel() # cx_error = depolarizing_error(cxerr, 2) # error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) # error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # # ex1 # qcs1 = [four_node(True, step) for i in range(extime)] # opt_qc1 = transpile(qcs1, basis_gates=['cx', 'u3'], optimization_level=0) # errors = get_error(opt_qc1, ideal_prob, error_model, 2) # ex1_mean.append(np.mean(errors)) # ex1_std.append(np.std(errors)) # # ex2 # qcs2 = [four_node(True, step) for i in range(extime)] # opt_qc2 = transpile(qcs2, basis_gates=['cx', 'u3'], optimization_level=3) # errors = get_error(opt_qc2, ideal_prob, error_model, 2) # ex2_mean.append(np.mean(errors)) # ex2_std.append(np.std(errors)) # # ex3 # qcs3 = [four_node(False, step) for i in range(extime)] # opt_qc3 = transpile(qcs3, basis_gates=['cx', 'u3'], optimization_level=3) # errors = get_error(opt_qc, ideal_prob, error_model, 2) # ex3_mean.append(np.mean(errors)) # ex3_std.append(np.std(errors)) # # ex4 # qcs4 = [four_node(False, step) for i in range(extime)] # nopt_qc = transpile(qcs4, basis_gates=['cx', 'u3'], optimization_level=0) # error = get_error(nopt_qc, ideal_prob, error_model, 2) # ex4_mean.append(np.mean(errors)) # ex4_std.append(np.std(errors)) # - # ### plot 3d res1 = np.array(ex1_mean).reshape(10, 10) res2 = np.array(ex2_mean).reshape(10, 10) res3 = np.array(ex3_mean).reshape(10, 10) res4 = np.array(ex4_mean).reshape(10, 10) # + # fig = plt.figure(figsize=(20, 10)) # ax = Axes3D(fig) # ax.plot_wireframe(errors, steps, res1, color='#E6855E', linewidth=2, label='With my optimization') # ax.plot_wireframe(errors, steps, res2, color='#F9DB57', linewidth=2, label='With my and qiskit optimizations') # ax.plot_wireframe(errors, steps, res3, color='#3DB680', linewidth=2, label='With qiskit optimizations') # ax.plot_wireframe(errors, steps, res4, color='#6A8CC7', linewidth=2, label='Without optimizations') # ax.set_xlabel('Cx error rate', labelpad=30, fontsize=30) # ax.set_ylabel('The number of steps', labelpad=30, fontsize=30) # ax.set_zlabel('Error', labelpad=30, fontsize=30) # plt.tick_params(labelsize=20) # plt.legend(fontsize=20) # plt.show() # - # ## 2. Multi step of 8 node graph with one partition # ## Target graph and probability transition matrix # + # In this case, we're gonna investigate matrix that has just one partition alpha = 0.85 target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) E = np.array([[1/8, 1/2, 0, 0, 0, 0, 0, 1/2], [1/8, 0, 1/2, 0, 0, 0, 0, 0], [1/8, 1/2, 0, 1/2, 0, 0, 0, 0], [1/8, 0, 1/2, 0, 1/2, 0, 0, 0], [1/8, 0, 0, 1/2, 0, 1/2, 0, 0], [1/8, 0, 0, 0, 1/2, 0, 1/2, 0], [1/8, 0, 0, 0, 0, 1/2, 0, 1/2], [1/8, 0, 0, 0, 0, 0, 1/2, 0]]) # use google matrix lt = len(target_graph) prob_dist = alpha*E + ((1-alpha)/lt)*np.ones((lt, lt)) init_state_eight = 1/np.sqrt(8)*np.array([np.sqrt(prob_dist[j][i]) for i in range(lt) for j in range(lt)]) # + # Circuit def eight_node(opt, step, initial, hardopt=False): rotation1 = np.radians(31.788) rotation2 = np.radians(90) rotation3 = np.radians(23.232) cq = QuantumRegister(3, 'control') tq = QuantumRegister(3, 'target') # ancilla for mct gates anc = QuantumRegister(3, 'mct anc') c = ClassicalRegister(3, 'classical') if opt: opt_anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, opt_anc, c) else: qc = QuantumCircuit(cq, tq, anc, c) # initialize with probability distribution matrix if initial is not None: qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation # T1 qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[2], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # T2 qc.x(cq[0]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.barrier() # T3 qc.x(cq[1:]) qc.mct(cq, tq[1], anc) qc.mct(cq, tq[2], anc) qc.x(cq[1:]) qc.barrier() # T4 qc.x(cq[1]) qc.mct(cq, tq[0], anc) qc.x(cq[1]) qc.barrier() # T5 qc.x(cq[2]) qc.mct(cq, tq[0], anc) qc.mct(cq, tq[2], anc) qc.x(cq[2]) qc.barrier() # T6 qc.x(tq[2]) qc.mct([*cq, *tq[1:]], tq[0], anc) qc.x(tq[2]) qc.barrier() # # Kdg operation if opt: qc.x(cq[:]) # qc.rcccx(cq[0], cq[1], cq[2], opt_anc[0]) qc.mct(cq, opt_anc[0], anc) qc.x(cq[:]) for ryq in tq: qc.cry(-pi/2, opt_anc[0], ryq) if hardopt: raise Exception('under_construction') else: qc.x(opt_anc[0]) qc.x(tq[0]) qc.mcry(-rotation3, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[1], anc) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(-rotation2, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) qc.cry(-rotation1, opt_anc[0], tq[0]) qc.x(opt_anc[0]) else: qc.x(cq[:]) for ryq in tq: qc.mcry(-pi/2, cq, ryq, anc) qc.barrier() qc.x(cq[:]) for i in range(1, 8): bins = list(format(i, '03b')) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) qc.x(tq[0]) qc.mcry(-rotation3, [*cq, tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [*cq, tq[0]], tq[1], anc) qc.mcry(3/2*pi, [*cq, tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(-rotation2, [*cq, tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(-rotation1, cq, tq[0], anc) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) # D operation qc.x(tq) qc.h(tq[2]) qc.ccx(tq[0], tq[1], tq[2]) qc.h(tq[2]) qc.x(tq) qc.barrier() # # K operation if opt: if hardopt: raise Exception('under...') else: qc.x(opt_anc[0]) qc.cry(rotation1, opt_anc[0], tq[0]) qc.x(tq[0]) qc.mcry(rotation2, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[1], anc) qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.mcry(rotation3, [opt_anc[0], tq[0]], tq[2], anc) qc.x(tq[0]) qc.x(opt_anc[0]) for anq in tq: qc.cry(pi/2, opt_anc[0], anq) qc.barrier() qc.x(cq[:]) qc.mct(cq, opt_anc[0], anc) qc.x(cq[:]) else: for i in range(1, 8): bins = list(format(i, '03b')) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) qc.mcry(rotation1, cq, tq[0], anc) qc.x(tq[0]) qc.mcry(rotation2, [*cq, tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(3/2*pi, [*cq, tq[0]], tq[2], anc) qc.mcry(3/2*pi, [*cq, tq[0]], tq[1], anc) qc.x(tq[0]) qc.mcry(rotation3, [*cq, tq[0]], tq[2], anc) qc.x(tq[0]) for ib, b in enumerate(bins): if b == '0': qc.x(cq[ib]) qc.x(cq[:]) for anq in tq: qc.mcry(pi/2, cq, anq, anc) qc.x(cq[:]) # # Tidg operation # T6 qc.x(tq[2]) qc.mct([*cq, *tq[1:]], tq[0], anc) qc.x(tq[2]) qc.barrier() # T5 qc.x(cq[2]) qc.mct(cq, tq[0], anc) qc.mct(cq, tq[2], anc) qc.x(cq[2]) qc.barrier() # T4 qc.x(cq[1]) qc.mct(cq, tq[0], anc) qc.x(cq[1]) qc.barrier() # T3 qc.x(cq[1:]) qc.mct(cq, tq[1], anc) qc.mct(cq, tq[2], anc) qc.x(cq[1:]) qc.barrier() # T2 qc.x(cq[0]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.barrier() # T1 qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[2], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # swap for cont, targ in zip(cq, tq): qc.swap(cont, targ) qc.measure(cq, c) return qc # - # circuit verifications qasm_sim = Aer.get_backend("qasm_simulator") for step in range(1, 11): opt_qc1 = transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) opt_qc2 = transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3) opt_qc3 = transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3) nopt_qc = transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) job1 = execute(opt_qc1, backend=qasm_sim, shots=10000) job2 = execute(opt_qc2, backend=qasm_sim, shots=10000) job3 = execute(opt_qc3, backend=qasm_sim, shots=10000) job4 = execute(nopt_qc, backend=qasm_sim, shots=10000) count1 = job1.result().get_counts() count2 = job2.result().get_counts() count3 = job3.result().get_counts() count4 = job4.result().get_counts() print(count1.get('000'), count2.get('000'), count3.get('000'), count4.get('000')) # + ex1_cx = [] ex1_u3 = [] ex2_cx = [] ex2_u3 = [] ex3_cx = [] ex3_u3 = [] ex4_cx = [] ex4_u3 = [] for step in trange(1, 11): opt_qc = transpile(eight_node(True, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex1_cx.append(ncx) ex1_u3.append(nu3) # ex2 opt_qc = transpile(eight_node(True, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex2_cx.append(ncx) ex2_u3.append(nu3) # ex3 opt_qc = transpile(eight_node(False, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex3_cx.append(ncx) ex3_u3.append(nu3) # ex4 nopt_qc = transpile(eight_node(False, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = nopt_qc.count_ops().get('cx', 0) nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0) ex4_cx.append(ncx) ex4_u3.append(nu3) # - steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) plt.xticks([i for i in range(11)]) # for cs, col, lab in zip(cx, color, labels): plt.plot(steps, ex4_cx, color= '#3EBA2B', label= '# of CX without optimizations', linewidth=3) plt.plot(steps, ex4_u3, color= '#6BBED5', label= '# of single qubit operations without optimizations', linewidth=3) plt.legend(fontsize=25) cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) for cs, col, lab in zip(cx, color, labels): plt.plot(steps, cs, color=col, label=lab, linewidth=3) plt.legend(fontsize=25) # + ex1_mean = [] ex1_std = [] ex2_mean = [] ex2_std = [] ex3_mean = [] ex3_std = [] ex4_mean = [] ex4_std = [] extime = 100 u3_error = depolarizing_error(0, 1) qw_step = range(1, 11) gate_error = np.arange(0, 0.03, 0.001) # errors, steps= np.meshgrid(gate_error, qw_step) bins = [format(i, '03b') for i in range(2**3)] step = 3 opt_qc = eight_node(True, step, init_state_eight) job = execute(opt_qc, backend=qasm_sim, shots=100000) count = job.result().get_counts(opt_qc) ideal_prob = [count.get(i, 0)/100000 for i in bins] for cxerr in tqdm(gate_error, desc="error"): # noise model error_model = NoiseModel() cx_error = depolarizing_error(cxerr, 2) error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # ex1 # opt_qc = [transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime)] # errors = [] # for eqc in opt_qc: # errors.append(get_error(eqc, ideal_prob, error_model, 3)) # ex1_mean.append(np.mean(errors)) # ex1_std.append(np.std(errors)) # # ex2 # errors = [] # opt_qc = [transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3) for i in range(extime)] # for eqc in opt_qc: # errors.append(get_error(eqc, ideal_prob, error_model, 3)) # ex2_mean.append(np.mean(errors)) # ex2_std.append(np.std(errors)) # # ex3 # errors = [] # opt_qc = [transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3)for i in range(extime)] # for eqc in opt_qc: # errors.append(get_error(eqc, ideal_prob, error_model, 3)) # ex3_mean.append(np.mean(errors)) # ex3_std.append(np.std(errors)) # ex4 errors = [] nopt_qc = [transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime)] for eqc in nopt_qc: errors.append(get_error(eqc, ideal_prob, error_model, 3)) ex4_mean.append(np.mean(errors)) ex4_std.append(np.std(errors)) # - fig = plt.figure(figsize=(20, 10)) sns.set() # plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations') # # plt.errorbar(gate_error, ex2_mean, yerr=ex2_std, label='With my and qiskit optimizations') # # plt.errorbar(gate_error, ex3_mean, yerr=ex3_std, label='With qiskit optimizations') plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations') plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30) plt.xlabel('cx error rate', fontsize=30) plt.ylabel('KL divergence', fontsize=30) plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() # + # 1step fig = plt.figure(figsize=(20, 10)) plt.plot(gate_error, ex1_mean, label='ex1') plt.plot(gate_error, ex2_mean, label='ex2') plt.plot(gate_error, ex3_mean, label='ex3') plt.plot(gate_error, ex4_mean, label='ex4') plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() # + # res1 = np.array(ex1_mean).reshape(10, 10) # res2 = np.array(ex2_mean).reshape(10, 10) # res3 = np.array(ex3_mean).reshape(10, 10) # res4 = np.array(ex4_mean).reshape(10, 10) # + # fig = plt.figure(figsize=(20, 10)) # ax = Axes3D(fig) # ax.plot_wireframe(errors, steps, res1, color='#E6855E', linewidth=2, label='With my optimization') # ax.plot_wireframe(errors, steps, res2, color='#F9DB57', linewidth=2, label='With my and qiskit optimizations') # ax.plot_wireframe(errors, steps, res3, color='#3DB680', linewidth=2, label='With qiskit optimizations') # ax.plot_wireframe(errors, steps, res4, color='#6A8CC7', linewidth=2, label='Without optimizations') # ax.set_xlabel('Cx error rate', labelpad=30, fontsize=30) # ax.set_ylabel('The number of steps', labelpad=30, fontsize=30) # ax.set_zlabel('Error', labelpad=30, fontsize=30) # plt.tick_params(labelsize=20) # plt.legend(fontsize=20) # plt.show() # - # ## 3. Multi step of 8 node graph with multi partition # + code_folding=[] alpha = 0.85 target_graph = np.array([[0, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1]]) E = np.array([[0, 0, 0, 1, 1/2, 0, 0, 0], [1, 0, 0, 0, 1/2, 0, 0, 0], [0, 1, 0, 0, 0, 1/2, 0, 0], [0, 0, 1, 0, 0, 1/2, 0, 0], [0, 0, 0, 0, 0, 0, 1/4, 1/4], [0, 0, 0, 0, 0, 0, 1/4, 1/4], [0, 0, 0, 0, 0, 0, 1/4, 1/4], [0, 0, 0, 0, 0, 0, 1/4, 1/4]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/8)*np.ones((8, 8)) init_state_eight = 1/np.sqrt(8)*np.array([np.sqrt(prob_dist[j][i]) for i in range(8) for j in range(8)]) # - def mch(qc, controls, target, anc, tganc): # multi control hadamard gate if len(controls) == 1: qc.ch(*controls, target) elif len(controls) == 2: qc.ccx(controls[0], controls[1], tganc[0]) qc.ch(tganc[0], target) qc.ccx(controls[0], controls[1], tganc[0]) elif len(controls) > 2: qc.mct(controls, tganc[0], anc) for tg in target: qc.ch(tganc[0], tg) qc.mct(controls, tganc[0], anc) return qc qasm_sim = Aer.get_backend("qasm_simulator") q = QuantumRegister(6) anc = QuantumRegister(3) tganc = QuantumRegister(1) c = ClassicalRegister(10) qc = QuantumCircuit(q, anc, tganc, c) mch(qc, [q[0], q[3]], [q[4], q[5]], anc, tganc) qc.barrier() qc.draw(output='mpl') qc.measure(q, c[:6]) qc.measure(anc, c[6:9]) qc.measure(tganc, c[9]) job = execute(qc, backend=qasm_sim, shots=1024) count = job.result().get_counts(qc) print(count) qc.draw(output='mpl') # + # Circuit def eight_node_multi(opt, step, initial, hardopt=False): rotation11 = np.radians(31.788) rotation12 = np.radians(23.231) rotation13 = np.radians(163.285) rotation21 = np.radians(31.788) rotation22 = np.radians(23.231) rotation31 = np.radians(148.212) # for multi qubit hadamrd gate hs = QuantumCircuit.ch cq = QuantumRegister(3, 'control') tq = QuantumRegister(3, 'target') # ancilla for mct gates anc = QuantumRegister(3, 'mct anc') tganc = QuantumRegister(1, 'tgancila') c = ClassicalRegister(3, 'classical') if opt: opt_anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, opt_anc, tganc, c) else: qc = QuantumCircuit(cq, tq, anc,tganc, c) # initialize with probability distribution matrix if initial is not None: qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation(opt) # T11 qc.x(cq[1]) qc.ccx(cq[1], cq[2], tq[1]) qc.x(cq[1]) qc.barrier() # T12 qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # T21 qc.x(cq[0]) qc.ccx(cq[0], cq[2], tq[2]) qc.x(cq[0]) qc.barrier() # # Kdg operation if opt: if hardopt: raise Exception('under const') else: # K1dg qc.x(cq[0]) # s1 qc.x(tq[0]) # s2 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[1]) # s3 qc.mcry(-rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) qc.x(tq[1]) # e3 qc.x(tq[0]) # e2 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # s4 qc.mcry(-rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e4 qc.cry(-rotation11, cq[0], tq[0]) qc.x(cq[0]) # e1 qc.barrier # K2dg # map qc.x(cq[1]) qc.ccx(cq[1], cq[0], opt_anc[0]) qc.x(cq[1]) # op qc.ch(opt_anc[0], tq[2]) mch(qc, [opt_anc[0], tq[0]], tq[1], anc, tganc) qc.x(tq[0])# s1 qc.mcry(-rotation22, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e1 qc.cry(-rotation21, opt_anc[0], tq[0]) qc.barrier # K3dg #map qc.ccx(cq[1], cq[0], opt_anc[1]) # op qc.ch(opt_anc[1], tq[2]) qc.ch(opt_anc[1], tq[1]) qc.cry(-rotation31, opt_anc[1], tq[0]) qc.barrier else: # K1dg qc.x(cq[0]) # s1 qc.x(tq[0]) # s2 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[1]) # s3 qc.mcry(-rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) # rotation 3 dg qc.x(tq[1]) # e3 qc.x(tq[0]) # e2 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # s4 qc.mcry(-rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e4 qc.cry(-rotation11, cq[0], tq[0]) qc.x(cq[0]) # e1 # K2dg qc.x(cq[1]) # s1 qc.x(tq[0]) # s2 mch(qc, [cq[0], cq[1], tq[0]], [tq[2]], anc, tganc) qc.x(tq[0]) # e2 mch(qc, [cq[0], cq[1], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # s3 qc.mcry(-rotation22, [cq[0], cq[1], tq[0]], tq[1], anc) qc.x(tq[0]) # e3 qc.mcry(-rotation21, [cq[0], cq[1]], tq[0], anc) qc.x(cq[1]) # K3dg mch(qc, [cq[0], cq[1]], [tq[1], tq[2]], anc, tganc) qc.mcry(-rotation31, [cq[0], cq[1]], tq[0], anc) # D operation qc.x(tq) qc.h(tq[2]) qc.ccx(tq[0], tq[1], tq[2]) qc.h(tq[2]) qc.x(tq) qc.barrier() # # K operation if opt: if hardopt: raise Exception('under') else: # K3 qc.cry(rotation31, opt_anc[1], tq[0]) qc.ch(opt_anc[1], tq[1]) qc.ch(opt_anc[1], tq[2]) #unmap qc.ccx(cq[1], cq[0], opt_anc[1]) qc.barrier() # K2 qc.cry(rotation21, opt_anc[0], tq[0]) qc.x(tq[0]) # s1 qc.mcry(rotation22, [opt_anc[0], tq[0]], tq[1], anc) qc.x(tq[0]) mch(qc, [opt_anc[0], tq[0]], tq[1], anc, tganc) qc.ch(opt_anc[0], tq[2]) # unmap qc.x(cq[1]) qc.ccx(cq[1], cq[0], opt_anc[0]) qc.x(cq[1]) # op qc.barrier # K1 qc.x(cq[0]) # s1 qc.cry(rotation11, cq[0], tq[0]) qc.x(tq[0]) # s2 qc.mcry(rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # e2 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) #s3 qc.x(tq[1]) # s4 qc.mcry(rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) qc.x(tq[1]) # 4 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[0]) # e3 qc.x(cq[0]) # e1 qc.barrier else: # K3 qc.mcry(rotation31, [cq[0], cq[1]], tq[0], anc) mch(qc, [cq[0], cq[1]], [tq[1], tq[2]], anc, tganc) # K2 qc.x(cq[1]) qc.mcry(rotation21, [cq[0], cq[1]], tq[0], anc) qc.x(tq[0]) # e3 qc.mcry(rotation22, [cq[0], cq[1], tq[0]], tq[1], anc) qc.x(tq[0]) # s3 mch(qc, [cq[0], cq[1], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # e2 mch(qc, [cq[0], cq[1], tq[0]], [tq[2]], anc, tganc) qc.x(tq[0]) # s2 qc.x(cq[0]) qc.x(cq[1]) # s1 # K1 qc.cry(rotation11, cq[0], tq[0]) qc.x(tq[0]) # e4 qc.mcry(rotation12, [cq[0], tq[0]], tq[1], anc) qc.x(tq[0]) # s4 mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc) qc.x(tq[0]) # e2 qc.x(tq[1]) # e3 qc.mcry(rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) # rotation 3 dg qc.x(tq[1]) # s3 mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc) qc.x(tq[0]) # s2 qc.x(cq[0]) # s1 # T21 dg qc.x(cq[0]) qc.ccx(cq[0], cq[2], tq[2]) qc.x(cq[0]) qc.barrier() # T12dg qc.x(cq[0]) qc.x(cq[2]) qc.mct(cq, tq[1], anc) qc.x(cq[0]) qc.x(cq[2]) qc.barrier() # T11 dg qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) # swap for cont, targ in zip(cq, tq): qc.swap(cont, targ) qc.measure(cq, c) return qc # - qc = eight_node_multi(True, 1, None) qc.draw(output='mpl') # circuit verifications qasm_sim = Aer.get_backend('qasm_simulator') init_state = [np.sqrt(1/64) for i in range(64)] for step in range(1, 11): opt_qc1 = transpile(eight_node_multi(True, step, init_state), basis_gates=['cx', 'u3'], optimization_level=0) opt_qc2 = transpile(eight_node_multi(True, step, init_state), basis_gates=['cx', 'u3'], optimization_level=3) opt_qc3 = transpile(eight_node_multi(False, step, init_state), basis_gates=['cx', 'u3'], optimization_level=3) nopt_qc = transpile(eight_node_multi(False, step, init_state), basis_gates=['cx', 'u3'], optimization_level=0) job1 = execute(opt_qc1, backend=qasm_sim, shots=10000) job2 = execute(opt_qc2, backend=qasm_sim, shots=10000) job3 = execute(opt_qc3, backend=qasm_sim, shots=10000) job4 = execute(nopt_qc, backend=qasm_sim, shots=10000) count1 = job1.result().get_counts() count2 = job2.result().get_counts() count3 = job3.result().get_counts() count4 = job4.result().get_counts() print(count1.get('000'), count2.get('000'), count3.get('000'), count4.get('000')) # + ex1_cx = [] ex1_u3 = [] ex2_cx = [] ex2_u3 = [] ex3_cx = [] ex3_u3 = [] ex4_cx = [] ex4_u3 = [] for step in trange(1, 11): opt_qc = transpile(eight_node_multi(True, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex1_cx.append(ncx) ex1_u3.append(nu3) # ex2 opt_qc = transpile(eight_node_multi(True, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex2_cx.append(ncx) ex2_u3.append(nu3) # ex3 opt_qc = transpile(eight_node_multi(False, step, None), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex3_cx.append(ncx) ex3_u3.append(nu3) # ex4 nopt_qc = transpile(eight_node_multi(False, step, None), basis_gates=['cx', 'u3'], optimization_level=0) ncx = nopt_qc.count_ops().get('cx', 0) nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0) ex4_cx.append(ncx) ex4_u3.append(nu3) # - qc = eight_node_multi(False, 1, None) print(qc.depth()) qc = eight_node_multi(False, 2, None) print(qc.depth()) cx = [ex1_cx, ex4_cx] u3 = [ex1_u3, ex4_u3] color = ['#C23685', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'related works[6]'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.yticks(range(0, 9000, 500)) plt.xticks(range(0, 11, 1)) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) plt.plot(steps, ex4_cx, color= '#3EBA2B', label="# of CX paper circuit", linewidth=3) plt.plot(steps, ex4_u3, color= '#6BBED5', label="# of single qubit gates of paper circuit", linewidth=3) plt.legend(fontsize=25) cx = [ex1_cx, ex4_cx] u3 = [ex1_u3, ex4_u3] color = ['#C23685', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'related works[6]'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.yticks(range(0, 4600, 200)) plt.xticks(range(0, 11, 1)) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) for cs, col, lab in zip(cx, color, labels): plt.plot(steps, cs, color=col, label=lab, linewidth=3) plt.legend(fontsize=25) # + ex1_mean = [] ex1_std = [] ex4_mean = [] ex4_std = [] extime = 10 u3_error = depolarizing_error(0, 1) gate_error = np.arange(0, 0.03, 0.001) # errors, steps= np.meshgrid(gate_error, qw_step) bins = [format(i, '03b') for i in range(2**3)] step = 5 opt_qc = eight_node_multi(False, step, init_state_eight) job = execute(opt_qc, backend=qasm_sim, shots=100000) count = job.result().get_counts(opt_qc) ideal_prob = [count.get(i, 0)/100000 for i in bins] for cxerr in tqdm(gate_error): # noise model error_model = NoiseModel() cx_error = depolarizing_error(cxerr, 2) error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2']) error_model.add_all_qubit_quantum_error(cx_error, ['cx']) # ex1 opt_qc = transpile(eight_node_multi(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) errors = [] for i in range(extime): error = get_error(opt_qc, ideal_prob, error_model, 3) errors.append(error) ex1_mean.append(np.mean(errors)) ex1_std.append(np.std(errors)) # ex4 nopt_qc = transpile(eight_node_multi(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime): error = get_error(nopt_qc, ideal_prob, error_model, 3) errors.append(error) ex4_mean.append(np.mean(errors)) ex4_std.append(np.std(errors)) # - fig = plt.figure(figsize=(20, 10)) sns.set() # plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations') plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations') plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30) plt.xlabel('cx error rate', fontsize=30) plt.ylabel('KL divergence', fontsize=30) plt.tick_params(labelsize=20) plt.legend(fontsize=20) plt.show() # Play ground q = QuantumRegister(1) qc = QuantumCircuit(q) rotation12 = np.radians(23.231) qc.u3(pi/2+rotation12, 0, pi, q[0]) unit = Aer.get_backend('unitary_simulator') job = execute(qc, backend=unit) uni = job.result().get_unitary() print(uni) q = QuantumRegister(1) qc = QuantumCircuit(q) rotation12 = np.radians(23.231) qc.u3(pi/2, 0, pi, q[0]) qc.ry(rotation12, q[0]) unit = Aer.get_backend('unitary_simulator') job = execute(qc, backend=unit) uni = job.result().get_unitary() print(uni) q = QuantumRegister(3,'qr') anc = QuantumRegister(2, 'anc') qc = QuantumCircuit(q, anc) qc.mcmt([q[0], q[1]], anc, QuantumCircuit.ch, [q[2]]) qc.draw(output='mpl') q = QuantumRegister(6) qc = QuantumCircuit(q) qc.initialize(init_state, q) nqc = transpile(qc, basis_gates=['cx', 'h', 'x', 'u3']) nqc.draw(output='mpl') # ## 4. Multi step of 512 node graph with multi partition
https://github.com/Chibikuri/qwopt
Chibikuri
import pennylane as qml import numpy as np import tensorflow as tf qml.about() # simulator on cirq dev = qml.device('cirq.simulator', wires=3) def real(angles, **kwargs): qml.Hadamard(wires=0) qml.Rot(*angles, wires=0) def generator(w, **kwargs): qml.Hadamard(wires=0) qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RY(w[2], wires=0) qml.RY(w[3], wires=1) qml.RZ(w[4], wires=0) qml.RZ(w[5], wires=1) qml.CNOT(wires=[0, 1]) qml.RX(w[6], wires=0) qml.RY(w[7], wires=0) qml.RZ(w[8], wires=0) def discriminator(w): qml.Hadamard(wires=0) qml.RX(w[0], wires=0) qml.RX(w[1], wires=2) qml.RY(w[2], wires=0) qml.RY(w[3], wires=2) qml.RZ(w[4], wires=0) qml.RZ(w[5], wires=2) qml.CNOT(wires=[0, 2]) qml.RX(w[6], wires=2) qml.RY(w[7], wires=2) qml.RZ(w[8], wires=2) def real_disc_circuit(phi, theta, omega, disc_weights): real([phi, theta, omega]) discriminator(disc_weights) return qml.expval(qml.PauliZ(2)) @qml.qnode(dev, interface="tf") def gen_disc_circuit(gen_weights, disc_weights): generator(gen_weights) discriminator(disc_weights) return qml.expval(qml.PauliZ(2)) def prob_real_true(disc_weights): true_disc_output = real_disc_circuit(phi, theta, omega, disc_weights) # convert to probability prob_real_true = (true_disc_output + 1) / 2 return prob_real_true def prob_fake_true(gen_weights, disc_weights): fake_disc_output = gen_disc_circuit(gen_weights, disc_weights) # convert to probability prob_fake_true = (fake_disc_output + 1) / 2 return prob_fake_true def disc_cost(disc_weights): cost = prob_fake_true(gen_weights, disc_weights) - prob_real_true(disc_weights) return cost def gen_cost(gen_weights): return -prob_fake_true(gen_weights, disc_weights) phi = np.pi / 6 theta = np.pi / 2 omega = np.pi / 7 np.random.seed(0) eps = 1e-2 init_gen_weights = np.array([np.pi] + [0] * 8) + \ np.random.normal(scale=eps, size=(9,)) init_disc_weights = np.random.normal(size=(9,)) gen_weights = tf.Variable(init_gen_weights) disc_weights = tf.Variable(init_disc_weights) opt = tf.keras.optimizers.SGD(0.4) cost = lambda: disc_cost(disc_weights) print(cost) for step in range(50): opt.minimize(cost, disc_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val))
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import copy import itertools from qiskit import transpile from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.tools.visualization import plot_histogram from torch import optim # qiskit AQUA from qiskit.aqua.components.optimizers import ADAM from qiskit.aqua.components.uncertainty_models import UniformDistribution, UnivariateVariationalDistribution from qiskit.aqua.components.variational_forms import RY from qiskit.aqua.algorithms.adaptive import QGAN from qiskit.aqua.components.neural_networks.quantum_generator import QuantumGenerator from qiskit.aqua.components.neural_networks.numpy_discriminator import NumpyDiscriminator from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.components.initial_states import Custom alpha = 0.85 target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) E = np.array([[1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0], [1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4)) init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) # Number training data samples N = 1000 # Load data samples from log-normal distribution with mean=1 and standard deviation=1 mu = 1 sigma = 1 real_data = np.random.lognormal(mean = mu, sigma=sigma, size=N) # Set the data resolution # Set upper and lower data values as list of k min/max data values [[min_0,max_0],...,[min_k-1,max_k-1]] bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) print(real_data) plt.hist(real_data) # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # Run qGAN qgan.run(quantum_instance) # Plot progress w.r.t the generator's and the discriminator's loss function t_steps = np.arange(num_epochs) plt.figure(figsize=(6,5)) plt.title("Progress in the loss function") plt.plot(t_steps, qgan.g_loss, label = "Generator loss function", color = 'mediumvioletred', linewidth = 2) plt.plot(t_steps, qgan.d_loss, label = "Discriminator loss function", color = 'rebeccapurple', linewidth = 2) plt.grid() plt.legend(loc = 'best') plt.xlabel('time steps') plt.ylabel('loss') plt.show() # Plot progress w.r.t relative entropy plt.figure(figsize=(6,5)) plt.title("Relative Entropy ") plt.plot(np.linspace(0, num_epochs, len(qgan.rel_entr)), qgan.rel_entr, color ='mediumblue', lw=4, ls=':') plt.grid() plt.xlabel('time steps') plt.ylabel('relative entropy') plt.show() #Plot the PDF of the resulting distribution against the target distribution, i.e. log-normal log_normal = np.random.lognormal(mean=1, sigma=1, size=100000) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= bounds[1]] temp = [] for i in range(int(bounds[1]+1)): temp += [np.sum(log_normal==i)] log_normal = np.array(temp / sum(temp)) plt.figure(figsize=(6,5)) plt.title("CDF") samples_g, prob_g = qgan.generator.get_output(qgan.quantum_instance, shots=10000) samples_g = np.array(samples_g) samples_g = samples_g.flatten() num_bins = len(prob_g) print(prob_g) print(samples_g) plt.bar(samples_g, np.cumsum(prob_g), color='royalblue', width= 0.8, label='simulation') plt.plot( np.cumsum(log_normal),'-o', label='log-normal', color='deepskyblue', linewidth=4, markersize=12) plt.xticks(np.arange(min(samples_g), max(samples_g)+1, 1.0)) plt.grid() plt.xlabel('x') plt.ylabel('p(x)') plt.legend(loc='best') plt.show() print(len(qgan._ret['params_g'])) for i in qgan._ret['params_g']: print(i) gp = qgan._ret['params_g'] q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q) qc.ry(gp[0], q[0]) qc.ry(gp[1], q[1]) qc.cz(q[0], q[1]) qc.ry(gp[2], q[0]) qc.ry(gp[3], q[1]) job = execute(qc, backend=Aer.get_backend('statevector_simulator')) vec = job.result().get_statevector(qc) print(vec) qc.measure(q[0], c[1]) qc.measure(q[1], c[0]) shots = 10000 job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=shots) count = job.result().get_counts(qc) bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] pros = itertools.accumulate([count.get(i, 0)/shots for i in bins]) print(list(pros)) # plot_histogram(pros) # Circuit # Hardcoded now! num_qubits = [2] bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] def four_node(step): rotation = np.radians(31.788) cq = QuantumRegister(2, 'control') tq = QuantumRegister(2, 'target') c = ClassicalRegister(2, 'classical') anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, c) # initialize with probability distribution matrix initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # Kdg operation qc.x(cq) qc.rccx(cq[0], cq[1], anc[0]) qc.barrier() qc.ch(anc[0], tq[0]) qc.ch(anc[0], tq[1]) qc.x(anc[0]) qc.cry(-rotation, anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.barrier() # D operation qc.x(tq) qc.cz(tq[0], tq[1]) qc.x(tq) qc.barrier() # K operation qc.ch(anc[0], tq[0]) qc.cry(rotation, anc[0], tq[1]) qc.x(anc[0]) qc.ch(anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.rccx(cq[0], cq[1], anc[0]) qc.x(cq) qc.barrier() # Tidg operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # swap qc.swap(tq[0], cq[0]) qc.swap(tq[1], cq[1]) qc.measure(tq, c) return qc step = 1 qwqc = four_node(step) shots = 10000 job = execute(qwqc, backend=Aer.get_backend("qasm_simulator"), shots=shots) counts = job.result().get_counts(qwqc) probs = np.array(([0] * counts.get('00'), [1]* counts.get('01'), [2] * counts.get('10'), [3] * counts.get('11'))) real_data = [] for i in probs: for j in i: real_data.append(j) bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # Run qGAN qgan.run(quantum_instance)
https://github.com/Chibikuri/qwopt
Chibikuri
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import matplotlib.pyplot as plt import seaborn as sns import copy import itertools from qiskit import transpile from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.tools.visualization import plot_histogram from torch import optim # qiskit AQUA from qiskit.aqua.components.optimizers import ADAM from qiskit.aqua.components.uncertainty_models import UniformDistribution, UnivariateVariationalDistribution from qiskit.aqua.components.variational_forms import RY from qiskit.aqua.algorithms.adaptive import QGAN from qiskit.aqua.components.neural_networks.quantum_generator import QuantumGenerator from qiskit.aqua.components.neural_networks.numpy_discriminator import NumpyDiscriminator from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.components.initial_states import Custom # + code_folding=[6] alpha = 0.85 target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) E = np.array([[1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0], [1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4)) init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) # - # Check data format # + # Number training data samples N = 1000 # Load data samples from log-normal distribution with mean=1 and standard deviation=1 mu = 1 sigma = 1 real_data = np.random.lognormal(mean = mu, sigma=sigma, size=N) # Set the data resolution # Set upper and lower data values as list of k min/max data values [[min_0,max_0],...,[min_k-1,max_k-1]] bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) print(real_data) plt.hist(real_data) # - # ## Not generalized 4node # + # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # - # Run qGAN qgan.run(quantum_instance) # + # Plot progress w.r.t the generator's and the discriminator's loss function t_steps = np.arange(num_epochs) plt.figure(figsize=(6,5)) plt.title("Progress in the loss function") plt.plot(t_steps, qgan.g_loss, label = "Generator loss function", color = 'mediumvioletred', linewidth = 2) plt.plot(t_steps, qgan.d_loss, label = "Discriminator loss function", color = 'rebeccapurple', linewidth = 2) plt.grid() plt.legend(loc = 'best') plt.xlabel('time steps') plt.ylabel('loss') plt.show() # Plot progress w.r.t relative entropy plt.figure(figsize=(6,5)) plt.title("Relative Entropy ") plt.plot(np.linspace(0, num_epochs, len(qgan.rel_entr)), qgan.rel_entr, color ='mediumblue', lw=4, ls=':') plt.grid() plt.xlabel('time steps') plt.ylabel('relative entropy') plt.show() #Plot the PDF of the resulting distribution against the target distribution, i.e. log-normal log_normal = np.random.lognormal(mean=1, sigma=1, size=100000) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= bounds[1]] temp = [] for i in range(int(bounds[1]+1)): temp += [np.sum(log_normal==i)] log_normal = np.array(temp / sum(temp)) plt.figure(figsize=(6,5)) plt.title("CDF") samples_g, prob_g = qgan.generator.get_output(qgan.quantum_instance, shots=10000) samples_g = np.array(samples_g) samples_g = samples_g.flatten() num_bins = len(prob_g) print(prob_g) print(samples_g) plt.bar(samples_g, np.cumsum(prob_g), color='royalblue', width= 0.8, label='simulation') plt.plot( np.cumsum(log_normal),'-o', label='log-normal', color='deepskyblue', linewidth=4, markersize=12) plt.xticks(np.arange(min(samples_g), max(samples_g)+1, 1.0)) plt.grid() plt.xlabel('x') plt.ylabel('p(x)') plt.legend(loc='best') plt.show() # - print(len(qgan._ret['params_g'])) for i in qgan._ret['params_g']: print(i) gp = qgan._ret['params_g'] # + q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q) qc.ry(gp[0], q[0]) qc.ry(gp[1], q[1]) qc.cz(q[0], q[1]) qc.ry(gp[2], q[0]) qc.ry(gp[3], q[1]) job = execute(qc, backend=Aer.get_backend('statevector_simulator')) vec = job.result().get_statevector(qc) print(vec) qc.measure(q[0], c[1]) qc.measure(q[1], c[0]) shots = 10000 job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=shots) count = job.result().get_counts(qc) bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] pros = itertools.accumulate([count.get(i, 0)/shots for i in bins]) print(list(pros)) # plot_histogram(pros) # + # Circuit # Hardcoded now! num_qubits = [2] bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] def four_node(step): rotation = np.radians(31.788) cq = QuantumRegister(2, 'control') tq = QuantumRegister(2, 'target') c = ClassicalRegister(2, 'classical') anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, c) # initialize with probability distribution matrix initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # Kdg operation qc.x(cq) qc.rccx(cq[0], cq[1], anc[0]) qc.barrier() qc.ch(anc[0], tq[0]) qc.ch(anc[0], tq[1]) qc.x(anc[0]) qc.cry(-rotation, anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.barrier() # D operation qc.x(tq) qc.cz(tq[0], tq[1]) qc.x(tq) qc.barrier() # K operation qc.ch(anc[0], tq[0]) qc.cry(rotation, anc[0], tq[1]) qc.x(anc[0]) qc.ch(anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.rccx(cq[0], cq[1], anc[0]) qc.x(cq) qc.barrier() # Tidg operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # swap qc.swap(tq[0], cq[0]) qc.swap(tq[1], cq[1]) qc.measure(tq, c) return qc # - step = 1 qwqc = four_node(step) shots = 10000 job = execute(qwqc, backend=Aer.get_backend("qasm_simulator"), shots=shots) counts = job.result().get_counts(qwqc) probs = np.array(([0] * counts.get('00'), [1]* counts.get('01'), [2] * counts.get('10'), [3] * counts.get('11'))) real_data = [] for i in probs: for j in i: real_data.append(j) bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) # + # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # - # Run qGAN qgan.run(quantum_instance)
https://github.com/Chibikuri/qwopt
Chibikuri
# This cell is added by sphinx-gallery # It can be customized to whatever you like %matplotlib inline import pennylane as qml import numpy as np import tensorflow as tf dev = qml.device('cirq.simulator', wires=4) def real(angles, **kwargs): qml.RY(0.27740551, wires=0) qml.PauliX(wires =0) qml.CRY(0.20273270, wires=[0, 1]) qml.PauliX(wires =0) qml.CRY(np.pi/2, wires=[0, 1]) qml.CRY(np.pi/2, wires=[0, 2]) qml.PauliX(wires =0) qml.CRY(1.42492, wires=[0, 2]) qml.PauliX(wires =0) def generator(w, **kwargs): qml.Hadamard(wires=0) # qml.Hadamard(wires=1) qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RX(w[2], wires=2) qml.RY(w[3], wires=0) qml.RY(w[4], wires=1) qml.RY(w[5], wires=2) qml.RZ(w[6], wires=0) qml.RZ(w[7], wires=1) qml.RZ(w[8], wires=2) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[1, 2]) qml.RX(w[9], wires=0) qml.RY(w[10], wires=0) qml.RZ(w[11], wires=0) qml.RX(w[12], wires=1) qml.RY(w[13], wires=1) qml.RZ(w[14], wires=1) def discriminator(w): qml.Hadamard(wires=1) qml.RX(w[0], wires=1) qml.RX(w[1], wires=2) qml.RX(w[2], wires=3) qml.RY(w[3], wires=1) qml.RY(w[4], wires=2) qml.RY(w[5], wires=3) qml.RZ(w[6], wires=1) qml.RZ(w[7], wires=2) qml.RZ(w[8], wires=3) qml.CNOT(wires=[1, 2]) qml.CNOT(wires=[2, 3]) qml.RX(w[9], wires=2) qml.RY(w[10], wires=2) qml.RZ(w[11], wires=2) qml.RX(w[12], wires=3) qml.RY(w[13], wires=3) qml.RZ(w[14], wires=3) @qml.qnode(dev, interface="tf") def real_disc_circuit(phi, theta, omega, disc_weights): real([phi, theta, omega]) discriminator(disc_weights) return qml.expval(qml.PauliZ(3)) @qml.qnode(dev, interface="tf") def gen_disc_circuit(gen_weights, disc_weights): generator(gen_weights) discriminator(disc_weights) return qml.expval(qml.PauliZ(3)) def prob_real_true(disc_weights): true_disc_output = real_disc_circuit(phi, theta, omega, disc_weights) # convert to probability prob_real_true = (true_disc_output + 1) / 2 return prob_real_true def prob_fake_true(gen_weights, disc_weights): fake_disc_output = gen_disc_circuit(gen_weights, disc_weights) # convert to probability prob_fake_true = (fake_disc_output + 1) / 2 return prob_fake_true def disc_cost(disc_weights): cost = prob_fake_true(gen_weights, disc_weights) - prob_real_true(disc_weights) return cost def gen_cost(gen_weights): return -prob_fake_true(gen_weights, disc_weights) phi = np.pi / 6 theta = np.pi / 2 omega = np.pi / 7 np.random.seed(0) eps = 1e-2 init_gen_weights = np.array([np.pi] + [0] * 14) + \ np.random.normal(scale=eps, size=(15,)) init_disc_weights = np.random.normal(size=(15,)) gen_weights = tf.Variable(init_gen_weights) disc_weights = tf.Variable(init_disc_weights) print(gen_weights) opt = tf.keras.optimizers.SGD(0.4) cost = lambda: disc_cost(disc_weights) for step in range(100): opt.minimize(cost, disc_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val)) print("Prob(real classified as real): ", prob_real_true(disc_weights).numpy()) print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy()) cost = lambda: gen_cost(gen_weights) for step in range(100): opt.minimize(cost, gen_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val)) print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy()) print("Discriminator cost: ", disc_cost(disc_weights).numpy()) obs = [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0)] bloch_vector_real = qml.map(real, obs, dev, interface="tf") bloch_vector_generator = qml.map(generator, obs, dev, interface="tf") print("Real Bloch vector: {}".format(bloch_vector_real([phi, theta, omega]))) print("Generator Bloch vector: {}".format(bloch_vector_generator(gen_weights))) print(gen_weights) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer w = gen_weights.numpy() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.rx(w[0], q[0]) qc.rx(w[1], q[1]) qc.rx(w[2], q[2]) qc.ry(w[3], q[0]) qc.ry(w[4], q[1]) qc.ry(w[5], q[2]) qc.rz(w[6], q[0]) qc.rz(w[7], q[1]) qc.rz(w[8], q[2]) qc.cx(q[0], q[1]) qc.cx(q[1], q[2]) qc.rx(w[9], q[0]) qc.ry(w[10], q[0]) qc.rz(w[11], q[0]) qc.rx(w[12], q[1]) qc.ry(w[13], q[1]) qc.rz(w[14], q[1]) job = execute(qc, backend=Aer.get_backend("statevector_simulator")) vec = job.result().get_statevector() for i in vec: print(i)
https://github.com/Chibikuri/qwopt
Chibikuri
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # This cell is added by sphinx-gallery # It can be customized to whatever you like # %matplotlib inline # # # Quantum Generative Adversarial Networks with Cirq + TensorFlow # ============================================================== # # .. meta:: # :property="og:description": This demo constructs and trains a Quantum # Generative Adversarial Network (QGAN) using PennyLane, Cirq, and TensorFlow. # :property="og:image": https://pennylane.ai/qml/_images/qgan3.png # # This demo constructs a Quantum Generative Adversarial Network (QGAN) # (`Lloyd and Weedbrook # (2018) <https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.121.040502>`__, # `Dallaire-Demers and Killoran # (2018) <https://journals.aps.org/pra/abstract/10.1103/PhysRevA.98.012324>`__) # using two subcircuits, a *generator* and a *discriminator*. The # generator attempts to generate synthetic quantum data to match a pattern # of "real" data, while the discriminator tries to discern real data from # fake data (see image below). The gradient of the discriminator’s output provides a # training signal for the generator to improve its fake generated data. # # | # # .. figure:: ../demonstrations/QGAN/qgan.png # :align: center # :width: 75% # :target: javascript:void(0) # # | # # Using Cirq + TensorFlow # ~~~~~~~~~~~~~~~~~~~~~~~ # PennyLane allows us to mix and match quantum devices and classical machine # learning software. For this demo, we will link together # Google's `Cirq <https://cirq.readthedocs.io/en/stable/>`_ and `TensorFlow <https://www.tensorflow.org/>`_ libraries. # # We begin by importing PennyLane, NumPy, and TensorFlow. # # import pennylane as qml import numpy as np import tensorflow as tf # We also declare a 3-qubit simulator device running in Cirq. # # dev = qml.device('cirq.simulator', wires=4) # Generator and Discriminator # ~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # In classical GANs, the starting point is to draw samples either from # some “real data” distribution, or from the generator, and feed them to # the discriminator. In this QGAN example, we will use a quantum circuit # to generate the real data. # # For this simple example, our real data will be a qubit that has been # rotated (from the starting state $\left|0\right\rangle$) to some # arbitrary, but fixed, state. # # def real(angles, **kwargs): qml.RY(0.27740551, wires=0) qml.PauliX(wires =0) qml.CRY(0.20273270, wires=[0, 1]) qml.PauliX(wires =0) qml.CRY(np.pi/2, wires=[0, 1]) qml.CRY(np.pi/2, wires=[0, 2]) qml.PauliX(wires =0) qml.CRY(1.42492, wires=[0, 2]) qml.PauliX(wires =0) # For the generator and discriminator, we will choose the same basic # circuit structure, but acting on different wires. # # Both the real data circuit and the generator will output on wire 0, # which will be connected as an input to the discriminator. Wire 1 is # provided as a workspace for the generator, while the discriminator’s # output will be on wire 2. # # # + def generator(w, **kwargs): qml.Hadamard(wires=0) # qml.Hadamard(wires=1) qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RX(w[2], wires=2) qml.RY(w[3], wires=0) qml.RY(w[4], wires=1) qml.RY(w[5], wires=2) qml.RZ(w[6], wires=0) qml.RZ(w[7], wires=1) qml.RZ(w[8], wires=2) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[1, 2]) qml.RX(w[9], wires=0) qml.RY(w[10], wires=0) qml.RZ(w[11], wires=0) qml.RX(w[12], wires=1) qml.RY(w[13], wires=1) qml.RZ(w[14], wires=1) def discriminator(w): qml.Hadamard(wires=1) qml.RX(w[0], wires=1) qml.RX(w[1], wires=2) qml.RX(w[2], wires=3) qml.RY(w[3], wires=1) qml.RY(w[4], wires=2) qml.RY(w[5], wires=3) qml.RZ(w[6], wires=1) qml.RZ(w[7], wires=2) qml.RZ(w[8], wires=3) qml.CNOT(wires=[1, 2]) qml.CNOT(wires=[2, 3]) qml.RX(w[9], wires=2) qml.RY(w[10], wires=2) qml.RZ(w[11], wires=2) qml.RX(w[12], wires=3) qml.RY(w[13], wires=3) qml.RZ(w[14], wires=3) # - # We create two QNodes. One where the real data source is wired up to the # discriminator, and one where the generator is connected to the # discriminator. In order to pass TensorFlow Variables into the quantum # circuits, we specify the ``"tf"`` interface. # # # + @qml.qnode(dev, interface="tf") def real_disc_circuit(phi, theta, omega, disc_weights): real([phi, theta, omega]) discriminator(disc_weights) return qml.expval(qml.PauliZ(3)) @qml.qnode(dev, interface="tf") def gen_disc_circuit(gen_weights, disc_weights): generator(gen_weights) discriminator(disc_weights) return qml.expval(qml.PauliZ(3)) # - # QGAN cost functions # ~~~~~~~~~~~~~~~~~~~ # # There are two cost functions of interest, corresponding to the two # stages of QGAN training. These cost functions are built from two pieces: # the first piece is the probability that the discriminator correctly # classifies real data as real. The second piece is the probability that the # discriminator classifies fake data (i.e., a state prepared by the # generator) as real. # # The discriminator is trained to maximize the probability of # correctly classifying real data, while minimizing the probability of # mistakenly classifying fake data. # # The generator is trained to maximize the probability that the # discriminator accepts fake data as real. # # # + def prob_real_true(disc_weights): true_disc_output = real_disc_circuit(phi, theta, omega, disc_weights) # convert to probability prob_real_true = (true_disc_output + 1) / 2 return prob_real_true def prob_fake_true(gen_weights, disc_weights): fake_disc_output = gen_disc_circuit(gen_weights, disc_weights) # convert to probability prob_fake_true = (fake_disc_output + 1) / 2 return prob_fake_true def disc_cost(disc_weights): cost = prob_fake_true(gen_weights, disc_weights) - prob_real_true(disc_weights) return cost def gen_cost(gen_weights): return -prob_fake_true(gen_weights, disc_weights) # - # Training the QGAN # ~~~~~~~~~~~~~~~~~ # # We initialize the fixed angles of the “real data” circuit, as well as # the initial parameters for both generator and discriminator. These are # chosen so that the generator initially prepares a state on wire 0 that # is very close to the $\left| 1 \right\rangle$ state. # # # + phi = np.pi / 6 theta = np.pi / 2 omega = np.pi / 7 np.random.seed(0) eps = 1e-2 init_gen_weights = np.array([np.pi] + [0] * 14) + \ np.random.normal(scale=eps, size=(15,)) init_disc_weights = np.random.normal(size=(15,)) gen_weights = tf.Variable(init_gen_weights) disc_weights = tf.Variable(init_disc_weights) print(gen_weights) # - # We begin by creating the optimizer: # # opt = tf.keras.optimizers.SGD(0.4) # In the first stage of training, we optimize the discriminator while # keeping the generator parameters fixed. # # # + cost = lambda: disc_cost(disc_weights) for step in range(100): opt.minimize(cost, disc_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val)) # - # At the discriminator’s optimum, the probability for the discriminator to # correctly classify the real data should be close to one. # # print("Prob(real classified as real): ", prob_real_true(disc_weights).numpy()) # For comparison, we check how the discriminator classifies the # generator’s (still unoptimized) fake data: # # print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy()) # In the adversarial game we now have to train the generator to better # fool the discriminator. For this demo, we only perform one stage of the # game. For more complex models, we would continue training the models in an # alternating fashion until we reach the optimum point of the two-player # adversarial game. # # # + cost = lambda: gen_cost(gen_weights) for step in range(100): opt.minimize(cost, gen_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val)) # - # At the optimum of the generator, the probability for the discriminator # to be fooled should be close to 1. # # print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy()) # At the joint optimum the discriminator cost will be close to zero, # indicating that the discriminator assigns equal probability to both real and # generated data. # # print("Discriminator cost: ", disc_cost(disc_weights).numpy()) # The generator has successfully learned how to simulate the real data # enough to fool the discriminator. # # Let's conclude by comparing the states of the real data circuit and the generator. We expect # the generator to have learned to be in a state that is very close to the one prepared in the # real data circuit. An easy way to access the state of the first qubit is through its # `Bloch sphere <https://en.wikipedia.org/wiki/Bloch_sphere>`__ representation: # # # + obs = [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0)] bloch_vector_real = qml.map(real, obs, dev, interface="tf") bloch_vector_generator = qml.map(generator, obs, dev, interface="tf") print("Real Bloch vector: {}".format(bloch_vector_real([phi, theta, omega]))) print("Generator Bloch vector: {}".format(bloch_vector_generator(gen_weights))) # - print(gen_weights) # + from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer w = gen_weights.numpy() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.rx(w[0], q[0]) qc.rx(w[1], q[1]) qc.rx(w[2], q[2]) qc.ry(w[3], q[0]) qc.ry(w[4], q[1]) qc.ry(w[5], q[2]) qc.rz(w[6], q[0]) qc.rz(w[7], q[1]) qc.rz(w[8], q[2]) qc.cx(q[0], q[1]) qc.cx(q[1], q[2]) qc.rx(w[9], q[0]) qc.ry(w[10], q[0]) qc.rz(w[11], q[0]) qc.rx(w[12], q[1]) qc.ry(w[13], q[1]) qc.rz(w[14], q[1]) # - job = execute(qc, backend=Aer.get_backend("statevector_simulator")) vec = job.result().get_statevector() for i in vec: print(i)
https://github.com/Chibikuri/qwopt
Chibikuri
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import copy from qiskit import QuantumCircuit, QuantumRegister, Aer, execute np.set_printoptions(linewidth=10000, threshold=10000) # + def theoretical_prob(initial, step, ptran, nq): Pi_op = Pi_operator(ptran) swap = swap_operator(nq) operator = (2*Pi_op) - np.identity(len(Pi_op)) Szegedy = np.dot(operator, swap) Szegedy_n = copy.copy(Szegedy) print(id(Szegedy), id(Szegedy_n)) if step == 0: init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float) return init_prob elif step == 1: prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)], dtype=np.float) return prob else: for n in range(step-1): Szegedy_n = np.dot(Szegedy_n, Szegedy) probs = np.array([abs(i)**2 for i in np.dot(initial, Szegedy_n)], dtype=np.float) return probs def swap_operator(n_qubit): q1 = QuantumRegister(n_qubit//2) q2 = QuantumRegister(n_qubit//2) qc = QuantumCircuit(q1, q2) for c, t in zip(q1, q2): qc.swap(c, t) # FIXME backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend=backend) swap = job.result().get_unitary(qc) return swap def Pi_operator(ptran): ''' This is not a quantum operation, just returning matrix ''' lg = len(ptran) psi_op = [] count = 0 for i in range(lg): psi_vec = [0 for _ in range(lg**2)] for j in range(lg): psi_vec[count] = np.sqrt(ptran[j][i]) count += 1 psi_op.append(np.kron(np.array(psi_vec).T, np.conjugate(psi_vec)).reshape((lg**2, lg**2))) Pi = psi_op[0] for i in psi_op[1:]: Pi = np.add(Pi, i) return Pi def is_unitary(operator, tolerance=0.0001): h, w = operator.shape if not h == w: return False adjoint = np.conjugate(operator.transpose()) product1 = np.dot(operator, adjoint) product2 = np.dot(adjoint, operator) ida = np.eye(h) return np.allclose(product1, ida) & np.allclose(product2, ida) # + alpha = 0.85 target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) E = np.array([[1/8, 1/2, 0, 0, 0, 0, 0, 1/2], [1/8, 0, 1/2, 0, 0, 0, 0, 0], [1/8, 1/2, 0, 1/2, 0, 0, 0, 0], [1/8, 0, 1/2, 0, 1/2, 0, 0, 0], [1/8, 0, 0, 1/2, 0, 1/2, 0, 0], [1/8, 0, 0, 0, 1/2, 0, 1/2, 0], [1/8, 0, 0, 0, 0, 1/2, 0, 1/2], [1/8, 0, 0, 0, 0, 0, 1/2, 0]]) # use google matrix lt = len(target_graph) prob_dist = alpha*E + ((1-alpha)/lt)*np.ones((lt, lt)) init_state_eight = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(lt) for j in range(lt)]) # - Pi_op = Pi_operator(prob_dist) operator = (2*Pi_op) - np.identity(len(Pi_op)) lo = len(operator) initial = np.array([0 if i != 32 else 1 for i in range(lo)]) # initial = np.array([np.sqrt(1/lo) for i in range(lo)]) ideal = theoretical_prob(initial, 2, prob_dist, 6) for i, v in enumerate(ideal): print(i, v) import networkx as nx import matplotlib.pyplot as plt target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) Gs = nx.from_numpy_matrix(target_graph) G = nx.MultiDiGraph() pos = [(1, 1), (5, 1), (5, 5), (1, 5)] G.add_edges_from(Gs.edges()) plt.figure(figsize=(8,8)) nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50) plt.show() # + target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) Gs = nx.from_numpy_matrix(target_graph) G = nx.MultiDiGraph() # pos = [(1, 1), (2, 2), (3, 3), (1, 5), (2, 2), (6, 2), (6, 6), (2, 6)] pos = [(0, 0), (1, 1), (2, 2), (1, 3), (0, 4), (-1, 3), (-2, 2), (-1, 1)] G.add_edges_from(Gs.edges()) # pos = nx.spring_layout(G) plt.figure(figsize=(8,8)) nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50) plt.show() # + target_graph = np.array([[0, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1]]) Gs = nx.from_numpy_matrix(target_graph) print(Gs.edges()) G = nx.MultiDiGraph() # pos = [(1, 1), (2, 2), (3, 3), (1, 5), (2, 2), (6, 2), (6, 6), (2, 6)] pos = [(0, 0), (3, 3), (2, 9), (-1, 5), (5, 1), (4, 5), (8, 5), (9, 3)] G.add_edges_from(Gs.edges()) G.add_edges_from([(7, 6)]) # pos = nx.spring_layout(G, k=10) plt.figure(figsize=(10, 10)) nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50) plt.show() # -
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from tqdm import trange, tqdm from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.quantum_info import state_fidelity from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit import transpile QASM = Aer.get_backend('qasm_simulator') STATEVEC = Aer.get_backend('statevector_simulator') class FidelityAnalyzer: ''' This analyzer is for analyzing the fidelity performance under the noisy situation. Errors are very naive. If you put quantum circuit, this module analyze the fidelity decreasing automatically. ''' def __init__(self, one_error, two_error, measure_qubit, extime=10, shots=5000): if not isinstance(one_error, (float, int, np.ndarray, list)): raise ValueError('one error is must be float, int, array or list.') else: # error rate of u3 self.one_error = one_error if not isinstance(two_error, (float, int, np.ndarray, list)): raise ValueError('one error is must be float, int, array or list.') else: # error rate of cx self.two_error = two_error # TODO: make 3D plot when one error and two error are array self.shots = shots self.mes_qbt = measure_qubit self.extime = extime def fidelity_drop(self, qc, drawing=True, **kwargs): nqc = transpile(qc, optimization_level=0, basis_gates=['cx', 'u3']) # HACK efficient ways? if isinstance(self.one_error, (float, int)) and isinstance(self.two_error, (float, int)): fidelitis, std = self.fixed_fidelity(nqc) # FIXME more easy way self.pattern = 0 # FIXME more seeable elif isinstance(self.one_error, (float, int)) and isinstance(self.two_error, (np.ndarray, list)): fidelities, std = self._u3fix(nqc) self.pattern = 1 elif isinstance(self.two_error, (float, int)) and isinstance(self.one_error, (np.ndarray, list)): cxerror = depolarizing_error(self.two_error, 2) fidelities, std = self._cxfix(nqc) self.pattern = 2 else: fidelities, std = self._nofix(nqc) self.pattern = 3 if drawing: self._draw(fidelities, std, **kwargs) return fidelities def _u3fix(self, qc): nst = 2**len(self.mes_qbt) bins = [format(i, '0%db' % len(self.mes_qbt)) for i in range(nst)] # ideal result of this circuit ideal = execute(qc, backend=QASM, shots=self.shots*10) idealcounts = ideal.result().get_counts() idealst = np.array([idealcounts.get(i, 0)/(self.shots*10) for i in bins]) print(idealst) # making noise model with error rate u3error = depolarizing_error(self.one_error, 1) # start simulations mean_fid = [] std_fid = [] for two_err in tqdm(self.two_error): mid = [] noise_model = NoiseModel() cxerror = depolarizing_error(two_err, 2) noise_model.add_all_qubit_quantum_error(u3error, ['u3']) noise_model.add_all_qubit_quantum_error(cxerror, ['cx']) for t in range(self.extime): # execute! job = execute(qc, backend=QASM, noise_model=noise_model, shots=self.shots) counts = job.result().get_counts() stvec = [counts.get(i, 0)/self.shots for i in bins] stf = state_fidelity(idealst, stvec) mid.append(stf) print(stvec) mean_fid.append(np.mean(mid)) std_fid.append(np.std(mid)) return mean_fid, std_fid def _cxfix(self, qc): nst = 2**len(self.mes_qbt) bins = [format(i, '0%db' % len(self.mes_qbt)) for i in range(nst)] # ideal result of this circuit ideal = execute(qc, backend=QASM, shots=self.shots*10) idealcounts = ideal.result().get_counts() idealst = np.array([idealcounts.get(i, 0)/(self.shots*10) for i in bins]) # making noise model with error rate cxerror = depolarizing_error(self.two_error, 2) # start simulations mean_fid = [] std_fid = [] for one_er in tqdm(self.one_error): mid = [] noise_model = NoiseModel() u3error = depolarizing_error(one_er, 1) noise_model.add_all_qubit_quantum_error(u3error, ['u3']) noise_model.add_all_qubit_quantum_error(cxerror, ['cx']) for t in range(self.extime): job = execute(qc, backend=QASM, noise_model=noise_model, shots=self.shots) counts = job.result().get_counts() stvec = [counts.get(i, 0)/self.shots for i in bins] stf = state_fidelity(idealst, stvec) mid.append(stf) mean_fid.append(np.mean(mid)) std_fid.append(np.std(mid)) return mean_fid, std_fid def _nofix(self, qc): nst = 2**len(self.mes_qbt) bins = [format(i, '0%db' % len(self.mes_qbt)) for i in range(nst)] # ideal result of this circuit ideal = execute(qc, backend=QASM, shots=self.shots*10) idealcounts = ideal.result().get_counts() idealst = np.array([idealcounts.get(i, 0)/(self.shots*10) for i in bins]) # start simulations if len(self.one_error) != len(self.two_error): raise ValueError('length of array of one error \ and two error must be the same.') mean_fid = [] std_fid = [] for one_er, two_er in tqdm(zip(self.one_error, self.two_error)): mid = [] # HACK: might be efficient in top layer noise_model = NoiseModel() u3error = depolarizing_error(one_er, 1) cxerror = depolarizing_error(two_er, 2) noise_model.add_all_qubit_quantum_error(u3error, ['u3']) noise_model.add_all_qubit_quantum_error(cxerror, ['cx']) for t in range(self.extime): job = execute(qc, backend=QASM, noise_model=noise_model, shots=self.shots) counts = job.result().get_counts() stvec = [counts.get(i, 0)/self.shots for i in bins] stf = state_fidelity(idealst, stvec) mid.append(stf) mean_fid.append(np.mean(mid)) std_fid.append(np.std(mid)) return mean_fid, std_fid def _fixed_fidelity(self, qc): fidelity = 0 return fidelity def _draw(self, fidelities, std, errorbar=True, **kwargs): ''' drawing fidelity dropping ''' title = kwargs.get('title', 'Fidelity decrease') fontsize = kwargs.get('fontsize', 14) seaborn = kwargs.get('seaborn', True) plt.ylabel('Fidelity') if seaborn: sns.set() plt.title(title, fontsize=fontsize) if self.pattern == 0: raise Exception('No drawing is allowed in just \ one element(under construction)') elif self.pattern == 1: plt.xlabel('Two qubit gate error') if errorbar: plt.errorbar(self.two_error, fidelities, yerr=std) else: plt.plot(self.two_error, fidelities) elif self.pattern == 2: plt.xlabel('One qubit gate error') if errorbar: plt.errorbar(self.one_error, fidelities, yerr=std) else: plt.plot(self.one_error, fidelities) elif self.pattern == 3: raise Exception('under construction') else: pass plt.show() if __name__ == '__main__': q = QuantumRegister(4) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.x(q[0]) for i in range(3): qc.cx(q[0], q[1]) qc.cx(q[1], q[0]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) analyzer = FidelityAnalyzer(0.01, np.arange(0, 0.1, 0.01), [0, 1], extime=10) result = analyzer.fidelity_drop(qc) print(result)
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np import copy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, execute from .op_creater import OperationCreator from qiskit import transpile np.set_printoptions(linewidth=1000, precision=3) class CircuitComposer: ''' If you use google matrix as a probability distribution matrix, please use E as a graph ''' def __init__(self, graph, prob_tran, step, optimize=True): self.operator = OperationCreator(graph, prob_tran, optimize=optimize) self.n_qubit = self.operator.q_size self.graph = self.operator.graph self.ptran = self.operator.ptran self.step = step if self.step < 0: raise ValueError('The number of steps must be 0 and over') def qw_circuit(self, anc=True, name='quantumwalk', measurement=True, initialize=True, validation=True, optimization=True): cont = QuantumRegister(self.n_qubit//2, 'control') targ = QuantumRegister(self.n_qubit//2, 'target') anc = QuantumRegister(self.n_qubit//2, 'ancilla') qw = QuantumCircuit(cont, targ, anc, name=name) lp = len(self.ptran)**2 # HACK if isinstance(initialize, bool) and initialize: self._initialize(qw, [*cont, *targ]) # FIXME init_state = [1/np.sqrt(lp) for i in range(lp)] elif isinstance(initialize, (list, np.ndarray)): self._initialize(qw, [*cont, *targ], state=initialize) init_state = initialize else: # FIXME should be able to put arbitraly input initial init_state = [1] + [0 for i in range(lp-1)] qw = self._circuit_composer(qw, cont, targ, anc, optimization=optimization) # FIXME more efficient order if validation: qw, correct = self._circuit_validator(qw, [*cont, *targ], init_state) if measurement: c = ClassicalRegister(self.n_qubit//2, 'classical') qw.add_register(c) # TODO is this correct order? qw.measure(targ, c) if correct: print('Circuit is validated!') return qw else: raise Exception('Circuit validation failed') else: if measurement: c = ClassicalRegister(self.n_qubit//2, 'classical') qw.add_register(c) # TODO is this correct order? qw.measure(targ, c) return qw def _circuit_composer(self, circuit, cont, targ, anc, measurement=True, optimization=False): qubits = [*cont, *targ, *anc] if optimization: # HACK # ancillary qubits for optimizations opt_anc = QuantumRegister(self.n_qubit//2) circuit.add_register(opt_anc) opt_qubits = [*cont, *targ, *anc, *opt_anc] else: opt_qubits = [*cont, *targ, *anc] Ts = self.operator.T_operation() Kdg = self.operator.K_operation(dagger=True, optimization=optimization) K = self.operator.K_operation(dagger=False, optimization=optimization) D = self.operator.D_operation() # TODO remove commented out for step in range(self.step): for t in Ts: circuit.append(t, qargs=qubits) circuit.append(Kdg, qargs=opt_qubits) circuit.append(D, qargs=targ) circuit.append(K, qargs=opt_qubits) for tdg in Ts: circuit.append(tdg, qargs=qubits) for i, j in zip(cont, targ): circuit.swap(i, j) circuit.barrier() return circuit def _circuit_validator(self, circuit, qregs, init_state, remote=False, test_shots=100000, threshold=1e-4): # TODO check with unitary simulator(currently, ansilla is bothering...) nc = ClassicalRegister(self.n_qubit) circuit.add_register(nc) for q, c in zip(qregs, nc): circuit.measure(q, c) if remote: backend = IBMQ.get_backend('ibmq_qasm_simulator') else: backend = Aer.get_backend('qasm_simulator') theoretical_prob = self._theoretical_prob(init_state) print(theoretical_prob) vjob = execute(circuit, backend=backend, shots=test_shots) result = vjob.result().get_counts(circuit) rb = self.n_qubit bins = [format(i, '0%sb' % rb) for i in range(2**rb)] probs = np.array([result.get(bi, 0)/test_shots for bi in bins]) print(probs) # TODO check L2 norm is good enough to validate in larger case # and check threshold l2dist = self._L2_dist(theoretical_prob, probs) if l2dist < threshold: flag = True else: flag = False circuit.remove_final_measurements() return circuit, flag def _initialize(self, circuit, qregs, state='super'): if isinstance(state, (list, np.ndarray)): circuit.initialize(state, qregs) elif state == 'super': for qr in qregs: circuit.h(qr) else: pass return circuit @staticmethod def _L2_dist(pa, pb): # FIXME using array ps = [(p1 - p2)**2 for p1, p2 in zip(pa, pb)] return sum(ps) def _theoretical_prob(self, initial): Pi_op = self._Pi_operator() swap = self._swap_operator() operator = (2*Pi_op) - np.identity(len(Pi_op)) Szegedy = np.dot(operator, swap) Szegedy_n = copy.deepcopy(Szegedy) if self.step == 0: init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float) return init_prob elif self.step == 1: prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)], dtype=np.float) return prob else: for n in range(self.step-1): Szegedy_n = np.dot(Szegedy_n, Szegedy) probs = np.array([abs(i)**2 for i in np.dot(Szegedy_n, initial)], dtype=np.float) return probs def _swap_operator(self): q1 = QuantumRegister(self.n_qubit//2) q2 = QuantumRegister(self.n_qubit//2) qc = QuantumCircuit(q1, q2) for c, t in zip(q1, q2): qc.swap(c, t) # FIXME backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend=backend) swap = job.result().get_unitary(qc) return swap def _Pi_operator(self): ''' This is not a quantum operation, just returning matrix ''' lg = len(self.ptran) psi_op = [] count = 0 for i in range(lg): psi_vec = [0 for _ in range(lg**2)] for j in range(lg): psi_vec[count] = np.sqrt(self.ptran[j][i]) count += 1 psi_op.append(np.kron(np.array(psi_vec).T, np.conjugate(psi_vec)).reshape((lg**2, lg**2))) Pi = psi_op[0] for i in psi_op[1:]: Pi = np.add(Pi, i) return Pi def prob_transition(graph, gtype='normal', alpha=0.85): if gtype == 'google': return google_matrix(alpha, graph) else: pmatrix = np.zeros(graph.shape) indegrees = np.sum(graph, axis=0) for ix, indeg in enumerate(indegrees): if indeg == 0: pmatrix[:, ix] = graph[:, ix] else: pmatrix[:, ix] = graph[:, ix]/indeg return pmatrix # def is_unitary(operator, tolerance=0.0001): # h, w = operator.shape # if not h == w: # return False # adjoint = np.conjugate(operator.transpose()) # product1 = np.dot(operator, adjoint) # product2 = np.dot(adjoint, operator) # ida = np.eye(h) # return np.allclose(product1, ida) & np.allclose(product2, ida) # def google_matrix(alpha, C): # E = connect_to_E(C) # N = len(C) # G = alpha*E + (1-alpha)/N * np.ones((N, N), dtype=float) # return G # def connect_to_E(C): # ''' # C is conectivity matrix # C: np.array # output # E: np.array # ''' # N = len(C) # C = np.array(C) # E = np.zeros(C.shape) # rowsum = np.sum(C, axis=0) # for ind, val in enumerate(rowsum): # if val == 0: # for j in range(N): # E[j][ind] = 1/N # else: # for j in range(N): # E[j][ind] = C[j][ind]/val # assert(np.sum(np.sum(E, axis=0)) == N) # return E # if __name__ == '__main__': # # graph = np.array([[0, 1, 0, 0, 1, 0, 0, 1], # # [0, 0, 0, 1, 1, 0, 1, 0], # # [0, 0, 0, 1, 0, 1, 0, 1], # # [0, 1, 0, 0, 0, 0, 1, 0], # # [0, 1, 0, 0, 0, 1, 0, 1], # # [0, 1, 0, 0, 1, 0, 1, 1], # # [0, 1, 0, 0, 1, 0, 0, 1], # # [0, 1, 0, 0, 1, 0, 1, 0]]) # graph = np.array([[0, 1, 1, 0], # [0, 0, 0, 1], # [0, 0, 0, 1], # [0, 1, 1, 0]]) # # e = np.array([[1, 1, 1, 0], # # [1, 0, 0, 1], # # [1, 0, 0, 1], # # [1, 1, 1, 0]]) # pb = prob_transition(graph) # comp = CircuitComposer(graph, pb, 1) # comp.qw_circuit()
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np from .parser import GraphParser from qiskit import QuantumRegister, QuantumCircuit from numpy import pi class OperationCreator: ''' Creating operations of szegedy walk. reference: Loke, T., and J. B. Wang. "Efficient quantum circuits for Szegedy quantum walks." Annals of Physics 382 (2017): 64-84. all functions return instruction sets which can be added to a circuit directly ''' def __init__(self, graph, prob_tran, basis=0, optimize=True): self.parser = GraphParser(graph, prob_tran) self.graph = self.parser.graph self.ptran = self.parser.ptrans self.dim = self.parser.dim() self.q_size = self._qubit_size(len(self.parser)) self.basis_state = basis def T_operation(self): ''' This is the operation called T operation. This operator is converting some state to its reference state by replacing binary order NOTE: I'm not sure if there is an optimized way to do this, but, thinking we can do this if we use some boolean calcuration. ''' ref_states, ref_index = self.parser.reference_state() ref_index.append(len(self.graph)) T_instructions = [] for irf, rf in enumerate(ref_index[:-1]): temp = [] for i in range(rf, ref_index[irf+1]): # control from i and target from bins temp.append(self.graph[:, i]) Ti_op = self._bin_converter(temp, range(rf, ref_index[irf+1])) if Ti_op is not None: T_instructions.append(Ti_op) return T_instructions # TODO more understandable name def _bin_converter(self, states, cont, ancilla=True): if len(states) == 1: # if the length of state is 1, we don't need to move # with T operation pass else: ref_state = states[0] # make correspondence table convs = [self._take_bins(ref_state, st) for st in states[1:]] if convs == [[]]: # if all table elements are the same value, # we don't have to apply return None else: # TODO # here we have to optimize additional target ctable = self._addi_analysis(convs) target = [self._target_hm(cnv) for cnv in ctable] control = [list(self._binary_formatter(ct, self.q_size//2)) for ct in cont] # create instruction q_cont = QuantumRegister(self.q_size//2) q_targ = QuantumRegister(self.q_size//2) if ancilla: ancilla = QuantumRegister(self.q_size//2) qc = QuantumCircuit(q_cont, q_targ, ancilla, name='T%s' % cont[0]) else: ancilla = None qc = QuantumCircuit(q_cont, q_targ, name='T%s' % cont[0]) for cts, tgt in zip(control[1:], target): for ic, ct in enumerate(cts): if ct == '0' and tgt != set(): qc.x(q_cont[ic]) for tg in tgt: qc.mct(q_cont, q_targ[tg], ancilla) for ic, ct in enumerate(cts): if ct == '0' and tgt != set(): qc.x(q_cont[ic]) return qc.to_instruction() def _target_hm(self, state): # the place we have to change hm = [] for st in state: # FIXME this reverse operations must be done before here. # This reverse op is for making it applicable for qiskit. for ids, s in enumerate(zip(st[0][::-1], st[1][::-1])): if s[0] != s[1]: hm.append(ids) return set(hm) def _take_bins(self, ref_state, other): converter = [] for irf, rf in enumerate(ref_state): if rf == 1: converter.append([self._binary_formatter(irf, self.q_size//2)]) ct = 0 for iot, ot in enumerate(other): if ot == 1: converter[ct].append(self._binary_formatter(iot, self.q_size//2)) ct += 1 return converter # more understandable name def _addi_analysis(self, conversions): ''' remove duplications ''' for icv, cv in enumerate(conversions): # FIXME are there any efficient way rather than this? if cv[0][0] == cv[0][1] and cv[1][0] == cv[1][1]: conversions[icv] = [] conversion_table = conversions return conversion_table @staticmethod def _binary_formatter(n, basis): return format(n, '0%db' % basis) def K_operation(self, dagger=False, ancilla=True, optimization=True, n_opt_ancilla=2, rccx=True): ''' Args: dagger: ancilla: optimization: n_opt_ancilla: rccx create reference states from basis state or if this is Kdag, reverse operation TODO: should separate the creation part and optimization part ''' refs, refid = self.parser.reference_state() rotations = self._get_rotaions(refs, dagger) # create Ki operations qcont = QuantumRegister(self.q_size//2, 'control') qtarg = QuantumRegister(self.q_size//2, 'target') # 1, ancilla mapping optimization # if the number of reference states is the same as # the length of matrix, we can't apply first optimization method. if optimization and len(refid) != self.dim[0]: # TODO surplus ancillary qubits should be used efficientry # separate the optimization part and creation part if n_opt_ancilla > len(qcont): # FIXME: raise ValueError('too much ancillary qubits') opt_anc = QuantumRegister(n_opt_ancilla, name='opt_ancilla') if ancilla: anc = QuantumRegister(self.q_size//2) qc = QuantumCircuit(qcont, qtarg, anc, opt_anc, name='opt_Kop') else: anc = None qc = QuantumCircuit(qcont, qtarg, opt_anc, name='opt_Kop_n') # HACK # Unlke to bottom one, we need to detect which i we apply or not qc = self._opt_K_operation(qc, qcont, qtarg, anc, opt_anc, refid, rotations, dagger, rccx) opt_K_instruction = qc.to_instruction() return opt_K_instruction else: if ancilla: anc = QuantumRegister(self.q_size//2) qc = QuantumCircuit(qcont, qtarg, anc, name='Kop_anc') else: anc = None qc = QuantumCircuit(qcont, qtarg, name='Kop') ct = 0 for i in range(self.dim[0]): ib = list(self._binary_formatter(i, self.q_size//2)) if i in refid: rfrot = rotations[ct] ct += 1 for ibx, bx in enumerate(ib): if bx == '0': qc.x(qcont[ibx]) qc = self._constructor(qc, rfrot, qcont, qtarg, anc) for ibx, bx in enumerate(ib): if bx == '0': qc.x(qcont[ibx]) qc.barrier() K_instruction = qc.to_instruction() return K_instruction def _opt_K_operation(self, qc, qcont, qtarg, anc, opt_anc, refid, rotations, dagger, rcx=True): ''' TODO: apply each optimizations separately. using ancilla, the structure is a litlle bit different from usual one. we need to care about it. ''' # If you are using rccx, the phase is destroyed # you need to fix after one iteration # HACK # make the loop with rotations # we have to detect if we can apply ancilla optimization lv_table = self._level_detector(refid) if dagger: # mapping with rccx qc = self._map_ancilla_dag(qc, qcont, qtarg, anc, opt_anc, refid, rotations, lv_table, rcx) else: # fix phase of ancilla qc = self._map_ancilla(qc, qcont, qtarg, anc, opt_anc, refid, rotations, lv_table, rcx) return qc def _level_detector(self, refid): lv_table = [] mx_bin = self.dim[0] for i in range(1, mx_bin): if i in refid: pre_i = list(self._binary_formatter(i-1, self.q_size//2)) bin_i = list(self._binary_formatter(i, self.q_size//2)) for ilv, st in enumerate(zip(pre_i, bin_i)): if st[0] != st[1]: lv_table.append(ilv) break return lv_table # FIXME too much argument def _map_ancilla_dag(self, qc, cont, targ, anc, opt_anc, refid, rotations, lv_table, rcx): ''' applying dagger operation the number of rotaions is corresponding to the number of partitions of matrix. ''' n_partitions = len(refid) - 1 # FIXME debug settings!!!!!!! # opt_level = len(opt_anc) opt_level = 2 start = min(lv_table) end = start + opt_level # mapping once from control to ancillary qubits # iopt is for pointing the index of ancillary qubits # procedure # In the case of the number of partitioin is one # 1. detect the position of partitions if the position is the # second most left or right, apply operations. # 2. else, we need to detect the level of optimization if n_partitions == 1: # HACK if refid[-1] == 1 or refid[-1] == self.dim[0] - 1: qc = self._mapping(qc, cont, opt_anc[0], False, anc) for rotation in rotations: qc = self._constructor(qc, rotation, [opt_anc[0]], targ, anc) qc.x(opt_anc[0]) # no inverse is required here else: if opt_level == self.q_size//2 - 1: # print('hello') pass # general case # print(refid) # print(lv_table) for iopt, opt in enumerate(range(start, end)): # TODO: do we have to take indices? # qc.cx(cont[opt], opt_anc[iopt]) raise Warning('Under construction') else: raise Warning('the case of the number of partition is over \ 1 is being under constructing.') # print(qc) return qc @staticmethod def _mapping(qc, cont, targ, rcx, anc): if len(cont) == 1: qc.cx(cont, targ) elif len(cont) == 2: if rcx: qc.rccx(cont[0], cont[1], targ) else: qc.ccx(cont[0], cont[1], targ) else: qc.mct(cont, targ, anc) return qc def _map_ancilla(self, qc, cont, targ, anc, opt_anc, refid, rotations, lv_table, rcx): ''' ''' n_partitions = len(refid) - 1 # FIXME debug settings!!!!!!! # opt_level = len(opt_anc) opt_level = 2 start = min(lv_table) end = start + opt_level if n_partitions == 1: # HACK if refid[-1] == 1 or refid[-1] == self.dim[0] - 1: for rotation in rotations: qc = self._constructor(qc, rotation, [opt_anc[0]], targ, anc) qc.x(opt_anc[0]) # This corresponds to the reverse operation qc = self._mapping(qc, cont, opt_anc[0], False, anc) # no inverse is required here else: for iopt, opt in enumerate(range(start, end)): # TODO: do we have to take indices? # qc.cx(cont[opt], opt_anc[iopt]) raise Warning('Under construction') else: raise Warning('the case of the number of partition is over \ 1 is being under constructing.') return qc def _qft_constructor(self): ''' Thinking if we can reduce the number of operations with qft ''' pass def _constructor(self, circuit, rotations, cont, targ, anc): # TODO check if len(rotations) == 1: circuit.mcry(rotations[0], cont, targ[0], anc) return circuit elif len(rotations) == 2: circuit.mcry(rotations[0], cont, targ[0], anc) circuit.mcry(rotations[1], cont, targ[1], anc) return circuit else: circuit.mcry(rotations[0], cont, targ[0], anc) circuit.x(targ[0]) circuit.mcry(rotations[1], [*cont, targ[0]], targ[1], anc) circuit.x(targ[0]) for irt, rt in enumerate(rotations[2:]): # insted of ccc...hhh... for tg in targ[irt+1:]: circuit.mcry(pi/2, [*cont, *targ[:irt+1]], tg, anc) circuit.x(targ[:irt+2]) circuit.mcry(rt, [*cont, *targ[:irt+2]], targ[irt+2], anc) circuit.x(targ[:irt+2]) return circuit def _get_rotaions(self, state, dagger): rotations = [] if self.basis_state != 0: raise Exception('Under construction') else: for st in state: rt = self._rotation(st, [], dagger) rotations.append(rt) return rotations def _rotation(self, state, rotations, dagger): lst = len(state) if lst == 2: if sum(state) != 0: rotations.append(2*np.arccos(np.sqrt(state[0]/sum(state)))) else: rotations.append(0) else: if sum(state) != 0: rotations.append(2*np.arccos( np.sqrt(sum(state[:int(lst/2)])/sum(state)))) else: rotations.append(0) self._rotation(state[:int(lst/2)], rotations, dagger) if dagger: rotations = [-i for i in rotations] return rotations def D_operation(self, n_anilla=0, mode='basic', barrier=False): ''' This operation is for flipping phase of specific basis state ''' # describe basis state as a binary number nq = int(self.q_size/2) basis_bin = list(self._binary_formatter(self.basis_state, nq)) # create operation qr = QuantumRegister(nq) Dop = QuantumCircuit(qr, name='D') if n_anilla > 0: anc = QuantumRegister(n_anilla) Dop.add_register(anc) for q, b in zip(qr, basis_bin): if b == '0': Dop.x(q) # creating cz operation if barrier: Dop.barrier() Dop.h(qr[-1]) Dop.mct(qr[:-1], qr[-1], None) Dop.h(qr[-1]) if barrier: Dop.barrier() for q, b in zip(qr, basis_bin): if b == '0': Dop.x(q) D_instruction = Dop.to_instruction() return D_instruction @staticmethod def _qubit_size(dim): qsize = int(np.ceil(np.log2(dim))) return 2*qsize def prob_transition(graph): pmatrix = np.zeros(graph.shape) indegrees = np.sum(graph, axis=0) for ix, indeg in enumerate(indegrees): if indeg == 0: pmatrix[:, ix] = graph[:, ix] else: pmatrix[:, ix] = graph[:, ix]/indeg return pmatrix if __name__ == '__main__': # graph = np.array([[0, 1, 0, 0], # [0, 0, 1, 1], # [0, 0, 0, 1], # [0, 1, 1, 0]]) # graph = np.array([[0, 1, 0, 0, 1, 0], # [0, 0, 0, 1, 1, 0], # [0, 0, 0, 1, 1, 1], # [0, 1, 1, 0, 0, 0], # [0, 1, 0, 0, 0, 1], # [0, 1, 0, 0, 1, 0]) # graph = np.array([[0, 0, 1, 0, 0, 0, 0, 1], # [0, 0, 0, 1, 0, 0, 1, 0], # [0, 0, 1, 0, 0, 1, 1, 1], # [0, 0, 0, 0, 0, 1, 1, 0], # [0, 0, 0, 1, 1, 1, 1, 1], # [0, 0, 0, 0, 1, 1, 1, 1], # [0, 0, 0, 0, 1, 0, 0, 1], # [0, 0, 0, 0, 1, 0, 1, 0]]) graph = np.array([[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0]]) pb = prob_transition(graph) opcreator = OperationCreator(graph, pb) # opcreator.D_operation() # opcreator.T_operation() opcreator.K_operation(dagger=True)
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag, dag_to_circuit class Converter: ''' Converting quantum circuit to dag and extract information used for optimizations ''' def __init__(self): pass def converter(self, qc): dag = circuit_to_dag(qc) return dag def reverser(self, dag): circuit = dag_to_circuit(dag) return circuit if __name__ == '__main__': q = QuantumRegister(4) qc = QuantumCircuit(q) dag = Converter().converter(qc) dag.draw()
https://github.com/Chibikuri/qwopt
Chibikuri
from .ruleset import ruleset from .converter import Converter from qiskit import transpile import sys # FIXME out of pep write __init__.py sys.path.append('../') from compiler import parser class Optimizer: def __init__(self, graph, prob_dist): pass def optimize(self, qc, n_rules, config, **kwargs): ''' qc: QuantumCircuit n_rules: the number of rules config: toml file kwargs: optimization config ''' # nqc = transpile(qc, basis_gates=['cx', 'u3']) dag = Converter().converter(qc) rule = ruleset.Rules(config) errors = [] # FIXME detect the number of rules for i in range(n_rules): dag, success = eval('rule._rule%s(dag)' % str(i)) if not success: errors.append(i) if len(errors) == 0: print('All optimization rules are applied successfully!') else: ms = str(errors)[1:-1] print('Rules, %s are not applied for some reasons!' % ms)
https://github.com/Chibikuri/qwopt
Chibikuri
from qiskit import QuantumRegister from qiskit.transpiler.passes import Unroller import toml import sys ''' FIXME This scheme might be unefficient. TODO easier to write and make some parser make rule description language with some language Thinking Rust or Python or ... ''' class Rules: ''' In this script, making the rules of how to optimize the quantum circuit and what order. The order of appling rule is rule0, rule1, rule2, ...ruleN in the default. TODO make this executable in arbitrary order ''' def __init__(self, config): ''' HACK config: converted toml (opened toml) ''' self.toml = toml.load(config) def apply_rules(self): pass def _rule0(self, dag): ''' optimization about ancillary qubits In this optimization, once map the control operations to ancillae qubits, and then, reduce the number of operations. Input: dag: DAG Output: dag: DAG, success(bool) ''' # FIXME if the position of partition is symmetry, # we can't apply this optimization because it's redundunt # procedure 1, add ancilal or find ancilla # FIXME p_rule0 = self.toml['rule0'] n_ancilla = p_rule0['n_ancilla'] # unrolling dag to basis compornents ndag = Unroller(['ccx', 'cx', 'x', 'h', 'u3']).run(dag) ndag_nodes = [i for i in ndag.nodes()] ndag_names = [i.name for i in ndag_nodes] # FIXME taking parameters dynamically dag_nodes = [i for i in dag.nodes()] if n_ancilla < 0: raise ValueError('The number of ancillary qubits \ must be 0 or over 0') # adding ancilla qubit q = QuantumRegister(n_ancilla, name='opt ancilla') dag.add_qreg(q) ndag.draw() return dag, False def _rule1(self, dag): ''' Compressing neighbor controll operations In this optimization, search which control operations can be cancelled out, and then delete them. ''' return dag, False def _rule2(self, dag): ''' Using phase optimizations In this optimiation, replace K operation with QFT or other phasian methods ''' return dag, True
https://github.com/Chibikuri/qwopt
Chibikuri
import sys sys.path.append('../../') import unittest import numpy as np from qwopt.compiler.op_creater import OperationCreator from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute, transpile STATE_VECTOR = Aer.get_backend('statevector_simulator') QASM = Aer.get_backend('qasm_simulator') class OpcreatorTest(unittest.TestCase): def test_Kop(self): graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) pb = prob_transition(graph, gtype='google') # print(pb) op_creator = OperationCreator(graph, pb) nq = op_creator.q_size shots = 100000 bins = [format(i, '0%sb' % str(nq//2)) for i in range(2**(nq//2))] cont = QuantumRegister(nq//2, 'cont') targ = QuantumRegister(nq//2, 'targ') anc = QuantumRegister(nq//2, 'ancillae') c = ClassicalRegister(nq//2) qc = QuantumCircuit(cont, targ, anc, c) qc.h(cont) Kop = op_creator.K_operation() qc.append(Kop, qargs=[*cont, *targ, *anc]) qc.measure(targ, c) nqc = transpile(qc, basis_gates=['cx', 'u3', 'h', 'x']) # print(nqc) job = execute(qc, backend=QASM, shots=shots) counts = job.result().get_counts(qc) # print(counts) prob = [counts.get(i, 0)/shots for i in bins] # print(prob)s def test_Top(self): ''' Experiment 1 for two dim ''' graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) pb = prob_transition(graph, gtype='google') op_creator = OperationCreator(graph, pb) Tops = op_creator.T_operation() nq = op_creator.q_size qr = QuantumRegister(nq) c = ClassicalRegister(nq//2) anc = QuantumRegister(nq//2) qc = QuantumCircuit(qr, anc, c) # first element is input value and second one is ideal output target = [[0, 1/np.sqrt(2), 0, 1/np.sqrt(2)], [1/np.sqrt(2), 0, 1/np.sqrt(2), 0]] qc.x(qr[0]) qc.initialize(target[0], [qr[2], qr[3]]) for ts in Tops: qc.append(ts, qargs=[*qr, *anc]) qc.measure(qr[2:5], c) shots = 100000 job = execute(qc, backend=QASM, shots=shots) count = job.result().get_counts(qc) bins = [format(i, "02b") for i in range(4)] prob = [count.get(i, 0)/shots for i in bins] # FIXME is rtol value proper? isCorrect = np.isclose([i**2 for i in target[1]], prob, rtol=1e-2) self.assertEqual(all(isCorrect), True) def test_Dop(self): graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) pb = prob_transition(graph, gtype='google') op_creater = OperationCreator(graph, pb) nq = op_creater.q_size shots = 1000 targ = QuantumRegister(nq//2, 'target') qc = QuantumCircuit(targ) Dop = op_creater.D_operation() qc.append(Dop, qargs=targ) job = execute(qc, backend=STATE_VECTOR) vec = job.result().get_statevector(qc) nqc = transpile(qc, basis_gates=['cx', 'h', 'x']) ideal = [-1.0+0.0j, -0.0+0.0j, -0.0+0.0j, -0.0+0.0j,] isCorrect = np.isclose(ideal, vec) self.assertEqual(all(isCorrect), True) def prob_transition(graph, gtype='normal', alpha=0.85): if gtype == 'google': return google_matrix(alpha, graph) else: pmatrix = np.zeros(graph.shape) indegrees = np.sum(graph, axis=0) for ix, indeg in enumerate(indegrees): if indeg == 0: pmatrix[:, ix] = graph[:, ix] else: pmatrix[:, ix] = graph[:, ix]/indeg return pmatrix def google_matrix(alpha, C): E = connect_to_E(C) N = len(C) G = alpha*E + (1-alpha)/N * np.ones((N, N), dtype=float) return G def connect_to_E(C): ''' C is conectivity matrix C: np.array output E: np.array ''' N = len(C) C = np.array(C) E = np.zeros(C.shape) rowsum = np.sum(C, axis=0) for ind, val in enumerate(rowsum): if val == 0: for j in range(N): E[j][ind] = 1/N else: for j in range(N): E[j][ind] = C[j][ind]/val assert(np.sum(np.sum(E, axis=0))==N) return E if __name__ == '__main__': unittest.main()
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
# These are versions of some of our important functions # that were duplicates or non-generalized forms that I # am retiring to here in case something goes wrong import pandas as pd import numpy as np def get_probabilities_2state_sys(states): num_total = np.shape(states)[0] * np.shape(states)[1] num_ones = np.shape(np.where(states == 1))[1] num_zeros = num_total - num_ones prob_one = num_ones/num_total prob_zero = num_zeros/num_total assert round(prob_one+prob_zero, 3) == 1. return prob_one, prob_zero def get_conditional_probability_2parent_2state(Astates, Bstates, Cstates): #I'm in progress of generalizing this in probabilities.ipynb, but feel free to pick up where I left off """A and B are parent nodes. C is child node""" num111, num101, num011, num001, num110, num100, num010, num000 = 0, 0, 0, 0, 0, 0, 0, 0 num11, num01, num10, num00 = 0,0,0,0 #Add up cases where C=1 indC_one_row = np.where(Cstates == 1)[0] #index of row with a 1 indC_one_col = np.where(Cstates == 1)[1] #index of corresponding coln with a 1 for i in range(len(indC_one_col)): # loop through all times C=1 A = Astates.iloc[indC_one_row[i], indC_one_col[i]] B = Bstates.iloc[indC_one_row[i], indC_one_col[i]] if A == 1: if B == 1: num111 += 1 #C=1, B=1, A=1 num11 += 1 #B=1, A=1 elif B == 0: num101 += 1 #C=1, B=0, A=1 num01 += 1 #B=0, A=1 elif A == 0: if B == 1: num110 += 1 #C=1, B=1, A=0 num10 += 1 #B=1, A=0 elif B == 0: num100 += 1 #C=1, B=0, A=0 num00 += 1 #B=0, A=0 # Add up states where C=0 indC_zero_row = np.where(Cstates == 0)[0] indC_zero_col = np.where(Cstates == 0)[1] for i in range(len(indC_zero_col)): # loop through all times C=0 A = Astates.iloc[indC_zero_row[i], indC_zero_col[i]] B = Bstates.iloc[indC_zero_row[i], indC_zero_col[i]] if A == 1: if B == 1: num011 += 1 #C=0, B=1, A=1 num11 += 1 #B=1, A=1 elif B == 0: num001 += 1 #C=0, B=0, A=1 num01 += 1 #B=0, A=1 elif A == 0: if B == 1: num010 += 1 #C=0, B=1, A=0 num10 += 1 #B=1, A=0 elif B == 0: num000 += 1 #C=0, B=0, A=0 num00 += 1 #B=0, A=0 # Calculate conditional probabilities num_total = np.shape(Astates)[0] * np.shape(Astates)[1] """The variable names are in the order CBA (cases, testing, stay at home). """ P111 = num111/num11 P101 = num101/num01 P110 = num110/num10 P100 = num100/num00 P011 = num011/num11 P001 = num001/num01 P010 = num010/num10 P000 = num000/num00 states = np.array(['0|00','1|00','0|01','1|01','0|10','1|10','0|11','1|11']) #I believe this is the order Matt was talking about with top to bottom, left to right in the table from the paper conditional_probabilities = np.array([P000,P100,P001,P101,P010,P110,P011,P111]) #in this order, the first two, second two, etc. should each add to 1 as pairs (columns in the paper's table) # Make graph for circuit input ProbA1, ProbA0 = get_probabilities_2state_sys(Astates) ProbB1, ProbB0 = get_probabilities_2state_sys(Bstates) graph = { 'StayAtHome': ([], [ProbA0, ProbA1]), # P(A = 0), P(A = 1) 'Testing': ([], [ProbB0, ProbB1]), #P(B = 0), P(B = 1) #P(C=0|A=0,B=0), P(C=1|A=0,B=0), P(C=0|A=0,B=1), P(C=1|A=0,B=1), P(C=0|A=1,B=0), P(C=1|A=1,B=0), P(C=0|A=1,B=1), P(C=1|A=1,B=1) 'Cases': (['StayAtHome','Testing'], [P000, P100, P010, P110, P001, P101, P011, P111]) } return states, conditional_probabilities, graph def Margies_marginal_probabilities(ntwk_results): #a combined version of this with Ella's is kept in the real code #ntwk_results: dict, counts resulting from network run (should have 2^n entries) #marg_probs: array of length n, marginal probabilities that each qubit is 0, #from most significant to least significant n = len(list(ntwk_results.keys())[0]) prob = np.zeros(n) total = sum(ntwk_results.values()) for i in range(n): for key in ntwk_results: if int(key[i]) == 0: prob[i] += ntwk_results[key] prob[i] = prob[i]/total return prob def Ella_3qubit_marginal_probabilities(pstates_dict): # Works for 3 qubits only C0, B0, A0, numtot = 0, 0, 0, 0 for key in pstates_dict: Cstate=key[0] Bstate=key[1] Astate=key[2] numtot += pstates_dict[key] if Cstate == '0': C0 += pstates_dict[key] if Bstate == '0': B0 += pstates_dict[key] if Astate == '0': A0 += pstates_dict[key] ProbC0 = C0/numtot ProbB0 = B0/numtot ProbA0 = A0/numtot return ProbC0, ProbB0, ProbA0 def Ella_marginal_probabilities_general(pstates_dict): """Works for n qubits""" n = len(list(pstates_dict.keys())[0]) #number of qubits in state Probs = np.empty(n) numZeros, numtot = np.zeros(n), 0 for key in pstates_dict: numtot += pstates_dict[key] for i in range(n): #print(i) state=key[i] if state == '0': numZeros[i] += pstates_dict[key] for i in range(n): Probs[i] = numZeros[i]/numtot return Probs # Test the marginal prob functions with some simulated output from our 3 qubit run! #pick the function to use (comment others out) funct = Ella_marginal_probabilities_general #funct = Ella_3qubit_marginal_probabilities #funct = Margies_marginal_probabilities result1 = {'000': 2783, '001': 1240, '100': 603, '111': 815, '110': 294, '010': 1712, '101': 485, '011': 260} print(funct(result1)) def get_lesser_model_states(): statedataStayHome = {'MarHome' : data['MarHome'], 'AprHome' : data['AprHome'], 'MayHome' : data['MayHome'], 'JunHome' : data['JunHome']} statesStayHome = pd.DataFrame(data=statedataStayHome) statedataTests = {'MarTest' : data['MarTest'], 'AprTest' : data['AprTest'], 'MayTest' : data['MayTest'], 'JunTest' : data['JunTest']} statesTests = pd.DataFrame(data=statedataTests) statedataCases = {'MarCases' : data['MarCases'], 'AprCases' : data['AprCases'], 'MayCases' : data['MayCases'], 'JunCases' : data['JunCases']} statesCases = pd.DataFrame(data=statedataCases) # 0 = increasing. 1 = flat or decreasing return statesStayHome, statesTests, statesCases data = pd.read_csv('data/lesser_model_data.csv') Astates, Bstates, Cstates = get_lesser_model_states() print(get_conditional_probability_2parent_2state(Astates, Bstates, Cstates)) """ # ALTERNATE SECTION OF GENERALIZED CONDITIONAL PROBABILITY CODE TO CONSIDER SHORTENING BY LIKE 3 LINES def f(c, *ps): for key in keys: num_c, tot_c = 0, 0 n = len(c) for i in range(n): all_ps = all([ps[j][i] == key[j] for j in range(len(ps))]) if all_ps: tot_c += 1 if c[i] == thing before |: num_c += 1 """ def generate_cond_keys_old(s_0, s_i): ############################################## #THIS FUNCTION WILL GENERATE A LIST OF STRINGS TO USE AS KEYS FOR CONDITIONAL PROBABILITIES ### INPUT ### # s_0 int number of states of the child node # s_i list number of states for each parent node, from most to least significant ### OUTPUT ### # list of strings to use as keys for conditional probabilities (included commas in case there is ever an >11-state node!) ############################################## ranges = [range(0, elem) for elem in list([s_0])+list(s_i)] enumed = product(*ranges) cond_keys = [] for enum in enumed: enum = list(enum) parent_str = ",".join(str(x) for x in enum[1:]) cond_keys.append("%s|%s"%(str(enum[0]), parent_str)) return cond_keys
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.providers import JobStatus from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.providers.aer.noise import NoiseModel from qiskit.tools.visualization import plot_histogram from math import * import import_ipynb import numpy as np import math import itertools from network_setup import * # Helper Functions def find_num_states(numprobs, in_edges): if in_edges == 0: # if parent node numstates = numprobs elif in_edges > 0: # if child node numstates = (numprobs/(2**(in_edges+1))) * 2 return numstates def find_numstates_parents(graph, parentvarnames): """Eqn 21 from https://arxiv.org/pdf/2004.14803.pdf""" numstates_parents = 0 for i in range(len(parentvarnames)): parent = parentvarnames[i] parentprobs = graph[parent] numprobs = len(parentprobs[1]) # number of states if parent node, number of conditional states if child node in_edges = len(graph[parent][0]) # aka num of parents of this parent numstates_parents += find_num_states(numprobs, in_edges) return numstates_parents #TODO assertAlmostEqual(angle_from_probability(0.2, 0.8), 2.2143) def angle_from_probability(p0, p1): '''Equation 20 from https://arxiv.org/pdf/2004.14803.pdf''' angle = 2 * atan2(sqrt(p1), sqrt(p0)) return angle def num_qbits_needed_general(graph): '''Equation 22 from https://arxiv.org/pdf/2004.14803.pdf''' sumterm = 0 ancillaterms = [] varnum = 0 for var in graph: probs = graph[var] numprobs = len(probs[1]) # number of states if parent node, number of conditional states if child node in_edges = len(graph[var][0]) # aka num of parents numstates = find_num_states(numprobs, in_edges) sumterm += math.ceil(np.log2(numstates)) if in_edges > 0: parentvarnames = graph[var][0] # list of parent names numstates_parents = find_numstates_parents(graph, parentvarnames) ancillaterm = numstates_parents/2 + math.ceil(np.log2(numstates)) - 1 ancillaterms.append(ancillaterm) qbits = sumterm + max(ancillaterms) -1 # equation (22) WITH AN EXTRA -1 cbits = sumterm # number of measurements return (qbits, cbits) def num_qbits_needed(graph): '''Equation 15 from https://arxiv.org/pdf/2004.14803.pdf''' max_edges = -1 for state in graph: in_edges = len(graph[state][0]) # aka num of parents if in_edges > max_edges: max_edges = in_edges qbits = len(graph) + max_edges - 1 # equation (15) cbits = len(graph) # number of measurements return (qbits, cbits) def run_circuit(circuit, output_file='results', draw_circuit=True, use_sim=True, use_noise=False, use_qcomp=False, shots=1024): if draw_circuit: %config InlineBackend.figure_format circuit.draw(output='mpl') if use_noise or use_qcomp: IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_qasm_simulator') if use_sim: simulator = Aer.get_backend('qasm_simulator') if use_noise: noise_model = NoiseModel.from_backend(qcomp) basis_gates = noise_model.basis_gates coupling_map = qcomp.configuration().coupling_map job = execute(circuit, backend=simulator, coupling_map=coupling_map, noise_model=noise_model, basis_gates=basis_gates, shots=shots) else: job = execute(circuit, backend=simulator, shots=shots) print(job.result().get_counts()) plot_histogram(job.result().get_counts()).savefig(output_file+"-sim.png") if use_qcomp: job = execute(circuit, backend=qcomp, shots=shots) job_monitor(job) if(job.status() == JobStatus.ERROR): print("Error: Check with IBMQ") print(job.result().get_counts()) plot_histogram(job.result().get_counts()).savefig(output_file+'-qcomp.png') return job.result() def check_node_processed(bit_assignment, node): # split node into states states = node.replace(' ','').split(',') if len(states) <= 2: # qbit has been assigned return node in bit_assignment else: # this means multistate qbits have been processed (down to LSB) return (node +'q0') in bit_assignment def add_cnry(circuit, n, angle, control_bits, target, ancilla_bits): ''' Creates generalized cny gate for any n. circuit: existing circuit to modify n: number of control bits required (number of "C"s wanted for this gate) angle: angle to rotate by (rad) control_bits: list (len n) target: qbit you want to rotate ancilla_bits: list (len n-1); these are left clean (in same state as initially) Note: could also try rewriting using Qiskit's built-in mcx gates https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.mcx.html https://qiskit.org/documentation/tutorials/circuits_advanced/1_advanced_circuits.html ''' # TODO Qiskit has some of these higher order gates implemented # Check that Qiskits version matches whats described in the paper and change to those if n == 1: circuit.cry(angle,control_bits[0],target) return circuit # assert some things are true assert n >= 2 assert len(control_bits) == n assert len(ancilla_bits) >= n-1 #circuit.barrier() # for visualization # hardcode first ccx gate circuit.ccx(control_bits[0], control_bits[1], ancilla_bits[0]) # loop to create ccx gates for i in range(2, n): circuit.ccx(control_bits[i], ancilla_bits[i-2], ancilla_bits[i-1]) # add rotate block circuit.cry(angle, ancilla_bits[n-2], target) # loop to create remaining ccx gates for i in range(n-1, 1, -1): circuit.ccx(control_bits[i], ancilla_bits[i-2], ancilla_bits[i-1]) # hardcode last ccx gate circuit.ccx(control_bits[0], control_bits[1], ancilla_bits[0]) #circuit.barrier() # for visualization return circuit def controlled_m_qbit_rotation(circuit, control_qbits, target_qbits, probs, ancilla_bits): ''' From Fig. 9 in paper recursive to build m-1 rotation (decompose rotation gate)''' if len(target_qbits) == 0: return circuit # how many target qbits do we have? num_targets = len(target_qbits) p0 = 0 for i in range(2**(num_targets-1)): # prob that the qbit is 0 p0 += probs[i] p1 = 0 for i in range(2**(num_targets-1), min(len(probs), 2**(num_targets))): p1 += probs[i] angle = angle_from_probability(p0, p1) # add controlled rotation gate qc = add_cnry(circuit, len(control_qbits), angle, control_qbits, target_qbits[0], ancilla_bits[:(len(control_qbits)-1)]) # recursively add another controlled m rot for MSB = 1 qc = controlled_m_qbit_rotation(circuit, control_qbits+[target_qbits[0]], target_qbits[1:], probs[2**(num_targets-1):], ancilla_bits) # now add an x gate qc.x(target_qbits[0]) # add another controlled m rot for MSB = 0 qc = controlled_m_qbit_rotation(circuit, control_qbits+[target_qbits[0]], target_qbits[1:], probs[:2**(num_targets-1)], ancilla_bits) # add one last x gate qc.x(target_qbits[0]) return qc # This is the heavy lifter of the project # This function turns a graph into the quantum circuit def create_circuit(graph, qc, starting_qbit=0, ancilla_bits=[]): # Create a dictionary to hold which states are assigned to which qubits and counters to track the allocation bit_assignment = {} last_free_qbit = qc.num_qubits-1 next_free_qbit = starting_qbit # Allocate ancilla_bits # Count number of qbits needed and the remaining bits are ancillia needed_qbits = 0 for node in graph: num_states = len(node.split(',')) if num_states == 1: num_states = 2 needed_qbits += ceil(log2(num_states)) if ancilla_bits == []: for i in range(qc.num_qubits-needed_qbits): ancilla_bits.append(last_free_qbit) last_free_qbit -= 1 else: pass # TODO Assert we have enough qubits ############################## PARENTLESS/ROOT NODES ############################## # loop and find the parentless/root nodes, assign their rotations first # States are ',' seperated for node in graph: number_of_parents = len(graph[node][0]) if number_of_parents == 0: probs = graph[node][1] # how many states does this parentless/root node have? root_states = node.replace(' ','').split(',') if len(root_states) <= 2: # root node has 2 states, simple controlled rotate qc.ry(angle_from_probability(probs[0], probs[1]), next_free_qbit) # keep track of what node is what qbit bit_assignment[node] = next_free_qbit next_free_qbit += 1 else: # root node has 2+ states needed_qbits = ceil(log2(len(root_states))) sub_start_qbit = next_free_qbit # bit allocation time for i in range(needed_qbits): bit_assignment[node+'q'+str(i)] = next_free_qbit next_free_qbit += 1 # Create a graph for the recursive call and populate it sub_graph = {} sub_probs_list = [] # now calculate rotations for i in range(needed_qbits-1, -1, -1): sub_parents_list = [] sub_probs_list = [] for j in range(needed_qbits-1, i, -1): # get a list of sub parents # Sub_parent names are just the index of the qubit, not symbolic sub_parents_list.append(str(j)) # Calculate marginal probabilities from subsets of the table for k in range(0, len(probs), int(2**(i+1))): subsubsub_probif0 = 0 subsubsub_probif1 = 0 for x in range(k, k+int(2**(i)), 1): subsubsub_probif0 += probs[x] for x in range(k+int(2**(i)), min(int(k+2**(i+1)), len(probs)), 1): subsubsub_probif1 += probs[x] total = subsubsub_probif0 + subsubsub_probif1 sub_marg_0 = subsubsub_probif0 / total sub_marg_1 = subsubsub_probif1 / total sub_probs_list.append(sub_marg_0) sub_probs_list.append(sub_marg_1) # now we have completete sub parent and sub prob lists sub_graph[str(i)] = (sub_parents_list, sub_probs_list) # Recursively call this function to implement the sub graph (qc, _, ancilla_bits) = create_circuit(sub_graph,qc, sub_start_qbit, ancilla_bits) ############################## PARENTED NODES ############################## # now deal with all other parented nodes qc.barrier() # for visualization # loop and find each node that has all its parents complete and add it # TODO: A topological sort will prevent useless looping and this while True block while True: # loop until no states are added found_new = False for node in graph: # Get all the states for this node states = node.replace(' ','').split(',') # Check that this node is unprocessed but all it's parents are if check_node_processed(bit_assignment, node): # node has been processed continue all_parents = True # flag to detect if all parents are processed for parent in graph[node][0]: # check if parent has been processed if not check_node_processed(bit_assignment, parent): # parent has not been processed :( try a new node all_parents = False break if not all_parents: # check next node continue # otherwise, now we found a node we are ready to process! number_of_parents = len(graph[node][0]) found_new = True # do bit assignments if len(states) <= 2: needed_qbits = 1 bit_assignment[node] = next_free_qbit target_qbits = [next_free_qbit] next_free_qbit += 1 else: # node has 2+ states needed_qbits = ceil(log2(len(states))) sub_start_qbit = next_free_qbit target_qbits = [] # bit allocation time for i in range(needed_qbits): bit_assignment[node+'q'+str(i)] = next_free_qbit target_qbits.append(next_free_qbit) next_free_qbit += 1 # count number of columns in prob table # This is done by counting the number of states in the parents and the child # This determines the implied shape of the probability table # TODO: The table should just have this shape count = 1 parent_state_enumeration = [] for parent_states in graph[node][0]: parent_state = parent_states.replace(' ','').split(',') if len(parent_state) == 1: parent_state_enumeration.append([0,1]) count *= 2 else: count *= len(parent_state) parent_state_enumeration.append([i for i in range(len(parent_state))]) parent_state_total = itertools.product(*parent_state_enumeration) # Now encode each collumn in the probability table into the circuit for i, parent_state_combo in enumerate(parent_state_total): ########## ADD FIRST ROW OF X GATES IF PARENT QUBIT IS 0 ########## assert len(parent_state_combo) == number_of_parents all_parent_qbits = [] # loop through node's parents for j, parent in enumerate(graph[node][0]): # convert to binary string (on a per parent basis) num_parent_bits = ceil(log2(len(parent.split(',')))) # This allows 2 state nodes to optionally not have a comma if len(parent.split(',')) == 1: num_parent_bits = 1 #FIXME: There has to be a better way to detect where to apply X gates current_state = bin(parent_state_combo[j])[2:].zfill(num_parent_bits)[::-1] # apply x gates to each one of the qbits for each parent (going down) if num_parent_bits == 1: # only one bit all_parent_qbits.append(bit_assignment[parent]) if current_state == '0': # add an x gate qc.x(bit_assignment[parent]) else: # Multibit parent, selectivly X for k in range(num_parent_bits): current_parent_bit = bit_assignment[parent+'q'+str(k)] all_parent_qbits.append(current_parent_bit) if current_state[k] == '0': qc.x(current_parent_bit) ########## ADD ROTATION GATES ########## this_num_states = len(states) if this_num_states == 1: this_num_states = 2 probs = graph[node][1] # Extract this collumn of probabilities this_state_probs = probs[(i*this_num_states):(i+1)*this_num_states] qc.barrier() qc = controlled_m_qbit_rotation(qc, all_parent_qbits, target_qbits, this_state_probs, ancilla_bits) qc.barrier() ########## ADD SECOND ROW OF X GATES ########## # loop through node's parents and add the complementary X gates as done above # TODO This should be a function, not repeated code for j, parent in enumerate(graph[node][0]): # convert to binary string (on a per parent basis) num_parent_bits = ceil(log2(len(parent.split(',')))) if len(parent.split(',')) == 1: num_parent_bits = 1 current_state = bin(parent_state_combo[j])[2:].zfill(num_parent_bits)[::-1] # apply x gates going back up if num_parent_bits == 1: # only one bit if current_state == '0': # add an x gate qc.x(bit_assignment[parent]) else: for k in range(num_parent_bits): current_parent_bit = bit_assignment[parent+'q'+str(k)] if current_state[k] == '0': # add an x gate qc.x(current_parent_bit) qc.barrier() # done!!! if not found_new: # completed a full loop over the nodes and all were added break # Report Bit Assignments, also returned print(bit_assignment) return (qc, bit_assignment, ancilla_bits) def make_circuit(network, size=(4,3), draw = True): graph = build_graph(network) qc = QuantumCircuit(size[0], size[1]) qc, bits, _ = create_circuit(graph, qc) if draw == True: qc.draw(output="mpl") for i in range(len(bits)): qc.measure(i,i) return qc #change lesser here to alabio or mallard to try different example covid models #Mallard requires 16 qubits and has 10 measurable states, size=(4,3) #Alabio requires size=(32,16) qc = make_circuit(get_lesser_model_nodes, size=(4,3)) result = run_circuit(qc, "lesser_model", draw_circuit=True, shots=1024, use_sim=True, use_qcomp=False, use_noise=False) # Here are the first 2 examples from the paper # The paper provides full circuits for these graphs that can be compared against to ensure accuracy # size = (5,4) oil_graph = {'IR': ([], [.75, .25]), # From 2004.14803, Fig 10 'SM': (['IR'], [.3, .7, .8, .2]), #P(0|!A), P(1|!A), P(0|A), P(1|A) 'OI': ([], [.6, .4]), 'SP': (['OI', 'SM'], [.9, .1, .5, .5, .4, .6, .2, .8]) } # size = (12,10) liquidity = {'X1': (['X9'], [.488,.552,.067,.933]), 'X2': (['X4'], [.76,.24,1,0]), 'X3': (['X5'], [1,0,.949,.051]), 'X4': (['X9', 'X1'], [.151,.849,.874,.126,1,0,1,0]), 'X5': (['X8','X4'],[0,1,0,1,.723,.277,.311,.689]), 'X6': ([], [.98,.02]), 'X7': (['X6'],[.988,.012,.429,.571]), 'X8': (['X7'],[.006,.994,.875,.125]), 'X9': (['X8'],[0,1,.982,.018]), 'X10': (['X4','X2','X1'],[.684,.316,0,1,0,1,.474,.526,1,0,0,1,.481,.519,1,0]) }
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
import numpy as np import matplotlib.pyplot as plt import operator from qiskit.tools.visualization import plot_bloch_multivector from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit import QuantumCircuit, Aer, execute, IBMQ import import_ipynb import circuitgenerator as circ def determine_color(state): if state == '0': color='red' elif state=='1': color='green' elif state=='2': color='forestgreen' elif state=='3': color='darkgreen' return color def make_counts_hist(counts_results): probabilities = np.array([counts_results[k] for k in counts_results]) / sum(counts_results.values()) print(probabilities) plt.bar(list(counts_results.keys()), counts_results.values()) plt.ylabel('Counts') plt.xticks(list(counts_results.keys()), [None]) xpos_text = -0.3 for key in counts_results: Cstate=key[0] Bstate=key[1] Astate=key[2] Ccolor, Bcolor, Acolor = determine_color(Cstate, Bstate, Astate) plt.text(xpos_text, -200,'Cases', color=Ccolor) plt.text(xpos_text, -400, 'Tests', color=Bcolor) plt.text(xpos_text, -600,'Home', color=Acolor) xpos_text += 1 plt.show() return def get_marginal_probabilities(state_counts, whichstate=0): #state_counts: dict, counts for each state from network result (should have 2^n entries) #whichstate: integer representing the state that you want the marginal probability of (for a 2-state system this #could be 0 or 1). #marg_probs: array of length n, marginal probabilities that each qubit is whichstate, #from most significant to least significant qubit n = len(list(state_counts.keys())[0]) #number of qubits prob = np.zeros(n) total = sum(state_counts.values()) for i in range(n): for key in state_counts: if int(key[i]) == whichstate: prob[i] += state_counts[key] prob[i] = prob[i]/total return prob def make_prob_hist(counts_results, var_labels, top_n_probs='all', whichvar=['all',2], probdict={}): """ INPUTS: counts_results: dictionary from circuitgenerator where keys are multi-qubit states and values are counts var_labels: IF WHICHVAR[0] = 'all': list of strings of variable names. Order of variable names in var_labels needs to be the same as the order of variables in a multi-qubit state in counts_results IF WHICHVAR[0] is not 'all': list of strings of state names for the variable chosen in whichvar top_n_probs: optional. So that you can make a histogram of n most likely probabilities. Default='all'. Change to integer if you only want top n whichvar: list- first entry integer giving index of the variable in a key of counts_results that you want to marginal probabilities for. Default='all' includes all variables and doesn't calculate marginal probabilities. Second entry is the number of states that variable can be in. Default is 2 states. probdict: dictionary of probabilities you want a histogram of. keys will be label on x axis and values will be probabilities. """ if probdict == {}: counts_results = dict(sorted(counts_results.items(), key=operator.itemgetter(1),reverse=True)) #sorts dictionary by decreasing counts probabilities = np.array([counts_results[k] for k in counts_results]) / sum(counts_results.values()) else: #this example is to plot most probable ways to get decreasing deaths or cases probabilities = probdict plt.bar(probabilities.keys(), probabilities.values()) plt.ylabel('Probability') plt.xticks(rotation=90) plt.title('Most Probable ') plt.show() return if (top_n_probs == 'all') & (whichvar[0] == 'all'): plt.bar(np.arange(len(counts_results)), probabilities) plt.ylabel('Probability') plt.xticks(np.arange(len(counts_results)), [None]) xpos_text = -0.3 for key in counts_results: for i in range(len(key)): state=key[i] color = determine_color(state) plt.text(xpos_text, -0.03-0.02*i,var_labels[i], color=color) xpos_text += 1 plt.show() elif (top_n_probs != 'all') & (whichvar[0] == 'all'): plt.bar(np.arange(top_n_probs), probabilities[0:top_n_probs]) plt.ylabel('Probability') plt.xticks(np.arange(top_n_probs), [None]) xpos_text = -0.3 counter = 0 for key in counts_results: if counter < top_n_probs: for i in range(len(key)): state=key[i] color = determine_color(state) plt.text(xpos_text, -0.03-0.02*i,var_labels[i], color=color) xpos_text += 1 counter += 1 plt.show() elif (top_n_probs == 'all') & (whichvar[0] != 'all'): pvar = [] for i in range(whichvar[1]): pvar.append(get_marginal_probabilities(counts_results, whichstate=i)[whichvar[0]]) plt.bar(np.arange(whichvar[1]), pvar) plt.ylabel('Probability') plt.xticks(np.arange(whichvar[1]), [None]) xpos_text = -0.3 for i in range(len(pvar)): state = i color = determine_color(str(state)) plt.text(xpos_text, -0.07,var_labels[i], color=color) xpos_text += 1 plt.show() elif (top_n_probs != 'all') & (whichvar[0] != 'all'): pvar = [] for i in range(whichvar[1]): pvar.append(get_marginal_probabilities(counts_results, whichstate=i)[whichvar[0]]) numbars = min(whichvar[1], top_n_probs) plt.bar(np.arange(numbars), pvar) plt.ylabel('Probability') plt.xticks(np.arange(numbars), [None]) xpos_text = -0.3 for i in range(numbars): state = i color = determine_color(str(state)) plt.text(xpos_text, -0.07,var_labels[i], color=color) xpos_text += 1 plt.show() return results = {'000': 2783, '001': 1240, '100': 603, '111': 815, '110': 294, '010': 1712, '101': 485, '011': 260} results_maxtomin = {'000': 2783, '010': 1712, '001': 1240, '111': 815, '100': 603, '101': 485, '110': 294, '011': 260} graph = {'StayAtHome': ([], [0.645, 0.355]), 'Testing': ([], [0.62, 0.38]), 'Cases': (['StayAtHome', 'Testing'], [0.8181818181818182, 0.18181818181818182, 0.8412698412698413, 0.15873015873015872, 0.7068965517241379, 0.29310344827586204, 0.23076923076923078, 0.7692307692307693])} alabio_counts_results = {'0001010100100101': 8, '0001101100011011': 2, '0101010011010100': 2, '0000111101100001': 1, '0001011000101011': 1, '0001111011100111': 1, '0000111001001000': 1, '0000110101000100': 1, '0001101101011000': 6, '0001110101010000': 1, '0000010001001001': 1, '0000001001011010': 1, '0000110101010100': 4, '0001110010011001': 2, '0001100110011010': 2, '0000101111101000': 16, '0011000011111001': 1, '1001010010101000': 9, '0000110110101011': 2, '0000000101001000': 2, '0000110101001000': 1, '1000000110010101': 1, '0001111011101010': 1, '1001111100011010': 2, '0000110000101010': 2, '0001001011010100': 3, '0000011010011000': 3, '0001000001110100': 1, '0001001101101010': 12, '0010101101010100': 1, '1000100000111000': 1, '0000101000101001': 6, '0001000101010100': 1, '0000110100011010': 6, '0000001111011010': 1, '0000010010011011': 1, '0001000100010001': 1, '0100010110100101': 3, '0000000101101001': 11, '1111010101010111': 3, '0000000000101000': 7, '0001011010111010': 1, '0001100000101010': 2, '1001111001011001': 1, '0001001011101011': 5, '0000011100100001': 1, '0000011101011001': 4, '1101011100100100': 1, '0001110100011011': 1, '0001000011001010': 1, '0001010100001000': 2, '0010011011100100': 3, '0000010110011010': 1, '0000110011001010': 1, '0000011011010101': 1, '0000010001100110': 1, '1010100010111001': 1, '1000000011011011': 1, '0000010010011000': 4, '0001111101111010': 1, '0000101111011010': 2, '0000110011011010': 2, '0001001010101011': 4, '1100000101100101': 2, '0000100111011001': 5, '0111010010111001': 1, '0001000111101001': 14, '1000100010011010': 1, '0101110111100101': 2, '0000110011010101': 2, '0001110100111010': 2, '0000001100011001': 1, '0001011010010010': 1, '0001001100101011': 5, '0000111110101000': 11, '0001100101100100': 3, '0000110100011011': 1, '0000011000101001': 2, '0000010101011001': 6, '0001100110010101': 2, '0000010101001000': 1, '0001110110101010': 4, '0000110000100110': 1, '0000011001101010': 3, '0000000100101011': 3, '0001111011011011': 2, '1001111001101000': 5, '1111111100101010': 3, '0001001100001011': 1, '1001010101100101': 1, '0110001000100100': 2, '1000101011011010': 2, '0000010011101010': 3, '0000010100100110': 1, '0001110010011010': 1, '0000111100101000': 9, '0110110010111001': 2, '0001000110111001': 1, '0001110100101011': 1, '0001000101010001': 1, '1000101011101010': 3, '0000010011010100': 1, '0000100101001001': 2, '0000100101100000': 2, '1001010010101011': 2, '0000100110011001': 5, '0000111100001010': 1, '0000111101000101': 1, '0111011101101011': 6, '1110101010100100': 1, '0100001100010110': 1, '0011001010100101': 3, '0000000010101000': 12, '0000001011011001': 7, '0000000000011010': 1, '0001110110101000': 7, '0000101010101010': 6, '0000111111101011': 2, '0010010100100100': 1, '0101011011101001': 14, '0011111011101000': 2, '0001111110011000': 5, '0001011010010000': 1, '0000101101011000': 17, '0001011001101010': 2, '0000100001101010': 4, '0001000100100110': 1, '0000011100101000': 6, '0001010001100101': 1, '0000101111011001': 6, '0001010010111010': 1, '0001011010010101': 3, '0001100000101000': 3, '1001010110101011': 1, '0000111110101011': 1, '0100110010010100': 1, '0000010110100100': 1, '0001111111101010': 2, '0001110011011000': 7, '0001011110101011': 2, '0000110110001001': 1, '0001010000100101': 1, '0001100110100100': 3, '0001010110001001': 1, '0000001101001001': 1, '0001111000101000': 1, '0001100001011001': 2, '0001001001101001': 11, '0000101000101010': 3, '0001110000011000': 1, '0000001011011010': 1, '0001010110111000': 3, '1001010110101001': 2, '0000011010011010': 1, '0111011100101011': 7, '0000110100100100': 1, '0000011101111001': 1, '0001011111101000': 13, '0000010010101010': 3, '0001110111101011': 1, '0000001011010111': 1, '0000100010100100': 2, '0000111111010010': 1, '0000000100111000': 1, '0001010011011010': 5, '0000001111011001': 2, '0000101101010011': 1, '0000110011101001': 11, '0000110111011010': 1, '0010111110010101': 2, '0111010010100100': 3, '0000011010011011': 2, '0000111011011000': 5, '0010111010101000': 20, '0001001000110101': 1, '1110101001100100': 2, '0110111100010110': 1, '1100101011101001': 11, '0001000001101001': 6, '0000010111100110': 1, '0000001111010111': 1, '0000110101011000': 19, '0001000111010000': 1, '0000000111111001': 1, '0001000011011000': 25, '0000100001010100': 1, '0001001100011011': 1, '0001011011100110': 2, '0000110101100101': 4, '0001100100101010': 3, '0001100101101000': 16, '0000110001101000': 14, '0000110110101001': 11, '0001001110101000': 10, '0001000011101011': 4, '0000110100011001': 11, '0000110101101001': 20, '0000111100111001': 1, '0000110000101000': 11, '0001100010011001': 2, '0001100010011010': 1, '1001010101101001': 14, '0110000000100101': 1, '0001010111101011': 3, '0000110101001001': 2, '1100101010101001': 7, '0010110100100100': 2, '0000110111010100': 1, '0001000101111001': 1, '0100110111100101': 3, '0001010100011000': 29, '0000011000010000': 1, '0000111011010111': 1, '0001110100011000': 7, '1101011100100101': 2, '0000010110001001': 1, '0000000011011001': 1, '0000011111011010': 3, '0001101010011001': 3, '0111011100010110': 2, '0000110010011000': 13, '0001001110101011': 4, '0001111100011001': 2, '0001000101000110': 1, '0000001101100100': 2, '0000000010100001': 1, '1000001100011000': 4, '0000110011011011': 3, '0000010111010111': 1, '0001000110110100': 1, '1000100000101001': 1, '0110001011010100': 1, '0001000111100011': 1, '0001010111001000': 3, '0001110101111000': 2, '0101001110010101': 2, '0000000001011010': 1, '0000000101101010': 2, '0001000111101010': 8, '0001100101011001': 10, '0000110111001001': 1, '0001000010010001': 1, '0000110000111000': 2, '0001111110001000': 1, '0001000111100100': 2, '0001101011010101': 1, '0001000001101011': 7, '0001010101111010': 2, '0000001110011001': 2, '0001011010100110': 2, '0000101100011000': 11, '0001011110011000': 11, '0111000000010111': 1, '0010110101100100': 2, '0001011001010110': 1, '0001001000111000': 1, '0001011101010001': 1, '0001100011011001': 4, '0010101111010101': 1, '0010111011100100': 1, '0001101100100000': 2, '0001011101110001': 1, '0001101110101000': 8, '0001110100101001': 9, '0001010011010000': 1, '0001100011100000': 1, '0000111011111011': 1, '0001010101100110': 2, '0001100110101001': 6, '0001001100101010': 11, '0001011110111000': 2, '0001100110011001': 4, '0101011101101000': 18, '1001010110011001': 2, '0001010011011011': 1, '0000000101010100': 1, '0001001000011000': 9, '0101100100100101': 2, '0000111111011010': 2, '0001101101100110': 1, '1100100101100111': 1, '1000000110101011': 1, '0100000011010100': 1, '0000011000100111': 2, '0001111010111000': 3, '0001001101010001': 1, '0000100110010101': 1, '0000110101100001': 1, '0001110011010101': 1, '0000100101001000': 1, '1100100101100101': 3, '0001111010010101': 1, '0001011100101001': 23, '0001010110001010': 1, '0001011010101011': 6, '1001010101110100': 2, '0000111101011011': 2, '0001010001011001': 5, '0000010000101000': 3, '0000100111010101': 2, '0001111101011000': 6, '0001010111100100': 4, '0001011010011001': 9, '0101010101010100': 1, '0000001000011001': 3, '1001111100011001': 2, '0001101010011010': 2, '0001111011010000': 1, '0000110110010011': 1, '0000100001101000': 12, '0001010011101011': 4, '0001110101011001': 4, '1000000011101000': 9, '0001010110101000': 22, '0001000011100110': 3, '0100010111010101': 1, '0000010100100101': 2, '0000110101011011': 5, '0001101001101010': 1, '0001000111111001': 1, '0110110010100100': 4, '0000110100101001': 24, '0001001001100101': 2, '0011111100100100': 3, '0000110001011000': 7, '1000001100011001': 3, '0001110111100100': 1, '0000110011010110': 1, '0000000000011011': 2, '0001100000111011': 1, '0001011000011001': 6, '0000011100011011': 2, '0010111100100100': 2, '0001101100001000': 3, '1001010011001000': 1, '0000111001011011': 1, '0001011101100110': 2, '0000110111101011': 1, '0000101100111000': 1, '0001000101111000': 2, '0000101001101010': 2, '0000000101110101': 1, '0101011011100101': 2, '0011101010101000': 9, '1011111011101000': 5, '1001010110101000': 9, '1001010101100100': 5, '1111111100010110': 1, '0001011110010101': 2, '0000010010011001': 3, '0001001101101011': 6, '0001101011011010': 2, '0000001101111010': 1, '0000110001010100': 1, '0000010110011001': 1, '0000000100011000': 11, '0000010000001001': 1, '0001001001101010': 3, '0001000100010101': 4, '0001001011011001': 13, '0100111010101001': 15, '0000100101101011': 3, '1000000010100100': 1, '0001100010100110': 1, '0000010101100101': 2, '1000101001111000': 2, '1001010110011011': 1, '0001000011111000': 4, '0000011001101011': 1, '0000110100011000': 14, '0100001011101001': 4, '1001010101011000': 12, '0101110011100101': 2, '0001100011100100': 4, '0000011110111000': 1, '1011001101010100': 2, '1000101011000100': 1, '0000010100100010': 1, '0001001000101001': 6, '0000111110011001': 5, '0001100100010100': 2, '0000100101101010': 8, '0000111010100110': 1, '0000011001101000': 2, '0110110011111001': 1, '0001110001011001': 2, '0000110011110100': 1, '0101000101100101': 10, '1000001100101011': 2, '0000100010011010': 1, '0100011101101000': 5, '0000000010010100': 1, '0001110100101010': 3, '0000010111010100': 1, '1001010101100110': 2, '0001010111101010': 7, '0001111111011011': 1, '0001100010100001': 1, '0011101010100100': 1, '0001001011001000': 1, '0000010101101000': 22, '0001010100010101': 4, '0000111100010100': 2, '0000011100011010': 4, '0000010010100111': 1, '0001001010100110': 1, '0000111111000110': 1, '0001010000100100': 1, '0000100011101010': 2, '0000100011011011': 1, '0001000000001001': 1, '0001010101101001': 18, '0001110101001010': 1, '0000111101100111': 1, '0000010000100101': 1, '0001001100011010': 4, '0001011001101000': 9, '1110101001101011': 1, '0001001110111001': 1, '0000011010111000': 1, '0001000111100101': 3, '0000010101111000': 1, '0001111011011010': 1, '1001010101001001': 1, '0001101010011000': 5, '0001101111011010': 2, '0000000101011001': 7, '0001010001101000': 16, '0001110100100100': 3, '0000010101101010': 3, '1001010011011000': 5, '0001010111011011': 2, '0001000100101010': 10, '0001000100001011': 1, '0000011011101010': 4, '0000110010101000': 26, '0001111100101000': 5, '0001101010001001': 1, '0000100110100100': 3, '0000111000101000': 4, '0011001100010100': 2, '1110101011010110': 1, '0000010100011011': 2, '0110100000100101': 1, '0000011100010100': 1, '1000000011011000': 7, '0000101001101001': 4, '0000110010011010': 3, '1100101101010110': 1, '0001001100011000': 21, '0000011101001001': 1, '0000010101011010': 3, '1000101011010101': 1, '1100100111010111': 1, '0001101101011001': 2, '0000010100010101': 3, '0000111101011010': 5, '0100010110010101': 1, '0001011101011001': 20, '0001101100101000': 12, '0000011110011011': 2, '0000001110101010': 1, '0000100110001000': 2, '0000111000010000': 1, '0000111100011001': 8, '0011000010111001': 1, '0001011111010000': 1, '0111000101010110': 1, '0001001101101001': 26, '0001100111111011': 1, '0001110100100101': 1, '0001010110101010': 2, '0000111001011001': 4, '0000111010011001': 4, '0000111001011000': 5, '0110101011010100': 1, '0001011110101010': 4, '0100000010101001': 6, '0001010100011010': 3, '0001010011100111': 2, '0001001101100010': 1, '0001110101100100': 2, '0000011111011011': 1, '0001000110010100': 2, '0001010001001010': 2, '0001011110010001': 1, '0001000010011000': 20, '0001000100100100': 8, '0000110001100000': 1, '0000101000010111': 1, '0001000010111011': 1, '1111010111100100': 1, '0011101100010100': 2, '0000001011001000': 1, '0011000010010000': 2, '0000111000010100': 1, '0000101010110100': 1, '0001001001011011': 1, '0000010001010101': 1, '0000101111011000': 10, '0110110011010100': 1, '0001000101011001': 15, '0000110000001000': 1, '1000001100101001': 5, '0001100101001001': 2, '0001100011011000': 4, '0001000110011011': 1, '0000110111101000': 15, '0001000101101011': 4, '0001010011101010': 5, '0001000100100000': 1, '0000000100101001': 11, '0000111101001001': 1, '0000010010010001': 2, '0001000001101010': 8, '0000100110001001': 1, '0000001000011000': 3, '0001111111101000': 7, '0000110011010111': 1, '0001001000010100': 3, '0000111010010000': 1, '0000011111111001': 1, '0001001110100100': 4, '0000110100111001': 2, '0001110010011011': 3, '0001000011000100': 1, '0001101000101001': 2, '1000000010101011': 2, '0001101001011001': 1, '0001100001101001': 2, '0000110100111000': 3, '0001000010111000': 2, '1001010010011000': 3, '0101011110010100': 2, '0110000011100111': 1, '0001000011100000': 1, '0001000100001000': 4, '0011001011100100': 1, '0001101000011010': 1, '0000100011010101': 2, '0000100101010101': 3, '0111101010010100': 1, '0101001000100110': 2, '0001101110111010': 1, '0000001101010100': 1, '0001010111100110': 3, '0000000100001001': 1, '0001000100011000': 27, '0001010001101010': 7, '0001011100011001': 10, '1001010011101001': 5, '0110111100101011': 2, '0001010000011001': 6, '0011001011101000': 26, '0110000001100100': 1, '0000100110011011': 1, '0001100001101011': 1, '0001001110011011': 1, '0000111010011011': 4, '0000000001101011': 2, '0000110111100000': 1, '0001010011011000': 16, '0001000011011001': 21, '1011011101100100': 4, '0001011100001000': 3, '0000011110011010': 2, '0000010111101000': 8, '0001101000011000': 1, '1000000010100110': 1, '0000010111100100': 1, '0001010100111001': 2, '1000101011100000': 1, '0000000001011001': 4, '0001100010100100': 2, '0001010101100000': 1, '0000011001101001': 4, '0000111110000110': 1, '1000001100010111': 1, '0000100100111010': 1, '0000001101101011': 1, '0001111111011001': 3, '0001001011010000': 1, '0001010001010100': 1, '0001100110111001': 1, '0000110010010101': 3, '0000101100001010': 1, '0000001010011001': 4, '0001011011101011': 2, '0000010110010100': 1, '0000110100010000': 1, '0000101001011000': 1, '0000110110111011': 1, '0101001010101001': 24, '0001101101100101': 2, '0000010101011000': 6, '0001000000011001': 7, '0000110100001001': 2, '0000010100101010': 8, '1001010010101010': 4, '0000111110101010': 3, '0000111110110101': 1, '0111110101010110': 1, '1000101011010100': 1, '0001011101011010': 8, '0000101000001000': 2, '0000111111110100': 1, '0011001010101000': 21, '0001010001011011': 1, '0000010110100000': 1, '0000001100011011': 3, '0000000100101010': 5, '0000100101110111': 1, '1000000110011001': 2, '0001001000111001': 1, '0000101100001011': 1, '0101111101101000': 8, '0000110011110110': 1, '0101111011100101': 1, '0000011101010010': 1, '0101010111010101': 1, '0101100100010100': 1, '0001000110011001': 8, '0001000111111011': 1, '0001100001011000': 3, '0001110101011000': 11, '0000101101110111': 1, '0001010010010001': 1, '0001010111111000': 4, '0000101100101001': 16, '0001011100001001': 1, '0000111000001001': 1, '0001000110101010': 5, '1000000011011001': 1, '0000100010011000': 12, '0110000000100100': 2, '0001000110101000': 29, '0001100101011011': 1, '0001100010100000': 3, '0000010100111000': 1, '0000110011011001': 5, '0001110101101011': 3, '0111100000100100': 3, '0010111011101000': 20, '0000111001101000': 10, '0001001100001001': 2, '0001010111111001': 1, '0000001001101001': 2, '0110101011111000': 1, '0011110010100100': 2, '0000001101101001': 9, '0001000010010100': 2, '0000010010010100': 2, '0000110001011011': 1, '0001011111011010': 1, '0000000101101000': 16, '0001010010100110': 2, '0001000000101010': 2, '0001010000001010': 2, '0000010010101000': 17, '1001010101101000': 33, '0001011101010011': 1, '0000101000011010': 1, '0000011110011001': 1, '0000101100001001': 1, '0000001100011000': 7, '0000011000101010': 1, '0000000111001000': 1, '0111011101010110': 1, '0000101010011001': 5, '0100000100100101': 1, '0000101011011001': 2, '1000100010101000': 6, '0001011110001001': 3, '0000001011101010': 3, '0000100011111000': 2, '0001110001101010': 3, '0000000000101001': 3, '0000111010101010': 3, '0000110010110100': 1, '0000110100101010': 7, '0000111010010110': 1, '0001001010100010': 1, '0100011100100101': 1, '0000101110101011': 1, '0001001111001010': 2, '0001001111011001': 4, '0001000011101000': 34, '1001010110111000': 2, '0000101010010101': 1, '0001011001011000': 7, '0001000101100100': 5, '0000110001101001': 7, '0101101011010100': 1, '0000111111100100': 1, '0101000100010100': 2, '0001101100100100': 1, '0000100011101000': 25, '0001010001011010': 2, '0000000000010101': 1, '0000110010001010': 1, '0000101110100100': 4, '0000011111001001': 1, '0000110101101010': 9, '0001000111100001': 1, '0000111011011011': 3, '0111000101100111': 1, '0001101110101001': 3, '0101010011100101': 9, '1111111101101010': 1, '0001011100010000': 1, '0001110101011010': 1, '1001010010101001': 4, '0001010100101011': 11, '0001000101001000': 4, '0000001010111010': 1, '0001011101010100': 4, '0000100010000101': 1, '0001010001111001': 2, '0000110011111010': 1, '0001111100011010': 1, '1000101011011011': 1, '0001010110111001': 1, '0001010100001010': 2, '0000111001101001': 5, '0001011100101000': 28, '0001000111011001': 8, '0111011100010101': 1, '0110111100111000': 2, '0000000010011000': 4, '0000111110100100': 1, '0011101011101000': 7, '0010100100010100': 2, '0001110101100101': 4, '0001110001010100': 1, '0001000011010100': 2, '0000011101011011': 1, '0001010010111000': 3, '0000000101011000': 11, '0001011111011000': 7, '0000011111101010': 2, '0000100110011000': 5, '0000100100110110': 1, '0001000011010111': 2, '0001001111100101': 1, '0111001000100100': 3, '0000011111011001': 1, '0000011011011010': 1, '0001000111101000': 22, '1000100010101011': 2, '0000000111011001': 2, '0001001011011011': 2, '0001010110001000': 2, '0001011100100000': 1, '0000011001011000': 2, '0001101100010010': 1, '0001101101101010': 1, '0000101010111001': 1, '0001010001011000': 10, '0001000101001011': 2, '0000001011101011': 2, '0011111010101000': 9, '0001011001011001': 2, '0000111111011001': 6, '0001110110101001': 8, '0000111111010110': 1, '0000101101010000': 1, '0000010010110011': 1, '0000000100011001': 3, '0000000010010111': 1, '0000011011110101': 1, '0000011001011011': 1, '0100101000101000': 13, '0100000011101001': 1, '0110101000100100': 1, '0000100011100100': 4, '0100111100100101': 2, '0000011100011000': 10, '0001010101010101': 3, '0000001010001001': 1, '0000110101111001': 2, '0000110000011010': 1, '0100111011100101': 2, '0000110001010001': 1, '0001010010101000': 33, '0001110000101001': 3, '0000100011100000': 1, '0001000011101010': 11, '0000111010100001': 2, '0000101101101001': 15, '0000001001101010': 1, '0000100001011000': 7, '0001011011001001': 1, '0000100001011011': 1, '0000011101100000': 1, '1100100100100101': 2, '0001001001010101': 1, '0000110100100101': 5, '0000100001101001': 6, '1001111100101001': 1, '0001000111011011': 3, '1000100010110110': 1, '0000110011111000': 1, '0001001101101000': 37, '0000111101010100': 4, '1111010011111001': 3, '0011110011100100': 3, '1110101001010101': 1, '0001100010000001': 1, '0001001111011010': 6, '0000100111001000': 2, '0000101111100010': 1, '1000001100101000': 4, '1001010101111000': 1, '0000100100101001': 15, '0001010101011010': 3, '0000101100100000': 2, '1100101010100100': 1, '1111010111010100': 1, '1001010101011011': 3, '0000001100101001': 7, '0000111101001000': 2, '0000010010101011': 2, '0111000000010101': 1, '1110101011010100': 1, '0001001100010111': 1, '0000111000011000': 5, '1000100000101000': 8, '1001010010011001': 2, '0100011100101000': 7, '0001001100110100': 3, '0000100111110100': 1, '0000110111011000': 9, '0000000010000100': 1, '0001011011110101': 1, '0000010001100100': 1, '0000011011001000': 1, '0000010011101011': 1, '0001011001001000': 1, '0100011101100101': 2, '0000000100001000': 3, '0000010010011010': 3, '0001001011101010': 9, '0101111101100101': 1, '0001110000011011': 1, '0001001000010101': 1, '0001001111100100': 4, '0001000001011010': 4, '0111011010100101': 1, '0001100001011010': 2, '0010001101010100': 1, '0000001110011000': 2, '0001101011101011': 1, '0001111101011001': 5, '0001010010011000': 16, '1011011011101000': 27, '0001010000101010': 4, '0000110000111001': 1, '0000101100011010': 2, '0001011011010101': 2, '0011010100100100': 6, '0001011101111001': 2, '0001000111010100': 2, '0010101010100111': 1, '0001010100111011': 1, '0000011000101000': 2, '0001011110001000': 3, '0001110100111000': 2, '0010001011101000': 5, '0000110010011001': 7, '0100100011010100': 1, '0000010100011010': 1, '0000110110101000': 10, '0110111101101010': 8, '0000101100101011': 6, '0001100110100011': 1, '0001000010001001': 1, '0001101101110001': 1, '0000010101011011': 2, '0100000010010100': 1, '0101101011101001': 4, '0101001000101000': 10, '0001011010001000': 2, '0001110001101011': 2, '0001101101101011': 3, '0000101100001000': 1, '0000000101111001': 1, '0001101110101010': 1, '0001000001011001': 5, '1000000010101010': 1, '0000100111000110': 1, '0000001111011000': 2, '0001000010011001': 7, '0001010111101001': 14, '0100011101100100': 2, '0101000011101001': 10, '0000100100100110': 1, '0000110011101011': 2, '0000110100110100': 1, '0101111111010100': 2, '1100100101010100': 3, '0000101110101010': 2, '0101000011100101': 1, '0001100011010100': 2, '0001110011110100': 1, '0000101101101010': 2, '0101100101100101': 1, '0001000111101011': 1, '0000000101010000': 1, '0001010110101011': 2, '0101110101010100': 1, '0000000001101010': 1, '0000101100010000': 1, '0000011111101001': 2, '0000001101011000': 13, '0011011100100100': 1, '0001111011101011': 5, '0000001011010101': 1, '0001001101100000': 3, '0000100000101010': 3, '0001010101101000': 30, '0000000001011000': 2, '0000010011101001': 14, '0001001110101001': 10, '1001010101010001': 1, '0000100000100111': 1, '0001001000011001': 4, '0001001011111001': 1, '0001000000011010': 1, '0000101100101000': 25, '0001001111111011': 1, '0000010001011000': 2, '0001011101101001': 19, '0001111111011000': 2, '0100111010100101': 1, '0000100011011001': 8, '0000110010010110': 1, '0001111010111001': 3, '0001101100011000': 13, '0001011101011000': 17, '0000011110101001': 10, '1000100000011001': 1, '0001001110100101': 1, '0000110011101010': 5, '0101111100100100': 1, '0001011100011011': 3, '0000110010100110': 1, '1001010011010101': 1, '0001000010000100': 2, '0110001011111000': 1, '0001011100010100': 2, '0001101100100011': 1, '0001100001010010': 1, '0000011011111000': 1, '1111010011100100': 3, '0001110010101000': 13, '0000101111111000': 1, '0000101100010100': 2, '0000001111100100': 2, '0000100010101011': 5, '0001011111011011': 2, '0001010110011001': 9, '0000100110101000': 12, '0000011010101011': 2, '0000110000011000': 5, '0001011011011011': 1, '0001001111101000': 12, '0000011001100100': 2, '0001000010101000': 39, '0000111101101000': 5, '1011010011100100': 3, '0110001010010100': 1, '0001100000101001': 4, '0000110010101011': 3, '0110111100010101': 5, '0001001010001011': 1, '1000100010101001': 3, '0110110100010111': 1, '0001010010011001': 17, '1010000011100101': 2, '0000100011001000': 3, '0000000011011011': 1, '0001100100010101': 1, '0001001000101010': 3, '0111101101010110': 1, '0000100101001010': 2, '0110010101010110': 1, '0000111000111000': 1, '0111011100111000': 6, '0001011110010111': 1, '0000100011010111': 1, '1110000101010110': 1, '0000111101010000': 2, '0000100001101011': 2, '0001010100101000': 57, '0001100110101000': 3, '0001000010100000': 2, '0001001000011010': 2, '0000100110100101': 4, '0001010111111010': 1, '0001000101011000': 28, '1011011010101000': 30, '0001001101010101': 1, '0000110110011000': 6, '0000110001101011': 1, '0110010100010110': 1, '0001000111010101': 1, '0100100110010100': 2, '0001011000101000': 10, '0001001100111000': 3, '0001101111101000': 7, '0000100100101000': 25, '1001010011011011': 1, '0001001010001001': 1, '0001110111101000': 7, '0000110010101001': 14, '0001010000101001': 19, '0000010011011000': 5, '0000001100100100': 2, '0001110010010100': 1, '1001010101001000': 2, '0000110000010100': 1, '0001100101101001': 12, '0010011101100100': 1, '0001010100001001': 1, '0001011000011010': 3, '0000111110001000': 1, '0001010101000100': 1, '0000001001100101': 1, '0000011111101011': 1, '0000100011011000': 13, '0000010000010000': 1, '0000101110100101': 2, '0000100100100000': 1, '0001001011100001': 1, '0000110010111000': 2, '0000101101011010': 3, '0001110010100110': 2, '0101001011010100': 1, '0000110111001000': 1, '0001001100101001': 26, '0000000100010100': 1, '0001001111100001': 2, '0001010010011011': 4, '0001110101101000': 15, '0100011110010100': 2, '0001111010011010': 1, '0001010100100000': 3, '0000000100100100': 3, '0001011111101010': 3, '0001010011110101': 1, '1000000110101000': 12, '1000101011000101': 1, '0001100101010101': 1, '0010001101111001': 1, '0001111101011010': 1, '0000100111100011': 1, '0001110110101011': 1, '0001011100011010': 4, '0000001101101010': 1, '1101010100010100': 3, '0000000111100100': 2, '0000010100111010': 1, '0100101001101000': 13, '0000101010010100': 3, '0101011010101001': 14, '0001001001011001': 4, '0001100000011011': 2, '0010101010101000': 23, '0001000010101001': 16, '0001011010001001': 2, '0001110010010101': 2, '0001001010011010': 1, '0001110100100111': 1, '0001101100111011': 1, '0001010001111000': 1, '0001010101010100': 1, '0000000100011010': 6, '0001000110100100': 1, '0000000111011011': 1, '0000110100100110': 2, '0001010011100110': 2, '0001110110011011': 1, '0100110110100100': 1, '1000000110100000': 1, '1000000110011011': 1, '0001110001101000': 5, '0000010110101010': 1, '0001010111010111': 1, '0001011111010110': 1, '0111000001100100': 1, '1000000011010101': 1, '0001000011011010': 8, '0000010110010111': 1, '0001110101101001': 17, '1001111001101001': 4, '1001010011101000': 8, '0001011101001000': 1, '0001110110011000': 4, '0110110011100100': 1, '1000101000010100': 1, '1000101011101011': 4, '0000001100101000': 9, '0001101011011000': 5, '0001100100011000': 6, '0000101100110100': 1, '0001010010010000': 2, '0001010010001001': 1, '0001101011011001': 2, '0001111111100100': 1, '0001111100101001': 4, '0011010110100100': 1, '0111011100101010': 12, '0000001111011011': 1, '0001010111000110': 1, '0001011100000000': 1, '0111001010010100': 1, '0110100001100100': 2, '0000100000001001': 1, '0000100100010011': 1, '1000000110101001': 5, '0110010110100100': 1, '0100111011101001': 14, '0001101110100100': 2, '0001001010100001': 1, '0101000010101001': 12, '1000101011011001': 6, '0101000100100101': 1, '0000101110010110': 1, '0001011101011011': 4, '0001010000010100': 1, '0001001101100100': 2, '0001110111011010': 2, '0001010111011010': 5, '0000101011011000': 1, '0001100011110111': 1, '0001000101101010': 13, '0100111100101000': 9, '0000000011101011': 1, '0000010000011011': 1, '0001010000011000': 7, '0001101010100000': 1, '0000000001111001': 1, '0000011101011000': 14, '1000000011111000': 1, '0001010101101011': 3, '0110111100101010': 4, '0000100010010100': 1, '0000101000011001': 3, '0001001101001001': 1, '0000100000011000': 3, '0000111000011010': 1, '0000100001011001': 1, '0001111000011000': 1, '0011000011100101': 3, '0110100010100111': 1, '0001000101100010': 1, '0111101010100100': 1, '0110100001010111': 1, '0001010010011010': 4, '0000010101110111': 1, '0100100011100101': 1, '0000000011101001': 2, '0000110101100100': 2, '0010011011101000': 10, '1001010101111001': 1, '0000110011001000': 4, '0001001111011000': 8, '0000010101100100': 4, '0101100011010100': 1, '0111111100010100': 1, '0001101100010101': 1, '0000001111101011': 3, '0100010010100101': 1, '0000110011100110': 1, '0001110111011000': 4, '0001001000001011': 1, '0000111011011001': 6, '0000111111101001': 8, '0001001110011010': 4, '0000001111101000': 10, '1000100010011000': 7, '0101110110010101': 1, '0000101010011011': 1, '0001011000101001': 7, '0010011010101000': 7, '0110100111100110': 2, '0000000001101000': 3, '0110011100100110': 1, '0000011110101000': 6, '0000011110101010': 4, '0100000010100101': 1, '0001101101101000': 14, '0100101100100111': 1, '0000010111101001': 6, '0001100010101000': 16, '0000111110011010': 1, '0001000111111000': 2, '0001110101001001': 1, '1000000010101000': 3, '0001010110110100': 1, '0001000110101001': 16, '0001110010101010': 3, '0001101110011000': 8, '0100010111100100': 1, '1001010101011010': 5, '0000110000101011': 2, '0001001100101000': 38, '0000110010100111': 2, '0001000111011000': 10, '0111100100010110': 1, '0000100101011001': 19, '0001111010101010': 2, '0000100110101010': 2, '0100011000100101': 1, '0000001100010101': 1, '0001101111101011': 1, '0001100111011011': 3, '0000110001001000': 2, '0000101100100101': 3, '0000010101101001': 8, '0001100100101011': 2, '1000000010101001': 2, '0000110111011001': 6, '0000111010010100': 1, '0100110100010100': 5, '0001110011011010': 1, '0001111111100110': 1, '1000000110111000': 1, '0000101001011001': 2, '0000010010101001': 15, '0001111100111010': 1, '1000001100100101': 2, '0001011111100101': 2, '0000010010010111': 1, '0100110110100101': 6, '0001100000100110': 2, '0001011110101001': 12, '0001100010101011': 2, '0000100101010000': 2, '0001100101100000': 1, '0001011001100100': 1, '0000000010100110': 1, '0110011100101011': 2, '0001001010010101': 3, '0000100110101011': 1, '0100111101101000': 15, '0000001000101001': 4, '1010001011101000': 8, '0001111011010101': 1, '0000100101011010': 3, '0000011101101000': 6, '0001001111011011': 1, '0001110011101010': 3, '1001010101100000': 1, '0001001101111010': 1, '0000011111100100': 3, '0001011110100000': 1, '0001001101010000': 1, '0001010001101011': 4, '1000000011010100': 1, '0001100011101000': 12, '0001110011100000': 2, '0110110100010110': 1, '1000001100101010': 1, '0000011011100111': 1, '0001110101010100': 1, '0011100101010100': 2, '0000010100100100': 3, '1000100010100100': 1, '0101101000101000': 8, '0001000011101001': 10, '0001100101011000': 4, '0001001110101010': 6, '0101001100100111': 1, '0000010011011011': 1, '0000100010101001': 5, '0001100100111011': 1, '0001110001101001': 2, '0000100010111000': 1, '0001100000000100': 1, '0001000100111000': 2, '1001010011010001': 1, '0001001010001000': 1, '0110011100111000': 3, '0001010000101000': 25, '0000110100101000': 39, '0000110101000101': 1, '0001010011101000': 31, '0000101111010100': 1, '0011110110100100': 1, '0001011001101001': 10, '0111011011100101': 1, '0001011010100000': 2, '0000110100100000': 1, '0000001101101000': 16, '1000000011101001': 5, '0000011101010000': 1, '0000010011101000': 19, '0110100001100101': 1, '0100110010100101': 2, '0000111010111001': 1, '0001001010100000': 1, '0001010110010111': 3, '0001100100001011': 1, '0000000101101011': 1, '0001010000001000': 1, '0000001101111000': 1, '0000001011000101': 1, '0000100100101011': 6, '0001101110100110': 1, '0001110011101001': 7, '0000110101100000': 4, '0111011101101010': 7, '0001100101010000': 1, '0001010111011000': 14, '0000100100100100': 4, '0000110001011001': 3, '0000111100100111': 1, '0101000010111001': 1, '0001001001011000': 10, '0000101101011001': 10, '0000111011110100': 1, '0001101100101011': 3, '0000110000111011': 1, '0110011101111000': 1, '0001001100100110': 3, '0111101010010101': 2, '0001110000011001': 2, '0001010010101011': 8, '0001011011111000': 1, '0001100111011000': 2, '0001001010011001': 17, '0100011011101001': 11, '0000100111111000': 1, '1001111100101000': 3, '0110111101010101': 2, '0110001010100100': 3, '0001011010011010': 4, '0001100101101011': 2, '0000101010000100': 1, '0000011111001000': 2, '0010111010100100': 6, '0001011111001001': 1, '0011000101010111': 1, '0001011101111010': 2, '0100001100100111': 1, '0101100011010110': 1, '0001000000101001': 11, '0111010011100100': 1, '0000001111101001': 3, '0000100100101010': 11, '0000110110001000': 1, '0001111000101001': 1, '0000000010111011': 1, '0000011010011001': 6, '0001000010101011': 7, '0101100010101001': 3, '1001010101000100': 1, '1010000010100101': 2, '0001000101100000': 2, '0100111101100100': 3, '0001111011011001': 3, '0001111111101011': 1, '0000100100111001': 3, '0001101101010101': 1, '0001010101100101': 4, '0001101111011001': 2, '0000000101100100': 5, '0001000100011010': 7, '0000011100101001': 10, '0111000000100100': 2, '0000100111101001': 12, '0000010100101011': 3, '0001010000010101': 2, '0000011011011000': 10, '0000011000011000': 2, '0000111001101010': 1, '0001011011011010': 2, '0000001101100101': 1, '0011011110010101': 2, '0000011011011001': 4, '0001110011101011': 6, '0000010100011000': 12, '0000100101111000': 3, '0000010000010100': 1, '0000110011011000': 16, '0000010110011000': 6, '0001110011010100': 2, '1001010011011001': 2, '0001000110100101': 1, '0010101011101000': 15, '0001001101110101': 1, '0001100111101000': 7, '0000001000011011': 1, '0000101111100100': 1, '0010001011100101': 1, '0110001001101011': 1, '0111000011100111': 1, '0000000100100110': 1, '0001111110101000': 8, '1000000110011010': 2, '0000111111101000': 11, '0000110001001010': 1, '0100011011100101': 1, '0011110101100100': 1, '0000001101011001': 5, '0001110011011001': 2, '1101011100101000': 20, '0001110010011000': 5, '0000100100011000': 21, '0001011001001001': 1, '0001100000011010': 1, '1000100000011000': 4, '0001000111010010': 1, '0011000100010100': 2, '0000001010110101': 1, '0100100010101001': 9, '0001000101101001': 34, '0000100111011010': 1, '0111000110000101': 1, '0000101000111000': 1, '0000010000011000': 3, '0001101101011011': 2, '0101011111010100': 1, '0001111011111010': 1, '0001100100011010': 2, '0001011111011001': 1, '0001010011010100': 4, '0001011001001010': 1, '0001101100100101': 2, '0000010000011001': 2, '0000111110011011': 1, '1000000110011000': 2, '0000100111100101': 2, '0001010100100100': 1, '0000100101101000': 32, '0001100100101001': 10, '0001010100101001': 36, '0001011001011011': 1, '0001111101011011': 2, '1000000110010100': 1, '0000110111101010': 6, '0000100001100110': 1, '1001010101011001': 10, '0111110011100100': 2, '0001111000011010': 1, '0001000001101000': 16, '0001101110011001': 2, '0001000010100100': 5, '0000110100100001': 1, '0000001001001000': 1, '0110011101101011': 1, '0001111110011010': 1, '0001100111010100': 2, '0001000011010101': 1, '1000100000100001': 1, '0001001010101010': 7, '0001011001011010': 1, '0000101110011000': 4, '0001001100010100': 3, '0001001011011000': 16, '0000100011101001': 8, '1110100000100100': 3, '0001011100011000': 20, '0001001110011000': 5, '0001110110001011': 1, '0000101001111010': 1, '0100001010100100': 1, '0001111010011000': 3, '0000000101100000': 1, '0000100100011010': 4, '0000111011010100': 1, '0001001101100101': 7, '0001110110100110': 1, '0001110100101000': 18, '0101000011010110': 2, '0001110010110001': 1, '1101111010101001': 1, '0001011011001000': 2, '0111001100010101': 2, '0001001100100101': 4, '0001001110011001': 11, '0000001100110110': 1, '0001010110011000': 7, '0001011011101010': 7, '0001101100101001': 12, '1001010101101011': 2, '0000000011011000': 6, '0001001011011010': 4, '0000001010011010': 2, '0001111101101000': 5, '0001010110101001': 9, '0000001111101010': 1, '0001100010101010': 3, '1110000111100110': 1, '0000110001011010': 1, '0000111111011000': 5, '0100000100010100': 1, '0111000001100101': 1, '0000100000110100': 1, '0001001100100001': 1, '0001100100111010': 2, '0001011010010100': 1, '0000001011110000': 1, '0000101010011000': 13, '0000110000010101': 1, '0000111111111000': 1, '0101111101100100': 1, '0111101010111000': 1, '0001001001011010': 3, '0000000100010101': 1, '0000001100011010': 2, '0110111101101011': 2, '0000011110011000': 1, '0000010111101011': 2, '0101111100101000': 4, '0000000010011010': 1, '0000011111111000': 1, '0001101101100100': 1, '0001001001010100': 1, '0001000011011011': 5, '0110011101101010': 2, '0001001111001000': 1, '0001010111100111': 1, '0000001110100001': 1, '0000000011100100': 2, '0000001011010100': 1, '0001101111011000': 4, '0000010111001001': 1, '0000101110010100': 1, '0001011010011000': 18, '0001000110011000': 7, '0010100011010000': 2, '1110101011111000': 1, '1011001101111001': 1, '0001110111101001': 5, '0011001100111001': 1, '0001111100000100': 2, '0001000011001000': 1, '0001100001101000': 1, '0001001110001010': 1, '0000000011101000': 6, '0000001110100101': 1, '0001010001100100': 2, '0001000010111010': 1, '0000010001101000': 7, '0000101101100101': 3, '1110101011100100': 1, '0001000001011011': 1, '0001010111011001': 13, '0110011100101010': 3, '0110101001010101': 1, '0000110111101001': 9, '0001010100110101': 1, '0000100010101000': 13, '0111001011010110': 2, '0001001111101011': 1, '0001000101001001': 2, '0000001001011001': 1, '0001101111100000': 1, '0000101101111010': 1, '0001100000100000': 1, '0001011111100100': 1, '0000111011101011': 3, '0000011111011000': 2, '0001101100101010': 1, '0000100011110100': 1, '0110111101111000': 3, '0001100100101000': 17, '0100011010101001': 6, '0001011000010100': 2, '0000010000101011': 1, '0000101110101001': 2, '0001011000100001': 1, '0001001101001000': 1, '0100001110010100': 1, '0001000010101010': 9, '0001101001111001': 1, '0001010001101001': 12, '0111100011100111': 1, '0000010010110100': 1, '0111001011111000': 2, '0000100101101001': 20, '0001001101110111': 1, '0001110010101011': 3, '0111101001101011': 1, '0000110100010101': 4, '0001000101111010': 1, '1000000110100101': 1, '0001010001001011': 1, '0000010000101010': 3, '0000111011000100': 1, '1000101001101010': 1, '0011010101100100': 4, '0001100101011010': 1, '0001001100100100': 8, '0001001100000100': 1, '0001011000011000': 6, '0001110010000100': 1, '0001101101111000': 2, '0000000100111001': 1, '0001000001001011': 1, '0001000101011011': 4, '0000110101101000': 13, '0000011110110100': 1, '0001000010010101': 1, '0001011010111001': 1, '0000101101100100': 1, '0000101010110101': 1, '0000101011100110': 2, '0000010001101011': 1, '0001001111101010': 4, '0001001100001000': 2, '0000101010100110': 1, '0001100100011001': 5, '0011000011010000': 1, '0000010001101001': 3, '0000100111100100': 7, '0001001000100111': 1, '0001111101101001': 9, '0000011010101010': 1, '0000010000011010': 1, '0000101101011011': 2, '0000000100010010': 1, '0000001010101011': 1, '0000000001101001': 6, '0000010100101000': 22, '0001000100010100': 2, '0000100000010001': 1, '0000101100110110': 1, '0001110111011001': 1, '0001111010011001': 1, '0000110010101010': 6, '0100001011100100': 1, '0000001000101010': 2, '0101000010100101': 2, '0001111100011000': 4, '0001111011010111': 1, '0001011101110100': 2, '0000001101011011': 2, '0000100011101011': 4, '0001000100101001': 34, '0001000110011010': 5, '0110111101100110': 2, '0001111110011001': 2, '0000111000111010': 1, '0000011001011010': 1, '0100111100100100': 4, '0001000100011001': 13, '0110110010010100': 1, '0010101010100101': 1, '0001000100111011': 1, '0101011101100100': 4, '0101001010100100': 2, '0001110010101001': 9, '0001011001101011': 1, '0001100011011011': 2, '0010101110010101': 1, '0001010011001010': 1, '0001011001111011': 1, '0001000101010101': 4, '0000101011101011': 1, '0000110101101011': 5, '0101001100010110': 1, '0000101000011000': 5, '0001101010101010': 3, '0000100101110101': 1, '0000011000111001': 1, '0101011001100101': 1, '0000100110011010': 2, '0101011010100101': 2, '0100011011010100': 2, '0001100111010001': 1, '0001010100010010': 1, '0000110000100101': 3, '0001010101011001': 9, '0010011000010101': 1, '0001010101011011': 2, '0001110110111000': 1, '0001101110001000': 2, '0000001001001001': 1, '0100101011101001': 9, '0000000100101000': 16, '0100100010010100': 5, '0000100010011011': 3, '0000100111101010': 1, '0100111111010100': 1, '0001001111101001': 6, '0000110010100001': 1, '0001011011011001': 9, '0000101100010001': 1, '0001000101101000': 46, '0100100010100101': 3, '0101001011100100': 2, '0000110010100011': 1, '0001010000101011': 1, '0000111011010101': 1, '0000100101100110': 2, '0000101100011001': 8, '1011010111100100': 1, '0001111101000100': 1, '0001011000100000': 1, '0001000011100001': 1, '0000100100011011': 1, '0000100111101000': 22, '0001010010101001': 27, '0001000111000100': 1, '0001000001100110': 1, '0000110100101011': 1, '1001010110011000': 2, '0000000010100010': 1, '0000110100111010': 1, '0001001101011001': 8, '0001101111101001': 1, '0001010011011001': 10, '1000100000011011': 1, '0011111010100100': 3, '0000000100011011': 1, '1010000010111001': 2, '1001010010010100': 1, '0101110111010101': 1, '0000110110011001': 14, '0001100111101010': 1, '0000110000010110': 1, '0001010011101001': 13, '0000110101110101': 1, '0000110000100100': 1, '0001000000011000': 6, '0000010000100100': 1, '0000001011011011': 1, '0000111011100010': 1, '0101010110100101': 1, '0001000011100100': 1, '0000001001011000': 2, '1001010011101011': 2, '0000000010101010': 3, '0000110101010101': 4, '0000000101011011': 3, '0001111111101001': 2, '0000111000100110': 1, '1001010011100000': 1, '0000011111100101': 1, '0011111011100100': 1, '0000001110101001': 4, '0000110100001000': 2, '0000100011010100': 3, '0001110101100000': 1, '0101110010100101': 1, '0000010011001001': 1, '0001000001100001': 1, '0001000001010000': 1, '0001011101110011': 1, '0001011101111011': 1, '0000111101011001': 8, '0001011000010000': 1, '0001011011011000': 10, '0110110111100100': 1, '0000010001011001': 1, '0001101100011010': 3, '0001010101011000': 13, '0000101101111000': 2, '0101001001101000': 7, '0000110010111010': 1, '0001110100111001': 4, '0000101111101011': 2, '0001001110010110': 1, '0001000101110110': 1, '1001111100010111': 1, '0000110011101000': 32, '0110001100010101': 1, '1000100010011001': 1, '0000000111101001': 2, '0000110101100111': 1, '1010001010101000': 17, '0001110011001000': 1, '0001001110111000': 1, '0010011010100100': 1, '0101101001101000': 3, '0000110100010100': 2, '0001100010101001': 3, '0000010000101001': 4, '0000010111011010': 1, '0000100100010101': 1, '0000001011100110': 1, '0000000111101000': 4, '0100001001101000': 1, '0000000100010000': 2, '0000001110101000': 5, '1000000011001001': 1, '0000000111011000': 4, '0000110111111000': 3, '1000000011101010': 1, '0001100101100110': 2, '0000010110111000': 2, '0000001011011000': 9, '1001111001100100': 1, '0011011001010101': 2, '0001001100011001': 21, '1011011010100100': 5, '0001011101100111': 3, '0000010001101010': 1, '0001000110111011': 1, '0100111010010100': 3, '0000100111011000': 8, '0001100001101010': 3, '1000101011011000': 10, '0000110001100100': 3, '0001011111101011': 1, '0000110101111011': 1, '0001001101111000': 2, '1000101011001000': 2, '0000110010010100': 1, '0000010100101001': 13, '0101010111100101': 3, '0001000001000111': 1, '0000111101011000': 12, '0000100110111001': 2, '0001100110101011': 2, '0000010111101010': 2, '0000010110101001': 8, '0001111100011011': 2, '0000110000101001': 8, '1000101011010000': 2, '0000111000011001': 2, '0000100101010100': 2, '0000101111010000': 1, '0000010011011001': 6, '0000010110101011': 1, '1001010110011010': 1, '0001011010111000': 2, '0001011110011001': 5, '0001111011011000': 4, '0100111101100101': 1, '0001100111011001': 3, '0000110111011011': 1, '0000100000101001': 1, '0001001011110101': 1, '0001101001011000': 1, '0000000111101010': 3, '0000100000101011': 1, '0001110111101010': 2, '0000110101011010': 4, '0010110010100100': 1, '1100101011010100': 1, '0001110011101000': 12, '0001101111101010': 1, '0001011001100001': 1, '1101010010100101': 6, '0001010101001001': 1, '0001000100001001': 2, '0110111101010110': 1, '0000100100011001': 11, '0000010100010100': 2, '0000111010011010': 1, '0001110000101000': 5, '1001010010111000': 1, '0001000100101000': 42, '0101101100010110': 1, '0001000111100000': 1, '0001010101101010': 4, '0001010011111000': 1, '0000100100100001': 2, '0000001101011010': 2, '0000000000011000': 1, '0001100101101010': 4, '0001001101011000': 24, '0000101100100100': 7, '0001110001100100': 1, '0000101111101001': 10, '0001101010101011': 3, '0001010100101010': 13, '1000101001101001': 1, '0000001010101010': 1, '0101111100100101': 1, '0001000010011010': 5, '0000011101101001': 10, '0001101101101001': 8, '0011000101100111': 1, '0000111000101001': 4, '1011010010100100': 6, '0110101000101011': 1, '0000111110011000': 12, '1000101011100010': 1, '0000010101110101': 1, '0000101010101011': 3, '0001011110100101': 1, '0001000111011010': 3, '0000100110100011': 1, '0000101101101000': 29, '0100010101010100': 1, '0001010010101010': 11, '0001101101100000': 1, '0000100010011001': 7, '0001010111101000': 23, '1000100000101010': 1, '0000110011010100': 1, '0001011000011011': 2, '0000101100101010': 7, '0000100101011000': 19, '0000101101001000': 2, '0001001101011011': 3, '0000101011101010': 5, '0001000001011000': 8, '0001110100011001': 5, '0001001011001001': 1, '0000111000101011': 2, '0000110110011011': 4, '0001010010010101': 4, '0001011010010001': 1, '1100111110010100': 2, '0001001010010100': 3, '0001111100010100': 1, '0001010100011011': 5, '0001100011101011': 3, '0100101101100111': 1, '0000111111010001': 1, '1000000011101011': 1, '0101100011101001': 5, '0000110001100001': 1, '0000110100001010': 1, '0001100100001001': 1, '0001000110111000': 3, '0010000011111001': 1, '0001001100100000': 2, '1000101001000100': 1, '0110001010100111': 1, '0001111110101001': 5, '0001001010001010': 1, '0001000110010101': 1, '0100010010010100': 2, '0000111100101001': 17, '0000100110101001': 8, '0001110110011001': 3, '0001100110011011': 2, '0001100000011000': 1, '0000101010011010': 1, '0001011010100010': 1, '0001010011100001': 1, '0000100000101000': 8, '0000001000010101': 1, '0101011101100101': 3, '0011000110010110': 2, '0001111000011001': 1, '0000010111011000': 3, '0000010101111001': 1, '0000000010011001': 6, '0011100011010000': 1, '0000001100101011': 2, '0100001000101000': 8, '0110001011100100': 2, '0000101110011010': 2, '0000101111001001': 3, '0000101110101000': 14, '0001110000101010': 2, '0001100111100100': 1, '0001110110011010': 2, '0101001011101001': 14, '0000011010110100': 1, '0001100011011010': 1, '0000100101100100': 3, '0001101000100111': 1, '0000011111101000': 1, '0000110000011001': 3, '1001010010010110': 2, '0010010011100100': 2, '0000101110011001': 6, '0000011111100001': 1, '0001000001111001': 1, '0001000100111001': 1, '0000000000111000': 1, '0001000101011010': 8, '0001000001010100': 3, '0001110101011011': 2, '0000110101011001': 8, '0001101111111000': 1, '0000000010100100': 1, '0000010100001000': 1, '0111101000100100': 1, '0101011000100101': 1, '0000011101010111': 1, '0000100011011010': 2, '0001010100011001': 12, '0110101001100100': 1, '0001110001100111': 1, '0000101111100101': 3, '0111001011100100': 2, '0000000010101001': 8, '0001100100111000': 1, '0000100100000100': 1, '0100001010101001': 7, '0001011110101000': 10, '0000010011010000': 1, '0001000101100001': 3, '0000000111011010': 1, '0000110101111000': 3, '0000001000111000': 1, '0001000101010000': 1, '0001100011101001': 5, '0111100011010101': 1, '0111011100100110': 1, '0001100110011000': 5, '0000101111101010': 4, '0000100101011011': 1, '0101101010100100': 1, '0001001010011000': 9, '0001000110001000': 3, '0111010110010100': 1, '0000100010001000': 1, '0000010101101011': 3, '1011001101100111': 1, '0000111110101001': 4, '0001000010001000': 3, '0001011110011010': 2, '0001011011010100': 1, '0000000000101010': 2, '0100100011101001': 11, '0001011010101010': 5, '0000000101010101': 3, '0000011110100100': 1, '0100011100100100': 3, '0001000110101011': 4, '0000000001011011': 1, '0000001011111001': 3, '0001001001001001': 1, '1001010011101010': 1, '0001101100011001': 3, '1000000011100100': 1, '0000111100011000': 9, '0000001110100100': 1, '0000111011011010': 2, '0101101010101001': 4, '0010100101010100': 2, '0001011101101000': 15, '0110011101010101': 1, '0001000100011011': 9, '0000110010011011': 1, '0000010100011001': 8, '0001000011110101': 1, '0001011111111000': 1, '0001111000011011': 1, '0000110110110110': 1, '0001000000101000': 19, '1000101001011000': 5, '0001011101100000': 1, '0000010110101000': 8, '0001011110111011': 1, '0001100010011000': 10, '0000110000011011': 2, '0000011010100111': 2, '0001110101101010': 4, '1001010101101010': 6, '0000001010011000': 6, '0000111000101010': 2, '0000111010011000': 7, '0000110101010001': 2, '0101111011101001': 3, '0000101101101011': 6, '0000111101101001': 14, '0001110100011010': 2, '0000111000011011': 1, '0001001110110100': 1, '1110100001100100': 2, '0001100111101001': 3, '1000100010011011': 1, '0001101001101001': 2, '1000101011100110': 2, '1000000110101010': 1, '0001010100100110': 2, '0001000100101011': 6, '0001001101011010': 3, '0000111011101010': 4, '0001011100111010': 1, '0001010110010100': 1, '0001110101001000': 1, '0000100100000000': 1, '0001011111101001': 12, '0000101101100110': 1, '0000111111100101': 1, '0000001101100000': 2, '0001110001011000': 1, '0001110100000100': 1, '0000000010101011': 2, '1011011011100100': 8, '0000010110010001': 1, '0000111100011010': 5, '0111001010010110': 2, '0001110001011010': 2} alabio_counts_results = dict(sorted(alabio_counts_results.items(), key=operator.itemgetter(1),reverse=True)) #sorts dictionary by decreasing counts varlabels = ['Test','Mask','Work1','Work2','Rec1','Rec2','Age','Race1','Race2','Pov1','Pov2','Health1','Health2','Cases1','Cases2','Deaths'] # find first 10 entries where cases are decreasing deccaseskey = [] deccasesval = [] for key in alabio_counts_results: cases1 = key[13] cases2 = key[14] if (cases1 == '1') & (cases2 == '1'): # 1 = dec/flat cases deccaseskey.append(key) prob = np.array(alabio_counts_results[key]) / sum(alabio_counts_results.values()) deccasesval.append(prob) if len(deccaseskey) >= 10: break # find first 10 entries where deaths are decreasing decdeathskey = [] decdeathsval = [] for key in alabio_counts_results: deaths = key[15] if (deaths == '1'): # 1 = dec/flat cases decdeathskey.append(key) prob = np.array(alabio_counts_results[key]) / sum(alabio_counts_results.values()) decdeathsval.append(prob) if len(decdeathskey) >= 10: break topprobs_alabio_cases = dict(zip(deccaseskey,deccasesval)) topprobs_alabio_deaths = dict(zip(decdeathskey,decdeathsval)) """examples""" var_labels = ['Cases', 'Tests', 'Home'] make_prob_hist(results, var_labels, top_n_probs='all') make_prob_hist(results, var_labels, top_n_probs=4) make_prob_hist(results_maxtomin, ['Increasing','Decreasing'], top_n_probs='all', whichvar=[0,2]) make_prob_hist(topprobs_alabio_cases, varlabels, probdict = topprobs_alabio_cases) make_prob_hist(topprobs_alabio_deaths, varlabels, probdict = topprobs_alabio_deaths) """Lesser model before rotation - for presentation""" q = QuantumRegister(3) qc = QuantumCircuit(q) qc.id(0) simulator = Aer.get_backend('statevector_simulator') result = execute(qc, backend=simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) """Lesser model after rotation - for presentation""" q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ry(circ.angle_from_probability(.62,.38), 0) qc.ry(circ.angle_from_probability(0.645,0.355), 1) qc.ry(circ.angle_from_probability(0.73,0.27),2) simulator = Aer.get_backend('statevector_simulator') result = execute(qc, backend=simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector)
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
# DATA SETUP ''' Note: for more information about our data pre-processing and categorizing into states, see the README in the data folder. We have cited sources for all data used and included a brief description of the states we decided on there.''' import numpy as np import pandas as pd from qubayes_tools import * from probabilities_temp import * ################################################# # COVID-19 EXAMPLES: def build_graph(ntwk_func, filename = None, **kwargs): if filename == None: nodes = ntwk_func(**kwargs) else: nodes = ntwk_func(filename = filename, **kwargs) graph = {} for node in nodes: if node.parents == []: #this is a root node, we just need to calculate probabilities ct = 1 probs = [] got_probs = get_probabilities(node) newkey = "" for state_i in node.states.keys(): state_key = node.name + "_" + state_i if ct == len(node.states.keys()): newkey += state_key else: newkey += state_key + "," probs.append(got_probs[state_key]) ct += 1 graph.update({newkey : ([], probs)}) else: #this is a child node, we need conditional probabilities! cond_probs = [] p_nodes = [] #initialize a list in which to place parent nodes p_names = [] #get names in same order! for anode in nodes: #loop thru all nodes in network if anode.name in node.parents: p_nodes.append(anode) p_names.append(str.join(",",[(anode.name + '_' + s) for s in anode.states.keys()])) cond_prob_dict = get_conditional_probability(node, p_nodes) # i need to write func(node, p_node[0], p_node[1], ... p_node[n]) p_ct = 0 newkey = "" for p_str in generate_parent_str(p_nodes[:]): s_ct = 0 for state_i in node.states.keys(): cond_str = node.name + "_" + state_i + "|" + p_str cond_probs.append(cond_prob_dict[cond_str]) if p_ct == 0: if s_ct == 0: newkey += node.name + "_" + state_i else: newkey += "," + node.name + "_" + state_i s_ct += 1 p_ct += 1 graph.update({newkey : (p_names, cond_probs)}) return graph def get_lesser_model_nodes(filename='data/lesser_model_data.csv'): lesserdata = pd.read_csv(filename) statedataStayHome = {'MarHome' : lesserdata['MarHome'], 'AprHome' : lesserdata['AprHome'], 'MayHome' : lesserdata['MayHome'], 'JunHome' : lesserdata['JunHome']} StayHome = Node("StayHome", np.ndarray.flatten(np.array(pd.DataFrame(data=statedataStayHome))), states = {"No" : 0, "Yes" : 1}) statedataTests = {'MarTest' : lesserdata['MarTest'], 'AprTest' : lesserdata['AprTest'], 'MayTest' : lesserdata['MayTest'], 'JunTest' : lesserdata['JunTest']} Tests = Node("Tests", np.ndarray.flatten(np.array(pd.DataFrame(data=statedataTests))), states = {"GT5" : 0, "LE5" : 1}) statedataCases = {'MarCases' : lesserdata['MarCases'], 'AprCases' : lesserdata['AprCases'], 'MayCases' : lesserdata['MayCases'], 'JunCases' : lesserdata['JunCases']} Cases = Node("Cases", np.ndarray.flatten(np.array(pd.DataFrame(data=statedataCases))), states = {"Inc" : 0, "noInc" : 1}, parents = ["Tests", "StayHome"]) return Cases, Tests, StayHome def get_mallard_model_nodes(filename='data/mallardmodeldata.csv'): mallarddata = pd.read_csv(filename) Cases = Node("Cases", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarCases':mallarddata['MarCases'], 'AprCases':mallarddata['AprCases'], 'MayCases':mallarddata['MayCases'], 'JunCases':mallarddata['JunCases']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}, parents = ["Test", "Mask", "Work", "Rec","Race","Poverty"]) Test = Node("Test", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarTest':mallarddata['MarTest'],'AprTest':mallarddata['AprTest'],'MayTest':mallarddata['MayTest'], 'JuneTest':mallarddata['JunTest']}))), states = {"GT5" : 0, "LE5" : 1}) Mask = Node("Mask", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarMask':mallarddata['MarMask'],'AprMask':mallarddata['AprMask'],'MayMask':mallarddata['MayMask'],'JunMask':mallarddata['JunMask']}))), states = {"No" : 0, "Yes" : 1}) Work = Node("Work", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarWork':mallarddata['MarWork'],'AprWork':mallarddata['AprWork'],'MayWork':mallarddata['MayWork'],'JunWork':mallarddata['JunWork']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Rec = Node("Rec", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarRec':mallarddata['MarRec'],'AprRec':mallarddata['AprRec'],'MayRec':mallarddata['MayRec'],'JunRec':mallarddata['JunRec']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Death = Node("Death", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarDeath':mallarddata['MarDeath'],'AprDeath':mallarddata['AprDeath'],'MayDeath':mallarddata['MayDeath'],'JunDeath':mallarddata['JunDeath']}))), states = {"Inc" : 0, "notInc" : 1}, parents = ["Cases", "Age"]) Age = Node("Age", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarAge':mallarddata['MarAge'],'AprAge':mallarddata['AprAge'],'MayAge':mallarddata['MayAge'],'JunAge':mallarddata['JunAge']}))), states = {"Old" : 0, "Young" : 1}) return Cases, Test, Mask, Work, Rec, Death, Age def get_alabio_model_nodes(filename='data/alabiomodeldata.csv'): alabiodata = pd.read_csv(filename) Cases = Node("Cases", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarCases':alabiodata['MarCases'], 'AprCases':alabiodata['AprCases'], 'MayCases':alabiodata['MayCases'], 'JunCases':alabiodata['JunCases']}))), states={"Inc":0,"Min":1,"Mod":2,"Maj":3}, parents=["Test", "Mask", "Work", "Rec", "Race", "Poverty"]) Test = Node("Test", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarTest':alabiodata['MarTest'],'AprTest':alabiodata['AprTest'],'MayTest':alabiodata['MayTest'], 'JuneTest':alabiodata['JunTest']}))), states={"GT5" : 0, "LE5" : 1}) Mask = Node("Mask", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarMask':alabiodata['MarMask'],'AprMask':alabiodata['AprMask'],'MayMask':alabiodata['MayMask'],'JunMask':alabiodata['JunMask']}))), states = {"No" : 0, "Yes" : 1}) Work = Node("Work", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarWork':alabiodata['MarWork'],'AprWork':alabiodata['AprWork'],'MayWork':alabiodata['MayWork'],'JunWork':alabiodata['JunWork']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Rec = Node("Rec", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarRec':alabiodata['MarRec'],'AprRec':alabiodata['AprRec'],'MayRec':alabiodata['MayRec'],'JunRec':alabiodata['JunRec']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Death = Node("Death", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarDeath':alabiodata['MarDeath'],'AprDeath':alabiodata['AprDeath'],'MayDeath':alabiodata['MayDeath'],'JunDeath':alabiodata['JunDeath']}))), states = {"Inc" : 0, "notInc" : 1}, parents = ["Cases", "Age", "Race", "Poverty", "Health"]) Age = Node("Age", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarAge':alabiodata['MarAge'],'AprAge':alabiodata['AprAge'],'MayAge':alabiodata['MayAge'],'JunAge':alabiodata['JunAge']}))), states = {"Old" : 0, "Young" : 1}) Race = Node("Race", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarRace':alabiodata['MarRace'],'AprRace':alabiodata['AprRace'],'MayRace':alabiodata['MayRace'],'JunRace':alabiodata['JunRace']}))), states = {"LE15":0, "15to30":1, "30to45":2, "GT45":3}) Poverty = Node("Poverty", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarPoverty':alabiodata['MarPoverty'],'AprPoverty':alabiodata['AprPoverty'],'MayPoverty':alabiodata['MayPoverty'],'JunPoverty':alabiodata['JunPoverty']}))), states={"LE11":0, "11to13":1, "13to15":2, "GT15":3}) Health = Node("Health", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarHealth':alabiodata['MarHealth'],'AprHealth':alabiodata['AprHealth'],'MayHealth':alabiodata['MayHealth'],'JunHealth':alabiodata['JunHealth']}))), states={"Rare":0, "SomewhatCom":1, "Common":2, "VeryCom":3}) return Cases, Test, Mask, Work, Rec, Death, Age, Race, Poverty, Health ################################################# """ # MAKE YOUR OWN HERE! def MyDataSetup(*input, **kwargs): ########################## # INPUT # # input str filename with data # **kwargs whatever else you need # OUTPUT # # *data tuple of Nodes return data """ print(build_graph(get_mallard_model_nodes)) print(build_graph(get_lesser_model_nodes))
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
import numpy as np import pandas as pd import matplotlib.pyplot as plt from qubayes_tools import * from network_setup import * def get_probabilities(node): ############################################ # USE THIS FUNCTION TO FIND THE PROBABILITIES FOR AN INDIVIDUAL NODE IN THE NETWORK ### INPUT ### # node: Node Node object in network ### OUTPUT ### # probs: dict probabilities ############################################ data= node.data states = node.states name = node.name num_total = len(data) #total number of data points with which to calculate probabilities probs = {} prob_sum = 0 for state in states.keys(): #loop through different state strings prob = np.shape(np.where(data == states[state]))[1]/num_total prob_sum += prob probs.update({name + "_" + state : prob}) assert round(prob_sum, 3) == 1. return probs def get_conditional_probability(child, *ps): ############################################ ### THIS FUNCTION CALCULATES CONDITIONAL PROBABILITIES FOR CHILD NODE ### THAT HAS s_m STATES AND m PARENT NODES EACH WITH s_i STATES WHERE i = 0, ..., m-1 ### INPUTS ### # child Node # *ps Node(s) or a single list of Nodes ### OUTPUT ### # a dictionary of conditional probabilities ############################################ #we might want to add some assert statements checking that all inputs have the same shape #also use assert to check that for all p in ps, ps.name is in child.parents, and vice versa if type(ps[0]) == list: ps = ps[0] if type(ps[0]) != Node: print("ERROR: This input is not right!") keys = generate_cond_keys(child, ps) cond_probs = {key: 0 for key in keys} #initialize a dictionary for conditional probabilities for key in keys: numer, tot = 0, 0 n = len(child.data) for i in range(n): all_ps = True for j in range(len(ps)): p = ps[j] if p.data[i] != int(p.states[key.split("|")[1].split(",")[j].split("_")[1]]): all_ps = False break if all_ps: tot += 1 if child.data[i] == int(child.states[key.split("|")[0].split("_")[1]]): numer += 1 cond_probs.update({key : numer/tot}) return cond_probs Cases, Tests, StayHome = get_lesser_model_nodes() get_conditional_probability(Cases, StayHome, Tests) get_conditional_probability(Cases, Tests, StayHome) Cases, Test, Mask, Work, Rec, Death, Age = get_mallard_model_nodes() get_conditional_probability(Cases, Test, Mask , Work, Rec) Cases, Test, Mask, Work, Rec, Death, Age, Race, Poverty, Health = get_alabio_model_nodes() get_conditional_probability(Cases, Test, Mask, Work, Rec, Poverty, Race) # example: results from running simple model on simulator: # {'000': 2783, '001': 1240, '100': 603, '111': 815, '110': 294, '010': 1712, '101': 485, '011': 260} def get_marginal_0probabilities(state_counts): #state_counts: dict, counts for each state from network result (should have 2^n entries) #marg_probs: array of length n, marginal probabilities that each qubit is 0, #from most significant to least significant qubit n = len(list(state_counts.keys())[0]) #number of qubits prob = np.zeros(n) total = sum(state_counts.values()) for i in range(n): for key in state_counts: if int(key[i]) == 0: prob[i] += state_counts[key] prob[i] = prob[i]/total return prob # get marginal probabilities for simulation results - lesser model results = {'000': 2783, '001': 1240, '100': 603, '111': 815, '110': 294, '010': 1712, '101': 485, '011': 260} #margProb = marginal_probabilities(results) #margCompare = marginal_probabilities_general(results) #print(margProb) #print(margCompare) def func(**counts): return counts["c001"] func(c000=4928, c001=82743, c100=48937, c111=9288842) C,B,A = get_lesser_model_nodes() print(C.name) get_conditional_probability(C, B, A)
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
from itertools import product import numpy as np from network_setup_temp import * def generate_cond_keys(child, ps): ############################################## #THIS FUNCTION WILL GENERATE A LIST OF STRINGS TO USE AS KEYS FOR CONDITIONAL PROBABILITIES ### INPUT ### # s_0 int number of states of the child node # s_i list number of states for each parent node, from most to least significant ### OUTPUT ### # list of strings to use as keys for conditional probabilities (included commas in case there is ever an >11-state node!) ############################################## cname = child.name cstates = child.states ranges = [[child.name], child.states.keys()] for p in ps: ranges.append([str(p.name)]) ranges.append(p.states.keys()) enumed = product(*ranges) add = [",","_"] cond_keys = [] for enum in enumed: suff = 0 enum = list(enum) parent_str = '' for i in range(2,len(enum)-1): suff = (suff + 1)%2 parent_str += str(enum[i]) + add[suff] parent_str += str(enum[len(enum)-1]) cond_keys.append("%s_%s|%s"%(str(enum[0]), str(enum[1]), parent_str)) return cond_keys def generate_parent_str(ps): ############################################## #THIS FUNCTION WILL GENERATE A LIST OF STRINGS TO USE AS KEYS FOR CONDITIONAL PROBABILITIES ### INPUT ### # s_0 int number of states of the child node # s_i list number of states for each parent node, from most to least significant ### OUTPUT ### # list of strings to use as keys for conditional probabilities (included commas in case there is ever an >11-state node!) ############################################## ranges = [] for p in ps: ranges.append([str(p.name)]) ranges.append(p.states.keys()) enumed = product(*ranges) add = [",","_"] cond_keys = [] for enum in enumed: suff = 0 enum = list(enum) parent_str = '' for i in range(len(enum)-1): suff = (suff + 1)%2 parent_str += str(enum[i]) + add[suff] parent_str += str(enum[len(enum)-1]) cond_keys.append("%s"%(parent_str)) return cond_keys class Node: # A single variable in the Bayesian network def __init__(self, name, data, states=None, parents=[]): ### INPUTS ### # name: str name of variable # data: array state data for the node # states: dict keys are state names, values are the int each takes on in the data # parents: list strings of names of parent nodes to this node ############## if states == None: states = {} for i in range(max(data) + 1): states.update({str(i) : i}) self.name = name self.data = data self.states = states self.parents = parents C,B,A = get_lesser_model_nodes() generate_parent_str([C,B,A])
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
import pandas as pd import numpy as np march = pd.read_csv('march.csv', names = ['region', 'day', 'rec', 'work']) april = pd.read_csv('april.csv', names = ['region', 'day', 'rec', 'work']) may = pd.read_csv('may.csv', names = ['region', 'day', 'rec', 'work']) june = pd.read_csv('june.csv', names = ['region', 'day', 'rec', 'work']) print(np.shape(march)) print(np.shape(april)) print(np.shape(may)) print(np.shape(june)) print(np.shape(march.region)) print(357./7.) i=0 marrecavgs = [] marworkavgs = [] aprrecavgs = [] aprworkavgs = [] mayworkavgs = [] mayrecavgs = [] junrecavgs = [] junworkavgs = [] marrecstate = [] marworkstate = [] aprrecstate = [] aprworkstate = [] mayrecstate = [] mayworkstate = [] junrecstate = [] junworkstate = [] zerolow = 0. onelow = -26. twolow = -53. while i < np.shape(march)[0]: marwk = march.iloc[i:i+7] marrecavg = np.mean(marwk.rec) marworkavg = np.mean(marwk.work) marrecavgs.append(marrecavg) marworkavgs.append(marworkavg) if marrecavg > zerolow: marrecstate.append(3) elif (marrecavg < zerolow) & (marrecavg > onelow): marrecstate.append(2) elif (marrecavg < onelow) & (marrecavg > twolow): marrecstate.append(1) elif marrecavg < twolow: marrecstate.append(0) if marworkavg > zerolow: marworkstate.append(3) elif (marworkavg < zerolow) & (marworkavg > onelow): marworkstate.append(2) elif (marworkavg < onelow) & (marworkavg > twolow): marworkstate.append(1) elif marworkavg < twolow: marworkstate.append(0) aprwk = april.iloc[i:i+7] aprrecavg = np.mean(aprwk.rec) aprworkavg = np.mean(aprwk.work) aprrecavgs.append(aprrecavg) aprworkavgs.append(aprworkavg) if aprrecavg >= zerolow: aprrecstates.append(3) elif (aprrecavg < zerolow) & (aprrecavg >= onelow): aprrecstate.append(2) elif (aprrecavg < onelow) & (aprrecavg >= twolow): aprrecstate.append(1) elif aprrecavg < twolow: aprrecstate.append(0) if aprworkavg >= zerolow: aprworkstate.append(3) elif (aprworkavg < zerolow) & (aprworkavg >= onelow): aprworkstate.append(2) elif (aprworkavg < onelow) & (aprworkavg >= twolow): aprworkstate.append(1) elif aprworkavg < twolow: aprworkstate.append(0) maywk = may.iloc[i:i+7] mayrecavg = np.mean(maywk.rec) mayworkavg = np.mean(maywk.work) mayrecavgs.append(mayrecavg) mayworkavgs.append(mayworkavg) if mayrecavg > zerolow: mayrecstate.append(3) elif (mayrecavg < zerolow) & (mayrecavg > onelow): mayrecstate.append(2) elif (mayrecavg < onelow) & (mayrecavg > twolow): mayrecstate.append(1) elif mayrecavg < twolow: mayrecstate.append(0) if mayworkavg > zerolow: mayworkstate.append(3) elif (mayworkavg < zerolow) & (mayworkavg > onelow): mayworkstate.append(2) elif (mayworkavg < onelow) & (mayworkavg > twolow): mayworkstate.append(1) elif mayworkavg < twolow: mayworkstate.append(0) junwk = june.iloc[i:i+7] junrecavg = np.mean(junwk.rec) junworkavg = np.mean(junwk.work) junrecavgs.append(junrecavg) junworkavgs.append(junworkavg) if junrecavg > zerolow: junrecstate.append(3) elif (junrecavg < zerolow) & (junrecavg > onelow): junrecstate.append(2) elif (junrecavg < onelow) & (junrecavg > twolow): junrecstate.append(1) elif junrecavg < twolow: junrecstate.append(0) if junworkavg > zerolow: junworkstate.append(3) elif (junworkavg < zerolow) & (junworkavg > onelow): junworkstate.append(2) elif (junworkavg < onelow) & (junworkavg > twolow): junworkstate.append(1) elif junworkavg < twolow: junworkstate.append(0) i += 7 print(len(marrecavgs)) print(len(aprrecavgs)) print(len(mayrecavgs)) print(len(junrecavgs)) print(len(marworkavgs)) print(len(aprworkavgs)) print(len(mayworkavgs)) print(len(junworkavgs)) print(len(marrecstate)) print(len(aprrecstate)) print(len(mayrecstate)) print(len(junrecstate)) print(len(marworkstate)) print(len(aprworkstate)) print(len(mayworkstate)) print(len(junworkstate)) mobility_data_andstates = pd.DataFrame(data={'marrec': marrecavgs, 'aprrec' : aprrecavgs, 'mayrec':mayrecavgs, 'junrec':junrecavgs ,'marwork':marworkavgs, 'aprwork':aprworkavgs, 'maywork':mayworkavgs, 'junwork':junworkavgs ,'marrecstates':marrecstate, 'aprrecstates':aprrecstate, 'mayrecstates':mayrecstate, 'junrecstates':junrecstate ,'marworkstates':marworkstate, 'aprworkstates':aprworkstate, 'mayworkstates':mayworkstate, 'junworkstates':junworkstate}) print(mobility_data_andstates) #mobility_data_andstates.to_csv('mobility_data_andstates.csv')
https://github.com/KMU-quantum-classroom/qiskit-classroom
KMU-quantum-classroom
"""Widget for converting informations""" # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # pylint: disable=no-name-in-module from PySide6.QtGui import QDragEnterEvent, QDropEvent from PySide6.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPlainTextEdit, QPushButton, QFileDialog, QCheckBox, ) from PySide6.QtCore import Qt, Signal from .expression_enum import QuantumExpression from .input_model import Input, QuantumCircuitInput, DiracInput, MatrixInput EXPRESSION_PLACEHOLDERS: dict[QuantumExpression:str] = { QuantumExpression.CIRCUIT: """from qiskit import QuantumCircuit quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.x(0) quantum_circuit.cx(0, 1) """, QuantumExpression.DIRAC: "sqrt(2)*|00>/2+sqrt(2)*|11>/2", QuantumExpression.MATRIX: """[[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]""", QuantumExpression.NONE: "", } class ExpressionPlainText(QPlainTextEdit): """ ExpressionPlainText """ file_dropped = Signal(object) def __init__(self, parent) -> None: super().__init__(parent=parent) self.setAcceptDrops(True) self.set_ui() def set_ui(self) -> None: """ set UI """ self.setFixedHeight(250) def dragEnterEvent(self, event: QDragEnterEvent) -> None: # pylint: disable=invalid-name """ handle drag event and accept only url """ if event.mimeData().hasUrls(): event.accept() else: event.ignore() def dropEvent(self, event: QDropEvent) -> None: # pylint: disable=invalid-name """ handle drop event and emit file imported event """ if event.mimeData().hasUrls(): files = [u.toLocalFile() for u in event.mimeData().urls()] self.file_dropped.emit(files) event.accept() def set_placeholder_text(self, expression: QuantumExpression) -> None: """set placeholder for expression plain text Args: expression (QuantumExpression): selection """ self.setPlaceholderText("") self.setPlaceholderText(EXPRESSION_PLACEHOLDERS[expression]) class InputWidget(QWidget): """Widget group for certain input""" def set_ui(self) -> None: """show widgets""" def get_input(self) -> Input: """return user input Returns: Input: user input class """ return Input class QuantumCircuitInputWidget(InputWidget): """Widget group for QuantumCircuit Input""" file_imported = Signal(str) def __init__(self, parent: QWidget) -> None: super().__init__(parent) self.set_ui() def set_ui(self): """set ui for QuantumCircuitInputWidget""" vbox = QVBoxLayout(self) vbox.setAlignment(Qt.AlignmentFlag.AlignCenter) value_name_box = QHBoxLayout() value_name_label = QLabel("value name") value_name_box.addWidget(value_name_label) self.value_name_text = QLineEdit() self.value_name_text.setPlaceholderText("input value name of quantum circuit") value_name_box.addWidget(self.value_name_text) load_box = QHBoxLayout() load_box.addStretch() self.load_push_button = QPushButton("or load...") self.load_push_button.setMinimumWidth(150) self.load_push_button.clicked.connect(self.on_file_load_clicked) load_box.addWidget(self.load_push_button) vbox.addLayout(value_name_box) vbox.addLayout(load_box) def on_file_load_clicked(self) -> None: """ handling file dialog """ filename = QFileDialog.getOpenFileName( self, "Open .py", "", "python3 script (*.py)" )[0] self.file_imported.emit(filename) def get_input(self) -> QuantumCircuitInput: user_input = QuantumCircuitInput( self.value_name_text.text().strip(), ) return user_input class DiracInputWidget(InputWidget): """Widget group for Dirac Notaion input""" def __init__(self, parent: QWidget) -> None: super().__init__(parent) self.set_ui() def get_input(self) -> DiracInput: return DiracInput() class MatrixInputWidget(InputWidget): """Widget group for matrix input""" matrix_plain_text: QPlainTextEdit num_cubit_text: QLineEdit do_measure_checkbox: QCheckBox def __init__(self, parent: QWidget) -> None: super().__init__(parent) self.set_ui() def set_ui(self): vbox = QVBoxLayout(self) vbox.setAlignment(Qt.AlignmentFlag.AlignCenter) hbox = QHBoxLayout() num_cubit_label = QLabel("number of cubit") self.num_cubit_text = QLineEdit(self) self.num_cubit_text.setToolTip("input 3 digits number") self.do_measure_checkbox = QCheckBox("do measure this circuit?", self) self.do_measure_checkbox.setToolTip("do measure all qubits") hbox.addWidget(num_cubit_label) hbox.addWidget(self.num_cubit_text) hbox.addWidget(self.do_measure_checkbox) vbox.addLayout(hbox) def get_input(self) -> Input: return MatrixInput( int(self.num_cubit_text.text()), self.do_measure_checkbox.isChecked() )
https://github.com/KMU-quantum-classroom/qiskit-classroom
KMU-quantum-classroom
""" worker for convert and visualize expressions """ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 asyncio import datetime import random import os import string import sys import matplotlib as mpl import matplotlib.pyplot as plt from .expression_enum import QuantumExpression from .input_model import Input, QuantumCircuitInput, MatrixInput mpl.rcParams["font.size"] = 9 mpl.rcParams["text.usetex"] = True mpl.rcParams["text.latex.preamble"] = r"\usepackage{{amsmath}}" ARRAY_TO_LATEX_IMPORT = "from qiskit.visualization import array_to_latex" CONVERTER_IMPORT = "from qiskit_class_converter import ConversionService" def add_new_line(strings: list[str]) -> str: """add \\n between every line Args: strings (list[str]): list of line Returns: str: joined string with \\n """ return "\n".join(strings) # pylint: disable=too-many-instance-attributes class ConverterWorker: """worker for convert expression and visualize expression""" # pylint: disable=too-many-arguments def __init__( self, from_expression: QuantumExpression, to_expression: QuantumExpression, input_data: Input, expression_text: str, shows_result: bool, ) -> None: self.from_expression = from_expression self.to_expression = to_expression self.__injected_sourcecode_path = ConverterWorker.generate_random_file_name() # copy text self.expression_text = "" + expression_text self.input_data = input_data self.shows_result = shows_result @staticmethod def generate_random_file_name() -> str: # pragma: no cover # this method implmented with random function """return generated file name Returns: str: generated file name """ return ( "/tmp/" + "".join(random.choice(string.ascii_letters) for _ in range(10)) + ".py" ) @staticmethod def write_converting_code(file_path: str, code: str) -> bool: # pragma: no cover """write code to file_path Args: file_path (str): target code (str): contents Returns: bool: is succesful """ try: with open(file_path, mode="w", encoding="UTF-8") as file: file.write(code) except FileNotFoundError: return False return True def __generate_code(self): # pragma: no cover expression_text = self.expression_text if self.from_expression is QuantumExpression.MATRIX: input_data: MatrixInput = self.input_data expression_text = f"{input_data.value_name}={expression_text}" ConverterWorker.write_converting_code( self.__injected_sourcecode_path, add_new_line( [ expression_text, CONVERTER_IMPORT, ARRAY_TO_LATEX_IMPORT, self.generate_conversion_code(), self.generate_visualization_code(), ] ), ) def generate_conversion_code(self) -> str: """generate the conversion code according to the conversion method. Returns: str: generated conversion code """ if self.to_expression == self.from_expression: return "" matrix_to_qc_option: dict[str, str] = {"label": "unitary gate"} default_option: dict[str, str] = {"print": "raw"} option: dict[str, str] = {} if self.to_expression is QuantumExpression.CIRCUIT: option = matrix_to_qc_option else: option = default_option first_line = ( "converter = ConversionService(conversion_type=" + f"'{self.from_expression.value[1]}_TO_{self.to_expression.value[1]}', " + f"option={option})" ) next_line: str = "" if self.from_expression is QuantumExpression.CIRCUIT: quantum_circuit_input: QuantumCircuitInput = self.input_data next_line = ( "result = converter.convert" + f"(input_value={quantum_circuit_input.value_name})" ) if self.from_expression is QuantumExpression.MATRIX: matrix_input: MatrixInput = self.input_data next_line = add_new_line( [ "from qiskit import QuantumCircuit", "" f"result = converter.convert(input_value={matrix_input.value_name})", f"quantum_circuit = QuantumCircuit({matrix_input.num_qubits})", "quantum_circuit.append(result, list(range(result.num_qubits)))", "quantum_circuit.measure_all()" if matrix_input.do_measure else "", ] ) return add_new_line([first_line, next_line]) def generate_visualization_code(self) -> str: """generate visualiszation code according to the conversion method Returns: str: visualization code """ if self.to_expression is not self.from_expression: if self.to_expression is QuantumExpression.MATRIX: return add_new_line( [ ( "for gate, name in zip(reversed(result['gate'])," + "reversed(result['name'])):" ), "\totimes=' \\\\otimes '", """\tprint('\\stackrel{' + otimes.join(name[1]) +'}' + f'{{{gate}}}')""", "print(f\"= \\stackrel{{result}}{{{result['result']}}}\")" if self.shows_result else "", ] ) if self.to_expression is QuantumExpression.CIRCUIT: return add_new_line( [ 'quantum_circuit.draw(output="mpl")' + f'.savefig("{self.__injected_sourcecode_path+".png"}", ' + 'bbox_inches="tight")' ] ) if self.to_expression is QuantumExpression.DIRAC: return add_new_line(["print(result)"]) else: if self.to_expression is QuantumExpression.MATRIX: matrix_input: MatrixInput = self.input_data return add_new_line( [f"print(array_to_latex({matrix_input.value_name}, source=True))"] ) if self.to_expression is QuantumExpression.CIRCUIT: qunatum_input: QuantumCircuitInput = self.input_data return add_new_line( [ f'{qunatum_input.value_name}.draw(output="mpl")' + f'.savefig("{self.__injected_sourcecode_path+".png"}",' + 'bbox_inches="tight")' ] ) return "" async def run(self) -> str: """inject expression convert code to user's source code and create subprocess for drawing converted expresion Returns: str: path of subprocess created image """ print("now running") print(datetime.datetime.now().time()) self.__generate_code() stdout, stderr = await self.run_subprocess() if stdout: print(f"output {stdout}") if stderr: stderr: str = stderr print(f"error {stderr}") if stderr.find("SyntaxError") != -1: raise SyntaxError if stderr.find("NameError") != -1: raise NameError print("end at ") print(datetime.datetime.now().time()) # remove injected source code if not self.cleanup(): print("error removing file") if self.to_expression is QuantumExpression.CIRCUIT: return self.__injected_sourcecode_path + ".png" return self.draw_latex(latex=stdout) async def run_subprocess(self) -> (str, str): """run generated script's subprocess Returns: (str, str): subprocess's stdout and stderr """ proc = await asyncio.create_subprocess_exec( sys.executable, self.__injected_sourcecode_path, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await proc.communicate() await proc.wait() return (stdout.decode(), stderr.decode()) def cleanup(self) -> bool: """remove generated script Returns: bool: result of removing file """ try: os.remove(self.__injected_sourcecode_path) except FileNotFoundError: return False return True def draw_latex(self, latex: str) -> str: # pragma: no cover """ render latex to image and save as file. Args: latex (str): latex matrix code Raises: MatrixNotFound: when latex not have matrix Returns: str: image file path """ # this code avoid latex runtime error (\n ocurse error) latex = latex.replace("\n", " ").strip() fig = plt.figure() fig.text(0, 0, f"${latex}$") output = self.__injected_sourcecode_path + ".png" fig.savefig(output, dpi=200, bbox_inches="tight") plt.close() return output
https://github.com/KMU-quantum-classroom/qiskit-classroom
KMU-quantum-classroom
"""test worker.py""" # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 unittest from unittest import mock from qiskit_classroom.expression_enum import QuantumExpression from qiskit_classroom.worker import ConverterWorker from qiskit_classroom.input_model import QuantumCircuitInput, MatrixInput VALUE_NAME = "value_name" QUANTUM_CIRCUIT_CODE = """from qiskit import QuantumCircuit quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.x(0) quantum_circuit.cx(0, 1)""" MATRIX_CODE = """[[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]""" RANDOM_FILE_NAME = "random_file_name" QC_TO_MATRIX_EXPECTED = [ "converter = ConversionService(conversion_type='QC_TO_MATRIX'," + " option={'print': 'raw'})\n" + f"result = converter.convert(input_value={VALUE_NAME})", "for gate, name in zip(reversed(result['gate']),reversed(result['name'])):\n" + "\totimes=' \\\\otimes '\n" + "\tprint('\\stackrel{' + otimes.join(name[1]) +'}' + f'{{{gate}}}')\n", ] MATRIX_TO_QC_EXPECTED = [ "converter = ConversionService(conversion_type='MATRIX_TO_QC'," + " option={'label': 'unitary gate'})\n" + "from qiskit import QuantumCircuit\n" + f"""result = converter.convert(input_value={VALUE_NAME}) quantum_circuit = QuantumCircuit(2) quantum_circuit.append(result, list(range(result.num_qubits))) quantum_circuit.measure_all()""", f"""quantum_circuit.draw(output="mpl").savefig("{RANDOM_FILE_NAME + ".png"}", """ + """bbox_inches="tight")""", ] class ConverterWorkerTest(unittest.IsolatedAsyncioTestCase): """test converter worker""" def setUp(self): ConverterWorker.generate_random_file_name = mock.Mock( return_value=RANDOM_FILE_NAME ) ConverterWorker.write_converting_code = mock.Mock(return_value=True) self.quantum_circuit_input = QuantumCircuitInput(VALUE_NAME) self.matrix_input = MatrixInput(2, True) self.matrix_input.value_name = VALUE_NAME def test_generate_conversion_code_quantum_circuit_to_matrix(self): """test generate_conversion_code Conversion method: QC_TO_MATRIX """ worker = ConverterWorker( QuantumExpression.CIRCUIT, QuantumExpression.MATRIX, self.quantum_circuit_input, QUANTUM_CIRCUIT_CODE, False, ) self.assertEqual(worker.generate_conversion_code(), QC_TO_MATRIX_EXPECTED[0]) def test_generate_visualization_code_quantum_circuit_to_matrix(self): """test generate_visualization_code Conversion method: QC_TO_MATRIX """ worker = ConverterWorker( QuantumExpression.CIRCUIT, QuantumExpression.MATRIX, self.quantum_circuit_input, QUANTUM_CIRCUIT_CODE, False, ) self.assertEqual(worker.generate_visualization_code(), QC_TO_MATRIX_EXPECTED[1]) def test_generate_conversion_code_matrix_to_quantum_circuit(self): """test generate_conversion_code Conversion method: MATRIX_TO_QC """ worker = ConverterWorker( QuantumExpression.MATRIX, QuantumExpression.CIRCUIT, self.matrix_input, MATRIX_CODE, False, ) self.assertEqual(worker.generate_conversion_code(), MATRIX_TO_QC_EXPECTED[0]) def test_generate_visualiazation_code_matrix_to_quantum_circuit(self): """test generate_visualization_code Conversion method: MATRIX_TO_QC """ worker = ConverterWorker( QuantumExpression.MATRIX, QuantumExpression.CIRCUIT, self.matrix_input, MATRIX_CODE, False, ) self.assertEqual(worker.generate_visualization_code(), MATRIX_TO_QC_EXPECTED[1]) def test_generate_conversion_code(self): """test generate_conversion_code test it return "" """ worker = ConverterWorker( QuantumExpression.MATRIX, QuantumExpression.MATRIX, None, "", False ) self.assertEqual(worker.generate_conversion_code(), "") def test_generate_visualization_code(self): """test generated_visualization_code test case returns "" """ worker = ConverterWorker( QuantumExpression.CIRCUIT, QuantumExpression.DIRAC, None, "", False ) self.assertEqual(worker.generate_visualization_code(), "print(result)") worker.to_expression = QuantumExpression.NONE self.assertEqual(worker.generate_visualization_code(), "") worker.to_expression = QuantumExpression.CIRCUIT worker.input_data = QuantumCircuitInput(VALUE_NAME) self.assertEqual( worker.generate_visualization_code(), f'{VALUE_NAME}.draw(output="mpl")' + f'.savefig("{RANDOM_FILE_NAME + ".png"}",' + 'bbox_inches="tight")', ) worker.from_expression = QuantumExpression.MATRIX worker.to_expression = QuantumExpression.MATRIX worker.input_data: MatrixInput = MatrixInput(2, True) self.assertEqual( worker.generate_visualization_code(), f"print(array_to_latex({worker.input_data.value_name}, source=True))", ) async def test_run_quantum_circuit_to_matrix(self): """test run method""" worker = ConverterWorker( QuantumExpression.CIRCUIT, QuantumExpression.MATRIX, self.quantum_circuit_input, QUANTUM_CIRCUIT_CODE, False, ) worker.run_subprocess = mock.AsyncMock(return_value=(" ", " ")) worker.cleanup = mock.Mock(return_value=True) worker.draw_latex = mock.Mock(return_value="") run_result = await worker.run() self.assertEqual(run_result, "") worker.cleanup.assert_called_once() worker.run_subprocess.assert_awaited_once() worker.draw_latex.assert_called_once() async def test_run_matrix_to_quantum_circuit(self): """test run matrix to quantum circuit""" worker = ConverterWorker( QuantumExpression.MATRIX, QuantumExpression.CIRCUIT, self.matrix_input, MATRIX_CODE, False, ) worker.run_subprocess = mock.AsyncMock(return_value=(" ", " ")) worker.cleanup = mock.Mock(return_value=True) run_result = await worker.run() self.assertEqual(run_result, f"{RANDOM_FILE_NAME}" + ".png") worker.cleanup.assert_called_once() worker.run_subprocess.assert_awaited_once()
https://github.com/spencerking/QiskitSummerJam-LocalSequenceAlignment
spencerking
pip install qiskit --upgrade pip install numpy --upgrade import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright a = "AACCAGTCG" b = "CACCGTAA" import itertools import numpy as np # Initialize an (n+1)*(m+1) matrix # Where n and m are len(a) and len(b) respectively H = np.zeros((len(a) + 1, len(b) + 1), np.int) # Compare every character in a against every character in b # Matches (white cells) are denoted with 1 for i, j in itertools.product(range(1, H.shape[0]), range(1, H.shape[1])): if a[i - 1] == b[j - 1]: H[i, j] = 1 # print("Before removing extra rows:") # print(H) # TODO # Verify this doesn't break if we swap a and b for x in range(0, abs(H.shape[0] - H.shape[1])): H = np.delete(H, 0, 0) H = np.delete(H, 0, 1) # print("After removing extra rows:") print(H) # print(H.shape[0]) # print(H.shape[1]) # I'm really unsure if this is the right approach diag_H = np.array([]) diagonal = np.diag(H, k=0) # print(diagonal) diag_len = len(diagonal) diag_H = diagonal for i in range(1, H.shape[1]): diagonal = np.diag(H, k=i) # print(diagonal) # If the diagonal is shorter than the rows, append zeros if diag_len > len(diagonal): zeros = np.zeros((1, (diag_len-len(diagonal))), dtype=int) diagonal = np.append(diagonal, zeros) diag_H = np.vstack((diag_H, diagonal)) # Otherwise append the diagonal as a row else: diag_H = np.vstack((diag_H, diagonal)) print(diag_H) # TODO from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library import QFT # Create a 3 qubit quantum register # qr[0] is x, qr[1] is y, qr[2] is f(x,y) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.h(qr[0]) circuit.h(qr[1]) # Feed the circuit into the BB # TODO sub_q = QuantumRegister(3) sub_circ = QuantumCircuit(sub_q, name='BB') sub_inst = sub_circ.to_instruction() circuit.append(sub_inst, [qr[0], qr[1], qr[2]]) # QFT on qr[0] and qr[1] qft = QFT(num_qubits=2) circuit.compose(qft, inplace=True) # Measure all 3 circuit.measure(qr, cr) circuit.draw(output='mpl')
https://github.com/alexyev/quantum_options_pricing
alexyev
#!pip install qiskit #!pip install qiskit_finance import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_finance.circuit.library import LogNormalDistribution num_uncertainty_qubits = 3 spot = 3.0 vol = 0.2 #volatility rate = 0.05 #annual interest rate T = 100 / 365 #100 days until expiry # returns are log-normally distributed, values relating to this distribution shown here mu = (rate - 0.5 * vol ** 2) * T + np.log(spot) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma ** 2 / 2) variance = (np.exp(sigma ** 2) - 1) * np.exp(2 * mu + sigma ** 2) stddev = np.sqrt(variance) # setting the lowest and highest values considered by our model low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # loading the option's probability distribution onto the quantum computer uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma ** 2, bounds=(low, high) ) x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price strike_price = 3.40 # scalar that determines accuracy of final output # the lower the better c_approx = 0.25 # setup piecewise linear # only works if stock price at maturity is above strike breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # use the uncertainty model and the our objective function # to create a quantum circuit num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # show the behaviour of the payoff function x = uncertainty_model.values y = np.maximum(0, x - strike_price) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() exact_value = np.dot(uncertainty_model.probabilities, y) print("exact expected value:\t%.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend("aer_simulator"), shots=1024) problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
https://github.com/alexyev/quantum_options_pricing
alexyev
#!pip install qiskit #!pip install qiskit_finance import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_finance.circuit.library import LogNormalDistribution # Since we're still modelling the same underlying with the same spot price, # we use the same probability loading num_uncertainty_qubits = 3 spot = 3.0 vol = 0.2 #volatility rate = 0.05 #annual interest rate T = 100 / 365 #100 days until expiry # returns are log-normally distributed, values relating to this distribution shown here mu = (rate - 0.5 * vol ** 2) * T + np.log(spot) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma ** 2 / 2) variance = (np.exp(sigma ** 2) - 1) * np.exp(2 * mu + sigma ** 2) stddev = np.sqrt(variance) # setting the lowest and highest values considered by our model low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # loading the option's probability distribution onto the quantum computer uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma ** 2, bounds=(low, high) ) # visualize the encoded probability distribution on the quantum computer x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # Now that we're using a put option, # we compute the payoff if the function falls below the strike # set the strike price strike_price = 3.40 # scalar that determines accuracy of final output # the lower the better rescaling_factor = 0.25 # setup piecewise linear function that only pays # if price falls below our strike breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) european_put = european_put_objective.compose(uncertainty_model, front=True) # visualize the behaviour of the payoff function x = uncertainty_model.values y = np.maximum(0, strike_price - x) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # find the exact expected value of the option classically exact_value = np.dot(uncertainty_model.probabilities, y) print("exact expected value:\t%.4f" % exact_value) epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend("aer_simulator"), shots=100) problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
https://github.com/alexyev/quantum_options_pricing
alexyev
#!pip install qiskit #!pip install qiskit_finance import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import Aer, QuantumRegister, QuantumCircuit, execute, AncillaRegister, transpile from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_finance.circuit.library import LogNormalDistribution # to represent the two different underlyings, we map them to different dimensions # this variable represents the number of uncertainty qubits per dimension num_uncertainty_qubits = 2 # same parameters from European calls and puts spot = 2.0 vol = 0.2 rate = 0.05 T = 100 / 365 # 100 days till options expiry # resulting parameters for log-normal distribution mu = (rate - 0.5 * vol ** 2) * T + np.log(spot) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma ** 2 / 2) variance = (np.exp(sigma ** 2) - 1) * np.exp(2 * mu + sigma ** 2) stddev = np.sqrt(variance) # lowest and highest spot prices considered low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # for simplicity in our use case, we'll say that they both have the same prob. dist. dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma ** 2 * np.eye(dimension) # constructing the circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plotting the uncertainty model into a PDF x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities resolution = np.array([2 ** n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) fig = plt.figure(figsize=(10, 8)) ax = fig.gca(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # to integrate with the quantum adder circuit over the integers, # we need to map our expected spots to integer values, and then # convert them back. Here we calculate the # of qubits needed to do so weights = [] for n in num_qubits: for i in range(n): weights += [2 ** i] # aggregating circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits # num of summation qubits from the adder n_aux = agg.num_qubits - n_s - agg.num_state_qubits # num auxilliary qubits strike_price = 3.40 # mapping the strike price from the real #'s to integer values over # qubits max_value = 2 ** n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2 ** num_uncertainty_qubits - 1) ) # approximation error c_approx = 0.25 #creating a piecewise linear function that only pays # max(S1 + S2 - K, 0) breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2 ** num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the problem in a formal framework qr_state = QuantumRegister(u.num_qubits, "state") # loads the prob. dist. qr_obj = QuantumRegister(1, "obj") # encodes function values ar_sum = AncillaRegister(n_s, "sum") # # of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional ancilla qubits objective_index = u.num_qubits # qubit in which our answer lies #constructing the circuit basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plotting the exact payoff function x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas # # of qubits that encodes the state print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) # running the circuit job = execute(basket_option, backend=Aer.get_backend("statevector_simulator")) # evaluating the statevector we get from the job value = 0 state = job.result().get_statevector() if not isinstance(state, np.ndarray): state = state.data for i, a in enumerate(state): b = ("{0:0%sb}" % num_state_qubits).format(i)[-num_state_qubits:] prob = np.abs(a) ** 2 if prob > 1e-4 and b[0] == "1": value += prob # undoing the earlier integer mapping mapped_value = ( basket_objective.post_processing(value) / (2 ** num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # using amplitude estimation to recover the payoff # set target precision and confidence level epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend("aer_simulator"), shots=100) problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) result = ae.estimate(problem) # check our confidence interval conf_int = ( np.array(result.confidence_interval_processed) / (2 ** num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2 ** num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
https://github.com/qismib/TraNQI
qismib
#importing packages import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * ####################### #IMPLEMENTING QUANTUM CLASS: 1 trainable parameter #Hadamard gate (superposition) + Rotation_Y (trainable parameter) + Measure_Z. Returning the expectation value over n_shots class QuantumCircuit: """ This class provides an interface to interact with our Quantum Circuit """ def __init__(self, n_qubits, backend, shots): #-----Circuit definition self._circuit = qiskit.QuantumCircuit(n_qubits) self.theta = qiskit.circuit.Parameter('theta') all_qubits = [i for i in range (n_qubits)]#qubits vector self._circuit.h(all_qubits)#over all the qubits self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() #----- self.backend = backend self.shots = shots def run(self, thetas): #acting on a simulator t_qc = transpile(self._circuit, self.backend)#matching the features of a quantum device qobj = assemble(t_qc, shots = self.shots, parameter_binds = [{self.theta: theta} for theta in thetas])#assembling features (circuit, sampling, parameter list) job = self.backend.run(qobj)#running on the simulator result = job.result().get_counts() #counts for each values: |0> or |1>. DIVERSO DA LINK counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probability for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) #testing the implementation simulator = qiskit.Aer.get_backend('qasm_simulator') n_qubits = 1 circuit = QuantumCircuit(n_qubits, simulator, 100) print(circuit._circuit) #circuit._circuit.draw(output='mpl')#to print as a pyplot figure (new library needed) exp = circuit.run([np.pi]) print('Expected value for rotation pi: {}'.format(exp[0])) ####################### #CREATING A QUANTUM CLASSICAL CLASS #extending autograd functions for a quantum layer(forward and backward) class HybridFunction(Function): """Hybrid quantum-classical function definition""" @staticmethod def forward(ctx, input, quantum_circuit, shift): """Forward pass computation""" ctx.shift = shift ctx.quantum_circuit = quantum_circuit # context variable (it may take multiple values and return them related to the context). Used to keep track for backpropagation expectation_z = ctx.quantum_circuit.run(input[0].tolist()) #evaluating model with trainable parameter result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) #saves a given tensor for a future call to backward (trainable parameter and the result obtained) return result @staticmethod def backward(ctx, grad_output): #grad_output os previous gradient """Backward computation""" input, expectation =ctx.saved_tensors #evaluated in forward input_list = np.array(input.tolist()) #shifting parameters shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients=[] for i in range(len(input_list)): #evaluating model after shift expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) #evaluating gradient with finite difference formula gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None #returns the chain of previous gradient and evaluated gradient class Hybrid(nn.Module): """Hybrid quantum-cassical layer definition""" def __init__(self, n_qubits ,backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(n_qubits, backend, shots) self.shift = shift #parameter shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) #calling forward and backward ##################3 #DATA LOADING #training data n_samples=100 X_train=datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) #keeping only labels 0 and 1 idx=np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] #tensor values X_train.targets = X_train.targets[idx]#tensor labels #making batches (dim = 1). Ir returns an iterable(pytorch tensor) train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True) data_iter = iter(train_loader)#making the iterable an iterator, an object with the next method that can be used in a for cycle #showing samples n_samples_show = 6 fig, axes = plt.subplots(nrows=1, ncols=int(n_samples_show), figsize=(10, 3)) #subolot returns the figure and axis that are indipendent as default while n_samples_show > 0: images, targets = data_iter.__next__() axes[int(n_samples_show) - 1].imshow(images[0].numpy().squeeze(), cmap='gray')#squeeze removes unuseful dim(1). Converting into a numpy vector axes[int(n_samples_show) - 1].set_xticks([]) axes[int(n_samples_show) - 1].set_yticks([]) axes[int(n_samples_show) - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 #validation data n_samples = 50 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True) ######################### #CREATING THE NN class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) #input = gray scale self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() #deactivating randomly some neurons to avoid overfitting self.fc1 = nn.Linear(256, 64) #input dimension: CH(16) x Matrix_dim (4x4) self.fc2 = nn.Linear(64,1) self.hybrid = Hybrid(n_qubits, qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi/2 ) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)),2) x = F.max_pool2d(F.relu(self.conv2(x)),2) x = self.dropout(x) x = x.view(1,-1) #reshaping tensor x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) #calling the forward method return torch.cat((x, 1-x),-1)#returning probabilities ####################### #TRAINING AND TESTING #function to train the nn def training_loop (n_epochs, optimizer, model, loss_fn, train_loader): loss_values = [] for epoch in range(0, n_epochs, +1): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad()#getting rid of previous gradients output = model(data)#forward pass loss = loss_fn(output, target) loss.backward() optimizer.step()#updating parameters total_loss.append(loss.item())#item transforms into a number loss_values.append(sum(total_loss)/len(total_loss))#obtainign the average loss print('Training [{:.0f}%] Loss: {:.4f}'.format(100*(epoch+1)/n_epochs, loss_values[-1])) return loss_values #defining a function to test our net def validate(model, test_loader, loss_function, n_test, axes): correct = 0 total_loss = [] count = 0 with torch.no_grad(): # disabling the gradient as we don't want to update parameters for batch_idx, (data, target) in enumerate(test_loader): output = model(data) #evaluating the model on test data # evaluating the accuracy of our model pred = output.argmax(dim=1, keepdim=True) # we are interested in the max value of probability correct += pred.eq(target.view_as(pred)).sum().item() # checking if it matches with label #evluating loss function loss = loss_function(output, target) total_loss.append(loss.item()) #printing the resut as images if count >= n_test: continue else: axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred.item())) count += 1 print('Performance on test data: \n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%' .format(sum(total_loss)/len(total_loss),(correct / len(test_loader))*100)) #Training the NN #we can use any optimiser, learning rate and cost/loss function to train over multiple epochs model = Net() params = list(model.parameters()) learning_rate = 0.001 optimizer = optim.Adam(params, learning_rate) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] model.train() #training the module in training mode(specifying the intention to the layers). Used for dropout or batchnorm loss_list = (training_loop(epochs, optimizer, model, loss_func, train_loader)) #plotting the training graph plt.figure(num=2) plt.plot(loss_list) plt.title('Hybrid NN Training convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') ########################### #TESTING THE NN n_test_show = 6 fig, axes = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3)) model.eval() validate(model, test_loader, loss_func, n_test_show, axes) plt.show()
https://github.com/qismib/TraNQI
qismib
# useful additional packages import matplotlib.pyplot as plt #%matplotlib inline import numpy as np from pprint import pprint # importing QISKit from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer qx_config = { "APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829', "url": 'https://quantumexperience.ng.bluemix.net/api' } backend = 'local_qasm_simulator' # run on local simulator by default '''register(qx_config['APItoken'], qx_config['url']) backend = least_busy(available_backends({'simulator': False, 'local': False})) print("the best backend is " + backend) ''' # Creating registers q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # quantum circuit to make an entangled bell state bell = QuantumCircuit(q2, c2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) # quantum circuit to measure q0 in the standard basis measureIZ = QuantumCircuit(q2, c2) measureIZ.measure(q2[0], c2[0]) bellIZ = bell+measureIZ # quantum circuit to measure q0 in the superposition basis measureIX = QuantumCircuit(q2, c2) measureIX.h(q2[0]) measureIX.measure(q2[0], c2[0]) bellIX = bell+measureIX # quantum circuit to measure q1 in the standard basis measureZI = QuantumCircuit(q2, c2) measureZI.measure(q2[1], c2[1]) bellZI = bell+measureZI # quantum circuit to measure q1 in the superposition basis measureXI = QuantumCircuit(q2, c2) measureXI.h(q2[1]) measureXI.measure(q2[1], c2[1]) bellXI = bell+measureXI # quantum circuit to measure q in the standard basis measureZZ = QuantumCircuit(q2, c2) measureZZ.measure(q2[0], c2[0]) measureZZ.measure(q2[1], c2[1]) bellZZ = bell+measureZZ # quantum circuit to measure q in the superposition basis measureXX = QuantumCircuit(q2, c2) measureXX.h(q2[0]) measureXX.h(q2[1]) measureXX.measure(q2[0], c2[0]) measureXX.measure(q2[1], c2[1]) bellXX = bell+measureXX # quantum circuit to make a mixed state mixed1 = QuantumCircuit(q2, c2) mixed2 = QuantumCircuit(q2, c2) mixed2.x(q2) mixed1.h(q2[0]) mixed1.h(q2[1]) mixed1.measure(q2[0], c2[0]) mixed1.measure(q2[1], c2[1]) mixed2.h(q2[0]) mixed2.h(q2[1]) mixed2.measure(q2[0], c2[0]) mixed2.measure(q2[1], c2[1]) '''circuits = [bellIZ,bellIX,bellZI,bellXI,bellZZ,bellXX] job = execute(circuits, backend) result = job.result() print(result.get_counts(bellXX)) plot_histogram(result.get_counts(bellXX))''' mixed_state = [mixed1,mixed2] job = execute(mixed_state, backend) result = job.result() counts1 = result.get_counts(mixed_state[0]) counts2 = result.get_counts(mixed_state[1]) from collections import Counter ground = Counter(counts1) excited = Counter(counts2) plot_histogram(ground+excited)
https://github.com/qismib/TraNQI
qismib
#!/usr/bin/env python # coding: utf-8 import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # importing packages import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * import time # Loading your IBM Quantum account(s) provider = IBMQ.load_account() # GLOBAL VARIABLE DEFINITION n_qubits = 3 simulator = qiskit.Aer.get_backend('qasm_simulator') n_shots = 1000 shift = np.pi / 2 #chosing the real quantum computer or the simulator from qiskit.providers.ibmq import least_busy # We execute on the least busy device (among the actual quantum computers) #simulator = least_busy(provider.backends(operational = True, simulator=False, status_msg='active', # filters=lambda x: x.configuration().n_qubits > 1)) simulator = provider.get_backend('ibmq_athens') print("We are executing on...",simulator) print("It has",simulator.status().pending_jobs,"pending jobs") import itertools # creating a list of all possible outputs of a quantum circuit, used for the expectation value def create_QC_OUTPUTS(n_qubits): measurements = list(itertools.product([1, 0], repeat=n_qubits)) return [''.join([str(bit) for bit in measurement]) for measurement in measurements] # Hadamard gate (superposition) + Rotation_Y (trainable parameter) + Measure_Z. Returning the frequency of results (00, 01, 10, 11 for 2 qubits) class QuantumCircuit: """ This class provides an interface to interact with our Quantum Circuit """ def __init__(self, n_qubits, backend, shots): # -----Circuit definition self._circuit = qiskit.QuantumCircuit(n_qubits) self.n_qubits = n_qubits self.parameters = qiskit.circuit.ParameterVector('parameters', n_qubits) all_qubits = [i for i in range(n_qubits)] # qubits vector self._circuit.h(all_qubits) # over all the qubits self._circuit.barrier() for k in range(n_qubits): self._circuit.ry(self.parameters[k], k) self._circuit.measure_all() # ----- self.backend = backend self.shots = shots self.QC_OUTPUTS = create_QC_OUTPUTS(n_qubits) def expectation_Z_parameters(self, counts, shots, n_qubits): expects = np.zeros(n_qubits) i = 0 for key in counts.keys(): percentage = counts[key] / shots if (i < 3): expects[i] += percentage i += 1 else: i = 0 return expects def expectation_Z_counts(self, counts, shots, n_qubits): expects = np.zeros(len(self.QC_OUTPUTS)) for k in range(len(self.QC_OUTPUTS)): key = self.QC_OUTPUTS[k] perc = counts.get(key, 0) / shots expects[k] = perc return expects def run(self, thetas): # acting on a simulator thetas = thetas.squeeze() # print(thetas) p_circuit = self._circuit.bind_parameters({self.parameters[k]: thetas[k].item() for k in range(self.n_qubits)}) job_sim = qiskit.execute(p_circuit, self.backend, shots=self.shots) result = job_sim.result() counts = result.get_counts(p_circuit) # print('C: ', counts) # expectation_parameters = self.expectation_Z_parameters(counts, self.shots, self.n_qubits) expectation_counts = self.expectation_Z_counts(counts, self.shots, self.n_qubits) return expectation_counts circuit = QuantumCircuit(n_qubits, simulator, n_shots) print(circuit._circuit) circuit._circuit.draw(output = 'mpl', filename = 'N_qubits.png')#to print as a pyplot figure (new library needed) rotation = torch.Tensor([np.pi / 4] * n_qubits) exp = circuit.run(rotation) print('Expected value for rotation pi/4: {}'.format(exp)) class HybridFunction(Function): """Hybrid quantum-classical function definition""" @staticmethod def forward(ctx, input, quantum_circuit, shift): """Forward pass computation""" ctx.shift = shift ctx.quantum_circuit = quantum_circuit # context variable (it may take multiple values and return them related to the context). Used to keep track for backpropagation expectation_z = ctx.quantum_circuit.run(input) # evaluating model with trainable parameter result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) # saves a given tensor for a future call to backward (trainable parameter and the result obtained) # input = parametri che passo(3), result = risultati del calcolo(2**n_qubit) return result @staticmethod def backward(ctx, grad_output): # grad_output os previous gradient """Backward computation""" input, expectation = ctx.saved_tensors # evaluated in forward input = torch.reshape(input, (-1,)) gradients = torch.Tensor() # iterating to evaluate gradient for k in range(len(input)): # shifting parameters shift_right, shift_left = input.detach().clone(), input.detach().clone() shift_right[k] += ctx.shift shift_left[k] -= ctx.shift # evaluating model after shift expectation_right = ctx.quantum_circuit.run(shift_right) expectation_left = ctx.quantum_circuit.run(shift_left) # evaluating gradient with finite difference formula gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients = torch.cat((gradients, gradient.float())) result = gradients.float() * grad_output.float() return (result).T, None, None class Hybrid(nn.Module): """Hybrid quantum-cassical layer definition""" def __init__(self, n_qubits, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(n_qubits, backend, shots) self.shift = shift # parameter shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) # calling forward and backward class AddGaussianNoise(object): def __init__(self, mean=0., std=5): self.std = std self.mean = mean def __call__(self, tensor): return tensor + torch.randn(tensor.size()) * self.std + self.mean def __repr__(self): return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std) #you can chose whether to use noisy training data or not # DATA LOADING # training data n_samples = 100 mean, std_dv = 0, 0.2 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) # keeping only labels 0 and 1 idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] # tensor values X_train.targets = X_train.targets[idx] # tensor labels # making batches (dim = 1). Ir returns an iterable(pytorch tensor) train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True) data_iter = iter( train_loader) # making the iterable an iterator, an object with the next method that can be used in a for cycle # showing samples n_samples_show = 6 fig, axes = plt.subplots(nrows=1, ncols=int(n_samples_show), figsize=(10, 3)) # subolot returns the figure and axis that are indipendent as default while n_samples_show > 0: images, targets = data_iter.__next__() axes[int(n_samples_show) - 1].imshow(images[0].numpy().squeeze(), cmap='gray') # squeeze removes unuseful dim(1). Converting into a numpy vector axes[int(n_samples_show) - 1].set_xticks([]) axes[int(n_samples_show) - 1].set_yticks([]) axes[int(n_samples_show) - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 n_samples = 2000 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True) # CREATING THE NN class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) # input = gray scale self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() # deactivating randomly some neurons to avoid overfitting self.fc1 = nn.Linear(256, 64) # input dimension: CH(16) x Matrix_dim (4x4) self.fc2 = nn.Linear(64, n_qubits) self.hybrid = Hybrid(n_qubits, simulator, n_shots, shift) self.fc3 = nn.Linear(2 ** n_qubits, 2) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), 2) x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = self.dropout(x) x = x.view(1, -1) # reshaping tensor x = F.relu(self.fc1(x)) x = self.fc2(x) # print('Params to QC: ', x) x = self.hybrid(x) # calling the forward method for the quantum layer # print('output of QC', x) x = torch.Tensor(x.float()) x = self.fc3(x) x = torch.softmax(x, dim=1) # evaluating probabilities (loss function is a cross entropy) return x def training_loop (n_epochs, optimizer, model, loss_fn, train_loader): loss_values = [] for epoch in range(0, n_epochs, +1): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad()#getting rid of previous gradients output = model(data)#forward pass loss = loss_fn(output, target) loss.backward() optimizer.step()#updating parameters total_loss.append(loss.item())#item transforms into a number loss_values.append(sum(total_loss)/len(total_loss))#obtainign the average loss print('Training [{:.0f}%] Loss: {:.4f}'.format(100*(epoch+1)/n_epochs, loss_values[-1])) return loss_values ####################### # TRAINING AND TESTING # Training the NN # we can use any optimizer, learning rate and cost/loss function to train over multiple epochs model = Net() params = list(model.parameters()) learning_rate = 0.01 optimizer = optim.Adam(params, learning_rate) loss_func = nn.CrossEntropyLoss() loss_list = [] model.train() # training the module in training mode(specifying the intention to the layers). Used for dropout or batchnorm epochs = 15 begin = time.time() loss_list = (training_loop(epochs, optimizer, model, loss_func, train_loader)) end = time.time() # plotting the training graph plt.figure(num=2) plt.plot(loss_list) plt.title('Hybrid NN Training convergence') plt.xlabel('Training Iterations') plt.ylabel('Cross Entropy Loss') plt.savefig('TC_NQ.pdf') #defining a function to test our net def validate(model, test_loader, loss_function, n_test, axes): correct = 0 total_loss = [] count = 0 with torch.no_grad(): # disabling the gradient as we don't want to update parameters for batch_idx, (data, target) in enumerate(test_loader): output = model(data) #evaluating the model on test data # evaluating the accuracy of our model pred = output.argmax(dim=1, keepdim=True) # we are interested in the max value of probability correct += pred.eq(target.view_as(pred)).sum().item() # checking if it matches with label #evaluating loss function loss = loss_function(output, target) total_loss.append(loss.item()) #printing the resut as images if count >= n_test: continue else: axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('P: {}'.format(pred.item())) count += 1 print('Performance on test data: \n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%' .format(sum(total_loss)/len(total_loss),(correct / len(test_loader))*100)) # TESTING THE NN n_test_show = 6 fig, axes = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3)) model.eval() validate(model, test_loader, loss_func, n_test_show, axes) print('The training has taken : ', end - begin, 's to complete') #testing the NN over set of noisy validation data, with different values of standard deviation class AddGaussianNoise(object): def __init__(self, mean=0., std=5): self.std = std self.mean = mean def __call__(self, tensor): return tensor + torch.randn(tensor.size()) * self.std + self.mean def __repr__(self): return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std) stop,mean, std_dv= 10, 0, 0.1 for i in range (1, stop): print('Gaussian noise with std deviation: ', std_dv) X_test_n = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor(), AddGaussianNoise(mean, std_dv)])) idx = np.append(np.where(X_test_n.targets == 0)[0][:n_samples], np.where(X_test_n.targets == 1)[0][:n_samples]) X_test_n.data = X_test_n.data[idx] # tensor values X_test_n.targets = X_test_n.targets[idx] # tensor labels test_loader_n = torch.utils.data.DataLoader(X_test_n, batch_size=1, shuffle=True) test_iter_n = iter(test_loader_n) fig_1, axes_1 = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3)) model.eval() validate(model, test_loader_n, loss_func, n_test_show, axes_1) std_dv = std_dv + 0.1
https://github.com/qismib/TraNQI
qismib
#------------------------------------------------------------------------------ # Qaoa.py # # Implementation of the Quantum Approximate Optimization Algorithm (QAOA) [1],[2] # specifically tailored for solving the MaxCut problem on graphs [3]. # This class facilitates the creation of QAOA circuits with # various types of mixer operators and allows execution on a quantum simulator # backend provided by Qiskit. # # The `Qaoa` class provides methods to: # - Initialize with QAOA parameters, graph instance, mixer type, and backend settings # - Create cost operator and various mixer operators (x, xx, y, yy, xy) # - Generate the complete QAOA circuit # # Initialization parameters include the number of QAOA layers, angles for the # mixer and cost operators, and options for setting verbosity, measurement, and # random seed. The class checks for consistency in the provided parameters and # supports visualizing the graph and QAOA circuit. # # Refs. # [1] https://arxiv.org/abs/1411.4028 # [2] https://learning.quantum.ibm.com/tutorial/quantum-approximate-optimization-algorithm # [3] https://en.wikipedia.org/wiki/Maximum_cut # # © Leonardo Lavagna 2024 # @ NESYA https://github.com/NesyaLab #------------------------------------------------------------------------------ import numpy as np from matplotlib import pyplot as plt from classes import Problems as P from functions import qaoa_utilities as utils from qiskit import QuantumCircuit from qiskit_aer import Aer from typing import List, Tuple from networkx import Graph from qiskit.circuit import ParameterVector class Qaoa: def __init__(self, p: int = 0, G: Graph = None, betas: List[float] = None, gammas: List[float] = None, mixer: str = "x", backend = Aer.get_backend('qasm_simulator'), measure: bool = True, seed: int = None, verbose: bool = True): """Initialize class QAOA. Args: p (int): Positive number of QAOA layers. The default is 0. G (Graph): A graph created with the Problem class used as MaxCut problem instance. The default is None. betas (float): Angles for the mixer operator. gammas (float): Angles for the cost operator. mixer (str): Type of mixer operator to be used. The default is "x". backend (Qiskit backend): Qiskit backend to execute the code on a quantum simulator. The default is Aer.get_backend('qasm_simulator'). measure (bool): If True measure the qaoa circuit. The default is True. seed (int): Seed for a pseudo-random number generator. The default is None. verbose (bool): If True enters in debugging mode. The default is True. """ # Setup self.p = p self.G = G self.mixer = mixer self.backend = backend self.measure = measure self.verbose = verbose self.seed = seed self.problems_class = P.Problems(p_type="custom", G=self.G) if self.seed is not None: np.random.seed(self.seed) if self.G is None: self.N = 0 self.w = [[]] self.betas = [] self.gammas = [] if self.G is not None: self.N = G.get_number_of_nodes() self.w = G.get_adjacency_matrix() if betas is None or gammas is None: self.betas = utils.generate_parameters(n=self.p, k=1) self.gammas = utils.generate_parameters(n=self.p, k=2) if betas is not None and gammas is not None: self.betas = betas self.gammas = gammas # Checking... if self.problems_class.__class__.__name__ != self.G.__class__.__name__ and G is not None: raise Exception("Invalid parameters. The graph G should be created with the Problems class.") if (self.p == 0 and self.G is not None) or (self.p > 0 and G is None): raise ValueError("If G is not the empty graph p should be a strictly positive integer, and viceversa.") if len(self.betas) != p or len(self.gammas) != p or len(self.betas) != len(self.gammas): raise ValueError("Invalid angles list. The length of betas and gammas should be equal to p.") # Initializing... if self.verbose is True: print(" --------------------------- ") print("| Intializing Qaoa class... |".upper()) print(" --------------------------- ") print("-> Getting problem instance...".upper()) if self.G is not None: self.G.get_draw() plt.show() if self.G is None: print("\t * G = ø") if self.betas is None and self.G is not None: print("-> Beta angles not provided. Generating angles...".upper()) print(f"\t * betas = {self.betas}") if self.gammas is None and self.G is not None: print("-> Gamma angles not provided. Generating angles...".upper()) print(f"\t * gammas = {self.gammas}") print("-> Getting the ansatz...".upper()) if self.G is not None: print(self.get_circuit()) if self.G is None: print("\t * Qaoa circuit = ø") print("-> The Qaoa class was initialized with the following parameters.".upper()) print(f"\t * Number of layers: p = {self.p};") if self.G is None: print(f"\t * Graph: G = ø;") if self.G is not None: print(f"\t * Graph: G = {self.G.p_type};") print("\t * Angles:") print(f"\t\t - betas = {self.betas};") print(f"\t\t - gammas = {self.gammas};") print(f"\t * Mixer Hamiltonian type: '{self.mixer}';") print(f"\t * Random seed: seed = {self.seed};") print(f"\t * Measurement setting: measure = {self.measure}.") def cost_operator(self, gamma: float) -> QuantumCircuit: """Create an instance of the cost operator with angle 'gamma'. Args: gamma (float): Angle for the cost operator. Returns: QuantumCircuit: Circuit representing the cost operator. """ qc = QuantumCircuit(self.N, self.N) for i,j in self.G.get_edges(): qc.cx(i, j) qc.rz(gamma, j) qc.cx(i, j) return qc def x_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the x-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for v in self.G.get_nodes(): qc.rx(beta, v) return qc def xx_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the xx-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.rxx(beta, i, j) return qc def y_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the y-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for v in self.G.get_nodes(): qc.ry(2 * beta, v) return qc def yy_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the yy-mixer operator with angle 'beta'. Args: beta (float): Time-slice angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.ryy(beta / 2, i, j) return qc def xy_mixer_operator(self, phi: float, psi: float) -> QuantumCircuit: """Create an instance of the xy-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) # X_iX_j for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.rxx(phi / 2, i, j) # Y_iY_j for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.ryy(psi / 2, i, j) return qc def get_circuit(self) -> QuantumCircuit: """Create an instance of the Qaoa circuit with given parameters. Returns: QuantumCircuit: Circuit representing the Qaoa. """ qc = QuantumCircuit(self.N, self.N) params = ParameterVector("params", 2 * self.p) betas = params[0 : self.p] gammas = params[self.p : 2 * self.p] qc.h(range(self.N)) qc.barrier(range(self.N)) for i in range(self.p): qc = qc.compose(self.cost_operator(gammas[i])) qc.barrier(range(self.N)) if self.mixer == "x": qc = qc.compose(self.x_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "xx": qc = qc.compose(self.xx_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "y": qc = qc.compose(self.y_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "yy": qc = qc.compose(self.yy_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "xy": qc = qc.compose(self.xy_mixer_operator(betas[i],betas[i])) qc.barrier(range(self.N)) qc.barrier(range(self.N)) if self.measure: qc.measure(range(self.N), range(self.N)) return qc
https://github.com/qismib/TraNQI
qismib
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.tools.monitor import * import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble import time # Loading your IBM Quantum account(s) provider = IBMQ.load_account() #backend_overview() # In[2]: #GLOBAL VARIABLES n_qubits = 1 n_shots = 1000 shift = np.pi/2 n_parameters = 3 momentum = 0.5 simulator = qiskit.Aer.get_backend('qasm_simulator') #can choose the simulator or the real quantum computer. The name of the variable is always 'simulator' from qiskit.providers.ibmq import least_busy from qiskit import IBMQ # We execute on the least busy device (among the actual quantum computers) #simulator = least_busy(provider.backends(operational = True, simulator=False, status_msg='active', #filters=lambda x: x.configuration().n_qubits > 1)) simulator = provider.get_backend('ibmq_athens') print("We are executing on...",simulator) print("It has",simulator.status().pending_jobs,"pending jobs") #IMPLEMENTING QUANTUM CLASS: 3 trainable parameters #Hadamard gate (superposition) + U_gate (3 trainable parameters) + Measure_Z. Returning the expectation value over n_shots class QuantumCircuit: """ This class provides an interface to interact with our Quantum Circuit """ def __init__(self, n_qubits, backend, shots): #-----Circuit definition self._circuit = qiskit.QuantumCircuit(n_qubits) self.parameters = qiskit.circuit.ParameterVector('parameters', 3) all_qubits = [i for i in range (n_qubits)]#qubits vector self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.u(self.parameters[0], self.parameters[1], self.parameters[2], all_qubits) self._circuit.measure_all() #----- self.backend = backend self.shots = shots self.n_qubits = n_qubits def draw(self): self._circuit.draw(output ='mpl') def expectation_Z(self,counts, shots, n_qubits): expects = np.zeros(n_qubits) for key in counts.keys(): percentage = counts[key]/shots check = np.array([(float(key[i]))*percentage for i in range(n_qubits)]) expects += check return expects def run(self, thetas): #acting on a simulator thetas = thetas.squeeze() p_circuit = self._circuit.bind_parameters({self.parameters[k]: thetas[k].item() for k in range(len(thetas))}) job_sim = qiskit.execute(p_circuit, self.backend, shots=self.shots) result = job_sim.result() counts = result.get_counts(p_circuit) #print(counts['0'], counts['1']) return self.expectation_Z(counts, self.shots, self.n_qubits) #testing the implementation circuit = QuantumCircuit(n_qubits, simulator, n_shots) print(circuit._circuit) circuit._circuit.draw(output = 'mpl', filename = 'U3_circuit.png')#to print as a pyplot figure (new library needed) rotation = torch.Tensor([np.pi/4]*3) exp = circuit.run(rotation) print('Expected value for rotation pi: {}'.format(exp)) ####################### #CREATING A QUANTUM CLASSICAL CLASS #extending autograd functions for a quantum layer(forward and backward) class HybridFunction(Function): """Hybrid quantum-classical function definition""" @staticmethod def forward(ctx, input, quantum_circuit, shift): """Forward pass computation""" ctx.shift = shift ctx.quantum_circuit = quantum_circuit # context variable (it may take multiple values and return them related to the context). Used to keep track for backpropagation expectation_z = ctx.quantum_circuit.run(input) # evaluating model with trainable parameter result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) # saves a given tensor for a future call to backward (trainable parameter and the result obtained) # input=parameters (3), result=resut of quantum operation (1) return result @staticmethod def backward(ctx, grad_output): #grad_output os previous gradient """Backward computation""" input, expectation = ctx.saved_tensors #evaluated in forward input = torch.reshape(input, (-1,)) gradients = torch.Tensor() #iterating to evaluate gradient for k in range(len(input)): #shifting parameters shift_right, shift_left = input.detach().clone(), input.detach().clone() shift_right[k] += ctx.shift shift_left[k] -= ctx.shift # evaluating model after shift expectation_right = ctx.quantum_circuit.run(shift_right) expectation_left = ctx.quantum_circuit.run(shift_left) #evaluating gradient with finite difference formula gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients = torch.cat((gradients, gradient.float())) result = gradients.float() * grad_output.float() return (result).T, None, None #returns the chain of previous gradient and evaluated gradient class Hybrid(nn.Module): """Hybrid quantum-cassical layer definition""" def __init__(self, n_qubits ,backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(n_qubits, backend, shots) self.shift = shift #parameter shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) #calling forward and backward class AddGaussianNoise(object): def __init__(self, mean=0., std=5): self.std = std self.mean = mean def __call__(self, tensor): return tensor + torch.randn(tensor.size()) * self.std + self.mean def __repr__(self): return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std) #DATA LOADING #training data, can chose whether to use a noisy set of training data n_samples = 100 std_dv, mean = 0.3, 0 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) #X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), # AddGaussianNoise(mean, std_dv)])) #keeping only labels 0 and 1 idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] #tensor values X_train.targets = X_train.targets[idx]#tensor labels #making batches (dim = 1). Ir returns an iterable(pytorch tensor) train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True) data_iter = iter(train_loader)#making the iterable an iterator, an object with the next method that can be used in a for cycle #showing samples n_samples_show = 6 fig, axes = plt.subplots(nrows=1, ncols=int(n_samples_show), figsize=(10, 3)) #subolot returns the figure and axis that are indipendent as default while n_samples_show > 0: images, targets = data_iter.__next__() axes[int(n_samples_show) - 1].imshow(images[0].numpy().squeeze(), cmap='gray')#squeeze removes unuseful dim(1). Converting into a numpy vector axes[int(n_samples_show) - 1].set_xticks([]) axes[int(n_samples_show) - 1].set_yticks([]) axes[int(n_samples_show) - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 #validation data n_samples = 2000 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True) #CREATING THE NN class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) #input = gray scale self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() #deactivating randomly some neurons to avoid overfitting self.fc1 = nn.Linear(256, 64) #input dimension: CH(16) x Matrix_dim self.fc2 = nn.Linear(64,3) self.hybrid = Hybrid(n_qubits, simulator, n_shots, shift ) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)),2) x = F.max_pool2d(F.relu(self.conv2(x)),2) x = self.dropout(x) x = x.view(1,-1) #reshaping tensor x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) #calling the forward method return torch.cat((x, 1-x),-1)#returning probabilities ####################### #TRAINING AND TESTING #function to train the nn def training_loop (n_epochs, optimizer, model, loss_fn, train_loader): loss_values = [] for epoch in range(0, n_epochs, +1): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad()#getting rid of previous gradients output = model(data)#forward pass loss = loss_fn(output, target) loss.backward() optimizer.step()#updating parameters total_loss.append(loss.item())#item transforms into a number loss_values.append(sum(total_loss)/len(total_loss))#obtainign the average loss print('Training [{:.0f}%] Loss: {:.4f}'.format(100*(epoch+1)/n_epochs, loss_values[-1])) return loss_values #Training the NN #we can use any optimizer, learning rate and cost/loss function to train over multiple epochs model = Net() params = list(model.parameters()) epochs = 20 optimizer = optim.SGD(params, learning_rate, momentum=momentum) loss_func = nn.CrossEntropyLoss() loss_list = [] model.train() #training the module in training mode(specifying the intention to the layers). Used for dropout or batchnorm begin = time.time() loss_list = (training_loop(epochs, optimizer, model, loss_func, train_loader)) end = time.time() #plotting the training graph plt.figure(num=2) plt.plot(loss_list) plt.title('Hybrid NN Training convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') plt.savefig('TC_U3.pdf') #defining a function to test our net def validate(model, test_loader, loss_function, n_test, axes): correct = 0 total_loss = [] count = 0 with torch.no_grad(): # disabling the gradient as we don't want to update parameters for batch_idx, (data, target) in enumerate(test_loader): output = model(data) #evaluating the model on test data # evaluating the accuracy of our model pred = output.argmax(dim=1, keepdim=True) # we are interested in the max value of probability correct += pred.eq(target.view_as(pred)).sum().item() # checking if it matches with label #evluating loss function loss = loss_function(output, target) total_loss.append(loss.item()) #printing the resut as images if count >= n_test: continue else: axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('P: {}'.format(pred.item())) count += 1 print('Performance on test data: \n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%' .format(sum(total_loss)/len(total_loss),(correct / len(test_loader))*100)) #TESTING THE NN n_test_show = 6 model.eval() validate(model, test_loader, loss_func, n_test_show, axes) print('The program took: ', end- begin, 's to complete') plt.show() ########################## #testing the NN with noisy validation data class AddGaussianNoise(object): def __init__(self, mean=0., std=5): self.std = std self.mean = mean def __call__(self, tensor): return tensor + torch.randn(tensor.size()) * self.std + self.mean def __repr__(self): return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std) stop,mean, std_dv= 9, 0, 0.2 for i in range (1, stop): std_dv = std_dv + 0.1 print('Gaussian noise with std deviation: ', std_dv) X_test_n = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor(), AddGaussianNoise(mean, std_dv)])) idx = np.append(np.where(X_test_n.targets == 0)[0][:n_samples], np.where(X_test_n.targets == 1)[0][:n_samples]) X_test_n.data = X_test_n.data[idx] # tensor values X_test_n.targets = X_test_n.targets[idx] # tensor labels test_loader_n = torch.utils.data.DataLoader(X_test_n, batch_size=1, shuffle=True) test_iter_n = iter(test_loader_n) fig_1, axes_1 = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3)) model.eval() validate(model, test_loader_n, loss_func, n_test_show, axes_1)
https://github.com/TanveshT/IBM-Quantum-Challenge
TanveshT
# Cell 1 import numpy as np from qiskit import Aer, QuantumCircuit, execute from qiskit.visualization import plot_histogram from IPython.display import display, Math, Latex from may4_challenge import plot_state_qsphere from may4_challenge.ex1 import minicomposer from may4_challenge.ex1 import check1, check2, check3, check4, check5, check6, check7, check8 from may4_challenge.ex1 import return_state, vec_in_braket, statevec # Cell 2 # press shift + return to run this code cell # then, click on the gate that you want to apply to your qubit # next, you have to choos # the qubit that you want to apply it to (choose '0' here) # click on clear to restart minicomposer(1, dirac=True, qsphere=True) # Cell 3 def create_circuit(): qc = QuantumCircuit(1) qc.x(0) return qc # check solution qc = create_circuit() state = statevec(qc) check1(state) plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) # Cell 4 def create_circuit2(): qc = QuantumCircuit(1) qc.h(0) return qc qc = create_circuit2() state = statevec(qc) check2(state) plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) # Cell 5 def create_circuit3(): qc = QuantumCircuit(1) qc.x(0) qc.h(0) return qc qc = create_circuit3() state = statevec(qc) check3(state) plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) # Cell 6 def create_circuit4(): qc = QuantumCircuit(1) qc.x(0) qc.h(0) qc.s(0) return qc qc = create_circuit4() state = statevec(qc) check4(state) plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) # Cell 7 # press shift + return to run this code cell # then, click on the gate that you want to apply followed by the qubit(s) that you want it to apply to # for controlled gates, the first qubit you choose is the control qubit and the second one the target qubit # click on clear to restart minicomposer(2, dirac = True, qsphere = True) # Cell 8 def create_circuit(): qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) return qc qc = create_circuit() state = statevec(qc) # determine final state after running the circuit display(Math(vec_in_braket(state.data))) check5(state) qc.draw(output='mpl') # we draw the circuit # Cell 9 def create_circuit6(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also # two classical bits for the measurement later qc.h(0) qc.cx(0,1) qc.y(1) return qc qc = create_circuit6() state = statevec(qc) # determine final state after running the circuit display(Math(vec_in_braket(state.data))) check6(state) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 qc.draw(output='mpl') # we draw the circuit # Cell 10 def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 1000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 1000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) check plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def create_circuit6(): qc = QuantumCircuit(3,3) # this time, we not only want two qubits, but also # two classical bits for the measurement later qc.h(0) qc.cx(0,1) qc.cx(1,2) return qc qc = create_circuit6() state = statevec(qc) display(Math(vec_in_braket(state.data))) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) qc.measure(2,2)# we perform a measurement on qubit q_1 and store the information on the classical bit c_1 qc.draw(output='mpl') # we draw the circuit def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) check8(counts) plot_histogram(counts)
https://github.com/TanveshT/IBM-Quantum-Challenge
TanveshT
#initialization %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import IBMQ from qiskit.compiler import transpile, assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.visualization import * from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter provider = IBMQ.load_account() # load your IBM Quantum Experience account # If you are a member of the IBM Q Network, fill your hub, group, and project information to # get access to your premium devices. # provider = IBMQ.get_provider(hub='', group='', project='') from may4_challenge.ex2 import get_counts, show_final_answer num_qubits = 5 meas_calibs, state_labels = complete_meas_cal(range(num_qubits), circlabel='mcal') # find the least busy device that has at least 5 qubits backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= num_qubits and not x.configuration().simulator and x.status().operational==True)) backend # run experiments on a real device shots = 8192 experiments = transpile(meas_calibs, backend=backend, optimization_level=3) job = backend.run(assemble(experiments, shots=shots)) print(job.job_id()) %qiskit_job_watcher # get measurement filter cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter #print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() # get noisy counts noisy_counts = get_counts(backend) plot_histogram(noisy_counts[0]) # apply measurement error mitigation and plot the mitigated counts mitigated_counts_0 = meas_filter.apply(noisy_counts[0]) plot_histogram([mitigated_counts_0, noisy_counts[0]]) # uncomment whatever answer you think is correct # answer1 = 'a' # answer1 = 'b' answer1 = 'c' # answer1 = 'd' # plot noisy counts plot_histogram(noisy_counts[1]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[1] mitigated_counts_1 = meas_filter.apply(noisy_counts[1]) plot_histogram([mitigated_counts_1, noisy_counts[1]]) # uncomment whatever answer you think is correct # answer2 = 'a' #answer2 = 'b' #answer2 = 'c' answer2 = 'd' # plot noisy counts plot_histogram(noisy_counts[2]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[2] mitigated_counts_2 = meas_filter.apply(noisy_counts[2]) plot_histogram([mitigated_counts_2, noisy_counts[2]]) # uncomment whatever answer you think is correct # answer3 = 'a' answer3 = 'b' #answer3 = 'c' # answer3 = 'd' # plot noisy counts plot_histogram(noisy_counts[3]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[3] mitigated_counts_3 = meas_filter.apply(noisy_counts[3]) plot_histogram([mitigated_counts_3, noisy_counts[3]]) # uncomment whatever answer you think is correct #answer4 = 'a' answer4 = 'b' #answer4 = 'c' #answer4 = 'd' # answer string show_final_answer(answer1, answer2, answer3, answer4)
https://github.com/TanveshT/IBM-Quantum-Challenge
TanveshT
%matplotlib inline # Importing standard Qiskit libraries import random from qiskit import execute, Aer, IBMQ, QuantumCircuit from qiskit.tools.jupyter import * from qiskit.visualization import * from may4_challenge.ex3 import alice_prepare_qubit, check_bits, check_key, check_decrypted, show_message # Configuring account provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \ # Initial setup random.seed(84) # do not change this seed, otherwise you will get a different key # This is your 'random' bit string that determines your bases numqubits = 100 bob_bases = str('{0:0100b}'.format(random.getrandbits(numqubits))) def bb84(): print('Bob\'s bases:', bob_bases) # Now Alice will send her bits one by one... all_qubit_circuits = [] for qubit_index in range(numqubits): # This is Alice creating the qubit thisqubit_circuit = alice_prepare_qubit(qubit_index) # This is Bob finishing the protocol below bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit) # We collect all these circuits and put them in an array all_qubit_circuits.append(thisqubit_circuit) # Now execute all the circuits for each qubit results = execute(all_qubit_circuits, backend=backend, shots=1).result() # And combine the results bits = '' for qubit_index in range(numqubits): bits += [measurement for measurement in results.get_counts(qubit_index)][0] return bits # Here is your task def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): # # # insert your code here to measure Alice's bits # # if bob_bases[qubit_index] == '1': qubit_circuit.h(0) qubit_circuit.measure(0,0) bits = bb84() print('Bob\'s bits: ', bits) check_bits(bits) alice_bases = '10000000000100011111110011011001010001111101001101111110001100000110000010011000111'\ '00111010010000110' # Alice's bases bits # # # insert your code here to extract the key # # key = '' n = len(alice_bases) for i in range(n): if bob_bases[i] == alice_bases[i]: key+=bits[i] check_key(key) m = '0011011010100011101000001100010000001000011000101110110111100111111110001111100011100101011010111010111010001'\ '1101010010111111100101000011010011011011011101111010111000101111111001010101001100101111011' # encrypted message # # # insert your code here to decrypt the message # # n = len(m) decrypted = '' for i in range(n): decrypted += str( int(key[i%50]) ^ int(m[i]) ) check_decrypted(decrypted) MORSE_CODE_DICT = { 'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-', 'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} # # # insert your code here to decode Alice's Morse code # # MORSE_CODE_REVERSE_DICT = dict([(value, key) for key, value in MORSE_CODE_DICT.items()]) solution = '' for word in decrypted.split('000'): for letter in word.split('00'): full_code = '' for morse_character in letter.split('0'): if morse_character == '1': full_code += '.' else: full_code += '-' solution += MORSE_CODE_REVERSE_DICT[full_code] solution+= ' ' show_message(solution)
https://github.com/TanveshT/IBM-Quantum-Challenge
TanveshT
from may4_challenge.ex4 import get_unitary U = get_unitary() print(U) print("U has shape", U.shape) from qiskit import QuantumCircuit, Aer, QuantumRegister from may4_challenge.ex4 import check_circuit, submit_circuit from qiskit.compiler import transpile from qiskit.extensions.quantum_initializer.isometry import Isometry from qiskit.quantum_info import Operator import numpy as np from scipy.linalg import hadamard from qiskit.quantum_info.operators.predicates import is_isometry ##### build your quantum circuit here qc = QuantumCircuit(4) # apply operations to your quantum circuit here def recursiveKronecker(k, hmat): if 2**(k-1) == 1: return hmat else: return np.kron(hmat, recursiveKronecker(k-1, hmat)) h2 = np.matrix([[1,1],[1,-1]]) h2 = h2/(2**0.5) h = recursiveKronecker(4, h2) v = h*U*h qc.h([0,1,2,3]) qc.isometry(v,[0,1,2,3],[]) qc.h([0,1,2,3]) sim = Aer.get_backend('qasm_simulator') new_qc = transpile(qc, backend = sim, seed_transpiler=11, optimization_level=2, basis_gates = ['u3','cx']) qc_basis = new_qc.decompose() qc.draw() ##### check your quantum circuit by running the next line check_circuit(qc_basis) # Send the circuit as the final answer, can re-submit at any time submit_circuit(qc_basis)
https://github.com/TheGupta2012/QickStart-Challenges
TheGupta2012
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" from qiskit import QuantumCircuit def make_bell_state(): qc = QuantumCircuit(2) ### your code here qc.x(0) qc.h(0) qc.cx(0,1) ### your code here return qc def test_function_1(): circuit = make_bell_state() return circuit test_function_1().draw() from grader.graders.problem_1.grader import grader1 grader1.evaluate(make_bell_state) def superposition_operation(n): qc = QuantumCircuit(n) ### Your code here for i in range(n): qc.h(i) ### Your code here return qc def test_function_2(): n = 5 operation = superposition_operation(n) return operation test_function_2().draw() from grader.graders.problem_1.grader import grader2 grader2.evaluate(superposition_operation) def make_even_odd(n): even = QuantumCircuit(n) odd = QuantumCircuit(n) ### your code here for i in range(1,n): even.h(i) odd.h(i) odd.x(0) ### your code here return (even, odd) def test_function_3(): n = 3 even, odd = make_even_odd(n) return even, odd even, odd = test_function_3() display(even.draw('mpl')) odd.draw('mpl') from grader.graders.problem_1.grader import grader3 grader3.evaluate(make_even_odd)
https://github.com/TheGupta2012/QickStart-Challenges
TheGupta2012
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" def get_min_swaps_line(N, controls, targets, connectivity_map): min_swaps = [] ### You code goes here length=len(controls) for i in range(length): if(targets[i] in connectivity_map[controls[i]]): min_swaps.append(0) else: min_swaps.append(abs(targets[i]-controls[i])-1) ### your code goes here return min_swaps def test_function_1(): controls = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5] targets = [2,3,4,5,1,3,4,5,1,2,4,5,1,2,3,5,1,2,3,4] connectivity_map = { 1 : [2], 2 : [1,3], 3 : [2,4], 4 : [3,5], 5 : [4] } N = 5 min_swaps = get_min_swaps_line(N, controls, targets, connectivity_map) return min_swaps test_function_1() from grader.graders.problem_2.grader import grader1 grader1.evaluate(get_min_swaps_line) import sys def get_min_swaps_graph(N, M, controls, targets, connectivity_map): min_swaps = [] ### You code goes here length=len(controls) for i in range(length): if(targets[i] in connectivity_map[controls[i]]): min_swaps.append(0) else: u=controls[i] v=targets[i] visited=[] distance=[] q=[] for i in range(N): visited.append(0) distance.append(sys.maxsize) for k in connectivity_map[u]: distance[k-1]=1 distance[u-1]=0 q.append(u) visited[u-1]=1 while(q): x=q.pop(0) templist=connectivity_map[x] length2=len(templist) for j in range(length2): if(visited[templist[j]-1]==1): continue if((distance[x-1]+1)<distance[templist[j]-1]): distance[templist[j]-1]=distance[x-1]+1 q.append(templist[j]) visited[templist[j]-1]=1 if(distance[v-1]==sys.maxsize): min_swaps.append(-1) continue min_swaps.append(distance[v-1]-1) ### your code goes here return min_swaps def test_function_2(): controls = [1, 2] targets = [2, 5] connectivity_map = { 1 : [2], 2 : [1,3], 3 : [2,4,5], 4 : [3], 5 : [3] } N = 5 M = 4 min_swaps = get_min_swaps_graph(N, M, controls, targets, connectivity_map) return min_swaps test_function_2() from grader.graders.problem_2.grader import grader2 grader2.evaluate(get_min_swaps_graph)
https://github.com/TheGupta2012/QickStart-Challenges
TheGupta2012
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition import numpy as np # build the quantum circuit q = QuantumCircuit(1) # init the state q.h(0) q.rz(np.pi/2,0) # already |0> # apply transformation q.rz(0, 0) q.rx(np.pi/2, 0) q.ry(0, 0) visualize_transition(q) def generate_bloch_operation(state): rotation = [0,0,0] ### Your code goes here if(state=='1'): rotation=[0,0,-2] elif(state=='+'): rotation=[0,0,-1] elif(state=='-'): rotation=[0,0,1] elif(state=='r'): rotation=[0,1,0] elif(state=='l'): rotation=[0,-1,0] ### Your code goes here return rotation def test_function_1(): state = '+' rotation = generate_bloch_operation(state) return rotation test_function_1() from grader.graders.problem_3.grader import grader1 grader1.evaluate(generate_bloch_operation) def get_total_bloch_ops(state, arz, arx, ary): total = 0 qc=QuantumCircuit(1) ### Your code goes here for i in arz: for j in arx: for k in ary: qc.reset(0) if(state=='1'): qc.x(0) elif(state=='+'): qc.h(0) elif(state=='-'): qc.x(0) qc.h(0) elif(state=='r'): qc.h(0) qc.rz(np.pi/2,0) elif(state=='l'): qc.h(0) qc.rz(-np.pi/2,0) qc.rz(i*np.pi/2,0) qc.rx(j*np.pi/2,0) qc.ry(k*np.pi/2,0) ### Your code goes here return total def test_function_2(): # say we have these arrays arz = [2] arx = [-2] ary = [0, 2] # initial state is |0> state = '0' # your function would return these two things total = get_total_bloch_ops(state, arz, arx, ary) return total test_function_2() from grader.graders.problem_3.grader import grader2 grader2.evaluate(get_total_bloch_ops) def get_larger_total_bloch_ops(state, arz, arx, ary): total = 0 ### Your code goes here ### Your code goes here return total def test_function_3(): # say we have these arrays arz = [2] arx = [-2] ary = [0, 2] # initial state is |0> state = '0' # your function would return these two things total = get_larger_total_bloch_ops(state, arz, arx, ary) return total test_function_3() from grader.graders.problem_3.grader import grader3 grader3.evaluate(get_larger_total_bloch_ops)
https://github.com/TheGupta2012/QickStart-Challenges
TheGupta2012
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" from qiskit import QuantumCircuit def dj_circuit_2q(oracle): dj_circuit = QuantumCircuit(3,2) ### Your code here dj_circuit.x(2) dj_circuit.barrier() dj_circuit.h(range(3)) dj_circuit.barrier() dj_circuit.compose(oracle, inplace = True) dj_circuit.barrier() dj_circuit.h(range(2)) dj_circuit.measure(range(2), range(2)) ### Your code here return dj_circuit def test_function_1(): # a constant oracle with f(x)=0 for all inputs oracle = QuantumCircuit(3) oracle.id(2) dj_circuit = dj_circuit_2q(oracle) return dj_circuit test_function_1().draw() from grader.graders.problem_4.grader import grader1 grader1.evaluate(dj_circuit_2q) def dj_circuit_4q(oracle): circuit = QuantumCircuit(5, 4) ### Your code here circuit.x(4) circuit.barrier() circuit.h(range(5)) circuit.barrier() circuit.compose(oracle, inplace = True) circuit.barrier() circuit.h(range(4)) circuit.measure(range(4), range(4)) ### Your code here return circuit def test_function_2(): oracle = QuantumCircuit(5) oracle.id(4) dj_circuit = dj_circuit_4q(oracle) return dj_circuit test_function_2().draw() from grader.graders.problem_4.grader import grader2 grader2.evaluate(dj_circuit_4q) from qiskit import QuantumCircuit def dj_circuit_general(n, oracle): dj_circuit = QuantumCircuit(n+1, n) ### Your code here dj_circuit.x(n) dj_circuit.barrier() dj_circuit.h(range(n+1)) dj_circuit.barrier() dj_circuit.compose(oracle, inplace = True) dj_circuit.barrier() dj_circuit.h(range(n)) dj_circuit.measure(range(n), range(n)) ### Your code here return dj_circuit def test_function_3(): N = 6 # constant oracle with f(x) = 0 oracle = QuantumCircuit(7) oracle.id(6) circuit = dj_circuit_general(N, oracle) return circuit test_function_3().draw() from grader.graders.problem_4.grader import grader3 grader3.evaluate(dj_circuit_general)
https://github.com/TheGupta2012/QickStart-Challenges
TheGupta2012
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" from qiskit import QuantumCircuit from numpy import * def qram_4q(m, array): ### your code here size=int(floor(log2(m))+3) n=size-2 qc=QuantumCircuit(size) binary=[] k=str(n) for i in array: binary.append(format(i, f'0{k}b')) i=0 qc.h(0) qc.h(1) qc.x(0) qc.x(1) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) i=i+1 qc.x(0) qc.x(1) qc.x(1) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) i=i+1 qc.x(1) qc.x(0) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) i=i+1 qc.x(0) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) return qc ### your code here def test_function_1(): m = 6 array = [3, 4, 5, 6] qram = qram_4q(m, array) return qram test_function_1().draw('mpl') from grader.graders.problem_5.grader import grader1 grader1.evaluate(qram_4q) def qram_general(n, m, array): ### your code here k=int(floor(log2(m))+1) l=int(log2(n)) size=k+l qc=QuantumCircuit(size) index=list(range(l)) binary=[] for i in array: binary.append(format(i, f'0{k}b')) qc.h(index) for i in range(n): b=format(i,f'0{l}b') inverted=[] for p in range(0,l): if(b[p]=='0'): qc.x(l-p-1) inverted.append(l-p-1) for j in range(1,k+1): if(binary[i][j-1]=='1'): qc.mct(index,size-j) for q in inverted: qc.x(q) return qc ### your code here def test_function_2(): n = 4 m = 4 array = [3,4,5,6] qram = qram_general(n, m, array) return qram test_function_2().draw('mpl') from grader.graders.problem_5.grader import grader2 grader2.evaluate(qram_general) from qiskit.circuit.library import RYGate,RXGate,RZGate def qram_rotations(n, rotations): ### your code here l=int(log2(n)) size=l+1 qc=QuantumCircuit(size) index=list(range(l)) full=list(range(size)) qc.h(index) for i in range(n): b=format(i,f'0{l}b') inverted=[] for p in range(0,l): if(b[p]=='0'): qc.x(l-p-1) inverted.append(l-p-1) qc.barrier() if(rotations[i][0]=='x'): multirx = RXGate(rotations[i][1]*2*pi).control(l,label=None) qc.append(multirx,full) elif(rotations[i][0]=='y'): multiry = RYGate(rotations[i][1]*2*pi).control(l,label=None) qc.append(multiry,full) elif(rotations[i][0]=='z'): multirz = RZGate(rotations[i][1]*2*pi).control(l,label=None) qc.append(multirz,full) qc.barrier() for q in inverted: qc.x(q) qc.barrier() return qc ### your code here def test_function_3(): n = 8 rotations = [('x', 0.123), ('y', -0.912),('z',-0.12),('x', 0.5),('z',0.5),('y', -0.5),('z',0.5),('x', 0.5)] qram = qram_rotations(n, rotations) return qram test_function_3().draw('mpl') from grader.graders.problem_5.grader import grader3 grader3.evaluate(qram_rotations)
https://github.com/emad-boosari/QuEST_Group
emad-boosari
# Packeges you must load from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import transpile from qiskit.providers.aer import QasmSimulator # The packeges you should load )() from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere from qiskit.quantum_info import DensityMatrix # For using Density matrix from qiskit.visualization import plot_state_city from qiskit.visualization import plot_state_hinton from qiskit.visualization import plot_state_paulivec from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.draw('mpl') ψ1 = Statevector(qc) ψ1.draw('latex') plot_state_qsphere(qc) Statevector(qc).draw('latex') ρ1 = DensityMatrix(qc) ρ1.draw('latex',prefix = '\\rho_1 = ') plot_state_city(qc) plot_state_hinton(qc) plot_state_paulivec(qc) plot_bloch_multivector(qc) qc.measure(q[0],c[0]) qc.draw('mpl') backend = QasmSimulator() result = backend.run(transpile(qc,backend),shots=1024).result() counts = result.get_counts() plot_histogram(counts) # It can be nice if you try the effect of different gates on a circuit with one qubit gate
https://github.com/emad-boosari/QuEST_Group
emad-boosari
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector, Operator from qiskit.visualization import plot_histogram # let me consider an arbitrary quantum circuit with 4 qubits and 4 classical bits qc = QuantumCircuit(4,4) # I apply some initial single quantum gates # These gates are also arbitrary without a particular purpose qc.h(range(4)) qc.barrier() qc.draw('mpl',initial_state=True) # To build a gate we define a quantum circuit without classical bit like below gate1 = QuantumCircuit(2, name = 'gate1') # Then we can use a bunch of the Qiskit gates in order to build an arbitrary gate. gate1.cz(0,1) gate1.x(0) gate1.barrier() gate1.h(1) gate1.barrier() gate1.cx(0,1) # Make this circuit as a gate for qiskit gate1.to_gate gate1.draw('mpl') # Now we can apply our gate on the qc circuit qc.append(gate1,[0,1]) qc.append(gate1,[0,2]) qc.append(gate1,[1,3]) qc.append(gate1,[0,3]) display(qc.draw('mpl'),Statevector(qc).draw('latex')) import numpy as np # you can write any unitary gate that you need. In the following I am trying to build one uni = np.zeros((4,4)) uni[0,0] = 1 uni[3,3] = 1 uni[1,2] = 1 uni[2,1] = 1 print(uni) # test of being unitary np.dot(np.transpose(uni),uni) from qiskit.quantum_info import Operator gate2 = Operator(uni) qc.barrier() qc.unitary(gate2,(2,3),label='gate2') qc.draw('mpl') for i in range(4): qc.measure(i,i) qc.draw('mpl',cregbundle=False) from qiskit import transpile from qiskit.visualization import plot_histogram from qiskit.providers.aer import QasmSimulator backend = QasmSimulator() job = transpile(qc,backend) result = backend.run(job,shots=1024).result() counts = result.get_counts() plot_histogram(counts) counts
https://github.com/emad-boosari/QuEST_Group
emad-boosari
!pip install qiskit !pip install pylatexenc from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector, Operator from qiskit.visualization import plot_histogram # function for plotting the quantum circuit def qplot(x): return x.draw('mpl', style= 'iqx', initial_state = True, scale = 0.7) n = 7 qc = QuantumCircuit(n) # Build a quantum circuit with 4 qubit qc.h(0) # Apply a Hadamard gate to the first qubit qc.barrier() qplot(qc) # we need to import Hadamard gate from qiskit.circuit.library from qiskit.circuit.library import HGate c_h = HGate().control(1) # Controlled Hadamard gate, 1 is number of control we want to use for i in range(1,n): qc.append(c_h,[0,i]) qc.barrier() qplot(qc) c_h2 = HGate().control(2) # Controlled Hadamard gate, controlled Hadamard gate with two control gate for i in range(2,n): qc.append(c_h2,[0,1,i]) qc. append(c_h2,[1,2,3]) qc.barrier() qplot(qc) # build a simple circuit circ = QuantumCircuit(3, name = "custom") circ.h(range(3)) circ.x(0) circ.cx(1,2) custom = circ.to_gate().control(1) qc.append(custom, [0,1,2,3]) qc.append(custom, [1,4,5,6]) qc.append(custom, [6,0,1,2]) qplot(qc) custom3 = circ.to_gate().control(3) qc.append(custom3, [0,1,2,3,4,5]) qc.append(custom3, [0,2,3,4,5,6]) qplot(qc)
https://github.com/adarsh1chand/Qiskit-Mentorship-Program-2021
adarsh1chand
import numpy as np #Operator Imports from qiskit import QuantumRegister, QuantumCircuit from qiskit.opflow import X, Y, Z, I, Zero, StateFn, CircuitStateFn, SummedOp, ListOp, PauliExpectation, PauliSumOp from qiskit.opflow.gradients import Gradient, Hessian from qiskit.circuit import Parameter from qiskit.utils import QuantumInstance from qiskit_machine_learning.neural_networks import OpflowQNN from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA # imports to plot stuff import matplotlib.pyplot as plt from IPython.display import display plt.style.use('dark_background') class QuantumODESolver(object): """ Main Class for the ODE solver using Hybrid Classical-Quantum neural network. Instantiate this class to use the solver. Implementation of the following paper: arXiv:2011.10395v2 in Qiskit. >> Developed as part of Qiskit Mentorship Program 2021 (Project #32: Solving Navier-Stokes equations using Qiskit for Water Management.) << Init Parameters --------------- num_qubits : Number of qubits in the quantum register of the quantum model circuit. variational_layers : Number of variational layers in the model circuit. encoder_layers : Number of encoder layers in the model circuit. """ def __init__(self, num_qubits = 1, variational_layers = 1, encoder_layers = 1): self.num_qubits = num_qubits self.encoder_layers = encoder_layers self.variational_layers = variational_layers self.encoder_symbols = [] self.unitary_symbols = [] self.model_circuit = QuantumCircuit(self.num_qubits) self.model = None self.measure_op = None self.gradient_op = None # Construct encoder block of the model self.construct_encoder() # Construct variational block of the model #self.construct_variational_ansatz() # Get measurement observable self.get_measurement_observable() # Forming combined model self.compile_model() print("Model compiled...........................") # Initialize unitary parameters self.unitary_params = np.random.random(size = (len(self.unitary_symbols), )) # Initialize gradient op of the model circuit self.gradient_op = Gradient(grad_method = 'fin_diff').convert(operator = self.model, params = (self.encoder_symbols)) def construct_encoder(self): """ Apply Quantum Feature map (Chebyshev sparse encoding) to the final model circuit. Feel free to change the code below to implement other quantum feature maps. Parameters ---------- None Returns ------- None """ self.encoder_block = QuantumCircuit(self.num_qubits, name = 'Encoder Block') x = Parameter('x') self.encoder_symbols.append(x) for i in range(self.num_qubits): self.encoder_block.ry(2 * (i+1) * np.arccos(x), i) #print("Encoder Block------------------------------------") #display(self.encoder_block.draw(output = 'mpl')) return def construct_variational_ansatz(self, layer): """ Apply Hardware-efficient ansatz as the variational block in the final model circuit. Feel free to change the code below to implement different architectures for the variational part of the model circuit. Parameters ---------- layer : Layer number of the variational block to be created. To differentiate between the subsequent layers of the same variational block, if the same block is repeated. If layer is same for two blocks, then the two blocks will have the same values for the unitary parameters. Returns ------- None """ self.variational_block = QuantumCircuit(self.num_qubits, name = 'Variational Block ' + str(layer + 1)) # First, we apply Wall of unitaries for i in range(self.num_qubits): theta_z0 = Parameter('theta_z0' + str(i) + str(layer)) self.unitary_symbols.append(theta_z0) theta_x = Parameter('theta_x' + str(i) + str(layer)) self.unitary_symbols.append(theta_x) theta_z1 = Parameter('theta_z1'+ str(i) + str(layer)) self.unitary_symbols.append(theta_z1) self.variational_block.rz(theta_z0, i) self.variational_block.rx(theta_x, i) self.variational_block.rz(theta_z1, i) # Next, we apply Entanglement wall (in a cyclic fashion, joining immediate neighbours) for i in range(1, self.num_qubits): self.variational_block.cx(i - 1, i) #if num_qubits > 1: # self.variational_block.cx(self.num_qubits-1, 0) #print("Variational block--------------------------------") #display(self.variational_block.draw(output = 'mpl')) return def get_measurement_observable(self): """ Construct operator for measurement of expectation value of the final model circuit. Note, can be any quantum circuit, but for now considering only the total magnetic spin of the quantum register. Feel free to change this functin as per design choice. Parameters ---------- None Returns ------- None """ self.measure_op = None for i in range(self.num_qubits): block = None for j in range(self.num_qubits): if j == i: if block is None: block = Z else: block = Z ^ block else: if block is None: block = I else: block = I ^ block if self.measure_op is None: self.measure_op = block else: self.measure_op = self.measure_op + block #print("Measurement op \n, ", self.measure_op) return def compile_model(self): """ Compile (concatenate) the variational blocks and encoder blocks to get the final model circuit expectation operator. Feel free to change the code of this function to change the overall architecture of the quantum model circuit (i.e, whether or not to repeat variational or encoder blocks ("Data re-uploading") etc.) Parameters ---------- None Returns ------- None """ measure = self.convert_to_statefn(self.measure_op, is_measurement = True) for i in range(self.encoder_layers): if i == 0: self.construct_variational_ansatz(layer = i) self.model_circuit.append(self.variational_block, range(self.num_qubits)) self.model_circuit.append(self.encoder_block, range(self.num_qubits)) self.construct_variational_ansatz(layer = self.encoder_layers) self.model_circuit.append(self.variational_block, range(self.num_qubits)) self.model = PauliExpectation().convert(measure @ CircuitStateFn(self.model_circuit)) return def convert_to_statefn(self, obj, is_measurement = False): """ Convert obj to StateFn, throws exception if cannot convert. """ try: if is_measurement: return ~StateFn(obj) else: return StateFn(obj) except Exception as err: print("Cannot convert object of type {} to StateFn ".format(type(obj))) print("Complete error log is as follows-------------") print(">> {} <<".format(err)) return def resolve_parameters(self, data, param_values): """ Resolves the parameter values for free parameters in the final model circuit. Parameters ---------- data : Classical data that goes into the encoder block. param_values : Parameter values for the free parameter in the unitary block. Returns ------- A dictionary that maps each free parameter in the final model circuit (encoder blocks + unitary blocks) to corresponding value. The output of this function can directly be used to bind parameter values in the model circuit operator (if successful). """ param_dict = {} data = np.array(data) if len(param_values.shape) == 1: param_values = list(param_values) else: param_values = list(param_values.flatten()) data_size = data.shape[0] model_param_values = [] model_param_vars = [] if data.shape[-1] != len(self.encoder_symbols) and len(data.shape) != len(self.encoder_symbols): print("Dimensionality of data does not match the number of free parameters for encoding data in the model circuit") return if len(param_values) != len(self.unitary_symbols): print(len(self.unitary_symbols)) print(len(param_values)) print("Number of param values supplied not equal to number of free parameters in the unitary blocks of the model circuit") return for var in self.encoder_symbols: model_param_vars.append(var) if len(data.shape) == 1: model_param_values.append(list(data)) else: for p in data: model_param_values.append(list(p)) #print("After resolving encoder params : ", model_param_values) for param in param_values: model_param_values.append([param] * data_size) #print("After resolving unitary params : ", model_param_values) for var in self.unitary_symbols: model_param_vars.append(var) param_dict = dict(zip(model_param_vars, model_param_values)) if len(param_dict.keys()) != len(self.encoder_symbols) + len(self.unitary_symbols): print("Resolving of parameters failed, check the number of parameter values passes for resolving !!") print("Number of free parameters : {}".format(len(self.encoder_symbols) + len(self.unitary_symbols))) print("Number of resolved params : {}".format(len(param_dict.keys()))) print(param_dict) return return param_dict def predict(self, data, param_values = None, is_training = False, verbose = False): """ Get expectation value and gradient at each data point from the model circuit. Parameters ---------- data: Classical Grid points which is to be encoded as input in the quantum model. param_values : (Optional) Parameter values for the unitary block parameters at which the model output should be evaluated. If not provided by user, it fills this variable with already stored parameter values in the object of QuantumODESolver class. is_training : Boolean flag to denote whether the call to this function is being made at the time of training. If True, then the function outputs both solution of the differential equation at grid points x and the corresponding gradients of the solution function at those points. If False, it just outputs the evaulated solution at grid points. verbose : (Optional) To print every predict function call output in each iteration of optimizer. Useful to check how many calls the optimizer makes to the predict function. Returns ------- Either two lists of solution values at grid points x and corresponding gradients at those points, or simply a list of solution values at grid points x. """ batch_size = 1 exp_values = [] grad_values = [] if param_values is None: param_values = self.unitary_params param_values = np.array(param_values).flatten() if len(param_values) == len(self.unitary_params): param_values = param_values[np.newaxis, :] else: if len(param_values.flatten()) % len(self.unitary_params) != 0: print("Cannot reshape the parameter values provided into shape = ({}, )".format(len(self.unitary_params))) sys.exit() batch_size = int(len(param_values.flatten()) / len(self.unitary_params)) param_values = np.reshape(param_values, newshape = (batch_size, len(self.unitary_params))) # Predicting for each batch of parameters supplied for batch in range(batch_size): batch_exp_value = None batch_grad_value = None if verbose: print("Predicting for batch {} / {}".format((batch + 1), batch_size), end = '\r') batch_param_values = param_values[batch] param_dict = self.resolve_parameters(data, batch_param_values) if param_dict is None: print("Prediction failed for batch {} / {}...".format((batch + 1), batch_size)) sys.exit() batch_exp_value = self.model.bind_parameters(param_dict) batch_exp_value = np.real(batch_exp_value.eval()).flatten() / self.num_qubits exp_values.append(list(batch_exp_value)) if is_training: batch_grad_value = np.real(self.gradient_op.bind_parameters(param_dict).eval()).flatten() grad_values.append(list(batch_grad_value)) if is_training: return exp_values, grad_values else: return exp_values def solution(self, x, param_values = None, is_training = False, verbose = False): """ Internally calls the predict function and outputs the value of solution for given array points in the arguments. Also takes care of the floating boundary condition. Parameters ---------- x : Numpy array of data grid points at which the solution (function that solves the required differential equation) needs to be evaluated. param_values : (Optional) Parameter values for the unitary block parameters at which the model output should be evaluated. If not provided by user, it fills this variable with already stored parameter values in the object of QuantumODESolver class. is_training : Boolean flag to denote whether the call to this function is being made at the time of training. If True, then the function outputs both solution of the differential equation at grid points x and the corresponding gradients of the solution function at those points. If False, it just outputs the evaulated solution at grid points. verbose : (Optional) To print every predict function call output in each iteration of optimizer. Useful to check how many calls the optimizer makes to the predict function. Returns ------- Either two lists of solution values at grid points x and corresponding gradients at those points, or simply a list of solution values at grid points x. """ u, du_dx = self.predict(x, param_values, is_training = True, verbose = verbose) # Floating boundary condition bc = self.predict(np.array([0.0]), param_values, verbose = verbose) # Reshaping arrays u = np.array(u) bc = np.array(bc) du_dx = np.array(du_dx) u = np.reshape(u, newshape = (u.shape[1], u.shape[0])) bc = np.reshape(bc, newshape = (bc.shape[1], bc.shape[0])) du_dx = np.reshape(du_dx, newshape = (du_dx.shape[1], du_dx.shape[0])) # With floating boundary condition, the value of function itself is defined in such a way # that the boundary condition is always satisfied irrespective of the model (quantum circuit's) output. u = np.array([1] * u.shape[1]) - bc + u if is_training: return u, du_dx else: return u def fit(self, x, y = None, epochs = 20, batch_size = 5, lr = 0.05, optimizer_maxiter = 5, verbose = False): """ Fit function for the quantum model used to train the model. Feel free to change the loss function method inside as per the differential equation required to solve. Parameters ---------- x : Numpy array of data grid points at which the model is fitted. y : (Optional) values which can be further used to define boundary conditions or initial conditions. Default to None. epochs : Number of epochs for which the model should be trained. batch_size : Number of data grid points to be taken in a single batch of training. Note, that the update to the parameter happens for each batch rather than at the end of epoch. lr : learning rate used for the ADAM optimizer. Not required if some other optimizer is chosen. optimizer_maxiter : Max iterations for which a single batch of training data should be used to update the parameter values. This parameter is passed to the optimizer (currently implemented for ADAM). verbose : (Optional) To print every loss function call output in each iteration of optimizer. Useful to check how many calls the optimizer makes to the loss function. Returns ------- List of parameter values after the model is trained. """ def loss_function(param_values): # get function value (f(x)) and gradients at points specified (array 'x' above) u, du_dx = self.solution(curr_batch, param_values, is_training = True, verbose = verbose) # Change the line below as per the differential equation required to solve # Following differential equation is taken from arXiv:2011.10395v2 loss = np.mean(np.log((du_dx + 20 * u *(0.1 + np.tan(20 * u))) ** 2), axis = 0) return loss epoch = 0 batch_start_idx = 0 curr_batch = x epoch_end = False print("Initial Loss : {}".format(loss_function(param_values = None))) print("Initial unitary params : {}".format(self.unitary_params)) print("Initial learning rate : {}".format(lr)) print("Training Begins...........................................................................................") while(epoch < epochs): epoch_loss = 0.0 batch_start_idx = 0 curr_batch = None epoch_end = False while(not epoch_end): print("Training for Batch {} / {}".format(int(batch_start_idx / batch_size) + 1, int(np.ceil(len(x) / batch_size))), end = '\r') curr_batch = x[batch_start_idx : min(batch_start_idx + batch_size, len(x))] self.unitary_params, epoch_loss , _ = ADAM(maxiter = optimizer_maxiter, lr = lr).optimize(len(self.unitary_symbols), loss_function, initial_point = self.unitary_params) if min(batch_start_idx + batch_size, len(x)) == len(x): epoch_end = True else: batch_start_idx += batch_size curr_batch = x print("Epoch : {}, Current Loss : {}".format((epoch + 1), loss_function(param_values = None))) print("Updated param values: ", self.unitary_params) print("Current learning rate : {}".format(lr)) print("-------------------------------------------------------------------------------------------------------") epoch += 1 #lr = (epoch + 1) * (1e-02 - 1e-04)/(epochs) return self.unitary_params def __call__(self): print("This model is constructed for-----") print("Number of qubits : {}".format(self.num_qubits)) print("Number of layers (depth) : For encoder block - {}, For variational block - {}".format(self.encoder_layers, self.variational_layers)) print("Structure of encoder block-----") display(self.encoder_block.draw(output = 'mpl')) print("Structure of variational block-----") display(self.variational_block.draw(output = 'mpl')) print("Complete model circuit looks like : ") display(self.model_circuit.draw(output = 'mpl')) print("Number of variational parameters : {}".format(len(self.unitary_symbols))) print("Number of encoder parameters : {}".format(len(self.encoder_symbols))) # Defining the solver architecture num_qubits = 6 enc_layers = 5 var_layers = 1 # Creating data grid points X = np.linspace(0, 0.9, 20) # Instantiating the solver solver = QuantumODESolver(num_qubits, var_layers, enc_layers) # Summary of model architecture solver() # Training the solver solver.fit(X, verbose = False) # Testing the solver X_test = np.linspace(0, 0.9, 30) predicted = solver.solution(X_test) plt.plot(X_test, np.exp(-20 * 0.1 * X_test) * np.cos(20 * X_test), c = 'yellow') plt.plot(X_test, predicted, c = 'blue') plt.show()
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import qiskit as qsk import numpy as np from qiskit.circuit.add_control import add_control def _qft(circuit, qregister): """ QFT on a circuit. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ def qft_rotations(circuit, qregister): """ Defines the rotations necessary for the QFT in a recursive manner. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ for i in reversed(qregister): circuit.h(i) for qubit in range(i.index): circuit.cu1(np.pi/float(2**(i.index-qubit)), qregister[qubit], qregister[i.index]) return circuit def qft_swap(circuit, qregister): """Swap registers for the QFT. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. n(int): qubit to do the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ n = len(qregister) for qubit in range(n//2): circuit.swap(qregister[qubit], qregister[n-qubit-1]) return circuit qft_rotations(circuit,qregister) qft_swap(circuit, qregister) return circuit def qft(circuit,qregister): """QFT. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qft_circuit= _qft(qsk.QuantumCircuit(qregister, name='QFT'), qregister) circuit.append(qft_circuit, qregister) return circuit def inverse_QFT(circuit,qregister): """ Inverse QFT. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qft_circuit= _qft(qsk.QuantumCircuit(qregister, name='QFT'), qregister) inverseqft = qft_circuit.inverse() circuit.append(inverseqft, qregister) return circuit def qpe(circuit, unitary, precision, ancilla, init_state=None): """Applies the quantum phase estimation for a given unitary. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. unitary(np.array): Unitary. precision(QuantumRegister): Quantum register for the precision of the QPE. ancilla(QuantumRegister): Quantum register for the ancilla, must be len(unitary)//2 = n_ancilla. init_state(list): Initial state for the ancilla qubit. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ #n_precision = len(precision) n_ancilla = len(ancilla) assert len(unitary)//2 == n_ancilla, "Ancilla qubits does't match the number needed to expand the eigenstate." #Ancilla (need to add a way to initialize states) if init_state is not None: assert len(init_state) == 2**n_ancilla , "Initial state not valid." circuit.initialize(init_state, ancilla) #Precision circuit.h(precision) #Build unitary U = qsk.extensions.UnitaryGate(unitary, label='U') U_ctrl = add_control(U, num_ctrl_qubits=1, label='Controlled_U',ctrl_state=1) repetitions = 1 for counting_qubit in precision: for _ in range(repetitions): circuit.append(U_ctrl, [counting_qubit,ancilla]) repetitions *= 2 inverse_QFT(circuit, precision) return circuit def QPE(circuit, unitary, precision, ancilla, init_state=None): """ Inverse QPE. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. unitary(np.array): Unitary. precision(QuantumRegister): Quantum register for the precision of the QPE. ancilla(QuantumRegister): Quantum register for the ancilla, must be len(unitary)//2 = n_ancilla. init_state(list): Initial state for the ancilla qubit. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qpe_circuit = qsk.QuantumCircuit(precision, name='QPE') qpe_circuit.add_register(ancilla) qpe_circuit= qpe(qpe_circuit, unitary, precision, ancilla, init_state=init_state) append_qbits = [i for i in precision] for i in ancilla: append_qbits.append(i) circuit.append(qpe_circuit, append_qbits) return circuit def inverse_QPE(circuit, unitary, precision, ancilla, init_state=None): """ Inverse QPE. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. unitary(np.array): Unitary. precision(QuantumRegister): Quantum register for the precision of the QPE. ancilla(QuantumRegister): Quantum register for the ancilla, must be len(unitary)//2 = n_ancilla. init_state(list): Initial state for the ancilla qubit. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qpe_circuit = qsk.QuantumCircuit(precision, name='QPE') qpe_circuit.add_register(ancilla) qpe_circuit= qpe(qpe_circuit, unitary, precision, ancilla, init_state=init_state) inverseqpe = qpe_circuit.inverse() append_qbits = [i for i in precision] for i in ancilla: append_qbits.append(i) circuit.append(inverseqpe, append_qbits) return circuit
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
%matplotlib inline import qiskit as qsk import numpy as np import matplotlib.pyplot as plt qreg = qsk.QuantumRegister(2, name='q') circ = qsk.QuantumCircuit(qreg) circ.draw('mpl') circ.x(qreg[0]); #Add x on 0 circ.draw('mpl') circ.h(qreg[0]); #Add x on 0 circ.draw('mpl') circ.cx(qreg[0], qreg[1]); #Add CNOT on 0 and 1 circ.draw(output='mpl') backend = qsk.Aer.get_backend('statevector_simulator') job = qsk.execute(circ, backend) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) creg = qsk.ClassicalRegister(2, name='c') circ.add_register(creg) circ.draw('mpl') circ.measure(qreg,creg) circ.draw('mpl') backend_sim = qsk.Aer.get_backend('qasm_simulator') job_sim = qsk.execute(circ, backend_sim, shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) from qiskit import IBMQ token = np.loadtxt("Token.txt", unpack=True, dtype=str) IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account(); backend_list = provider.backends() for i in backend_list: print(f'{i} \n') from qiskit.providers.ibmq import least_busy num_qubits = 2 backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= num_qubits and not x.configuration().simulator and x.status().operational==True)) backend from qiskit.tools.monitor import job_monitor job_exp = qsk.execute(circ, backend=backend) job_monitor(job_exp) result_exp = job_exp.result() from qiskit.visualization import plot_histogram counts_exp = result_exp.get_counts(circ) plot_histogram([counts_exp,counts], legend=['Device', 'Simulator']) job_id = job_exp.job_id() print('JOB ID: {}'.format(job_id)) retrieved_job = backend.retrieve_job(job_id) retrieved_job.result().get_counts(circ) qsk.__qiskit_version__ from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() from qiskit.aqua.operators import OperatorBase, ListOp, PrimitiveOp, PauliOp from qiskit.quantum_info import Pauli from qiskit.aqua.algorithms import VQE, NumPyEigensolver from qiskit.circuit.library import TwoLocal from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP import numpy as np ansatz = TwoLocal(num_qubits=2, rotation_blocks=['rx','rz'], entanglement_blocks='cx', entanglement='full', reps=1) ansatz.draw() optimizer = SLSQP(maxiter=100) Op = PauliOp(Pauli(label='II'), 0.5) - PauliOp(Pauli(label='XX'), 0.5) - 0.5*PauliOp(Pauli(label='YY')) + 0.5*PauliOp(Pauli(label='ZZ')) # Op = PrimitiveOp(primitive=[[1,0],[0,1]], coeff=2.) # xx = Pauli(label='XX') # yy = Pauli(label='YY') # zz = Pauli(label='ZZ') # ii = Pauli(label='II') # Op = ListOp([zz,yy,xx, ii], coeff=[0.5,-0.5,-0.5,0.5]) vqe = VQE(Op, ansatz, optimizer) backend = Aer.get_backend("statevector_simulator") vqe_result = np.real(vqe.run(backend)['eigenvalue'] ) vqe_result np.min(np.linalg.eig(Op.to_matrix())[0]) Op.to_matrix()
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Wrapping the controls in X-gates # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import scipy as sp import numpy as np import matplotlib.pyplot as plt import qiskit from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.providers.aer.noise import NoiseModel from qiskit.utils import QuantumInstance # Loading your IBM Q account(s) provider = IBMQ.load_account() def run_obs(qc, shots, backend_name='ibmq_santiago'): """Helper function to get the expected value of the | 11 > state. """ # Get device noise model device = provider.get_backend(backend_name) noise_model = NoiseModel.from_backend(device) coupling_map = device.configuration().coupling_map seed = 42 # Define the backend backend = QuantumInstance( backend=Aer.get_backend("qasm_simulator"), seed_transpiler=seed, optimization_level=1, noise_model=noise_model, shots=shots, ) qc = qc.copy() qc.measure_all() counts = backend.execute(qc).get_counts() return counts['11']/shots qc = QuantumCircuit(2) qc.x(0) qc.cx(0, 1) qc.draw('mpl') run_obs(qc, 1000) def fold_cx(qc, alpha): """ Fold the cx on the circuit given an alpha value. """ d = qc.depth() k = np.ceil(d*(alpha - 1)/2) n = k//d s = k%d instructions = [] for instruction, qargs, cargs in qc: if instruction.name == 'cx': instruction = qiskit.circuit.library.CXGate() barrier = qiskit.circuit.library.Barrier(len(qc)) instructions.append((instruction, qargs, cargs)) instructions.append((barrier, qargs, cargs)) for _ in range(2*int(n + s)): instructions.append((instruction, qargs, cargs)) instructions.append((barrier, qargs, cargs)) else: instructions.append((instruction, qargs, cargs)) folded_qc = qc.copy() folded_qc.data = instructions return folded_qc alpha_list = [1, 2, 5, 7, 9, 11] folds = [] for alpha in alpha_list: folds.append(fold_cx(qc, alpha)) expected_vals = [] for i in range(len(alpha_list)): expected_vals.append(run_obs(folds[i], shots=1000)) print(f"Alphas: {alpha_list}\nExpected values{expected_vals}") plt.plot(alpha_list, expected_vals, 'o') plt.xlabel(r"$\alpha$", size=14) plt.ylabel(r"E($\alpha$)", size=14) plt.show() def linear(x, a, b): """Linear fit """ return a*x + b y = expected_vals x = alpha_list x, y = np.array(x), np.array(y) popt, _ = sp.optimize.curve_fit(linear, x, y) print("Mitigated expectation value:", np.round(popt[1],3)) print("Unmitigated expectation value:", expected_vals[0]) print("Absolute error with mitigation:", np.round(np.abs(1 - popt[1]), 3)) print("Absolute error without mitigation:", np.round(np.abs(1 - expected_vals[0]), 3)) plt.plot(alpha_list, expected_vals, 'o') plt.plot(0, popt[1], '*', label="mitigated") plt.xlabel(r"$\alpha$", size=14) plt.ylabel(r"E($\alpha$)", size=14) plt.legend() plt.show() import qiskit.tools.jupyter %qiskit_version_table
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
from qiskit import Aer from qiskit.circuit.library import QFT from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.quantum_info import state_fidelity from qiskit.aqua.algorithms import HHL, NumPyLSsolver from qiskit.aqua.components.eigs import EigsQPE from qiskit.aqua.components.reciprocals import LookupRotation from qiskit.aqua.operators import MatrixOperator from qiskit.aqua.components.initial_states import Custom import numpy as np def create_eigs(matrix, num_ancillae, num_time_slices, negative_evals): """QPE for the eigenvalues estimation. Parameters ------------------------------------------------------------------- matrix(np.array): Unitary matrix for the QPE. num_ancillae(int): Number of ancillas. num_time_slices(float): An optional evolution time which should scale the eigenvalue onto the range (0,1] (or (−0.5,0.5] for negative eigenvalues).If None is internally computed. negative_evals(Boolean): Set True to indicate negative eigenvalues need to be handled """ ne_qfts = [None, None] if negative_evals: num_ancillae += 1 ne_qfts = [QFT(num_ancillae - 1), QFT(num_ancillae - 1).inverse()] return EigsQPE(MatrixOperator(matrix=matrix), QFT(num_ancillae).inverse(), num_time_slices=num_time_slices, num_ancillae=num_ancillae, expansion_mode='suzuki', expansion_order=2, evo_time=None, negative_evals=negative_evals, ne_qfts=ne_qfts) def fidelity(hhl, ref): """ Helper function for the fidelity comparing the solution from the HHL and the classical solution. """ solution_hhl_normed = hhl / np.linalg.norm(hhl) solution_ref_normed = ref / np.linalg.norm(ref) fidelity = state_fidelity(solution_hhl_normed, solution_ref_normed) return fidelity A = [[1, 1/3], [1/3, 4]] b = [1, 4] orig_size = len(b) A, b, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(A, b) # Initialize eigenvalue finding module eigs = create_eigs(matrix=A, num_ancillae=3, num_time_slices=50, negative_evals=False) num_q, num_a = eigs.get_register_sizes() # Initialize initial state module init_state = Custom(num_q, state_vector=b) # Initialize reciprocal rotation module reci = LookupRotation(negative_evals=eigs._negative_evals, evo_time=eigs._evo_time, scale=0.5) algo = HHL(matrix=A, vector=b, truncate_powerdim=truncate_powerdim, truncate_hermitian=truncate_hermitian, eigs=eigs, init_state=init_state, reciprocal=reci, num_q= num_q, num_a=num_a, orig_size=orig_size) result = algo.run(QuantumInstance(Aer.get_backend('statevector_simulator'))) print(f"solution: {np.round(result['solution'], 5)}") result_ref = NumPyLSsolver(A, b).run() print(f"classical solution: {np.round(result_ref['solution'], 5)} ") print(f"probability: {result['probability_result']}") fidelity(result['solution'], result_ref['solution']) orig_size = len(b) A, b, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(A, b) # Initialize eigenvalue finding module eigs = create_eigs(matrix=A, num_ancillae=3, num_time_slices=50, negative_evals=False) num_q, num_a = eigs.get_register_sizes() # Initialize initial state module init_state = Custom(num_q, state_vector=b) # Initialize reciprocal rotation module reci = LookupRotation(negative_evals=eigs._negative_evals, evo_time=eigs._evo_time, scale=0.5) algo = HHL(matrix=A, vector=b, truncate_powerdim=truncate_powerdim, truncate_hermitian=truncate_hermitian, eigs=eigs, init_state=init_state, reciprocal=reci, num_q= num_q, num_a=num_a, orig_size=orig_size) result = algo.run(QuantumInstance(Aer.get_backend('qasm_simulator'))) print(f"solution: {np.round(result['solution'], 5)}") result_ref = NumPyLSsolver(A, b).run() print(f"classical solution: {np.round(result_ref['solution'], 5)} ") print(f"probability: {result['probability_result']}") fidelity(result['solution'], result_ref['solution']) from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) #Apply Hadamard gate for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta) repetitions *= 2 qpe.draw() def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import numpy as np from math import pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram from qiskit.circuit.library.standard_gates import ZGate, XGate # Define circuit parameters a = '10x01xx' n = len(a) k = 7 circ = QuantumCircuit(k+n, k) circ.reset(range(k+n)) circ.h(range(k+n)) circ.barrier() for i in range(k): name = '$G_' + str(i) + '$' circ.append(QuantumCircuit(n, name=name).to_gate().control(1), [n+i]+list(range(n))) circ.barrier() circ.append(Gate(name="$QFT^{-1}$", num_qubits=k, params=[]), range(n, k+n)) circ.barrier() circ.measure(range(n, k+n), range(k)) circ.draw('mpl', reverse_bits=True, scale=0.5) def Gop(j): p = 2 ** j ctrl_bits = [] ctrl_state = '' for i in range(n): if a[n-i-1] != 'x': ctrl_bits.append(i+1) ctrl_state += a[n-i-1] G = QuantumCircuit(n+1, name='G'+str(j)) for i in range(p): G.append(XGate().control(len(ctrl_bits), ctrl_state=ctrl_state[::-1]), ctrl_bits + [0]) G.h(range(1, n+1)) G.x(range(1, n+1)) G.append(ZGate().control(n-1), reversed(range(1, n+1))) G.x(range(1, n+1)) G.h(range(1, n+1)) return G Gop(3).draw('mpl', reverse_bits=True, scale=0.5) QFT_inv = QuantumCircuit(k, name='QFT^{-1}') for i in reversed(range(k)): if i != k-1: QFT_inv.barrier() for j in reversed(range(i+1,k)): QFT_inv.cu1(-pi/(2 ** (j-i)), i, j) QFT_inv.h(i) QFT_inv.draw('mpl', reverse_bits=True) circ = QuantumCircuit(k+n+1, k) circ.reset(range(k+n+1)) circ.x(0) circ.h(range(k+n+1)) circ.z(n+1) circ.barrier() for i in range(k): circ.append(Gop(i).to_gate().control(1), [n+i+1]+list(range(n+1))) circ.barrier() circ.append(QFT_inv, range(n+1, k+n+1)) circ.barrier() circ.measure(range(n+1, k+n+1), range(k)) circ.draw(reverse_bits=True, scale=0.5) delta = 64 simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=delta).result() counts = result.get_counts(circ) plot_histogram(counts) x = list(counts.keys()) x = [pi*int(i[::-1], 2)/(2 ** k) for i in x] p = list(counts.values()) p = p.index(max(p)) theta = min(x[p], pi-x[p]) m_estimate = (2 ** n) * (theta ** 2) m = 2 ** a.count('x') print('Estimated Count:') print(m_estimate) print('Actual Count:') print(m)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
# Let's import all functions import numpy as np import scipy as sp from qiskit import Aer from qiskit.opflow import PauliTrotterEvolution, StateFn, PauliExpectation from qiskit.opflow import CircuitSampler, PauliOp from qiskit.opflow import I, X, Y, Z, Zero, One, Plus, Minus from qiskit.circuit import Parameter hamiltonian = (Z^Z) evo_time = Parameter('t') evolution_op = (evo_time*hamiltonian).exp_i() print(evolution_op) num_time_slices = 1 trotterized_op = PauliTrotterEvolution( trotter_mode='trotter', reps=num_time_slices).convert(evolution_op) trotterized_op.to_circuit().draw() hamiltonian = (X^X) evo_time = Parameter('t') evolution_op = (evo_time*hamiltonian).exp_i() num_time_slices = 1 trotterized_op = PauliTrotterEvolution( trotter_mode='trotter', reps=num_time_slices).convert(evolution_op) trotterized_op.to_circuit().draw() hamiltonian = (Y^Y) evo_time = Parameter('t') evolution_op = (evo_time*hamiltonian).exp_i() num_time_slices = 1 trotterized_op = PauliTrotterEvolution( trotter_mode='trotter', reps=num_time_slices).convert(evolution_op) trotterized_op.to_circuit().draw() hamiltonian = (Z^Z^Z^Z) evo_time = Parameter('t') evolution_op = (evo_time*hamiltonian).exp_i() num_time_slices = 1 trotterized_op = PauliTrotterEvolution( trotter_mode='trotter', reps=num_time_slices).convert(evolution_op) trotterized_op.to_circuit().draw() hamiltonian = (Z^Z) + (X^X) observable = (X^X) evo_time = Parameter('t') evolution_op = (evo_time*hamiltonian).exp_i() observable_measurement = StateFn(observable).adjoint() eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix()) initial_state = StateFn(eigenstates[0]) print(initial_state.to_circuit_op()) evo_and_measure = observable_measurement @ evolution_op @ initial_state print(evo_and_measure) num_time_slices = 1 trotterized_op = PauliTrotterEvolution( trotter_mode='trotter', reps=num_time_slices).convert(evo_and_measure) print(trotterized_op) # Let's calculate expectation values diagonalized_meas_op = PauliExpectation().convert(trotterized_op) print(diagonalized_meas_op) evo_time_points = [0.5, 0.75] hamiltonian_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points}) print(f"Observable at time {evo_time_points}: {np.round(hamiltonian_trotter_expectations.eval(), 3)}") sampler = CircuitSampler(backend=Aer.get_backend("qasm_simulator")) # sampler.quantum_instance.run_config.shots = 1000 sampled_trotter_exp_op = sampler.convert(hamiltonian_trotter_expectations) sampled_trotter_energies = sampled_trotter_exp_op.eval() print(f"Energies: {np.round(np.real(sampled_trotter_energies),3)}") import matplotlib.pyplot as plt def run_hs(shots): sampler = CircuitSampler(backend=Aer.get_backend("qasm_simulator")) sampler.quantum_instance.run_config.shots = shots hamiltonian_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: 0.5}) sampled_trotter_exp_op = sampler.convert(hamiltonian_trotter_expectations) sampled_trotter_energies = sampled_trotter_exp_op.eval() return np.real(sampled_trotter_energies) n_shots = [100, 1000, 2000, 5000, 7000, 10000] exp = [] for shots in n_shots: exp.append(run_hs(shots)) plt.plot(n_shots, exp, 'o', label=f"t={0.5}") plt.hlines(y=0., xmin=min(n_shots), xmax=max(n_shots) + 1, colors='red') plt.xlabel("# shots", size=16) plt.ylabel(r"$ \langle O \rangle $", size=16) plt.show()
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import IBMQ, QuantumCircuit, execute, assemble, schedule, transpile from qiskit.providers.ibmq.job import job_monitor from qiskit.tools.visualization import plot_histogram # Loading your IBM Q account(s) provider = IBMQ.load_account() # Get backend backend = provider.get_backend('ibmq_belem') config = backend.configuration() config.supported_instructions h_x_circ = QuantumCircuit(1, 1) h_x_circ.h(0) h_x_circ.x(0) h_x_circ.measure(0, 0) def h_reset_x_circ(n_resets): """Do h, then n_resets reset instructions, then x on a single qubit.""" qc = QuantumCircuit(1, 1) qc.h(0) qc.reset([0]*n_resets) qc.x(0) qc.measure(0,0) return qc circs0 = [h_x_circ, h_reset_x_circ(1), h_reset_x_circ(3), h_reset_x_circ(5)] job1q_0 = execute(circs0, backend, initial_layout=[0]) job_monitor(job1q_0) counts1 = job1q_0.result().get_counts() legend_1q = ['h -> x', 'h -> reset -> x', 'h -> 3*reset -> x', 'h -> 5*reset -> x' ] plot_histogram(counts1, legend=legend_1q, figsize=(9, 6)) initialize_x_circ = QuantumCircuit(1, 1) initialize_x_circ.initialize([1/np.sqrt(3), np.sqrt(2/3)]) initialize_x_circ.x(0) initialize_x_circ.measure(0, 0) def initialize_reset_x_circ(n_resets): """Initialize, then n_resets reset instructions, then x on a single qubit.""" qc = QuantumCircuit(1, 1) qc.initialize([1/np.sqrt(3), np.sqrt(2/3)]) qc.reset([0]*n_resets) qc.x(0) qc.measure(0,0) return qc circs1 = [initialize_x_circ, initialize_reset_x_circ(1), initialize_reset_x_circ(3), initialize_reset_x_circ(5)] job1q_1 = execute(circs1, backend, initial_layout=[0]) job_monitor(job1q_1) counts2 = job1q_1.result().get_counts() legend_1q1 = ['initialize -> x', 'initialize -> reset -> x', 'initialize -> 3*reset -> x', 'initialize -> 5*reset -> x' ] plot_histogram(counts2, legend=legend_1q1, figsize=(9, 6)) def multiq_custom_circ(n_resets): """Multi-qubit circuit on qubits 0, 1, 2 with ``n_resets`` reset instructions used.""" qc = QuantumCircuit(3, 3) qc.h(0) qc.h(1) qc.h(2) qc.reset([0]*n_resets) qc.cx(0, 2) qc.reset([1]*n_resets) qc.x(1) qc.measure(range(2), range(2)) return qc multiq_circs = [multiq_custom_circ(0), multiq_custom_circ(1), multiq_custom_circ(3)] # verify expected output from qiskit import Aer job_multiq_sim = execute(multiq_circs, backend=Aer.get_backend('qasm_simulator')) counts_multiq_sim = job_multiq_sim.result().get_counts() print("No reset sim counts, custom circ: ", counts_multiq_sim[0]) print("1 Reset sim counts, custom circ: ", counts_multiq_sim[1]) job_multiq = execute(multiq_circs, backend) job_monitor(job_multiq) counts_multiq = job_multiq.result().get_counts() legend_multiq = ['no reset', '1 reset', '3 resets'] plot_histogram(counts_multiq, legend=legend_multiq, figsize=(9, 6))
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import qiskit as qsk import numpy as np import matplotlib.pyplot as plt def measure_X(circuit,n): circuit.barrier(n) circuit.h(n) circuit.measure(n,n) return circuit def measure_Y(circuit,n): circuit.barrier(n) circuit.sdg(n) circuit.h(n) circuit.measure(n,n) return circuit def tomography(circuit): """ Tomography of a one qubit Circuit. """ qc_list = [] base = ['X', 'Y', 'Z'] for basis in base: Q = qsk.QuantumCircuit(1,1) Q.append(circuit, [0]) if basis == 'X': measure_X(Q, 0) qc_list.append(Q) if basis == 'Y': measure_Y(Q, 0) qc_list.append(Q) if basis == 'Z': Q.measure(0,0) qc_list.append(Q) return qc_list, base qc = qsk.QuantumCircuit(1) qc.h(0) qcs, bases = tomography(qc) backend_sim = qsk.Aer.get_backend('qasm_simulator') job = qsk.execute(qcs, backend_sim, shots=5000) result = job.result() for index, circuit in enumerate(qcs): print(result.get_counts(circuit)) print(f'Base measured {bases[index]}\n') def get_density_matrix(measurements,circuits): """Get density matrix from tomography measurements. """ density_matrix = np.eye(2, dtype=np.complex128) sigma_x = np.array([[0,1],[1,0]]) sigma_y = np.array([[0,-1j],[1j,0]]) sigma_z = np.array([[1,0],[0,-1]]) basis = [sigma_x, sigma_y, sigma_z] for index in range(len(circuits)): R = measurements.get_counts(index) if '0' in R.keys() and '1' in R.keys(): zero = R['0'] one = R['1'] elif '1' in R.keys(): zero = 0 one = R['1'] elif '0' in R.keys(): zero = R['0'] one = 0 total = sum(list(R.values())) expected = (zero - one)/total density_matrix += expected * basis[index] return 0.5*density_matrix density = get_density_matrix(result,qcs) print(density) def plot_density_matrix(DM): """Helper function to plot density matrices. Parameters ---------------------------------------------- DM(np.array): Density Matrix. """ from matplotlib.ticker import MaxNLocator fig = plt.figure(figsize=(16,10)) gs = fig.add_gridspec(1, 2) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[0, 1]) im = ax1.imshow(np.real(DM), cmap='Greys') ax1.yaxis.set_major_locator(MaxNLocator(integer=True)) ax1.xaxis.set_major_locator(MaxNLocator(integer=True)) ax1.set_title('Real Part',size=16) plt.colorbar(im, ax=ax1) im = ax2.imshow(np.imag(DM), cmap='Greys') plt.colorbar(im, ax=ax2) ax2.yaxis.set_major_locator(MaxNLocator(integer=True)) ax2.xaxis.set_major_locator(MaxNLocator(integer=True)) ax2.set_title('Imaginary Part',size=16) plt.show() plot_density_matrix(density) from qiskit.ignis.verification.tomography import state_tomography_circuits tomography_circuits = state_tomography_circuits(qc, [0], meas_labels='Pauli', meas_basis='Pauli') tomography_circuits[1].draw('mpl') backend_sim = qsk.Aer.get_backend('qasm_simulator') job = qsk.execute(tomography_circuits, backend_sim, shots=5000) result = job.result() from qiskit.ignis.verification.tomography import StateTomographyFitter state_fitter = StateTomographyFitter(result, tomography_circuits, meas_basis='Pauli') density_matrix = state_fitter.fit(method='lstsq') print(density_matrix) plot_density_matrix(density_matrix) qc = qsk.QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.draw('mpl') from qiskit.ignis.verification.tomography import state_tomography_circuits tomography_circuits = state_tomography_circuits(qc, [0,1,2], meas_labels='Pauli', meas_basis='Pauli') backend_sim = qsk.Aer.get_backend('qasm_simulator') job = qsk.execute(tomography_circuits, backend_sim, shots=5000) result = job.result() from qiskit.ignis.verification.tomography import StateTomographyFitter state_fitter = StateTomographyFitter(result, tomography_circuits, meas_basis='Pauli') density_matrix = state_fitter.fit(method='lstsq') plot_density_matrix(density_matrix) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/euler16/Distinguishing-Unitary-Gates-on-IBM-Quantum-Processor
euler16
import sys, time sys.path.append("../") import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) # Imports import qiskit as qk from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, least_busy from qiskit.tools.visualization import plot_histogram from qiskit import IBMQ from qiskit import Aer from math import pi print(qk.__version__) qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) # circuit construction # preparing the wavefunction qc.h(qr[0]) qc.barrier() qc.cx(qr[0], qr[1]) qc.barrier() qc.u3(1.2309,0,0,qr[0]) qc.barrier() # if we apply phase shift gate qc.u1((2.0/3)*pi,qr[0]) qc.u1((2.0/3)*pi,qr[1]) qc.barrier() # rotating the axis for measurement #qc.cx(qr[0],qr[1]) # THE IMPLEMENTATION PROVIDED BY THE AUTHORS SKIPS THIS CNOT APPLICATION!!! it shouldn't be # it shouldn't be there. Improves accuracy #qc.barrier() qc.u3(2.1862,6.5449,pi,qr[0]) qc.u3(0.9553,2*pi,pi,qr[1]) qc.barrier() qc.measure(qr,cr) # Running locally IBM backends respond too slowly print(Aer.backends()) backend = Aer.get_backend('qasm_simulator') job = execute(qc,backend) job.status result = job.result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) performance = { 'success':(counts['01']+counts['10'])/1024, 'failure':1 - (counts['01']+counts['10'])/1024 } plot_histogram(performance) IBMQ.load_accounts() # checking the backends large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration()['n_qubits'] > 1 and not x.configuration()['simulator']) print(large_enough_devices) backend = IBMQ.get_backend('ibmqx4') job = execute(qc,backend,max_credits=3) job.status result = job.result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) performance = { 'success':(counts['01']+counts['10'])/1024, 'failure':(counts['00']+counts['11'])/1024 } plot_histogram(performance) sqr = QuantumRegister(1) scr = ClassicalRegister(1) sqc = QuantumCircuit(sqr,scr) # constructing the circuit sqc.u3(1.1503,6.4850,2.2555,sqr[0]) sqc.barrier() # unidentified gate -- now assumed to be R2pi3. if identity then use qc.u1(0,q[0]) sqc.u1((2.0/3)*pi,sqr[0]) sqc.barrier() sqc.u3(1.231,0,0,sqr[0]) # X sqc.barrier() sqc.u1((2.0/3)*pi,sqr[0]) # U (unidentified gate) sqc.barrier() # measurement sqc.u3(0.7854,6.0214,6.1913,sqr[0]) sqc.barrier() sqc.measure(sqr,scr) # Running on local simulator backend = Aer.get_backend('qasm_simulator') job = execute(sqc,backend) result = job.result() counts = result.get_counts(sqc) print(counts) plot_histogram(counts) # Running on IBM backend = IBMQ.get_backend('ibmqx4') job = execute(sqc,backend,max_credits=3) result = job.result() counts = result.get_counts(sqc) print(counts) plot_histogram(counts)
https://github.com/lmarza/QuantumDeskCalculator
lmarza
from qiskit import * input1 = int(input("Enter a positive integer between 0 and 15: ")) input2 = int(input("Enter a positive integer between 0 and 15: ")) while (input1 < 0 or input1 > 15) or (input2 < 0 or input2 > 15): input1 = int(input("Enter a positive integer between 0 and 15: ")) input2 = int(input("Enter a positive integer between 0 and 15: ")) first = '{0:{fill}3b}'.format(input1, fill='0') second = '{0:{fill}3b}'.format(input2, fill='0') print(first, second) # We check which number is the longest and we take that length 'n' to declare two quantumRegisters that contain 'n' qubits. l = len(first) l2 = len(second) if l > l2: n = l else: n = l2 # Initializing the registers; three quantum registers with n bits each # 1 more with n+1 bits, which will hold the sum of the two #numbers # The last q-register has three bits to temporally store information # The classical register has n+1 bits, which is used to make the sum readable a = QuantumRegister(n) #First number b = QuantumRegister(n) #Second number c = QuantumRegister(n) #Carry bits supp = QuantumRegister(3) #support bit ris = QuantumRegister(n+1) #Result bits cl = ClassicalRegister(n+1) #Classical output # Combining all of them into one quantum circuit qc = QuantumCircuit(a, b, c, supp, ris, cl) qc.draw('mpl') # Setting up the registers using the values inputted # since the qubits initially always start from 0, we use not gate to set 1 our qubits where in the binary number # inserted there is a 1 for i in range(l): if first[i] == "1": qc.x(a[l - (i+1)]) #Flip the qubit from 0 to 1 for i in range(l2): if second[i] == "1": qc.x(b[l2 - (i+1)]) #Flip the qubit from 0 to 1 qc.draw('mpl') # Ripple Carry Adder # sum = (a xor b) xor cin # cout = (a and b) OR ((a xor b) and cin) # Note: instead of using an OR gate we can use a XOR one. # In fact the two AND, which are the inputs for the OR, can never both be equal to one, # so the last case in the truth table (A=1, B=1) of XOR and OR does not apply, making XOR and OR equal for i in range(n-1): #SUM #sum = (a xor b) xor cin # use cnots to write the XOR of the inputs on qubit 2 qc.cx(a[i], ris[i]) qc.cx(b[i], ris[i]) qc.cx(c[i], ris[i]) #CARRY #cout = (a and b) XOR ((a xor b) and cin) #cout = i+1 #cin = i # use ccx to write the AND of the inputs on qubit 3 qc.ccx(a[i],b[i],supp[2]) qc.cx(a[i], supp[0]) qc.cx(b[i], supp[0]) qc.ccx(supp[0], c[i], supp[1]) qc.cx(supp[1], c[i+1]) qc.cx(supp[2], c[i+1]) #reset to 0 supp qc.reset([9]*5) qc.reset([10]*5) qc.reset([11]*5) #SUM #sum = (a xor b) xor cin qc.cx(a[n-1], ris[n-1]) qc.cx(b[n-1], ris[n-1]) qc.cx(c[n-1], ris[n-1]) #CARRY #cout = (a and b) XOR ((a xor b) and cin) #cout = i+1 #cin = i # use ccx to write the AND of the inputs on qubit 3 qc.ccx(a[n-1],b[n-1],supp[2]) qc.cx(a[n-1], supp[0]) qc.cx(b[n-1], supp[0]) qc.ccx(supp[0], c[n-1], supp[1]) #note: instead of saving the last cout in the c qubit, we store it in the last digit of the result (hence the longer ris + 1) qc.cx(supp[1], ris[n]) qc.cx(supp[2], ris[n]) #reset to 0 supp qc.reset([9]*5) qc.reset([10]*5) qc.reset([11]*5) for i in range(n+1): qc.measure(ris[i], cl[i]) qc.draw('mpl') #Version using the local simulator #Set chosen backend and execute job num_shots = 100 #Setting the number of times to repeat measurement job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=num_shots) #Get results of program job_stats = job.result().get_counts() print(job_stats) #Version using the remote simulator IBMQ.load_account() provider = IBMQ.get_provider() backend = provider.get_backend('ibmq_qasm_simulator') counts = execute(qc, backend, shots=100).result().get_counts() print(counts) class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def executeQFT(qc, reg, n, pie): # Computes the quantum Fourier transform of reg, one qubit a time # Apply one Hadamard gate to the n-th qubit of the quantum register reg, and # then apply repeated phase rotations with parameters being pi divided by # increasing powers of two qc.h(reg[n]) for i in range(0, n): qc.cp(pie/float(2**(i+1)), reg[n-(i+1)], reg[n]) def inverseQFT(qc, reg, n, pie): # Performs the inverse quantum Fourier transform on a register reg. # Apply repeated phase rotations with parameters being pi divided by # decreasing powers of two, and then apply a Hadamard gate to the nth qubit # of the register reg. for i in range(n): qc.cp(-1*pie/float(2**(n-i)), reg[i], reg[n]) qc.h(reg[n]) def initQubits(str, qc, reg, n): # Flip the corresponding qubit in register if a bit in the string is a 1 for i in range(n): if str[i] == "1": qc.x(reg[n-(i+1)]) def printResult(first, second, qc,result, cl, n, operator): # Measure qubits for i in range(n+1): qc.measure(result[i], cl[i]) # Execute using the local simulator print(bcolors.BOLD + bcolors.OKCYAN + 'Connecting to local simulator...' + bcolors.ENDC) # Set chosen backend and execute job num_shots = 100 #Setting the number of times to repeat measurement print(bcolors.BOLD + bcolors.OKCYAN + 'Connect!' + bcolors.ENDC) print(bcolors.BOLD + bcolors.OKCYAN + f'Running the experiment on {num_shots} shots...' + bcolors.ENDC) job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=num_shots) # Get results of program job_stats = job.result().get_counts() for key, value in job_stats.items(): res = key prob = value print(bcolors.BOLD + bcolors.OKGREEN + f'\n{first} {operator} {second} = {res} with a probability of {prob}%' + bcolors.ENDC) def evolveQFTStateSum(qc, reg_a, reg_b, n, pie): # Evolves the state |F(ψ(reg_a))> to |F(ψ(reg_a+reg_b))> using the quantum # Fourier transform conditioned on the qubits of the reg_b. # Apply repeated phase rotations with parameters being pi divided by # increasing powers of two. l = len(reg_b) for i in range(n+1): if (n - i) > l - 1: pass else: qc.cp(pie/float(2**(i)), reg_b[n-i], reg_a[n]) import math pie = math.pi def sum(a, b, qc): n = len(a)-1 # Compute the Fourier transform of register a for i in range(n+1): executeQFT(qc, a, n-i, pie) # Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> # to |F(ψ(reg_a+reg_b))> for i in range(n+1): evolveQFTStateSum(qc, a, b, n-i, pie) # Compute the inverse Fourier transform of register a for i in range(n+1): inverseQFT(qc, a, i, pie) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) # check the inputs while (input1 < 0 or input1 > 2047) or (input2 < 0 or input2 > 2047): if input1 < 0 or input1 > 2047: print(bcolors.FAIL + "Invalid first input number" + bcolors.ENDC) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) if input2 < 0 or input2 > 2047: print(bcolors.FAIL + "Invalid second input number" + bcolors.ENDC) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) first = '{0:{fill}3b}'.format(input1, fill='0') second = '{0:{fill}3b}'.format(input2, fill='0') l1 = len(first) l2 = len(second) # Making sure that 'first' and 'second' are of the same length # by padding the smaller string with zeros if l2>l1: first,second = second, first l2, l1 = l1, l2 second = ("0")*(l1-l2) + second n = l1 # create the register based on the operation choosen a = QuantumRegister(n+1, "a") b = QuantumRegister(n+1, "b") accumulator = QuantumRegister(n+1, "accumulator") cl = ClassicalRegister(n+1, "cl") qc = QuantumCircuit(a, b, cl, name="qc") # Flip the corresponding qubit in register a if a bit in the string first is a 1 initQubits(first, qc, a, n) # Flip the corresponding qubit in register b if b bit in the string second is a 1 initQubits(second, qc, b, n) sum(a,b,qc) operator = '+' printResult(first, second, qc,a, cl, n, operator) qc.draw('mpl') def evolveQFTStateSub(qc, reg_a, reg_b, n, pie): # Evolves the state |F(ψ(reg_a))> to |F(ψ(reg_a-reg_b))> using the quantum # Fourier transform conditioned on the qubits of the reg_b. # Apply repeated phase rotations with parameters being pi divided by # increasing powers of two. l = len(reg_b) for i in range(n+1): if (n - i) > l - 1: pass else: qc.cp(-1*pie/float(2**(i)), reg_b[n-i], reg_a[n]) pie = math.pi def sub(a, b, qc): n = len(a) #Compute the Fourier transform of register a for i in range(0, n): executeQFT(qc, a, n-(i+1), pie) #Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> #to |F(ψ(reg_a-reg_b))> for i in range(0, n): evolveQFTStateSub(qc, a, b, n-(i+1), pie) #Compute the inverse Fourier transform of register a for i in range(0, n): inverseQFT(qc, a, i, pie) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) # check the inputs while (input1 < 0 or input1 > 2047) or (input2 < 0 or input2 > 2047): if input1 < 0 or input1 > 2047: print(bcolors.FAIL + "Invalid first input number" + bcolors.ENDC) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) if input2 < 0 or input2 > 2047: print(bcolors.FAIL + "Invalid second input number" + bcolors.ENDC) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) first = '{0:{fill}3b}'.format(input1, fill='0') second = '{0:{fill}3b}'.format(input2, fill='0') l1 = len(first) l2 = len(second) # Making sure that 'first' and 'second' are of the same length # by padding the smaller string with zeros if l2>l1: first,second = second, first l2, l1 = l1, l2 second = ("0")*(l1-l2) + second n = l1 # create the register based on the operation choosen a = QuantumRegister(n+1, "a") b = QuantumRegister(n+1, "b") accumulator = QuantumRegister(n+1, "accumulator") cl = ClassicalRegister(n+1, "cl") qc = QuantumCircuit(a, b, cl, name="qc") # Flip the corresponding qubit in register a if a bit in the string first is a 1 initQubits(first, qc, a, n) # Flip the corresponding qubit in register b if b bit in the string second is a 1 initQubits(second, qc, b, n) sub(a,b,qc) operator = '-' printResult(first, second, qc,a, cl, n, operator) qc.draw('mpl') def multiply(a, secondDec, result, qc): n = len(a) -1 # Compute the Fourier transform of register 'result' for i in range(n+1): executeQFT(qc, result, n-i, pie) # Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> # to |F(ψ((second * reg_a))>, where we loop on the sum as many times as 'second' says, # doing incremental sums for j in range(secondDec): for i in range(n+1): evolveQFTStateSum(qc, result, a, n-i, pie) # Compute the inverse Fourier transform of register a for i in range(n+1): inverseQFT(qc, result, i, pie) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) # check the inputs while (input1 < 0 or input1 > 2047) or (input2 < 0 or input2 > 2047): if input1 < 0 or input1 > 2047: print(bcolors.FAIL + "Invalid first input number" + bcolors.ENDC) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) if input2 < 0 or input2 > 2047: print(bcolors.FAIL + "Invalid second input number" + bcolors.ENDC) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) first = '{0:{fill}3b}'.format(input1, fill='0') second = '{0:{fill}3b}'.format(input2, fill='0') # for multiplication firstDec = input1 secondDec = input2 l1 = len(first) l2 = len(second) # Padding 'first' the same lenght of 'result' # since result can have at max len(first) + len(second) bits when multiplying first = ("0")*(l2) + first n = l1+l2 # create the register based on the operation choosen a = QuantumRegister(n+1, "a") b = QuantumRegister(n+1, "b") accumulator = QuantumRegister(n+1, "accumulator") cl = ClassicalRegister(n+1, "cl") qc = QuantumCircuit(a, b, cl, name="qc") # Flip the corresponding qubit in register a if a bit in the string first is a 1 initQubits(first, qc, a, n) multiply(a,secondDec,b,qc) operator = '*' printResult(first, second, qc, b, cl, n, operator) qc.draw('mpl') def div(dividend, divisor, accumulator,c_dividend, circ, cl_index): d = QuantumRegister(1) circ.add_register(d) circ.x(d[0]) c_dividend_str = '0' while c_dividend_str[0] == '0': sub(dividend, divisor, circ) sum(accumulator, d, circ) for i in range(len(dividend)): circ.measure(dividend[i], c_dividend[i]) result = execute(circ, backend=Aer.get_backend('qasm_simulator'), shots=10).result() counts = result.get_counts("qc") #print(counts) c_dividend_str = list(counts.keys())[0] #.split()[0] sub(accumulator, d, circ) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) # check the inputs while (input1 < 0 or input1 > 2047) or (input2 < 0 or input2 > 2047): if input1 < 0 or input1 > 2047: print(bcolors.FAIL + "Invalid first input number" + bcolors.ENDC) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) if input2 < 0 or input2 > 2047: print(bcolors.FAIL + "Invalid second input number" + bcolors.ENDC) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) first = '{0:{fill}3b}'.format(input1, fill='0') second = '{0:{fill}3b}'.format(input2, fill='0') # for multiplication firstDec = input1 secondDec = input2 l1 = len(first) l2 = len(second) if l2>l1: first,second = second, first l2, l1 = l1, l2 second = ("0")*(l1-l2) + second n = l1 # create the register based on the operation choosen a = QuantumRegister(n+1, "a") b = QuantumRegister(n+1, "b") accumulator = QuantumRegister(n+1, "accumulator") cl = ClassicalRegister(n+1, "cl") qc = QuantumCircuit(a, b, accumulator, cl, name="qc") # Flip the corresponding qubit in register a if a bit in the string first is a 1 initQubits(first, qc, a, n) initQubits(second, qc, b, n) div(a, b, accumulator, cl, qc, 0) operator = '/' printResult(first, second, qc, accumulator, cl, n, operator) qc.draw('mpl')
https://github.com/lmarza/QuantumDeskCalculator
lmarza
from qiskit import * from operations import addition, subtraction, multiplication, division from utils import bcolors, selectOperator, checkOperation, printResult, initQubits import math if __name__ == "__main__": print(bcolors.OKGREEN + '##########################################' + bcolors.ENDC) print(bcolors.OKGREEN + '####### Quantum Desk Calculator ########' + bcolors.ENDC) print(bcolors.OKGREEN + '##########################################'+ bcolors.ENDC) # take the operator and check operator = selectOperator() input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) # check the inputs while (input1 < 0 or input1 > 2047) or (input2 < 0 or input2 > 2047): if input1 < 0 or input1 > 2047: print(bcolors.FAIL + "Invalid first input number" + bcolors.ENDC) input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC)) if input2 < 0 or input2 > 2047: print(bcolors.FAIL + "Invalid second input number" + bcolors.ENDC) input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC)) #check if the operation is valid checkOperation(input1, input2, operator) first = '{0:{fill}3b}'.format(input1, fill='0') second = '{0:{fill}3b}'.format(input2, fill='0') # for multiplication firstDec = input1 secondDec = input2 l1 = len(first) l2 = len(second) # Making sure that 'first' and 'second' are of the same length # by padding the smaller string with zeros if operator == '+' or operator == '-' or operator == '/': if l2>l1: first,second = second, first l2, l1 = l1, l2 second = ("0")*(l1-l2) + second n = l1 elif operator == '*' : # Padding 'first' the same lenght of 'result' # since result can have at max len(first) + len(second) bits when multiplying first = ("0")*(l2) + first n = l1+l2 print() print(bcolors.OKCYAN + '#'*150 + bcolors.ENDC) print(bcolors.BOLD + bcolors.OKCYAN + 'You want to perform the following operation:'+ bcolors.ENDC) print(bcolors.BOLD + bcolors.OKCYAN + f'{input1} {operator} {input2} --> {first} {operator} {second} = ...' + bcolors.ENDC) # create the register based on the operation choosen # Add a qbit to 'a' and 'b' in case of overflowing results # (the result is only read on 'a' or 'accumulator', but since 'a' (or 'accumulator') and 'b' # should have the same lenght, we also add a qbit to 'b') a = QuantumRegister(n+1, "a") b = QuantumRegister(n+1, "b") accumulator = QuantumRegister(n+1, "accumulator") cl = ClassicalRegister(n+1, "cl") if operator == '+' or operator == '-' or operator == '*': qc = QuantumCircuit(a, b, cl, name="qc") # Flip the corresponding qubit in register a if a bit in the string first is a 1 initQubits(first, qc, a, n) # Flip the corresponding qubit in register b if b bit in the string second is a 1 if operator != '*': initQubits(second, qc, b, n) if operator == '+': addition.sum(a,b,qc) printResult(first, second, qc,a, cl, n, operator) elif operator == '-': subtraction.sub(a,b,qc) printResult(first, second, qc,a, cl, n, operator) elif operator == '*': multiplication.multiply(a,secondDec,b,qc) printResult(first, second, qc, b, cl, n,operator) elif operator == '/': qc = QuantumCircuit(a, b, accumulator, cl, name="qc") # Flip the corresponding qubit in register a and b if a,b bit in the string first,second is a 1 initQubits(first, qc, a, n) initQubits(second, qc, b, n) division.div(a, b, accumulator, cl, qc, 0) printResult(first, second, qc, accumulator, cl, n, operator) print(bcolors.OKCYAN + '#'*150 + bcolors.ENDC)
https://github.com/lmarza/QuantumDeskCalculator
lmarza
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/lmarza/QuantumDeskCalculator
lmarza
import math from qiskit import * from utils import bcolors, executeQFT, evolveQFTStateSum, inverseQFT pie = math.pi def sum(a, b, qc): n = len(a)-1 # Compute the Fourier transform of register a for i in range(n+1): executeQFT(qc, a, n-i, pie) # Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> # to |F(ψ(reg_a+reg_b))> for i in range(n+1): evolveQFTStateSum(qc, a, b, n-i, pie) # Compute the inverse Fourier transform of register a for i in range(n+1): inverseQFT(qc, a, i, pie)
https://github.com/lmarza/QuantumDeskCalculator
lmarza
import math from qiskit import * from operations import addition, subtraction pie = math.pi def div(dividend, divisor, accumulator,c_dividend, circ, cl_index): d = QuantumRegister(1) circ.add_register(d) circ.x(d[0]) c_dividend_str = '0' while c_dividend_str[0] == '0': subtraction.sub(dividend, divisor, circ) addition.sum(accumulator, d, circ) for i in range(len(dividend)): circ.measure(dividend[i], c_dividend[i]) result = execute(circ, backend=Aer.get_backend('qasm_simulator'), shots=10).result() counts = result.get_counts("qc") #print(counts) c_dividend_str = list(counts.keys())[0] #.split()[0] subtraction.sub(accumulator, d, circ)
https://github.com/lmarza/QuantumDeskCalculator
lmarza
import math from qiskit import * from utils import bcolors, executeQFT, evolveQFTStateSum, inverseQFT pie = math.pi def multiply(a, secondDec, result, qc): n = len(a) -1 # Compute the Fourier transform of register 'result' for i in range(n+1): executeQFT(qc, result, n-i, pie) # Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> # to |F(ψ((second * reg_a))>, where we loop on the sum as many times as 'second' says, # doing incremental sums for j in range(secondDec): for i in range(n+1): evolveQFTStateSum(qc, result, a, n-i, pie) # Compute the inverse Fourier transform of register a for i in range(n+1): inverseQFT(qc, result, i, pie)
https://github.com/lmarza/QuantumDeskCalculator
lmarza
import math from qiskit import * from utils import bcolors, executeQFT, evolveQFTStateSub, inverseQFT pie = math.pi def sub(a, b, qc): n = len(a) #Compute the Fourier transform of register a for i in range(0, n): executeQFT(qc, a, n-(i+1), pie) #Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> #to |F(ψ(reg_a-reg_b))> for i in range(0, n): evolveQFTStateSub(qc, a, b, n-(i+1), pie) #Compute the inverse Fourier transform of register a for i in range(0, n): inverseQFT(qc, a, i, pie)
https://github.com/Morcu/Qiskit_Hands-on-lab
Morcu
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/Morcu/Qiskit_Hands-on-lab
Morcu
from qiskit import * #Comando para que las graficas se vean en el notebook %matplotlib inline qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() circuit.draw(output='mpl') qr = QuantumRegister(2, 'quantum') cr = ClassicalRegister(2, 'classical') circuit.draw() circuit.draw(output='mpl') circuit.h(qr[0]) circuit.draw(output='mpl') circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') circuit.measure(qr, cr) circuit.draw(output='mpl') backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) ''' El IMB_TOKEN se puede obtener en: https://quantum-computing.ibm.com/account ''' #IBMQ.save_account('IMB_TOKEN', overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(group='open') provider.backends() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmqx2') job = execute(circuit, backend=qcomp) from qiskit.tools.monitor import job_monitor job_monitor(job) result = job.result() plot_histogram(result.get_counts(circuit))
https://github.com/Morcu/Qiskit_Hands-on-lab
Morcu
from qiskit import * from qiskit.tools.visualization import plot_histogram import numpy as np def NOT(input1): ''' NOT gate This function takes a binary string input ('0' or '1') and returns the opposite binary output'. ''' q = QuantumRegister(1) # a qubit in which to encode and manipulate the input c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # We encode '0' as the qubit state |0⟩, and '1' as |1⟩ # Since the qubit is initially |0⟩, we don't need to do anything for an input of '0' # For an input of '1', we do an x to rotate the |0⟩ to |1⟩ if input1=='1': qc.x( q[0] ) # Now we've encoded the input, we can do a NOT on it using x qc.x( q[0] ) # Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0] qc.measure( q[0], c[0] ) # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1) output = next(iter(job.result().get_counts())) return output print('\nResults for the NOT gate') for input in ['0','1']: print(' Input',input,'gives output',NOT(input)) def XOR(input1,input2): ''' XOR gate Takes two binary strings as input and gives one as output. The output is '0' when the inputs are equal and '1' otherwise. ''' q = QuantumRegister(2) # two qubits in which to encode and manipulate the input c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) # YOUR QUANTUM PROGRAM GOES HERE qc.cx(q[0],q[1]) qc.measure(q[1],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '0' when the inputs are equal and '1' otherwise. print('\nResults for the XOR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',XOR(input1,input2)) def AND(input1,input2): ''' AND gate Takes two binary strings as input and gives one as output. The output is '1' only when both the inputs are '1'. ''' q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) # YOUR QUANTUM PROGRAM GOES HERE qc.ccx(q[0], q[1], q[2]) qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '1' only when both the inputs are '1'. print('\nResults for the AND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',AND(input1,input2)) def NAND(input1,input2): ''' NAND gate Takes two binary strings as input and gives one as output. The output is '0' only when both the inputs are '1'. ''' q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) qc.ccx(q[0], q[1], q[2]) qc.x( q[2] ) # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '0' only when both the inputs are '1'. print('\nResults for the NAND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',NAND(input1,input2)) def OR(input1,input2): ''' OR gate Takes two binary strings as input and gives one as output. The output is '1' if either input is '1'. ''' q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) qc.cx(q[0],q[1]) qc.cx(q[1],q[2]) qc.x( q[2] ) # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '1' if either input is '1'. print('\nResults for the OR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',OR(input1,input2)) print('\nResults for the NOT gate') for input in ['0','1']: print(' Input',input,'gives output',NOT(input)) print('\nResults for the XOR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',XOR(input1,input2)) print('\nResults for the AND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',AND(input1,input2)) print('\nResults for the NAND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',NAND(input1,input2)) print('\nResults for the OR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',OR(input1,input2))
https://github.com/jlapeyre/Qurt.jl
jlapeyre
# This "activates" the project environment of the package `Qurt`. Normally you would use `Qurt` # from an environment external to the package. import Pkg Pkg.activate("."); # Now `Qurt` should be visible. # `import` imports the package, but no other symbols. import Qurt # Names of objects that are not imported are printed fully qualified, which is verbose. # So import more only so names are not printed fully qualified. import Graphs.SimpleGraphs.SimpleDiGraph import Qurt.NodeStructs.Node using BenchmarkTools # This provides tools like Python %timeit # `using` is similar to `import`. But this invocation imports all of the symbols on the export list of # `Qurt.Circuits` using Qurt.Circuits using Qurt.Interface # many symbols go here as a catch all. They may live elsewhere in the future. qc = Circuit(2, 2) using Qurt.IOQDAGs print_edges(qc) propertynames(qc) typeof(qc.graph) # digraph from `Graphs.jl` qc.nodes using Qurt.Builders import .Qurt.Elements: H, CX, X, Y, RX (nH, nCX) = @build qc H(1) CX(1,2); print_edges(qc) qc[nCX] qc.nodes.element Integer(qc.nodes.element[1]) import .Interface.getelement getelement(qc, 1) # This is currently a way to access the element @btime getelement($qc, 1) # Dollar sign is a detail of how @btime works @btime $qc.nodes.element[1] # This is no more or less efficient qc = Circuit(2) @build qc X(1) Y(2) @build qc begin X(1) Y(2) CX(1,2) RX{1.5}(1) end; g1 = @gate RX g2 = @gate RX{1.5} # circuit element identity and parameters g3 = @gate RX{1.5}(2) # Include wires add_node!(qc, (g1, 1.5), (2,)) add_node!(qc, g2, (2,)) add_node!(qc, g3) (qc[11:13])
https://github.com/jlapeyre/Qurt.jl
jlapeyre
from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Clbit, Qubit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CXCancellation from qiskit.dagcircuit import DAGCircuit import qiskit.dagcircuit from qiskit.circuit import QuantumCircuit, Qubit from qiskit.converters import circuit_to_dag import rustworkx as rx def make_cnot_circuit(): nq = 2 qc = QuantumCircuit(nq) (n1, n2, n3) = (4, 5, 3) for _ in range(n1): qc.cx(0, 1) for _ in range(n2): qc.cx(1, 0) for _ in range(n3): qc.cx(0, 1) return qc def cancel_cnots(qc): pass_manager = PassManager() pass_manager.append(CXCancellation()) out_circuit = pass_manager.run(qc) return out_circuit def make_and_cancel(): qc = make_cnot_circuit() cancel_cnots(qc)
https://github.com/Amey-2002/QAOA-Vehicle-Routing-Problem
Amey-2002
# importing required libraries import numpy as np import matplotlib.pyplot as plt import sys import operator #importing qiskit packages from qiskit import BasicAer from qiskit.quantum_info import Pauli from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.algorithms import QAOA from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer #Setting values for given problem n = 4# Total number of nodes(In the problem, (number of delivery centres + 1 depot)) veh = 2 # Total number of vehicles # randomnly placing nodes and computing distances between nodes np.random.seed(1543) x = (np.random.rand(n)-0.5)*10 y = (np.random.rand(n)-0.5)*10 matrix = np.zeros([n,n]) # creating the distance matrix to indicate distances between individual nodes for i in range(n): for j in range(i+1,n): matrix[i,j] = (x[i]-x[j])**2 + (y[i]-y[j])**2 matrix[j,i] = matrix[i,j] # print(matrix) # print(x,y) # encoding the problem into a QuadraticProgram instance def instance(n,veh,matrix,x_sol=0): #parameter for cost function A = np.max(matrix) * 100 #defining weights w matrix_vec = matrix.reshape(n ** 2) w_list = [matrix_vec[x] for x in range(n ** 2) if matrix_vec[x] > 0] w = np.zeros(n * (n - 1)) for i in range(len(w_list)): w[i] = w_list[i] # print(matrix_vec) # print(w) #Finding the value of Q (Q defines the interactions between variables) e1_id = np.eye(n) e1_1 = np.ones([n-1,n-1]) e2 = np.ones(n) e2_1 = np.ones(n-1) e2[0]=0 neg_e2 = np.ones(n) - e2 v = np.zeros([n,n*(n-1)]) for i in range(n): count = i - 1 for j in range(n * (n - 1)): if j // (n - 1) == i: count = i if j // (n - 1) != i and j % (n - 1) == count: v[i][j] = 1.0 # print(neg_e2) #print(v) v1 = np.sum(v[1:], axis=0) #print(v1) Q = A*(np.kron(e1_id,e1_1)) + np.dot(v.T,v) #Finding the value of g g = (w - 2*A*(np.kron(e2,e2_1) + v1.T) - 2*A*veh*(np.kron(neg_e2,e2_1) + v[0].T) ) #Finding the value of c c = 2 * A * (n-1) + 2 * A * (veh**2) try: #max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q,g,c,cost #creating the QuadraticProgram instance using the above calculated values def q_program(n,veh,matrix,Q,g,c): qp = QuadraticProgram() for i in range(n*(n-1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp #solving the problem using qiskit optimization techniques def solution(n,veh,matrix,qp): algorithm_globals.random_seed = 10598 backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, seed_simulator = algorithm_globals.random_seed, seed_transpiler = algorithm_globals.random_seed ) qaoa = QAOA(quantum_instance=quantum_instance) optimizer = MinimumEigenOptimizer(min_eigen_solver=qaoa) result = optimizer.solve(qp) _,_,_,cost = instance(n,veh,matrix,x_sol=result.x) print(result) print(result.x) return result.x, cost Q,g,c,cost=instance(n,veh,matrix) qp = q_program(n,veh,matrix,Q,g,c) quantum_solution, quantum_cost = solution(n,veh,matrix,qp) # print(qp) # print(quantum_cost) # print(cost) print(quantum_solution, quantum_cost) x_quantum = np.zeros(n**2) k = 0 for i in range(n ** 2): if i // n != i % n: x_quantum[i] = quantum_solution[k] k += 1 # Visualize the solution def visualize_solution(x, y, x_q, C, n, K, title_str): plt.figure() plt.scatter(x, y, s=200) for i in range(len(x)): plt.annotate(i, (x[i] + 0.15, y[i]), size=16, color='r') plt.plot(x[0], y[0], 'r*', ms=20) plt.grid() for ii in range(0, n ** 2): if x_q[ii] > 0: ix = ii // n iy = ii % n plt.arrow(x[ix], y[ix], x[iy] - x[ix], y[iy] - y[ix], length_includes_head=True, head_width=.25) plt.title(title_str+' cost = ' + str(int(C * 100) / 100.)) plt.show() visualize_solution(x, y, x_quantum, quantum_cost, n, veh, 'Quantum')
https://github.com/RavenPillmann/quantum-battleship
RavenPillmann
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/kanavsetia/qiskitcamp
kanavsetia
import numpy as np from qiskit.chemistry import bksf from qiskit.chemistry.fermionic_operator import FermionicOperator as FO import pdb from collections import OrderedDict from pyscf import gto, scf, ao2mo from pyscf.lib import param from scipy import linalg as scila from pyscf.lib import logger as pylogger # from qiskit.chemistry import AquaChemistryError from qiskit.chemistry import QMolecule from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager, transpile_dag, transpile from qiskit.aqua import Operator, QuantumInstance from qiskit.aqua.algorithms.adaptive import VQE from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.chemistry import FermionicOperator from qiskit.quantum_info import Pauli from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import CXCancellation, Optimize1qGates from qiskit import BasicAer from qiskit.chemistry.drivers import PySCFDriver, UnitsType import networkx as nx import int_func #initialize one_body matrix and the two_body matrix np.set_printoptions(linewidth=230,suppress=True) ########## Random Test Case ############## two_body = np.zeros([4,4,4,4]) one_body=np.zeros([4,4]) one_body[3,2]=.5 one_body[2,3]=0.5 one_body[0,3]=0.4 one_body[3,0]=0.4 one_body[3,1]=0.3 one_body[1,3]=0.3 one_body[1,2]=0.21 one_body[2,1]=0.21 two_body=np.einsum('ijkl->iljk',two_body) ########### H2O ###################### mol = gto.Mole() mol.atom = [['O',(0.0, 0.0,0.0)],['H',(1, 0, 0)], ['H',(-1.0,0.0,0.0)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=_q_.two_body_integrals ########### NH3 ###################### mol = gto.Mole() mol.atom = [['N', (0.0000, 0.0000, 0.0000)], ['H', (0.0000, -0.9377, -0.3816)], ['H', (0.8121, 0.4689 ,-0.3816)], ['H', (-0.8121, 0.4689 ,-0.3816)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=_q_.two_body_integrals ########### CH4 ###################### mol = gto.Mole() mol.atom=[['C', (2.5369, 0.0000, 0.0000)], ['H', (3.0739, 0.3100, 0.0000)], ['H', (2.0000, -0.3100, 0.0000)], ['H', (2.2269, 0.5369, 0.0000)], ['H', (2.8469, -0.5369, 0.0000)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=_q_.two_body_integrals # def r_mat(one_body, two_body) fer_op1=FO(h1=one_body,h2=two_body) # First step of the algorithm is to get the graph. edge_list=bksf.bravyi_kitaev_fast_edge_list(fer_op1) two_body=np.zeros([obs,obs,obs,obs]) fer_op1=FO(h1=one_body,h2=np.einsum('ijkl->iljk',two_body)) #initialize graph and calculate the degree G=nx.Graph() G.add_edges_from(edge_list.transpose()) degree=np.zeros(np.size(one_body,1)) #print([e for e in G.edges]) for i in range(obs): degree[i]=G.degree(i) # sort_deg=np.argsort(degree) #sort the edges with degree in descending order sort_deg=(-degree).argsort() #calculate r matrix to transform the Hamiltonian for renumbered fermionic modes. rmat=np.zeros([np.size(one_body,1),np.size(one_body,1)]) for i in range(np.size(one_body,1)): rmat[i,np.where(sort_deg==i)]=1 #initialize fermionic operator with the renumbered Hamiltonian fer_op1.transform(rmat) jw_qo=fer_op1.mapping('jordan_wigner') # Checking to make sure everything went correctly. edge_list=bksf.bravyi_kitaev_fast_edge_list(fer_op1) G=nx.Graph() G.add_edges_from(edge_list.transpose()) # degree=np.zeros(4) # print(edge_list) # # jw_qo=Operator(paulis=[[.4,Pauli.from_label('ZZZZ')],[.4,Pauli.from_label('IZZZ')]]) # Separating the x terms and the y terms in the Hamiltonian. X_paulis=[] Y_paulis=[] d=0 for i in jw_qo._paulis: if d%2==0: X_paulis.append(i) else: Y_paulis.append(i) d=d+1 for i in X_paulis: Y_paulis.append(i) # initialize the operator with reordered terms jw_x_qo=Operator(Y_paulis) # print(jw_x_qo.print_operators()) # Generating the circuit from the Operator class q = QuantumRegister(np.size(one_body,1), name='q') q_circ=jw_x_qo.evolve(None, 1, 'circuit', 1,q) # Getting rid of extra gates simulator = BasicAer.get_backend('qasm_simulator') pass_manager = PassManager() # pass_manager.append(CXCancellation()) pass_manager.append(Optimize1qGates()) # q_circ.draw() # print(q_circ.count_ops()) new_circ = transpile(q_circ, simulator, pass_manager=pass_manager) pass_manager=PassManager() pass_manager.append(CXCancellation()) for i in range(np.size(one_body,1)): new_circ = transpile(new_circ, simulator, pass_manager=pass_manager) # new_circ = transpile(new_circ, simulator, pass_manager=pass_manager) print("Gate count using the optimization based on the structure of the fermionic problem") print(new_circ.count_ops()) # q = QuantumRegister(4, name='q') # q_circ=jw_qo.evolve(None, 1, 'circuit', 1,q)
https://github.com/kanavsetia/qiskitcamp
kanavsetia
import numpy as np from qiskit.chemistry import bksf from qiskit.chemistry.fermionic_operator import FermionicOperator as FO import pdb from collections import OrderedDict from pyscf import gto, scf, ao2mo from pyscf.lib import param from scipy import linalg as scila from pyscf.lib import logger as pylogger # from qiskit.chemistry import AquaChemistryError from qiskit.chemistry import QMolecule from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager, transpile_dag, transpile from qiskit.aqua import Operator, QuantumInstance from qiskit.aqua.algorithms.adaptive import VQE from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.chemistry import FermionicOperator from qiskit.quantum_info import Pauli from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import CXCancellation, Optimize1qGates from qiskit import BasicAer from qiskit.chemistry.drivers import PySCFDriver, UnitsType import networkx as nx import int_func ########## Random Test Case ############## np.set_printoptions(linewidth=230,suppress=True) two_body = np.zeros([4,4,4,4]) one_body=np.zeros([4,4]) one_body[3,2]=.5 one_body[2,3]=0.5 one_body[0,3]=0.4 one_body[3,0]=0.4 one_body[3,1]=0.3 one_body[1,3]=0.3 one_body[1,2]=0.21 one_body[2,1]=0.21 ########### H2O ###################### mol = gto.Mole() mol.atom = [['O',(0.0, 0.0,0.0)],['H',(1, 0, 0)], ['H',(-1.0,0.0,0.0)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=np.zeros([obs,obs,obs,obs]) ########### NH3 ###################### mol = gto.Mole() mol.atom = [['N', (0.0000, 0.0000, 0.0000)], ['H', (0.0000, -0.9377, -0.3816)], ['H', (0.8121, 0.4689 ,-0.3816)], ['H', (-0.8121, 0.4689 ,-0.3816)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=np.zeros([obs,obs,obs,obs]) ########### CH4 ###################### mol = gto.Mole() mol.atom=[['C', (2.5369, 0.0000, 0.0000)], ['H', (3.0739, 0.3100, 0.0000)], ['H', (2.0000, -0.3100, 0.0000)], ['H', (2.2269, 0.5369, 0.0000)], ['H', (2.8469, -0.5369, 0.0000)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=np.zeros([obs,obs,obs,obs]) fer_op1=FO(h1=one_body,h2=np.einsum('ijkl->iljk',two_body)) jw_qo=fer_op1.mapping('jordan_wigner') # print(jw_qo.print_operators()) simulator = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(np.size(one_body,1), name='q') q_circ=jw_qo.evolve(None, 1, 'circuit', 1,q) print("Gate count without using any optimization") print(q_circ.count_ops()) pass_manager = PassManager() pass_manager.append(Optimize1qGates()) # q_circ.draw() new_circ = transpile(q_circ, simulator, pass_manager=pass_manager) pass_manager=PassManager() pass_manager.append(CXCancellation()) for i in range(np.size(one_body,1)): new_circ = transpile(new_circ, simulator, pass_manager=pass_manager) # new_circ = transpile(new_circ, simulator, pass_manager=pass_manager) print("Gate count using transpiler") print(new_circ.count_ops())
https://github.com/tsirlucas/quantum-realtime-comm
tsirlucas
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/rodolfocarobene/SPVQE
rodolfocarobene
import numpy as np from qiskit.circuit.library import TwoLocal from qiskit_nature.drivers import UnitsType from qiskit_nature.drivers.second_quantization.electronic_structure_driver import MethodType from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import ParityMapper from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem # ansatz def get_ansatz_test(): converter = QubitConverter(mapper=ParityMapper(), two_qubit_reduction=True) init_st = HartreeFock(4, (1,1), converter) ansatz = TwoLocal(num_qubits=4, rotation_blocks='ry', entanglement_blocks='cx', entanglement=[(0,1),(1,2),(1,3)], reps=2, name='TwoLocal', initial_state=init_st) return ansatz # hamiltonian def get_hamiltonian_test(dist): converter = QubitConverter(mapper=ParityMapper(), two_qubit_reduction=True) alt = np.sqrt(dist**2 - (dist/2)**2) geom = f'H .0 .0 .0; H .0 .0 {dist}; H .0 {alt} {dist/2}' driver = PySCFDriver(atom=geom, unit=UnitsType.ANGSTROM, basis='sto6g', spin=0, charge=1, method=MethodType.RHF) problem = ElectronicStructureProblem(driver) hamiltonian = problem.second_q_ops()[0] circuit_hamiltonian = converter.convert(hamiltonian, 2) return circuit_hamiltonian # DISTANZA 0.5 # NUMERO 1 vqe_pars_05_a = [-0.11550176, 0.12474728, 2.59668356, 3.8576121, 0.08466277, -0.08561239, 0.33366492, -0.09046052, -0.01809542, 0.03835604, -0.19827222, 0.61663081] spvqe_pars_05_a = [-0.14645914, 0.24085774, 2.4493363, 4.39635615, 0.0412351, -0.037009016, 0.13252825, -0.08387666, -0.06751748, -0.1701828, -0.44594079, 1.11174508] # NUMERO 2 vqe_pars_05_b = [0.05880473, -0.49585711, 1.38931493, 1.22058033, 0.04743988, -0.35168815, 1.23629905, 1.31486832, -0.04791204, -0.12251855, -0.42800105, -0.54385726] spvqe_pars_05_b = [-0.0524159, -0.35065509, 1.50978572, 1.44223811, 0.10572807, -0.3610393, 1.09925545, 1.16282622, 0.0417312, -0.03228112, -0.52763223, -0.54086796] # NUMERO 3 vqe_pars_05_c = [-0.13742697, 0.06666297, 1.00157735, 1.26190522, 0.11471872, 0.04703104, 1.76370044, 1.61734347, 0.12522114, 0.01627249, -0.5024544, -0.2438825 ] spvqe_pars_05_c = [-0.00932172, -0.26494813, 1.39315548, 1.32781559, 0.08164483, -0.23497221, 1.17428293, 1.23188309, -0.00308427, -0.00491096, -0.60690943, -0.58952378] # NUMERO 4 vqe_pars_05_d = [0.16870004, -0.43813479, 1.29677422, 1.25914724, -0.04299792, -0.35431175,1.29298694, 1.26077492, -0.15053771, -0.19731699, -0.51811108, -0.6556562] spvqe_pars_05_d = [5.02394671, 9.41745152, 1.68675252, 7.85071438, 3.19550059, 9.42166769, 5.09519325, 2.59998515, 1.88735871, 3.1531819, 5.93912936, 2.11561298] vqes_05 = [vqe_pars_05_a, vqe_pars_05_b, vqe_pars_05_c, vqe_pars_05_d] spvqes_05 = [spvqe_pars_05_a, spvqe_pars_05_b, spvqe_pars_05_c, spvqe_pars_05_d] # DISTANZA 1.0 # NUMERO 1 vqe_pars_10_a = [6.16740344, 3.20411669, 5.67528188 ,3.67933879, 2.95053784, 6.2426416, 5.32863549, 6.09733424, 3.16169489, 0.10689151, 5.8707268, 2.40834679] spvqe_pars_10_a = [ 5.52205337, 6.33947666, 4.99314629, 1.56646707, 6.42004486, 9.34654435, 1.64389086, 1.53953422, 0.73439052, 9.42814649, -0.27327807, 9.44921354] # NUMERO 2 vqe_pars_10_b = [-0.3512596, -0.0434752, 1.0358355, 1.46491864 , 0.20682505, -0.00289901, 1.43619352, 1.23273737, 0.29697954 ,-0.07741656, -0.64436651, -0.4226421 ] spvqe_pars_10_b = [-0.46588444 , 0.03577865 , 1.12642329, 1.60349416, 0.16878282, 0.03519882, 1.58751012, 1.25972376, 0.41562211, 0.01466055, -0.38381825, -0.28252069] # NUMERO 3 vqe_pars_10_c = [ 0.62969728, 0.11563254, 1.90128434, 1.46585069, 0.18945206, 0.26035458, 0.80622198, 0.43826824, -0.67497233 , 0.1055656 , -0.53464882, -1.27380774] spvqe_pars_10_c = [ 0.5916648 , 1.06775659 , 1.57289366 , 1.56449836, 0.74571656, 1.14593536, 1.64660689, 1.73306393, -0.25437019, -0.0159303 , 0.05439476, 0.16162612] # NUMERO 4 vqe_pars_10_d = [ 0.99493485, 0.46749555, 1.66718638, 1.57712555, 0.76606805, 0.69293642, 1.88378101, 1.78376671, -0.8351959, -0.06788017, 0.33365866, 0.21094284] spvqe_pars_10_d = [ 1.27976371, -0.48962493, -1.35773093, 1.44466152, 2.0692902, -1.85807479, -0.80085892 , 0.50904985, 2.18264396, 0.25188056, 0.82224704, -1.06459749] vqes_10 = [vqe_pars_10_a, vqe_pars_10_b, vqe_pars_10_c, vqe_pars_10_d] spvqes_10 = [spvqe_pars_10_a, spvqe_pars_10_b, spvqe_pars_10_c, spvqe_pars_10_d] # DISTANZA 1.5 (19_04_10_47.log) # NUMERO 1 vqe_pars_15_a = [0.09991746, 0.62611588, 1.89744194, 4.32594859, -0.07035062, -0.31686141, 0.54348101, 4.58529642, 0.05761779, -0.09718047, -0.71666062, 3.03730765] spvqe_pars_15_a = [0.21380667, 0.2427542, 2.65108444, 8.19294383, -0.25609082, 0.09342074, 0.35346509, 3.82999585, -0.06775606, 0.17041844, -0.20121347, 2.58884638] # NUMERO 2 vqe_pars_15_b = [-0.21548311, 0.20120314, 2.30422198, 4.48161905, 0.13964768, -0.19722156, 0.09335863, 0.23036292, -0.38731748, -0.07424302, -1.00785697, 0.98497606] spvqe_pars_15_b = [0.61714577, 2.47534277, 3.17142515, 4.70746919, 1.35411788, -1.58468248, 1.60239857, -0.02513338, -0.97090705, -1.55142321, -0.79341562, 1.60062894] # NUMERO 3 vqe_pars_15_c = [0.97968128, 1.57688493, 1.1570894, 1.60995628, 1.34060246, 1.39458515, 1.92058373, 0.14457375, 0.15368186, 0.51329187, 0.19821282, 0.04170353] spvqe_pars_15_c = [ 0.48976517, -0.08104914, 0.72184541, -1.75849263, 0.25320102, 0.03368859, 2.59738978, -0.78635837, 0.28449398, -0.04249177, 0.2943293, 0.62921035] # NUMERO 4 vqe_pars_15_d = [ 0.84450869, 1.25491968, -0.44514397, 2.38703763, 0.94495797, 0.15694397, 2.98751578, -0.692738 , -0.11166693, 0.72361479, -0.50367291, 0.49284549] spvqe_pars_15_d = [ 3.90221684e-01, -4.15178472e-02, -2.99633796e-01 ,-1.58264586e+00, 2.13748167e-01, -5.61087214e-04, 3.11964764e+00, -7.96008889e-01, -1.51861563e-01, -5.91138869e-02, -2.71376710e-01, 7.52653356e-01] vqes_15 = [vqe_pars_15_a, vqe_pars_15_b, vqe_pars_15_c, vqe_pars_15_d] spvqes_15 = [spvqe_pars_15_a, spvqe_pars_15_b, spvqe_pars_15_c, spvqe_pars_15_d] # DISTANZA 2.0 # NUMERO 1 vqe_pars_20_a = [0.23225322, 4.20509329, 1.82170197, 4.27582049, 0.05729869, 0.15604462, 0.06000301, -0.13579914, 0.08299985, -1.07408837, -1.21879918, 1.24899782] spvqe_pars_20_a = [1.43809554, 7.81734322, 3.17165507, 4.75015336, 2.33703869, -0.38781625, 0.44597784, -0.12498502, -0.12032009, -1.55407031, -0.10911732, 1.61769171] # NUMERO 2 vqe_pars_20_b = [6.65022149e-03, -9.50528847e-02, 1.60330579e+00, 7.19883316e+00, -1.57724593e-02, -1.29639965e+00, -2.27676219e-02, 3.24072370e+00, -7.34213970e-02, -1.27990560e+00, -1.48335812e+00, 1.75404689e+00] spvqe_pars_20_b = [0.79587883, 0.32760775, 3.35288526, 7.85590383, -0.0390306, -0.69694168, -1.4426973, 3.36124759, -0.01221064, 0.74481681, -1.12900567, 1.70637381] # NUMERO 3 vqe_pars_20_c = [-0.08454793, 5.11004342, 1.83282241, 4.5149173, 0.09799665, -0.57644001, -0.15790267, -0.14204233, 0.08811245, -1.19742568, -1.15342555, 1.45476172] spvqe_pars_20_c = [0.11532082, 8.09680516, 2.37427009, 4.68877452, 1.42678813, -0.14232414, 0.17262165, -0.04088128, -1.4429427, -1.6389454, -1.21152173, 1.53310367] # NUMERO 4 vqe_pars_20_d = [-0.10993742, 1.08577653, -0.05778733, 1.43690763, 0.8346593, -0.64097313, -0.55031438, -0.02333615, 0.35142381, 1.30165111, 0.38822238, 1.1910818 ] spvqe_pars_20_d = [-0.35471067, 1.3383629, 0.01617288, 1.44855139, 0.44430146, 1.60495214, 1.48593211, 0.08656238, -0.34956568, 1.54163135, -0.18345526, -1.55837365] vqes_20 = [vqe_pars_20_a, vqe_pars_20_b, vqe_pars_20_c, vqe_pars_20_d] spvqes_20 = [spvqe_pars_20_a, spvqe_pars_20_b, spvqe_pars_20_c, spvqe_pars_20_d] # DISTANZA 2.5 # NUMERO 1 vqe_pars_25_a = [-0.30538821, 4.60997242, 7.66433589, 4.17372787, 0.10927006, -0.51266663, 0.23441709, -0.334758, -0.22351772, -0.53313997, -1.533864, 1.46004641] spvqe_pars_25_a = [-1.24650601, 5.78497934, 9.18265278, 4.73156897, -0.08129257, -0.41884356, -0.65460038, -0.08477229, -0.97708064, 0.75940663, -1.0149008, 1.42565896] # NUMERO 2 vqe_pars_25_b = [-0.57303308, 4.98891235, 1.94492016 , 4.53017413, 0.62503729, -0.61011673, -0.20483872, -0.11683771, 0.10371051, -1.2520706, -0.91139273, 1.4457862 ] spvqe_pars_25_b = [-6.40316565e-01, 8.15161506e+00, 3.06074748e+00, 4.67190248e+00, 6.19902164e-01, -1.27453265e+00, 1.29407199e+00, -6.22156917e-03, -7.40268451e-01, -1.58162040e+00, -3.93077842e-01, 1.55191480e+00] # NUMERO 3 vqe_pars_25_c = [ 2.71938179e-02, 5.12982224e-01, 1.17797400e+00, -9.06135220e-02, 7.21795803e-04, -3.56296414e-01, 1.32625535e+00, 6.68248236e-03, 8.74291139e-02, -1.45434574e-01, -6.86335893e-01, -1.34254368e-01] spvqe_pars_25_c = [ 0.99843238, 0.44052177, -0.1961437, -1.02581547, -0.77302264, -0.7235378, -0.82344231, 0.26436617, 1.26044456, -0.31363713, -1.2597413, 1.28040742] # NUMERO 4 vqe_pars_25_d = [ 0.18502226, 0.81530577, 0.73862034, 1.64122226, 0.21070779, 0.89669377, 1.56170187, -0.22372298, 0.18602616 , 0.63184611, -0.52464817, 1.38476156] spvqe_pars_25_d = [ 1.53050786, 0.19805966, 0.09745304, -1.13801992, 0.4664388, 0.42438396, 1.14798148, 0.63809267, 2.067302, 0.01598754, 1.04750262, 1.75522881] vqes_25 = [vqe_pars_25_a, vqe_pars_25_b, vqe_pars_25_c, vqe_pars_25_d] spvqes_25 = [spvqe_pars_25_a, spvqe_pars_25_b, spvqe_pars_25_c, spvqe_pars_25_d] vqe = [vqes_05, vqes_10, vqes_15, vqes_20, vqes_25] spvqe = [spvqes_05, spvqes_10, spvqes_15, spvqes_20, spvqes_25] from mitiq import zne from functools import partial from qiskit import Aer, IBMQ from qiskit.utils import QuantumInstance from qiskit.providers.aer.noise import NoiseModel from qiskit.utils.mitigation import CompleteMeasFitter from qiskit.opflow import CircuitStateFn, StateFn, PauliExpectation, CircuitSampler #provider = IBMQ.load_account() dist = 2.5 qubit_op = get_hamiltonian_test(dist) my_ansatz = get_ansatz_test().assign_parameters(spvqe_pars_25_d).decompose() def get_expectation(ansatz): tot = 0 for pauli in qubit_op: psi = CircuitStateFn( ansatz ) measurable_expression = StateFn( pauli, is_measurement = True ).compose( psi ) expectation = PauliExpectation().convert( measurable_expression ) sampler_qasm = CircuitSampler( quantuminstance ).convert( expectation ) expect_sampling_qasm = sampler_qasm.eval().real tot += expect_sampling_qasm return tot shots = 10000 backend = Aer.get_backend('qasm_simulator' ) noise_model = NoiseModel.from_backend(provider.get_backend('ibmq_quito')) measurement_error_mitigation_cls=CompleteMeasFitter optimization_level = 0 quantuminstance = QuantumInstance(backend, shots=shots, noise_model=noise_model, optimization_level=optimization_level, measurement_error_mitigation_cls=measurement_error_mitigation_cls) scale_factors = [1.0, 2.0, 3.0, 3.5] mitigated = zne.execute_with_zne(my_ansatz, get_expectation, factory=zne.inference.RichardsonFactory(scale_factors=scale_factors), num_to_average=3, scale_noise=partial(zne.scaling.fold_gates_from_left)) not_mitigated = get_expectation(my_ansatz) quantuminstance = QuantumInstance(Aer.get_backend('statevector_simulator')) exact = get_expectation(my_ansatz) print(mitigated, not_mitigated, exact)
https://github.com/rodolfocarobene/SPVQE
rodolfocarobene
import itertools import warnings import numpy as np import PySimpleGUI as psg from qiskit import IBMQ, Aer from qiskit.algorithms.optimizers import ADAM, CG, COBYLA, L_BFGS_B, NFT, SPSA from qiskit.ignis.mitigation import CompleteMeasFitter from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.utils import QuantumInstance from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import ParityMapper warnings.simplefilter("ignore") def get_default_opt(): print("Loading default values") values = { "molecule": "H3+", "spin": 0, "charge": 0, "basis": ["sto-6g"], "varforms": ["TwoLocal"], "backend": ["hardware"], "noise": ["None"], "shots": 2048, "correction": ["False"], "optimizer": ["SPSA"], "dist_min": 1.4, "dist_max": 3.5, "dist_delta": 11, "lagrangiana": ["True", "Series"], "lag_op": ["spin-squared"], "lag_value_num": 2, "lag_mult_num_min": 1, "lag_mult_num_max": 4, "lag_mult_num_delta": 10, "lag_value_spin2": 0, "lag_mult_spin2_min": 0.5, "lag_mult_spin2_max": 4, "lag_mult_spin2_delta": 10, "lag_value_spinz": 0, "lag_mult_spinz_min": 0.2, "lag_mult_spinz_max": 0.2, "lag_mult_spinz_delta": 0.1, "series_itermax_min": 5, "series_itermax_max": 20, "series_itermax_step": 25, "series_step_min": 0.1, "series_step_max": 1, "series_step_step": 9, "series_lamb_min": 2, "series_lamb_max": 6, "series_lamb_step": 10, } return values def get_layout(): possible_molecules = [ "H3+", "H2", "H2+", "H2*", "H2-", "H2--", "H4", "H4*", "Li2", "Li2+", "LiH", "H2O", "C2H4", "N2", "Li3+", "Na-", "HeH+", ] possible_forms = ["TwoLocal", "SO(4)", "UCCSD", "EfficientSU(2)"] possible_basis = ["sto-3g", "sto-6g"] possible_noise = ["None", "ibmq_santiago", "ibmq_bogota", "ibm_perth", "ibmq_lima"] possible_bool = ["True", "False"] possible_lag = ["True", "False", "Series", "AUGSeries"] possible_optim = ["COBYLA", "CG", "SPSA", "L_BFGS_B", "ADAM", "NFT"] possible_lag_op = ["number", "spin-squared", "spin-z", "num+spin2", "spin2+spinz", "num+spinz", "num+spin2+spinz"] possible_backend = ["statevector_simulator", "qasm_simulator", "qasm_simulator_online", "hardware", "qasm_gpu"] layout = [ [ psg.Text("Molecola"), psg.Combo(possible_molecules, default_value="H3+", size=(5, 1), key="molecule"), psg.Text("Basis"), psg.Listbox(possible_basis, default_values=["sto-6g"], select_mode="extended", size=(7, 2), key="basis"), ], [ psg.Text("Scegli forma variazionale"), psg.Listbox( possible_forms, default_values=["TwoLocal"], select_mode="extended", size=(12, 4), key="varforms" ), ], [ psg.Text("Scegli il tipo di backend"), psg.Listbox( possible_backend, default_values=["statevector_simulator"], select_mode="extended", size=(17, 4), key="backend", ), psg.Text("shots"), psg.Input(default_text=1024, size=(4, 10), key="shots"), ], [ psg.Text("Scegli l'eventuale rumore"), psg.Listbox(possible_noise, default_values=["None"], select_mode="extended", size=(14, 5), key="noise"), ], [ psg.Text("Correction"), psg.Listbox(possible_bool, default_values=["False"], select_mode="extended", size=(5, 2), key="correction"), ], [ psg.Text("Optimizer"), psg.Listbox( possible_optim, default_values=["COBYLA"], select_mode="extended", size=(8, 6), key="optimizer" ), ], [ psg.Text("Distanze: Min"), psg.Input(default_text=0.3, size=(4, 10), key="dist_min"), psg.Text(" Max"), psg.Input(default_text=3.5, size=(4, 10), key="dist_max"), psg.Text(" Delta"), psg.Input(default_text=0.1, size=(4, 10), key="dist_delta"), ], [ psg.Text("Lagrangiana"), psg.Listbox( possible_lag, default_values=["Series"], select_mode="extended", size=(10, 4), key="lagrangiana" ), ], [ psg.Text("LagSeries(itermax) MIN:"), psg.Input(default_text=10, size=(4, 10), key="series_itermax_min"), psg.Text("MAX: "), psg.Input(default_text=20, size=(4, 10), key="series_itermax_max"), psg.Text("DELTA: "), psg.Input(default_text=20, size=(4, 10), key="series_itermax_step"), ], [ psg.Text("LagSeries(step) MIN:"), psg.Input(default_text=0.2, size=(4, 10), key="series_step_min"), psg.Text("MAX: "), psg.Input(default_text=1, size=(4, 10), key="series_step_max"), psg.Text("DELTA: "), psg.Input(default_text=10, size=(4, 10), key="series_step_step"), ], [ psg.Text("LagSeries(lamb) MIN:"), psg.Input(default_text=2, size=(4, 10), key="series_lamb_min"), psg.Text("MAX: "), psg.Input(default_text=6, size=(4, 10), key="series_lamb_max"), psg.Text("DELTA: "), psg.Input(default_text=10, size=(4, 10), key="series_lamb_step"), ], [ psg.Text("Operatore"), psg.Listbox(possible_lag_op, default_values=["number"], select_mode="extended", size=(18, 7), key="lag_op"), ], [ psg.Text("NUMBER: Value"), psg.Input(default_text=2, size=(4, 10), key="lag_value_num"), psg.Text("Mult: min"), psg.Input(default_text=0.2, size=(4, 10), key="lag_mult_num_min"), psg.Text("max"), psg.Input(default_text=1, size=(4, 10), key="lag_mult_num_max"), psg.Text("delta"), psg.Input(default_text=10, size=(4, 10), key="lag_mult_num_delta"), ], [ psg.Text("SPIN-2: Value"), psg.Input(default_text=0, size=(4, 10), key="lag_value_spin2"), psg.Text("Mult: min"), psg.Input(default_text=0.2, size=(4, 10), key="lag_mult_spin2_min"), psg.Text("max"), psg.Input(default_text=1, size=(4, 10), key="lag_mult_spin2_max"), psg.Text("delta"), psg.Input(default_text=10, size=(4, 10), key="lag_mult_spin2_delta"), ], [ psg.Text("SPIN-Z: Value"), psg.Input(default_text=0, size=(4, 10), key="lag_value_spinz"), psg.Text("Mult: min"), psg.Input(default_text=0.2, size=(4, 10), key="lag_mult_spinz_min"), psg.Text("max"), psg.Input(default_text=1, size=(4, 10), key="lag_mult_spinz_max"), psg.Text("delta"), psg.Input(default_text=10, size=(4, 10), key="lag_mult_spinz_delta"), ], [psg.Button("Inizia calcolo", font=("Times New Roman", 12))], ] return layout def retrive_VQE_options(argv): if "fast" in argv: values = get_default_opt() else: layout = get_layout() win = psg.Window("Definisci opzioni per VQE", layout, resizable=True, font="Lucida", text_justification="left") e_useless, values = win.read() win.close() set_optimizers(values) set_backend_and_noise(values) lagops = set_lagrange_ops(values) if values["dist_min"] >= values["dist_max"]: values["dist_max"] = values["dist_min"] + values["dist_delta"] / 2 options = { "dist": {"min": values["dist_min"], "max": values["dist_max"], "delta": values["dist_delta"]}, "molecule": { "molecule": values["molecule"], "spin": get_spin(values["molecule"]), "charge": get_charge(values["molecule"]), "basis": values["basis"], }, "varforms": values["varforms"], "quantum_instance": values["backend"], "shots": int(values["shots"]), "optimizer": values["optimizer"], "converter": QubitConverter(mapper=ParityMapper(), two_qubit_reduction=True), "lagrange": { "active": values["lagrangiana"], "operators": lagops, }, "series": { "itermax": np.arange( int(values["series_itermax_min"]), int(values["series_itermax_max"]), int(values["series_itermax_step"]) ), "step": np.arange( float(values["series_step_min"]), float(values["series_step_max"]), float(values["series_step_step"]) ), "lamb": np.arange( float(values["series_lamb_min"]), float(values["series_lamb_max"]), float(values["series_lamb_step"]) ), }, } options = set_dist_and_geometry(options) print_chose_options(options) return options def set_ops_num_spin2(values, lagops_list): mults_num = np.arange( float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"]) ) mults_spin2 = np.arange( float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"]) ) for mult_num in mults_num: for mult_spin2 in mults_spin2: mult_num = np.round(mult_num, 2) mult_spin2 = np.round(mult_spin2, 2) templist = [] templist.append(("number", int(values["lag_value_num"]), mult_num)) templist.append(("spin-squared", int(values["lag_value_spin2"]), mult_spin2)) lagops_list.append(templist) def set_ops_num_spinz(values, lagops_list): mults_num = np.arange( float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"]) ) mults_spinz = np.arange( float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"]) ) for mult_num in mults_num: for mult_spinz in mults_spinz: mult_num = np.round(mult_num, 2) mult_spinz = np.round(mult_spinz, 2) templist = [] templist.append(("number", int(values["lag_value_num"]), mult_num)) templist.append(("spin-z", int(values["lag_value_spinz"]), mult_spinz)) lagops_list.append(templist) def set_ops_spin2_spinz(values, lagops_list): mults_spin2 = np.arange( float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"]) ) mults_spinz = np.arange( float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"]) ) for mult_spin2 in mults_spin2: for mult_spinz in mults_spinz: mult_spin2 = np.round(mult_spin2, 2) mult_spinz = np.round(mult_spinz, 2) templist = [] templist.append(("spin-squared", int(values["lag_value_spin2"]), mult_spin2)) templist.append(("spin-z", int(values["lag_value_spinz"]), mult_spinz)) lagops_list.append(templist) def set_ops_num_spin2_spinz(values, lagops_list): mults_spin2 = np.arange( float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"]) ) mults_num = np.arange( float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"]) ) mults_spinz = np.arange( float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"]) ) for mult_spin2 in mults_spin2: for mult_spinz in mults_spinz: for mult_num in mults_num: mult_spin2 = np.round(mult_spin2, 2) mult_spinz = np.round(mult_spinz, 2) mult_num = np.round(mult_num, 2) templist = [] templist.append(("spin-squared", int(values["lag_value_spin2"]), mult_spin2)) templist.append(("spin-z", int(values["lag_value_spinz"]), mult_spinz)) templist.append(("number", int(values["lag_value_num"]), mult_num)) lagops_list.append(templist) def set_ops_num(values, lagops_list, operator): mults = np.arange( float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"]) ) for mult in mults: mult = np.round(mult, 2) lagops_list.append([(operator, int(values["lag_value_num"]), mult)]) def set_ops_spin2(values, lagops_list, operator): mults = np.arange( float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"]) ) for mult in mults: mult = np.round(mult, 2) lagops_list.append([(operator, int(values["lag_value_spin2"]), mult)]) def set_ops_spinz(values, lagops_list, operator): mults = np.arange( float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"]) ) for mult in mults: mult = np.round(mult, 2) lagops_list.append([(operator, int(values["lag_value_spinz"]), mult)]) def set_lagrange_ops(values): if float(values["lag_mult_num_min"]) >= float(values["lag_mult_num_max"]): values["lag_mult_num_max"] = float(values["lag_mult_num_min"]) + float(values["lag_mult_num_delta"]) / 2 if float(values["lag_mult_spin2_min"]) >= float(values["lag_mult_spin2_max"]): values["lag_mult_spin2_max"] = float(values["lag_mult_spin2_min"]) + float(values["lag_mult_spin2_delta"]) / 2 if float(values["lag_mult_spinz_min"]) >= float(values["lag_mult_spinz_max"]): values["lag_mult_spinz_max"] = float(values["lag_mult_spinz_min"]) + float(values["lag_mult_spinz_delta"]) / 2 if values["lagrangiana"] == ["False"]: lagops_list = [[("dummy", 0, 0)]] else: lagops_list = [] for operator in values["lag_op"]: if operator == "number": set_ops_num(values, lagops_list, operator) elif operator == "spin-squared": set_ops_spin2(values, lagops_list, operator) elif operator == "spin-z": set_ops_spinz(values, lagops_list, operator) elif operator == "num+spin2": set_ops_num_spin2(values, lagops_list) elif operator == "num+spinz": set_ops_num_spinz(values, lagops_list) elif operator == "spin2+spinz": set_ops_spin2_spinz(values, lagops_list) elif operator == "num+spin2+spinz": set_ops_num_spin2_spinz(values, lagops_list) return lagops_list def print_chose_options(options): quantum_instance_name = [] for ist in options["quantum_instance"]: quantum_instance_name.append(ist[1]) optimizers_name = [] for opt in options["optimizer"]: optimizers_name.append(opt[1]) print("OPZIONI SCELTE") print("mol_type: ", options["molecule"]["molecule"]) print("charge: ", options["molecule"]["charge"]) print("spin: ", options["molecule"]["spin"]) print("dist: ", options["dists"]) print("basis: ", options["molecule"]["basis"]) print("varforms: ", options["varforms"]) print("instances: ", quantum_instance_name) print("optimizer: ", optimizers_name) if options["lagrange"]["active"][0] != "False": print( "lagrange: ", "\n\tactive: ", options["lagrange"]["active"], "\n\toperator: ", options["lagrange"]["operators"], ) print( "series: ", "\n\titermax: ", options["series"]["itermax"], "\n\tstep: ", options["series"]["step"], "\n\tlamb: ", options["series"]["lamb"], ) def set_optimizers(values): optimizers = [] for opt in values["optimizer"]: if opt == "CG": optimizers.append((CG(maxiter=50), "CG")) elif opt == "COBYLA": optimizers.append((COBYLA(), "COBYLA")) elif opt == "ADAM": optimizers.append((ADAM(maxiter=100), "ADAM")) elif opt == "L_BFGS_B": optimizers.append((L_BFGS_B(maxiter=100), "LBFGSB")) elif opt == "SPSA": optimizers.append((SPSA(maxiter=500), "SPSA")) elif opt == "NFT": optimizers.append((NFT(maxiter=200), "NFT")) values["optimizer"] = optimizers def set_backend_and_noise(values): quantum_instance_list = [] provider = IBMQ.load_account() iteratore = list(itertools.product(values["backend"], values["noise"], values["correction"])) for backend, noise, corr in iteratore: if backend == "statevector_simulator": quantum_instance = QuantumInstance(Aer.get_backend("statevector_simulator")) noise = "None" elif backend == "qasm_simulator": quantum_instance = QuantumInstance( backend=QasmSimulator(), shots=int(values["shots"]) # Aer.get_backend('qasm_simulator'), ) elif backend == "qasm_gpu": quantum_instance = QuantumInstance( backend=Aer.get_backend("qasm_simulator"), backend_options={"method": "statevector_gpu"}, shots=int(values["shots"]), ) elif backend == "qasm_simulator_online": quantum_instance = QuantumInstance( backend=provider.backend.ibmq_qasm_simulator, # provider.get_backend('ibmq_qasm_simulator'), #QasmSimulator(method='statevector'), shots=int(values["shots"]), ) elif backend == "hardware": mybackend = provider.get_backend("ibmq_bogota") # just dummy, for hardware quantum_instance = mybackend if backend == "qasm_simulator" and noise != "None": device = provider.get_backend(noise) coupling_map = device.configuration().coupling_map noise_model = NoiseModel.from_backend(device) quantum_instance.coupling_map = coupling_map quantum_instance.noise_model = noise_model name = backend + "_" + noise if backend == "qasm_simulator" and noise != "None" and corr == "True": quantum_instance.measurement_error_mitigation_cls = CompleteMeasFitter quantum_instance.measurement_error_mitigation_shots = 1000 name += "_corrected" quantum_instance_list.append((quantum_instance, name)) values["backend"] = quantum_instance_list def set_dist_and_geometry(options): minimo = float(options["dist"]["min"]) massimo = float(options["dist"]["max"]) delta = float(options["dist"]["delta"]) dist = np.arange(minimo, massimo, delta) options["dists"] = dist geometries = [] mol_type = options["molecule"]["molecule"] if mol_type == "H3+": alt = np.sqrt(dist**2 - (dist / 2) ** 2, dtype="float64") for i, single_dist in enumerate(dist): geom = "H .0 .0 .0; H .0 .0 " + str(single_dist) geom += "; H .0 " + str(alt[i]) + " " + str(single_dist / 2) geometries.append(geom) elif mol_type == "Na-": geometries.append("Na .0 .0 .0") elif mol_type == "HeH+": for i, single_dist in enumerate(dist): geom = "He .0 .0 .0; H .0 .0 " + str(single_dist) geometries.append(geom) elif mol_type == "Li3+": alt = np.sqrt(dist**2 - (dist / 2) ** 2, dtype="float64") for i, single_dist in enumerate(dist): geom = "Li .0 .0 .0; Li .0 .0 " + str(single_dist) geom += "; Li .0 " + str(alt[i]) + " " + str(single_dist / 2) geometries.append(geom) elif mol_type == "C2H4": bot_alt = np.sin(180 - 121.3) * 1.087 fixed_dist = np.cos(180 - 121.3) * 1.087 for i, single_dist in enumerate(dist): top_alt = np.sin(180 - 121.3) * single_dist geom1 = "H " + str(-fixed_dist) + " " + str(top_alt) + " 0.0; " geom2 = "H " + str(-fixed_dist) + " " + str(-bot_alt) + " 0.0; " geom3 = "C 0.0 0.0 0.0; C " + str(single_dist) + " 0.0 0.0; " geom4 = "H " + str(fixed_dist) + " " + str(top_alt) + " 0.0; " geom5 = "H " + str(fixed_dist) + " " + str(-bot_alt) + " 0.0" geom = geom1 + geom2 + geom3 + geom4 + geom5 geometries.append(geom) elif "H2O" in mol_type: for single_dist in dist: alt = single_dist * np.cos(0.25) lung = single_dist * np.sin(0.25) + 0.9584 geom = "H .0 .0 .0; O .0 .0 0.9584; H .0 " + str(alt) + " " + str(lung) geometries.append(geom) elif "H2" in mol_type: for single_dist in dist: geom = "H .0 .0 .0; H .0 .0 " + str(single_dist) geometries.append(geom) elif "N2" in mol_type: for single_dist in dist: geom = "N .0 .0 .0; N .0 .0 " + str(single_dist) geometries.append(geom) elif "H4" in mol_type: for single_dist in dist: geom = "H .0 .0 .0; H .0 .0 " + str(single_dist) geom += "; H .0 .0 " + str(2 * single_dist) + "; H .0 .0 " + str(3 * single_dist) geometries.append(geom) elif "Li2" in mol_type: for single_dist in dist: geom = "Li .0 .0 .0; Li .0 .0 " + str(single_dist) geometries.append(geom) elif "LiH" in mol_type: for single_dist in dist: geom = "Li .0 .0 .0; H .0 .0 " + str(single_dist) geometries.append(geom) options["geometries"] = geometries return options def get_spin(mol_opt): mol_type = mol_opt if mol_type == "H3+": spin = 0 if mol_type == "Li3+": spin = 0 elif mol_type == "H2": spin = 0 elif mol_type == "H2*": spin = 2 elif mol_type == "H2+": spin = 1 elif mol_type == "H2-": spin = 1 elif mol_type == "H2--": spin = 0 elif mol_type == "H4": spin = 0 elif mol_type == "H4*": spin = 2 elif mol_type == "Li2": spin = 0 elif mol_type == "Li2+": spin = 1 elif mol_type == "H2O": spin = 0 elif mol_type == "LiH": spin = 0 elif mol_type == "C2H4": spin = 0 elif mol_type == "N2": spin = 0 elif mol_type == "Na-": spin = 0 elif mol_type == "HeH+": spin = 0 return spin def get_charge(mol_opt): mol_type = mol_opt if mol_type == "H3+": charge = 1 if mol_type == "Li3+": charge = 1 elif mol_type == "H2": charge = 0 elif mol_type == "H2*": charge = 0 elif mol_type == "H2+": charge = 1 elif mol_type == "H2-": charge = -1 elif mol_type == "H2--": charge = -2 elif mol_type == "H4": charge = 0 elif mol_type == "H4*": charge = 0 elif mol_type == "Li2": charge = 0 elif mol_type == "Li2+": charge = 1 elif mol_type == "LiH": charge = 0 elif mol_type == "H2O": charge = 0 elif mol_type == "C2H4": charge = 0 elif mol_type == "N2": charge = 0 elif mol_type == "Na-": charge = -1 elif mol_type == "HeH+": charge = 1 return charge
https://github.com/rodolfocarobene/SPVQE
rodolfocarobene
import logging import math from datetime import datetime import numpy as np from qiskit import IBMQ, Aer, QuantumCircuit from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B from qiskit.circuit import Parameter, QuantumRegister from qiskit.circuit.library import EfficientSU2, TwoLocal from qiskit.opflow.primitive_ops import PauliOp from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Pauli from qiskit.utils import QuantumInstance from qiskit_nature.algorithms import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.circuit.library import UCCSD, HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.drivers import Molecule, UnitsType from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.drivers.second_quantization.electronic_structure_driver import ( MethodType, ) from qiskit_nature.mappers.second_quantization import BravyiKitaevMapper, ParityMapper from qiskit_nature.problems.second_quantization.electronic import ( ElectronicStructureProblem, ) from qiskit_nature.results import EigenstateResult, ElectronicStructureResult from qiskit_nature.runtime import VQEProgram from qiskit_nature.transformers.second_quantization.electronic import ( ActiveSpaceTransformer, FreezeCoreTransformer, ) def order_of_magnitude(number): if number == 0: return -100 return math.floor(math.log(number, 10)) def get_date_time_string(): now = datetime.now() return now.strftime("%d_%m_%H_%M") myLogger = logging.getLogger("myLogger") myLogger.setLevel(logging.DEBUG) ch = logging.FileHandler("./logs/" + get_date_time_string() + ".log") ch.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) myLogger.addHandler(ch) def add_single_so4_gate(circuit, qubit1, qubit2, params, par0): myLogger.info("Inizio di add_single_so4_gate") circuit.s(qubit1) circuit.s(qubit2) circuit.h(qubit2) circuit.cx(qubit2, qubit1) circuit.u(params[par0], params[par0 + 1], params[par0 + 2], qubit1) par0 += 3 circuit.u(params[par0], params[par0 + 1], params[par0 + 2], qubit2) par0 += 3 circuit.cx(qubit2, qubit1) circuit.h(qubit2) circuit.sdg(qubit1) circuit.sdg(qubit2) myLogger.info("Fine di add_single_so4_gate") def construct_so4_ansatz(numqubits, init=None): myLogger.info("Inizio di construct_so4_ansatz") num_parameters = 6 * (numqubits - 1) so4_parameters = [] for i in range(num_parameters): name = "par" + str(i) new = Parameter(name) so4_parameters.append(new) quantum_reg = QuantumRegister(numqubits, name="q") if init is not None: circ = init else: circ = QuantumCircuit(quantum_reg) i = 0 j = 0 while i + 1 < numqubits: add_single_so4_gate(circ, i, i + 1, so4_parameters, 6 * j) j = j + 1 i = i + 2 i = 1 while i + 1 < numqubits: add_single_so4_gate(circ, i, i + 1, so4_parameters, 6 * j) j = j + 1 i = i + 2 myLogger.info("Fine di construct_so4_ansatz") return circ def create_lagrange_operator_ps(hamiltonian, auxiliary, multiplier, operator, value): myLogger.info("Inizio di create_lagrange_operator_ps") if operator == "number": idx = 0 elif operator == "spin-squared": idx = 1 elif operator == "spin-z": idx = 2 list_x_zeros = np.zeros(hamiltonian.num_qubits) list_z_zeros = np.zeros(hamiltonian.num_qubits) equality = auxiliary[idx].add(PauliOp(Pauli((list_z_zeros, list_x_zeros)), -value)) penalty_squared = (equality**2).mul(multiplier) lagrangian = hamiltonian.add(penalty_squared) myLogger.info("Fine di create_lagrange_operator_ps") return lagrangian def create_lagrange_operator_aug(hamiltonian, auxiliary, multiplier_simple, multiplier_square, operator, value): myLogger.info("Inizio di create_lagrange_operator_aug") if operator == "number": idx = 0 elif operator == "spin-squared": idx = 1 elif operator == "spin-z": idx = 2 list_x_zeros = np.zeros(hamiltonian.num_qubits) list_z_zeros = np.zeros(hamiltonian.num_qubits) equality = auxiliary[idx].add(PauliOp(Pauli((list_z_zeros, list_x_zeros)), -value)) penalty_squared = (equality**2).mul(multiplier_square) penalty_simple = equality.mul(-multiplier_simple) lagrangian = hamiltonian.add(penalty_squared).add(penalty_simple) myLogger.info("Fine di create_lagrange_operator_aug") return lagrangian def get_transformers_from_mol_type(mol_type): transf_list = [] if mol_type == "LiH": # transf_list.append(FreezeCoreTransformer(True)) #, [2, 3, 4])) transf_list.append(ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=3)) if mol_type == "H2O": transf_list.append(ActiveSpaceTransformer(num_electrons=4, num_molecular_orbitals=3)) if mol_type == "C2H4": transf_list.append(ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=2)) if mol_type == "N2": transf_list.append(ActiveSpaceTransformer(num_electrons=6, num_molecular_orbitals=3)) if mol_type == "Li3+": transf_list.append(ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=3)) if mol_type == "Na-": transf_list.append(FreezeCoreTransformer(True)) return transf_list def from_geometry_to_atoms(geometry): tot_atoms = [] atoms_geom = geometry.split(";") for single_atom_geom in atoms_geom: atom = single_atom_geom.split()[0] tot_atoms.append(atom) return tot_atoms def get_num_particles(mol_type, particle_number): alpha, beta = particle_number.num_alpha, particle_number.num_beta num_spin_orbitals = particle_number.num_spin_orbitals if mol_type == "LiH": a_b_spinorbs = 1, 1, 6 # 10#4 if mol_type == "Li3+": a_b_spinorbs = 1, 1, 6 # 10#4 elif mol_type == "H2O": a_b_spinorbs = 2, 2, 6 elif mol_type == "C2H4": a_b_spinorbs = 1, 1, 4 elif mol_type == "N2": a_b_spinorbs = 3, 3, 6 else: a_b_spinorbs = alpha, beta, num_spin_orbitals return a_b_spinorbs def prepare_base_vqe(options): myLogger.info("Inizio di prepare_base_vqe") spin = options["molecule"]["spin"] charge = options["molecule"]["charge"] basis = options["molecule"]["basis"] geometry = options["molecule"]["geometry"] var_form_type = options["var_form_type"] quantum_instance = options["quantum_instance"] optimizer = options["optimizer"] converter = options["converter"] init_point = options["init_point"] driver = PySCFDriver( atom=geometry, unit=UnitsType.ANGSTROM, basis=basis, spin=spin, charge=charge, method=MethodType.RHF ) transformers = get_transformers_from_mol_type(options["molecule"]["molecule"]) problem = ElectronicStructureProblem(driver, transformers) main_op = problem.second_q_ops()[0] driver_result = driver.run() particle_number = driver_result.get_property("ParticleNumber") alpha, beta, num_spin_orbitals = get_num_particles(options["molecule"]["molecule"], particle_number) num_particles = (alpha, beta) myLogger.info("alpha %d", alpha) myLogger.info("beta %d", beta) myLogger.info("spin-orb %d", num_spin_orbitals) qubit_op = converter.convert(main_op, num_particles=num_particles) init_state = HartreeFock(num_spin_orbitals, num_particles, converter) num_qubits = qubit_op.num_qubits myLogger.info("num qubit qubitop : %d", qubit_op.num_qubits) if init_state.num_qubits != num_qubits: myLogger.info("num qubit initsta: %d", init_state.num_qubits) init_state = None vqe_solver = create_vqe_from_ansatz_type( var_form_type, num_qubits, init_state, quantum_instance, optimizer, converter, num_particles, num_spin_orbitals, init_point, ) myLogger.info("Fine di prepare_base_vqe") return converter, vqe_solver, problem, qubit_op def store_intermediate_result(count, par, energy, std): global PARAMETERS PARAMETERS.append(par) log_string = str(count) + " " + str(energy) + " " + str(std) myLogger.info(log_string) def from_energy_pars_to_log_msg(pars, energy): message = "" for par in pars: message += str(par).strip() message += "," message = message[:-1] message += " ; " message += str(energy) message += "\n" return message def get_ansatz(var_form_type, num_qubits, init_state=None): if var_form_type == "TwoLocal": ansatz = TwoLocal( num_qubits=num_qubits, rotation_blocks="ry", entanglement_blocks="cx", initial_state=init_state, entanglement="linear", ) elif var_form_type == "EfficientSU(2)": ansatz = EfficientSU2( num_qubits=num_qubits, entanglement="linear", reps=1, skip_final_rotation_layer=True, initial_state=init_state, ) else: print("Ansatz non ancora implementato in get_ansatz()") return ansatz def create_vqe_from_ansatz_type( var_form_type, num_qubits, init_state, quantum_instance, optimizer, converter, num_particles, num_spin_orbitals, initial_point, ): myLogger.info("Inizio create_vqe_from_ansatz_type") if var_form_type in ("TwoLocal", "EfficientSU(2)"): ansatz = get_ansatz(var_form_type, num_qubits, init_state) if None in initial_point: initial_point = np.random.rand(ansatz.num_parameters) vqe_solver = VQE( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, callback=store_intermediate_result, quantum_instance=quantum_instance, ) elif var_form_type == "UCCSD": ansatz = UCCSD( qubit_converter=converter, initial_state=init_state, num_particles=num_particles, num_spin_orbitals=num_spin_orbitals, ) if None in initial_point: initial_point = np.random.rand(8) # MUST BE SET HERE vqe_solver = VQE( quantum_instance=quantum_instance, ansatz=ansatz._build(), optimizer=optimizer, callback=store_intermediate_result, initial_point=initial_point, ) elif var_form_type == "SO(4)": ansatz = construct_so4_ansatz(num_qubits, init=init_state) if None in initial_point: initial_point = np.random.rand(6 * (num_qubits - 1)) vqe_solver = VQE( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, callback=store_intermediate_result, quantum_instance=quantum_instance, ) else: raise Exception("VAR_FORM_TYPE NOT EXISTS") myLogger.info("Fine create_vqe_from_ansatz_type") return vqe_solver def solve_hamiltonian_vqe(options): myLogger.info("Inizio solve_hamiltonian_vqe") myLogger.info("OPTIONS") myLogger.info(options) converter, vqe_solver, problem, qubit_op = prepare_base_vqe(options) calc = GroundStateEigensolver(converter, vqe_solver) result = calc.solve(problem) myLogger.info("Fine solve_hamiltonian_vqe") myLogger.info(PARAMETERS[len(PARAMETERS) - 1]) myLogger.info("RESULT") myLogger.info(result) return result def get_runtime_vqe_program(options, num_qubits): # IBMQ.load_account() provider = IBMQ.get_provider(hub="ibm-q-research-2", group="uni-milano-bicoc-1", project="main") backend_list = [] backend_list.append(provider.get_backend("ibm_perth")) backend_list.append(provider.get_backend("ibm_lagos")) backend_list.append(provider.get_backend("ibmq_casablanca")) backend_list.append(provider.get_backend("ibmq_bogota")) backend_list.append(provider.get_backend("ibmq_manila")) quantum_instance = least_busy(backend_list) print("Run su backend: ", quantum_instance.backend_name) ansatz = get_ansatz(options["var_form_type"], num_qubits) init_point = options["init_point"] if None in init_point: init_point = np.random.rand(ansatz.num_parameters) global LAST_OPTIMIZER_OPT if LAST_OPTIMIZER_OPT is not None: options["optimizer"].set_options(LAST_OPTIMIZER_OPT) vqe_program = VQEProgram( ansatz=ansatz, optimizer=options["optimizer"], initial_point=init_point, provider=provider, backend=quantum_instance, shots=options["shots"], callback=store_intermediate_result, store_intermediate=True, ) return vqe_program def solve_lagrangian_vqe(options): myLogger.info("Inizio solve_lagrangian_vqe") myLogger.info("OPTIONS") myLogger.info(options) converter, vqe_solver, problem, qubit_op = prepare_base_vqe(options) if options["hardware"] is True: vqe_solver = get_runtime_vqe_program(options, qubit_op.num_qubits) aux_ops_not_converted = problem.second_q_ops()[1:4] aux_ops = convert_list_op_ferm_to_qubit(aux_ops_not_converted, converter, problem.num_particles) lagrange_op = qubit_op for operatore in options["lagrange"]["operators"]: operator = operatore[0] value = operatore[1] multiplier = operatore[2] lagrange_op = create_lagrange_operator_ps( lagrange_op, aux_ops, multiplier=multiplier, operator=operator, value=value ) old_result = vqe_solver.compute_minimum_eigenvalue(operator=lagrange_op, aux_operators=aux_ops) global PARAMETERS if options["hardware"] is True: for elem in old_result.optimizer_history["params"]: PARAMETERS.append(list(elem)) myLogger.info("OLDRESULT:") myLogger.info(old_result) new_result = problem.interpret(old_result) myLogger.info("Fine solve_lagrangian_vqe") myLogger.info("RESULT") myLogger.info(new_result) if options["hardware"] is True: LAST_OPTIMIZER_OPT = options["optimizer"].setting myLogger.info("OPTIMIZER SETTINGS:") myLogger.info(options["optimizer"].setting) return new_result def solve_aug_lagrangian_vqe(options, lamb): myLogger.info("Inizio solve_aug_lagrangian_vqe") myLogger.info("OPTIONS") myLogger.info(options) converter, vqe_solver, problem, qubit_op = prepare_base_vqe(options) if options["var_form_type"] == "UCCSD": vqe_solver = vqe_solver.get_solver(problem, converter) aux_ops_not_converted = problem.second_q_ops()[1:4] aux_ops = convert_list_op_ferm_to_qubit(aux_ops_not_converted, converter, problem.num_particles) lagrange_op = qubit_op for operatore in options["lagrange"]["operators"]: operator = operatore[0] value = operatore[1] multiplier = operatore[2] lagrange_op = create_lagrange_operator_aug( lagrange_op, aux_ops, multiplier_square=multiplier, multiplier_simple=lamb, operator=operator, value=value ) old_result = vqe_solver.compute_minimum_eigenvalue(operator=lagrange_op, aux_operators=aux_ops) myLogger.info("OLDRESULT:") myLogger.info(old_result) new_result = problem.interpret(old_result) myLogger.info("Fine solve_aug_lagrangian_vqe") myLogger.info("RESULT") myLogger.info(new_result) return new_result def convert_list_op_ferm_to_qubit(old_aux_ops, converter, num_particles): myLogger.info("Inizio convert_list_op_ferm_to_qubit") new_aux_ops = [] for old_aux_op in old_aux_ops: op_new = converter.convert(old_aux_op, num_particles) new_aux_ops.append(op_new) myLogger.info("Fine convert_list_op_ferm_to_qubit") return new_aux_ops def find_best_result(partial_results): penal_min = 100 optimal_par = [] tmp_result = ElectronicStructureResult() tmp_result.nuclear_repulsion_energy = 50 tmp_result.computed_energies = np.array([0]) tmp_result.extracted_transformer_energies = {"dummy": 0} for result, penalty, par in partial_results: myLogger.info("currE: %s", str(tmp_result.total_energies[0])) myLogger.info("GUARDO: %s", str(penalty)) myLogger.info("CONFRONTO: %s", str(penal_min)) if abs(order_of_magnitude(penalty) - order_of_magnitude(penal_min)) == 0: if tmp_result.total_energies[0] > result.total_energies[0]: tmp_result = result penal_min = penalty optimal_par = par elif penalty < penal_min: tmp_result = result penal_min = penalty optimal_par = par myLogger.info("newE: %s", str(tmp_result.total_energies[0])) return tmp_result, optimal_par def calc_penalty(lag_op_list, result, threshold, tmp_mult): penalty = 0 accectable_result = True for operatore in lag_op_list: if operatore[0] == "number": penalty += tmp_mult * ((result.num_particles[0] - operatore[1]) ** 2) myLogger.info("penalty at number: %s", str(penalty)) if abs(result.num_particles[0] - operatore[1]) > threshold: accectable_result = False if operatore[0] == "spin-squared": penalty += tmp_mult * ((result.total_angular_momentum[0] - operatore[1]) ** 2) myLogger.info("penalty at spin2: %s", str(penalty)) if abs(result.total_angular_momentum[0] - operatore[1]) > threshold: accectable_result = False if operatore[0] == "spin-z": penalty += tmp_mult * ((result.magnetization[0] - operatore[1]) ** 2) myLogger.info("penalty at spinz: %s", str(penalty)) if abs(result.magnetization[0] - operatore[1]) > threshold: accectable_result = False return penalty, accectable_result def solve_lag_series_vqe(options): iter_max = options["series"]["itermax"] step = options["series"]["step"] if "init_point" not in options: par = np.random.rand(get_num_par(options["var_form_type"], options["molecule"]["molecule"])) else: par = options["init_point"] mult = 0.01 threshold = 0.6 global PARAMETERS PARAMETERS = [par] partial_results = [] for i in range(iter_max): tmp_mult = mult + step * i lag_op_list = [] for single_op in options["lagrange"]["operators"]: operatore = (single_op[0], single_op[1], float(tmp_mult)) lag_op_list.append(operatore) options["lagrange"]["operators"] = lag_op_list options["init_point"] = par result = solve_lagrangian_vqe(options) if options["hardware"] is not True: par = PARAMETERS[len(PARAMETERS) - 1] penalty, accectable_result = calc_penalty(lag_op_list, result, threshold, tmp_mult) log_str = "Iter " + str(i) log_str += " mult " + str(np.round(tmp_mult, 2)) log_str += "\tE = " + str(np.round(result.total_energies[0], 7)) log_str += "\tP = " + str(penalty) log_str += "\tE-P = " + str(np.round(result.total_energies[0] - penalty, 7)) myLogger.info(log_str) if accectable_result: partial_results.append((result, penalty / tmp_mult, par)) if accectable_result and penalty / tmp_mult < 1e-8 and i > 4: break if not accectable_result and i == iter_max - 1: partial_results.append((result, penalty / tmp_mult, par)) result, optimal_par = find_best_result(partial_results) result = dummy_vqe(options, optimal_par) return result def dummy_vqe(options, optimal_par): myLogger.info("inizio dummy_vqe") options["optimizer"] = COBYLA(maxiter=0) options["init_point"] = optimal_par new_result = solve_hamiltonian_vqe(options) myLogger.info("fine dummy_vqe") return new_result def get_num_par(varform, mol_type): num_pars = 0 if mol_type == "H3+": if varform == "TwoLocal": num_pars = 16 elif varform == "SO(4)": num_pars = 18 elif varform == "UCCSD": num_pars = 16 elif varform == "EfficientSU(2)": num_pars = 8 elif mol_type == "Na-": if varform == "TwoLocal": num_pars = 24 else: raise Exception("varform not yet implemented for this mol") elif "H2O" in mol_type: if varform == "TwoLocal": num_pars = 16 elif varform == "EfficientSU(2)": num_pars = 8 elif varform == "SO(4)": num_pars = 30 elif varform == "UCCSD": num_pars = 24 else: raise Exception("varform not yet implemented for this mol") elif mol_type == "C2H4": if varform == "TwoLocal": num_pars = 8 else: raise Exception("varform not yet implemented for this mol") elif "H2" in mol_type: if varform == "TwoLocal": num_pars = 8 elif varform == "SO(4)": num_pars = 6 elif varform == "UCCSD": num_pars = 8 elif varform == "EfficientSU(2)": num_pars = 4 elif "H4" in mol_type: if varform == "TwoLocal": num_pars = 24 elif varform == "SO(4)": num_pars = 30 elif varform == "UCCSD": num_pars = 24 elif varform == "EfficientSU(2)": num_pars = 48 elif "Li2" in mol_type: if varform == "TwoLocal": num_pars = 72 else: raise Exception("varform not yet implemented for this mol") elif "LiH" == mol_type: if varform == "TwoLocal": num_pars = 16 elif varform == "EfficientSU(2)": num_pars = 8 else: raise Exception("varform not yet implemented for this mol") else: raise Exception("mol_type not totally implemented") return num_pars def solve_lag_aug_series_vqe(options): iter_max = options["series"]["itermax"] if "init_point" not in options: par = np.random.rand(get_num_par(options["var_form_type"], options["molecule"]["molecule"])) else: par = options["init_point"] mult = 0.01 step = options["series"]["step"] lamb = options["series"]["lamb"] global PARAMETERS PARAMETERS = [par] for i in range(iter_max): tmp_mult = mult + step * i lag_op_list = [] for single_op in options["lagrange"]["operators"]: operatore = (single_op[0], single_op[1], float(tmp_mult)) lag_op_list.append(operatore) options["lagrange"]["operators"] = lag_op_list options["init_point"] = par result = solve_aug_lagrangian_vqe(options, lamb) penalty = tmp_mult * ((result.num_particles[0] - operatore[1]) ** 2) penalty -= lamb * (result.num_particles[0] - operatore[1]) log_str = "Iter " + str(i) log_str += " mult " + str(np.round(tmp_mult, 2)) log_str += " lamb " + str(lamb) log_str += "\tE = " + str(np.round(result.total_energies[0], 7)) log_str += "\tE-P = " + str(np.round(result.total_energies[0] - penalty, 7)) myLogger.info(log_str) par = PARAMETERS[len(PARAMETERS) - 1] for operatore in lag_op_list: if operatore[0] == "number": lamb = lamb - tmp_mult * 2 * (result.num_particles[0] - operatore[1]) if operatore[0] == "spin-squared": lamb = lamb - tmp_mult * 2 * (result.total_angular_momentum[0] - operatore[1]) if operatore[0] == "spin-z": lamb = lamb - tmp_mult * 2 * (result.magnetization[0] - operatore[1]) # print(result.total_energies[0] - penalty, " ", penalty) return result def solve_VQE(options): global PARAMETERS PARAMETERS = [] global LAST_OPTIMIZER_OPT LAST_OPTIMIZER_OPT = None if not options["lagrange"]["active"]: vqe_result = solve_hamiltonian_vqe(options) elif not options["lagrange"]["series"]: lag_result = solve_lagrangian_vqe(options) optimal_par = PARAMETERS[len(PARAMETERS) - 1] vqe_result = dummy_vqe(options, optimal_par) else: if options["lagrange"]["augmented"]: vqe_result = solve_lag_aug_series_vqe(options) else: vqe_result = solve_lag_series_vqe(options) return vqe_result, PARAMETERS[len(PARAMETERS) - 1]
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
for i in range(100): # I define my dummy variable and my range that I will iterate over print(i, end=',') # I do my thing which is printing whatever the dummy variable is # the end =',' is added so that the output gets printed more compactly! super optional. i=0 # with while loops we need to give our dummy variable a value since it is not looking for i in something like a range while i<100: # while i is less than 100 we iterate through the loop print(i, end=',') # we do our thing and print our dummy variable i i=i+1 # we add 1 to i each time we loop through, this is ESSENTIAL to while loops, without this i would always # EQUAL 0 and the loop would NEVER end! # create a string to test against another string_1 = "I Love Physics" string_2 = 'i love physics' if string_1 == string_2: print('These strings are the same') # create a string to test against another string_1 = "I Love Physics" string_2 = 'i love physics' if string_1 == string_2: print('These strings are the same') else: print('These strings are NOT the same') # using a for loop for i in range(101): print(i, end=',') if i == 100: print('we counted until 100!') # using a while loop i=0 # starting point for our loop while i <= 100: print(i, end=',') if i == 100: print('we counted until 100!') i+=1
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
just_an_integer = 12 # a plain old number with no fractional parts a_float = 3.1415 # a float is a decimal that has a certain number of digits plain_old_string = 'Hey, I am a string!' # a character or list of characters wrapped in single or double quotes boolean_true = True # True or false, good for ifelse statements and comparative operators boolean_false = False a_list = [ True, 6, 18.99, "potato", False] # a list is a list (duh) of elements that can have lots of different data types # or even a single type or even other lists with their own elemetns!
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
1 + 1 6 - 2 print("Hello World!") my_integer = 8 my_decimal = 3.1415 my_expression = my_integer + my_decimal my_string_1 = "a string" my_string_2 = 'another string' my_list = [ my_integer, my_decimal, my_expression, my_string_1, my_string_2] print(my_integer) print(my_decimal) print(my_expression) print(my_string_1) print(my_string_2) print(my_list) print('my integer: ', my_integer) print('my decimal: ', my_decimal) print('my expression: ', my_expression) print('my first string:', my_string_1) print('my second string: ', my_string_2) print('my list: ', my_list)
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
from qiskit import * # this means that from the qiskit package # import ALL functionality(*) # we also want to see our results in insightful ways through graphs! from qiskit.visualization import * # bloch sphere graphs, bar graphs for measurements # We also need to import the simulators that we will use to make measurements S_simulator=Aer.backends(name='statevector_simulator')[0] # allows you to simulate statevectors M_simulator=Aer.backends(name='qasm_simulator')[0] # allows you to simulate measurements # X gate on |0> # make the circuit with one qubit and one classical bit qc=QuantumCircuit(1,1) # print out initial state to confirm that something happens when we use our gate! initial_state=execute(qc, S_simulator).result().get_statevector() print('Initial state: ', initial_state) # use the x gate on the first qubit qc.x(0) # print out results! state_after_gate= execute(qc, S_simulator).result().get_statevector() print('state after X gate: ', state_after_gate) # X gate on |1> # make the circuit with one qubit and one classical bit qc=QuantumCircuit(1,1) # Initialize circuit to |1> one = [0,1] qc.initialize(one, 0) # print out initial state to confirm that something happens when we use our gate! initial_state=execute(qc, S_simulator).result().get_statevector() print('Initial state: ', initial_state) # use the x gate on the first qubit qc.x(0) # print out results! state_after_gate= execute(qc, S_simulator).result().get_statevector() print('state after X gate: ', state_after_gate) # Y gate on |0> # make the circuit with one qubit and one classical bit qc=QuantumCircuit(1,1) # print out initial state to confirm that something happens when we use our gate! initial_state=execute(qc, S_simulator).result().get_statevector() print('Initial state: ', initial_state) # use the x gate on the first qubit qc.y(0) # print out results! state_after_gate= execute(qc, S_simulator).result().get_statevector() print('state after X gate: ', state_after_gate) # Y gate on |1> # make the circuit with one qubit and one classical bit qc=QuantumCircuit(1,1) # Initialize circuit to |1> one = [0,1] qc.initialize(one, 0) # print out initial state to confirm that something happens when we use our gate! initial_state=execute(qc, S_simulator).result().get_statevector() print('Initial state: ', initial_state) # use the x gate on the first qubit qc.y(0) # print out results! state_after_gate= execute(qc, S_simulator).result().get_statevector() print('state after X gate: ', state_after_gate) # Z gate on |0> # make the circuit with one qubit and one classical bit qc=QuantumCircuit(1,1) # print out initial state to confirm that something happens when we use our gate! initial_state=execute(qc, S_simulator).result().get_statevector() print('Initial state: ', initial_state) # use the x gate on the first qubit qc.z(0) # print out results! state_after_gate= execute(qc, S_simulator).result().get_statevector() print('state after Z gate: ', state_after_gate) # Z gate on |1> # make the circuit with one qubit and one classical bit qc=QuantumCircuit(1,1) # Initialize circuit to |1> one = [0,1] qc.initialize(one, 0) # print out initial state to confirm that something happens when we use our gate! initial_state=execute(qc, S_simulator).result().get_statevector() print('Initial state: ', initial_state) # use the x gate on the first qubit qc.z(0) # print out results! state_after_gate= execute(qc, S_simulator).result().get_statevector() print('state after Z gate: ', state_after_gate)
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
# first lets make a table of the possible inputs and outputs, first we need to install tabulate using # pip the python package installer # make sure it has its own cell pip install tabulate #Here are the possible inputs and corresponding outputs, from tabulate import tabulate print(tabulate([[ '|0>c |0>t', '|0>c |0>t' ], ['|0>c |1>t', '|0>c |1>t'], [ '|1>c |0>t', '|1>c |1>t' ], [ '|1>c |0>t', '|1>c |0>t' ]], headers=['Input', 'Output'])) from qiskit import * # this means that from the qiskit package # import ALL functionality(*) # we also want to see our results in insightful ways through graphs! from qiskit.visualization import * # bloch sphere graphs, bar graphs for measurements # We also need to import the simulators that we will use to make measurements S_simulator=Aer.backends(name='statevector_simulator')[0] # allows you to simulate statevectors M_simulator=Aer.backends(name='qasm_simulator')[0] # allows you to simulate measurements # make a quantum circuit with two qubits and two classical bits qc= QuantumCircuit(2,2) # Initialize first qubit to |1> so that we can see CNOT (cx) do something one = [0,1] qc.initialize(one, 0) # print out initial state to confirm that something happens when we use our gate! initial_state=execute(qc, S_simulator).result().get_statevector() print('Initial state: ', initial_state) # use the Cx gate, first qubit as control and second qubit as target qc.cx(0,1) # print out results! state_after_gate= execute(qc, S_simulator).result().get_statevector() print('state after CX gate: ', state_after_gate) # example of DJ algorithm (CX for balanced) # make circuit dj = QuantumCircuit(2,2) # Initialize second qubit one=[0,1] dj.initialize(one, 1) # we use barries to seperate steps dj.barrier() # Apply H gates dj.h(0) dj.h(1) dj.barrier() # Use cx as Uf dj.cx(0,1) dj.barrier() dj.h(0) dj.barrier() dj.measure(0,0) dj.draw(output='mpl') plot_histogram(execute(dj, M_simulator).result().get_counts()) # example of DJ algorithm (CX for balanced) # make circuit dj = QuantumCircuit(2,2) # Initialize second qubit one=[0,1] dj.initialize(one, 1) # we use barries to seperate steps dj.barrier() # Apply H gates dj.h(0) dj.h(1) dj.barrier() # do nothing for constant function dj.barrier() dj.h(0) dj.barrier() dj.measure(0,0) dj.draw(output='mpl') plot_histogram(execute(dj, M_simulator).result().get_counts())
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
# Do not forget to Import Qiskit from qiskit.visualization import * from qiskit import * S_simulator=Aer.backends(name='statevector_simulator')[0] M_simulator=Aer.backends(name='qasm_simulator')[0] # We will have two top qubits (n=2) and one bottom qubit so our circuit # will have 3 qubits in total. # Initialize *** grover = QuantumCircuit(3,3) # put the last qubit into the |1> state. one=[0,1] grover.initialize(one, 1) #barrier to seperate steps for organization grover.barrier() # Apply H to all the gates *** grover.h(0) grover.h(1) grover.h(2) #barrier to seperate steps for organization grover.barrier() #Black box Oracle *** grover.append(circuit.library.MCXGate(2, ctrl_state='10'), [0,1,2]) grover.barrier() # Phase Shift *** # Apply H to top qubits grover.h(0) grover.h(1) # Apply X to top qubits grover.x(0) grover.x(1) #barrier for organization grover.barrier() # H on second qubit grover.h(1) #barrier for organization grover.barrier() # Cnot on first and second qubits grover.cx(0,1) # barrier for organization grover.barrier() # H on second qubit grover.h(1) #barrier grover.barrier() # X on first and second qubits grover.x(0) grover.x(1) #barrier grover.barrier() # Apply H at the end *** grover.h(0) grover.h(1) grover.h(2) # barrier grover.barrier() # measure all the qubits and put the measurements in their corresponding classical bits grover.measure([0,1,2], [0,1,2]) #draw it out grover.draw(output='mpl')
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
# Fyi in a code cell use a hash symbol or more coloquially known as a # 'hashtag' to make a line comment, comments do not get interpreted # by the editor and are great for leaving notes and things # and mostly are used to express clarity so other programmers like me # and yur classmates can read what you did and why you did it """ You can make block comments that spam multiple lines using triple quotes above and below your block. Please use these, take notes when you copy examples and are writing your own code I will try to do my best to leave these for your guys when I write code """ print('I love Quantum Computing') # when I run this cell it doesnt read the rest, only prints # At the top of every Notebook we use for this course we need to import # all the Qiskit functionality, this is done using Import from qiskit import * # this means that from the qiskit package # import ALL functionality(*) # we also want to see our results in insightful ways through graphs! from qiskit.visualization import * # bloch sphere graphs, bar graphs for measurements # We also need to import the simulators that we will use to make measurements S_simulator=Aer.backends(name='statevector_simulator')[0] # allows you to simulate statevectors M_simulator=Aer.backends(name='qasm_simulator')[0] # allows you to simulate measurements # You should be able to run this import with NO ERRORS, if you do get an # error please contact me so we can trouble shoot this together # In qiskit we can make a quantum circut by using the QuantumCircuit # class, and specifying our number of Quantum bits and Classical bits # example make a Quantum Circuit with 1 qubit and 1 classical bit our_first_quantum_circuit = QuantumCircuit(1,1) # Note that you can call the circuit whatever you want, most of the time # you want to be as specific as possible #NOTE: Unless programmed otherwise ALL qubits start in the |0> state. # qiskit makes it really easy to use gates, we just need to know which # gate and which qubit(s) we want to use it on #use the hadammard gate on the first qubit in our circuit our_first_quantum_circuit.h(0) # Lets explain what we did! # I used the name of my circuit, then a '.' followed by the gate # h for hadammard, and the in paranthesis I will specify the qubit I am # using the gate on, Python counts starting at 0, so the first qubit # will always be coded as the zeroth! # Now we made a circuit, and used a gate, how do we know if it worked? # we Measure it! our_first_quantum_circuit.measure(0,0) # this measures our first qubit # Notice how I have two inputs for measurement, the first input # is the qubit we want to measure and the second is the classical bit # we want to store the measurement in # execute our measurement 1000 times job=execute(our_first_quantum_circuit, M_simulator, shots=1000) #get the results counts=job.result().get_counts() #plot them in a pretty histogram plot_histogram(counts) # we can also measure the statevector using the S_simulator! # lets make a new ciruit and try it out to get the state vector #make a new circuit state_circuit= QuantumCircuit(1,1) state_circuit.h(0) #NOTE: to find out state in a superposition of state we do NOT measure! # execute our measurement of the statevector job=execute(state_circuit, S_simulator) #get the results state_vector=job.result().get_statevector() #plot them in a pretty histogram print('This should be the |+> state: ', state_vector) our_first_quantum_circuit.draw() # the draw method draws your circuit # if you use pip install matplotlib in command line you use # the matplotlib drawer to get really pretty circuits our_first_quantum_circuit.draw(output='mpl')
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
# Do not forget to Import Qiskit from qiskit.visualization import * from qiskit import * S_simulator=Aer.backends(name='statevector_simulator')[0] M_simulator=Aer.backends(name='qasm_simulator')[0] # new import allows us to use CircuitOP() and CircuitStateFn() as well as operators I,X,Y,Z etc. from qiskit.aqua.operators import * from qiskit.quantum_info import random_unitary op=QuantumCircuit(1) # make an operator circuit, and turn it into an operator! DO NOT add a classical bit op.h(0) op =CircuitOp(op) psi = QuantumCircuit(1) # make a wavefunction circuit. psi=CircuitStateFn(psi) # psi is our ket and we can use psi.adjoint() to get its complext conjugate, the bra # so to do an expectation value of <psi| H |psi> we just do psi.adjoint() on H |psi> this can be done in the following way print('expectation value: ', psi.adjoint().compose(op).compose(psi).eval().real) op = (-1.0523732 * I^I) + (0.39793742 * I^Z) + (-0.3979374 * Z^I) \ + (-0.0112801 * Z^Z) + (0.18093119 * X^X) psi = QuantumCircuit(2) psi.x(0) psi.x(1) psi=CircuitStateFn(psi) print('expectation value: ', psi.adjoint().compose(op).compose(psi).eval().real) # Try to follow along a problem from a paper [1] # construct a circuit with 5 parameters. from random import uniform from math import pi thetas = [] n=5 for i in range(n): thetas.append(uniform(0,2*pi)) theta1 = thetas[0] theta2 = thetas[1] theta3 = thetas[2] theta4 = thetas[3] theta5 = thetas[4] print('starting thetas: ', thetas) # these random thetas are the starting values for our rotation operators variational_circuit=QuantumCircuit(5) #rotations that are dependent on theta variational_circuit.rx(theta1, 0) variational_circuit.rx(theta2, 1) variational_circuit.rx(theta3, 2) variational_circuit.rx(theta4, 3) variational_circuit.rx(theta5, 4) variational_circuit.barrier() #entangling block (dont worry too much) variational_circuit.cx(0,1) variational_circuit.barrier() variational_circuit.cx(2,1) variational_circuit.barrier() variational_circuit.cx(3,1) variational_circuit.barrier() variational_circuit.cx(4,3) variational_circuit.barrier() variational_circuit.draw(output='mpl') U = CircuitOp(variational_circuit) Z = QuantumCircuit(5) Z.z(1) Z = CircuitOp(Z) # we can easily find the complex conjugate of the U U_dag = U.adjoint() psi = QuantumCircuit(5) # make a wavefunction circuit. psi=CircuitStateFn(psi) print('expectation value: ', psi.adjoint().compose(U_dag).compose(Z).compose(U).compose(psi).eval().real) def make_variational_circuit(thetas): theta1 = thetas[0] theta2 = thetas[1] theta3 = thetas[2] theta4 = thetas[3] theta5 = thetas[4] variational_circuit=QuantumCircuit(5) #rotations that are dependent on theta variational_circuit.rx(theta1, 0) variational_circuit.rx(theta2, 1) variational_circuit.rx(theta3, 2) variational_circuit.rx(theta4, 3) variational_circuit.rx(theta5, 4) variational_circuit.barrier() #entangling block (dont worry too much) variational_circuit.cx(0,1) variational_circuit.barrier() variational_circuit.cx(2,1) variational_circuit.barrier() variational_circuit.cx(3,1) variational_circuit.barrier() variational_circuit.cx(4,3) variational_circuit.barrier() return variational_circuit def get_U_and_U_dag(variational_circuit): U = CircuitOp(variational_circuit) U_dag = U.adjoint() return U, U_dag # We can hardcode Z in here but thats not great convention # this is strictly for example and not practical def expectation_value(U, U_dag): psi = QuantumCircuit(5) # make a wavefunction circuit. psi=CircuitStateFn(psi) Z = QuantumCircuit(5) Z.z(1) Z = CircuitOp(Z) return psi.adjoint().compose(U_dag.compose(Z.compose(U))).compose(psi).eval().real # to shift our thetas it can be done a number of ways thetas_plus = [] thetas_minus = [] for i in range(len(thetas)): thetas_plus.append(thetas[i]+(0.5*pi)) thetas_minus.append(thetas[i]-(0.5*pi)) # our first gradient can be calculated now def get_eval(thetas): variational_circuit = make_variational_circuit(thetas) U, U_dag = get_U_and_U_dag(variational_circuit) return expectation_value(U,U_dag) def get_gradient(thetas): thetas_plus = [] thetas_minus = [] for i in range(len(thetas)): thetas_plus.append(thetas[i]+(0.5*pi)) thetas_minus.append(thetas[i]-(0.5*pi)) f_plus = get_eval(thetas_plus) f_minus = get_eval(thetas_minus) return 0.5*(f_plus - f_minus) get_gradient(thetas) def update_thetas(thetas): learning_rate=0.2 gradient = get_gradient(thetas) updated_thetas=[] for i in range(len(thetas)): updated_thetas.append(thetas[i] - (learning_rate*gradient)) return updated_thetas print('thetas before update: ', thetas) thetas = update_thetas(thetas) print('thetas after update: ', thetas) from random import uniform from math import pi thetas = [] n=5 for i in range(n): thetas.append(uniform(2*pi,2*pi)) print('thetas before update: ', thetas) print('gradient: ', get_gradient(thetas)) thetas = update_thetas(thetas) print('thetas after update: ', thetas) thetas_plus = [] thetas_minus = [] for i in range(len(thetas)): thetas_plus.append(thetas[i]+(0.5*pi)) thetas_minus.append(thetas[i]-(0.5*pi)) f_plus = get_eval(thetas_plus) f_minus = get_eval(thetas_minus) print(f_plus, f_minus) var = QuantumCircuit()
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector ### Creating 3 qubit and 2 classical bits in each separate register qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) ### A third party eve helps to create an entangled state def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a, b) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, a, b): qc.cx(a, b) qc.h(a) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): qc.barrier() qc.measure(a,0) qc.measure(b,1) teleportation_circuit.barrier() measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() from qiskit.extensions import Initialize import math qc = QuantumCircuit(1) initial_state = [0,1] init_gate = Initialize(initial_state) # qc.append(initialize_qubit, [0]) qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical registers crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) # Bob decodes qubits bob_gates(qc, 2, crz, crx) qc.draw() backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) qc.draw() cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts) def bob_gates(qc, a, b, c): qc.cz(a, c) qc.cx(b, c) qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob bob_gates(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() from qiskit import IBMQ IBMQ.save_account('### IMB TOKEN ') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_result) plot_histogram(exp_measurement_result) error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \ * 100./ sum(list(exp_measurement_result.values())) print("The experimental error rate : ", error_rate_percent, "%")