def mitigated_results(circuit, backend, results): # Import the required methods from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter) # Get noise model for backend noise_model = NoiseModel.from_backend(backend) # Create the measurement fitter qr = QuantumRegister(circuit.num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') job = execute(meas_calibs, backend=Aer.get_backend('qasm_simulator'), shots=8192, noise_model=noise_model) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') #print(meas_fitter.cal_matrix) # Plot the calibration matrix print("Calibration matrix") meas_fitter.plot_calibration() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts(0) print("Mitigated", backend, "results:\n", mitigated_counts) return (mitigated_counts)
def test_meas_cal_on_circuit(self): """Test an execution on a circuit.""" print("Testing measurement calibration on a circuit") # Generate the calibration circuits meas_calibs, state_labels, ghz = meas_calib_circ_creation() # Run the calibration circuits backend = Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots, seed_simulator=SEED, seed_transpiler=SEED) cal_results = job.result() # Make a calibration matrix meas_cal = CompleteMeasFitter(cal_results, state_labels) # Calculate the fidelity fidelity = meas_cal.readout_fidelity() job = qiskit.execute([ghz], backend=backend, shots=self.shots, seed_simulator=SEED, seed_transpiler=SEED) results = job.result() # Predicted equally distributed results predicted_results = {'000': 0.5, '111': 0.5} meas_filter = meas_cal.filter # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( results, method='pseudo_inverse').get_counts(0) output_results_least_square = meas_filter.apply( results, method='least_squares').get_counts(0) # Compare with expected fidelity and expected results self.assertAlmostEqual(fidelity, 1.0) self.assertAlmostEqual(output_results_pseudo_inverse['000'] / self.shots, predicted_results['000'], places=1) self.assertAlmostEqual(output_results_least_square['000'] / self.shots, predicted_results['000'], places=1) self.assertAlmostEqual(output_results_pseudo_inverse['111'] / self.shots, predicted_results['111'], places=1) self.assertAlmostEqual(output_results_least_square['111'] / self.shots, predicted_results['111'], places=1)
def test_meas_fitter_with_noise(self): """ Test the MeasurementFitter with noise """ print("Testing MeasurementFitter with noise") # pre-generated results with noise # load from pickled file fo = open( os.path.join(os.path.dirname(__file__), 'test_meas_results.pkl'), 'rb') tests = pickle.load(fo) fo.close() # Set the state labels state_labels = ['000', '001', '010', '011', '100', '101', '110', '111'] meas_cal = CompleteMeasFitter(None, state_labels, circlabel='test') for tst_index, _ in enumerate(tests): # Set the calibration matrix meas_cal.cal_matrix = tests[tst_index]['cal_matrix'] # Calculate the fidelity fidelity = meas_cal.readout_fidelity() meas_filter = MeasurementFilter(tests[tst_index]['cal_matrix'], state_labels) # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( tests[tst_index]['results'], method='pseudo_inverse') output_results_least_square = meas_filter.apply( tests[tst_index]['results'], method='least_squares') # Compare with expected fidelity and expected results self.assertAlmostEqual(fidelity, tests[tst_index]['fidelity'], places=0) self.assertAlmostEqual( output_results_pseudo_inverse['000'], tests[tst_index]['results_pseudo_inverse']['000'], places=0) self.assertAlmostEqual( output_results_least_square['000'], tests[tst_index]['results_least_square']['000'], places=0) self.assertAlmostEqual( output_results_pseudo_inverse['111'], tests[tst_index]['results_pseudo_inverse']['111'], places=0) self.assertAlmostEqual( output_results_least_square['111'], tests[tst_index]['results_least_square']['111'], places=0)
def mitigated_results(backend,circuit,results,results_sim): from qiskit import Aer, execute from qiskit import QuantumRegister # Import the required methods from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter) from qiskit.tools.visualization import plot_histogram import numpy numpy.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)}) # Get noise model for backend noise_model = NoiseModel.from_backend(backend) # Create the measurement fitter qr = QuantumRegister(circuit.num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') job = execute(meas_calibs, backend=Aer.get_backend('qasm_simulator'), shots=8192, noise_model=noise_model) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts(0) title = "Mitigated Grover on "+str(ibmqbackend.name()) display(plot_histogram([results_sim.get_counts(),results.get_counts(), mitigated_counts], title=title, legend=['sim','noisy', 'mitigated'])) return(mitigated_counts)
def generate_mitigator(num_qubits, noisy, shots=1024): meas_calibs, state_labels = complete_meas_cal(range(num_qubits)) experiments = transpile(meas_calibs, backend=noisy, optimization_level=3) job = noisy.run(assemble(experiments, shots=shots)) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) return job, meas_fitter.filter
def _qiskit_generate_samples_MEM(self: QiskitDevice) -> np.array: """ This function is used to overrite the default QiskitDevice.generate_samples method. It adds a simple mechanism to perform measurement error mitigation on the results of the computation. """ # branch out depending on the type of backend if self.backend_name in self._state_backends: # software simulator: need to sample from probabilities return super().generate_samples() # hardware or hardware simulator # ***here we actully perform the measurement error mitigation*** meas_calibs, state_labels = complete_meas_cal(qr=self._reg, circlabel="mcal") mitigation_run_args = self.run_args.copy() mitigation_run_args["shots"] = NUMBER_OF_SHOTS_FOR_QISKIT_ERROR_MITIGATION meas_job = qiskit.execute(meas_calibs, backend=self.backend, **mitigation_run_args) # TODO: Adding a cache here is a free performance boost meas_fitter = CompleteMeasFitter(meas_job.result(), state_labels, circlabel="mcal") mitigated_results = meas_fitter.filter.apply(self._current_job.result()) current_job_shots = sum(self._current_job.result().get_counts().values()) summed_counts = sum(mitigated_results.get_counts().values()) probs = [value / summed_counts for value in mitigated_results.get_counts().values()] samples = np.random.choice( np.array(list(mitigated_results.get_counts().keys())), current_job_shots, p=probs, replace=True, ) # reverse qubit order to match PennyLane convention return np.vstack([np.array([int(i) for i in s[::-1]]) for s in samples])
def matricaZaGreske(brojQubita, noise_model): qr = QuantumRegister(brojQubita) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') backend = Aer.get_backend('qasm_simulator') job = execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') return(meas_fitter.cal_matrix)
def generate_meas_calibration(results_file_path: str, runs: int): """ run the measurement calibration circuits, calculates the fitter matrix in few methods and saves the results The simulation results files will contain a list of dictionaries with the keys: cal_matrix - the matrix used to calculate the ideal measurement fidelity - the calculated fidelity of using this matrix results - results of a bell state circuit with noise results_pseudo_inverse - the result of using the psedo-inverse method on the bell state results_least_square - the result of using the least-squares method on the bell state Args: results_file_path: path of the json file of the results file runs: the number of different runs to save """ results = [] for run in range(runs): cal_results, state_labels, circuit_results = \ meas_calibration_circ_execution(3, 1000, SEED + run) meas_cal = CompleteMeasFitter(cal_results, state_labels, circlabel='test') meas_filter = MeasurementFilter(meas_cal.cal_matrix, state_labels) # Calculate the results after mitigation results_pseudo_inverse = meas_filter.apply(circuit_results, method='pseudo_inverse') results_least_square = meas_filter.apply(circuit_results, method='least_squares') results.append({ "cal_matrix": convert_ndarray_to_list_in_data(meas_cal.cal_matrix), "fidelity": meas_cal.readout_fidelity(), "results": circuit_results, "results_pseudo_inverse": results_pseudo_inverse, "results_least_square": results_least_square }) with open(results_file_path, "w") as results_file: json.dump(results, results_file)
def generate_error_mitigation_filter(q_list, noise_model): backend = get_sim_backend_from_name("qasm_simulator") qr = QuantumRegister(5) meas_cals, state_labels = complete_meas_cal(qubit_list=q_list, qr=qr) calibration_job = execute(meas_cals, backend=backend, shots=8192, noise_model=noise_model) cal_results = calibration_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) em_filter = meas_fitter.filter return em_filter
def measurement_error_mitigator(systemsize, sim, quantum_com_choice_results, shots=8192): if sim == "noisy_qasm": backend, coupling_map, noise_model = quantum_com_choice_results[sim] qr = QuantumRegister(systemsize) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') print('Calibrating POVM Matrix') job = execute(meas_calibs, backend=backend, shots=shots, noise_model=noise_model, coupling_map=coupling_map) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter print("Provider backend: ", backend) return meas_filter elif sim == "real": backend = quantum_com_choice_results[sim] qr = QuantumRegister(systemsize) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') print('Calibrating POVM Matrix') job = execute(meas_calibs, backend=backend, shots=shots) job_monitor(job, interval=2) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter print("Provider backend: ", backend) return meas_filter
def apply(self, qc_list, info_list, shots): meas_calibs, state_labels, measure_list = info_list[0], info_list[ 1], info_list[2] managed_results = IBMQ.qc_experiment(qc_list + meas_calibs, self.backend, shots).run() results = managed_results.combine_results() meas_fitter = CompleteMeasFitter(results, state_labels, qubit_list=measure_list) meas_filter = meas_fitter.filter measurement_error_mitigated_results = meas_filter.apply(results) return [results, measurement_error_mitigated_results]
def get_correction_matrix(qpu, max_age, access_token, used_qubits): """Return a correction matrix for the given QPU whit the maximum age in minutes""" app.logger.info('Getting calibration matrix for QPU ' + qpu + ' with max age of ' + str(max_age) + ' minutes') # Check for existing calibration matrix existing_matrix = calibration_matrixes.get(qpu) if existing_matrix is not None: age = datetime.now() - existing_matrix['Date'] app.logger.info('Calibration matrix for this QPU exists with age ' + str(age)) if age.total_seconds() < max_age * 60: app.logger.info('Returning existing calibration matrix!') return existing_matrix['Calibration_Matrix'] if access_token is None: app.logger.error('Unable to create new correction matrix without access key...') return None # Load account to enable execution of calibration circuits IBMQ.save_account(access_token, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = provider.get_backend(qpu) # Generate a calibration circuit for each state qr = qiskit.QuantumRegister(used_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # Execute each calibration circuit and store results app.logger.info('Executing ' + str(len(meas_calibs)) + ' circuits to create calibration matrix...') cal_results = [] for circuit in meas_calibs: app.logger.info('Executing circuit ' + circuit.name) cal_results.append(execute_job(circuit, backend)) # Generate calibration matrix out of measurement results meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') app.logger.info('Calibration matrix:') app.logger.info(meas_fitter.cal_matrix) # Store calibration matrix for later reuse calibration_matrixes[qpu] = {"Date": datetime.now(), "Calibration_Matrix": meas_fitter.filter} return meas_fitter.filter
def initialize_meas_calibration(self, N_qubits, layout): """ Set up the confusion matrix needed for measurement error mitigation. This is basically just boilerplate code from the Ignis Github https://github.com/Qiskit/qiskit-ignis """ if layout is None: cal_q = QuantumRegister(N_qubits) meas_cals, state_labels = complete_meas_cal(qr=cal_q) else: meas_cals, state_labels = complete_meas_cal(qubit_list=layout) # Run the calibration circuits with the device noise model backend = Aer.get_backend('qasm_simulator') job = execute(meas_cals, backend=backend, shots=10000, noise_model=self.noise_model) cal_results = job.result() return CompleteMeasFitter(cal_results, state_labels).filter
def _run_analysis(self, experiment_data, parameter_guess=None, plot=True, ax=None): state_labels = [] for datum in experiment_data.data(): state_label = datum['metadata']['state_label'] if state_label in state_labels: break state_labels.append(state_label) meas_fitter = CompleteMeasFitter(None, state_labels, circlabel='mcal') nstates = len(state_labels) for job_id in experiment_data.job_ids: full_result = experiment_data.backend.retrieve_job(job_id).result() # full_result might contain repeated experiments for iset in range(len(full_result.results) // nstates): try: date = full_result.date except: date = None try: status = full_result.status except: status = None try: header = full_result.header except: header = None result = Result(full_result.backend_name, full_result.backend_version, \ full_result.qobj_id, full_result.job_id, \ full_result.success, full_result.results[iset * nstates:(iset + 1) * nstates], \ date=date, status=status, header=header, **full_result._metadata) meas_fitter.add_data(result) results = [ AnalysisResultData('error_matrix', meas_fitter.cal_matrix, extra=state_labels) ] plots = [] if plot: figure, ax = plt.subplots(1, 1) meas_fitter.plot_calibration(ax=ax) plots.append(figure) return results, plots
def get_measurement_fitter(l, backend, device, shots): qb = QuantumRegister(l) qubit_list = list(range(l)) meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qb, circlabel='mcal') # Execute calibration circuits job = execute(meas_calibs, backend=backend, shots=shots, noise_model=device.noise_model, coupling_map=device.coupling_map, basis_gates=device.basis_gates) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') #meas_filter = meas_fitter.filter #mitigated_results = meas_filter.apply(results) #mitigated_counts = mitigated_results.get_counts(0) return meas_fitter
def apply_readout_correction(self, counts, qubit_list=None, **kwargs): if self.readout_correction_filter is None: for key in counts.keys(): num_qubits = len(key) break if qubit_list is None or qubit_list == {}: qubit_list = [i for i in range(num_qubits)] qr = QuantumRegister(num_qubits) meas_cals, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr) # Execute the calibration circuits job = self.execute_with_retries(meas_cals, self.n_samples) cal_results = job.result() # Make a calibration matrix meas_fitter = CompleteMeasFitter(cal_results, state_labels) # Create a measurement filter from the calibration matrix self.readout_correction_filter = meas_fitter.filter mitigated_counts = self.readout_correction_filter.apply(counts) return mitigated_counts
def test_meas_cal_on_circuit(self): """Test an execution on a circuit.""" print("Testing measurement calibration on a circuit") # Choose 3 qubits q1 = 1 q2 = 2 q3 = 3 # Generate the quantum register according to the pattern qr = qiskit.QuantumRegister(5) # Generate the calibration circuits meas_calibs, state_labels = \ complete_meas_cal(qubit_list=[1, 2, 3], qr=qr) # Run the calibration circuits backend = Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots) cal_results = job.result() # Make a calibration matrix meas_cal = CompleteMeasFitter(cal_results, state_labels) # Calculate the fidelity fidelity = meas_cal.readout_fidelity() # Make a 3Q GHZ state cr = ClassicalRegister(3) ghz = QuantumCircuit(qr, cr) ghz.h(qr[q1]) ghz.cx(qr[q1], qr[q2]) ghz.cx(qr[q2], qr[q3]) ghz.measure(qr[q1], cr[0]) ghz.measure(qr[q2], cr[1]) ghz.measure(qr[q3], cr[2]) job = qiskit.execute([ghz], backend=backend, shots=self.shots) results = job.result() # Predicted equally distributed results predicted_results = {'000': 0.5, '111': 0.5} meas_filter = meas_cal.filter # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( results, method='pseudo_inverse').get_counts(0) output_results_least_square = meas_filter.apply( results, method='least_squares').get_counts(0) # Compare with expected fidelity and expected results self.assertAlmostEqual(fidelity, 1.0) self.assertAlmostEqual(output_results_pseudo_inverse['000'] / self.shots, predicted_results['000'], places=1) self.assertAlmostEqual(output_results_least_square['000'] / self.shots, predicted_results['000'], places=1) self.assertAlmostEqual(output_results_pseudo_inverse['111'] / self.shots, predicted_results['111'], places=1) self.assertAlmostEqual(output_results_least_square['111'] / self.shots, predicted_results['111'], places=1)
# If no mitigation is applied, add ', memory=True', and .get_memory() to job.result() job = execute(qc, backend, shots=4096, optimization_level=0) results = job.result() # Mitigation Measurement, will run twice cal_circuits, state_labels = complete_meas_cal( qr=qc.qregs[0], circlabel='measurement_calibration') calculatedJob = execute(cal_circuits, backend, shots=4096, optimization_level=0) calculatedResults = calculatedJob.result() meas_fitter = CompleteMeasFitter(calculatedResults, state_labels) meas_filter = meas_fitter.filter mitigated_result = meas_filter.apply(results) device_counts = results.get_counts(qc) mitigated_counts = mitigated_result.get_counts(qc) output = [] # Reminder, if mitigated results are disabled, add ".get_memory()" to job.result(), and uncomment: # for x in range(0, 4096): # convert = int(mitigated_counts_2[x], 2) # output.append(convert) # And comment out:
## main part! from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter) cal_circuits, state_labels = complete_meas_cal( qr=circuit.qregs[0], circlabel="measerrormitigationcal" ) #circuit.qregs[0] is the quantum register to show all qubits we have #cal_circuits is the calibrated circuit of all qubits possible outcomes, state labels are 000 - 111 cal_job = execute(cal_circuits, qcom, shots=1024, optimization_level=0) print(cal_job.job_id()) job_monitor(cal_job) result_cal = cal_job.result() plot_histogram(result_cal.get_counts()) #Build the measurement fitter which extracts the parameters from calibration results meas_fitter = CompleteMeasFitter( result_cal, state_labels) #fit the calibrated results with actucal labels meas_fitter.plot_calibration() #Make the calibration filter to mitigate the results #This filter can be used for other 3 qubuits circuit meas_filter = meas_fitter.filter result_mitigated = meas_filter.apply( result_q ) #Generate mitigated result by applying filter to the quantum computer result #get result counts_q = result_q.get_counts() counts_mitigated = result_mitigated.get_counts() plot_histogram([counts_q, counts_mitigated], legend=["noisy result", 'mitigated result'])
def twospin_df(J, Bx, dB, Bz_max, dt_steps, dt_steps_bool, gamma, skip, provider, backend, pq1, pq2): count_list = [] calibrated_count_list = [] tarray, Bzarray, dt_or_steps, _ = adiabaticramp(J, Bx, dB, Bz_max, dt_steps, dt_steps_bool, gamma) if dt_steps_bool == 'dt': dt = dt_steps else: dt = dt_or_steps thetaarray, _ = theta(Bzarray, dt) # Calibration Matrix meas_calibs, state_labels = complete_meas_cal(qubit_list=[0, 1, 2, 3], qr=QuantumRegister(4), circlabel='4spin') cal_results = execute(meas_calibs, backend=Aer.get_backend('qasm_simulator'), shots=1000).result() meas_calibs, state_labels = complete_meas_cal(qubit_list=[0, 1, 2, 3], qr=QuantumRegister(4), circlabel='4spin') meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='4spin') #meas_fitter.plot_calibration() qmap = Layout() i = 0 while (i < len(thetaarray)): print('Bz = %f' % (Bzarray[i])) qr = QuantumRegister(4, 'qr') cr = ClassicalRegister(4, 'cr') circ = QuantumCircuit(qr, cr) #qmap.from_dict(input_dict={qr[0]: pq1, qr[1]: pq2}) circ.initialize([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 2, 3]) fourspin_instruction(circ, J, Bx, thetaarray[:i + 1], dt) circ.measure([0, 1, 2, 3], [0, 1, 2, 3]) result = execute(circ, Aer.get_backend('qasm_simulator'), shots=5000).result() counts = result.get_counts() counts['Time'] = tarray[i] counts['Bz'] = Bzarray[i] count_list.append(counts) with open("count_list.txt", "w") as output: output.write(str(count_list)) mitigated_counts = meas_fitter.filter.apply(result).get_counts() mitigated_counts['Time'] = tarray[i] mitigated_counts['Bz'] = Bzarray[i] calibrated_count_list.append(mitigated_counts) with open("calibrated_count_list.txt", "w") as output: output.write(str(calibrated_count_list)) i = i + 1 + skip # Creating dataframe df = pd.DataFrame(count_list) time_col = df.pop('Time') df.insert(0, 'Time', time_col) df['Exact'] = exactm(J, Bx, Bzarray, dt) df['Interaction'] = interactionm(J, Bx, thetaarray, dt) calibrated_df = pd.DataFrame(calibrated_count_list) time_col = df.pop('Time') df.insert(0, 'Time', time_col) if '0000' not in df: df['0000'] = 0 if '0001' not in df: df['0001'] = 0 if '0010' not in df: df['0010'] = 0 if '0011' not in df: df['0011'] = 0 if '0100' not in df: df['0000'] = 0 if '0101' not in df: df['0001'] = 0 if '0110' not in df: df['0010'] = 0 if '0111' not in df: df['0011'] = 0 if '1000' not in df: df['0000'] = 0 if '1001' not in df: df['0001'] = 0 if '1010' not in df: df['0010'] = 0 if '1011' not in df: df['0011'] = 0 if '1100' not in df: df['0000'] = 0 if '1101' not in df: df['0001'] = 0 if '1110' not in df: df['0010'] = 0 if '1111' not in df: df['0011'] = 0 df = df.fillna(0) if '0000' not in calibrated_df: calibrated_df['00'] = 0 if '0001' not in calibrated_df: calibrated_df['01'] = 0 if '0010' not in calibrated_df: calibrated_df['10'] = 0 if '0011' not in calibrated_df: calibrated_df['11'] = 0 if '0100' not in calibrated_df: calibrated_df['00'] = 0 if '0101' not in calibrated_df: calibrated_df['01'] = 0 if '0110' not in calibrated_df: calibrated_df['10'] = 0 if '0111' not in calibrated_df: calibrated_df['11'] = 0 if '1000' not in calibrated_df: calibrated_df['00'] = 0 if '1001' not in calibrated_df: calibrated_df['01'] = 0 if '1010' not in calibrated_df: calibrated_df['10'] = 0 if '1011' not in calibrated_df: calibrated_df['11'] = 0 if '1100' not in calibrated_df: calibrated_df['00'] = 0 if '1101' not in calibrated_df: calibrated_df['01'] = 0 if '1110' not in calibrated_df: calibrated_df['10'] = 0 if '1111' not in calibrated_df: calibrated_df['11'] = 0 calibrated_df = calibrated_df.fillna(0) # Calculating mz total = df['0000'] + df['0001'] + df['0010'] + df['0011'] + df[ '0100'] + df['0101'] + df['0110'] + df['0111'] + df['1000'] + df[ '1001'] + df['1010'] + df['1011'] + df['1100'] + df['1101'] + df[ '1110'] + df['1111'] df['mz'] = -(2 * df['0000'] + df['0001'] + df['0010'] + df['0100'] + df['1000'] - df['0111'] - df['1011'] - df['1101'] - df['1110'] - 2 * df['1111']) / total calibrated_df['mz'] = -(2 * df['0000'] + df['0001'] + df['0010'] + df['0100'] + df['1000'] - df['0111'] - df['1011'] - df['1101'] - df['1110'] - 2 * df['1111']) / total # Creating Files if dt_steps_bool == 'dt': df.to_csv( '4spin J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} dt={:.3f} gamma={:.3f}.csv' .format(J, Bx, dB, Bz_max, dt_steps, gamma)) calibrated_df.to_csv( 'Calibrated 4spin J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} dt={:.3f} gamma={:.3f}.csv' .format(J, Bx, dB, Bz_max, dt_steps, gamma)) else: df.to_csv( '4spin J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} BzSteps={:.3f} gamma={:.3f}.csv' .format(J, Bx, dB, Bz_max, dt_steps, gamma)) calibrated_df.to_csv( 'Calibrated 4spin J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} BzSteps={:.3f} gamma={:.3f}.csv' .format(J, Bx, dB, Bz_max, dt_steps, gamma)) return df, calibrated_df, dt_or_steps, thetaarray
def all_methods_data(interested_qubits, backend, itr, QDT_correlated, shots_per_point=1024, file_address=''): """Collect data for our method, Qiskit method, QDT, and standard Bayesian. Args: interested_qubits: an array of ints. REMEBER TO FOLLOW THE ORDER [LAST QUBIT, ..., FIRST QUBIT] backend: backend from provider.get_backend(). itr: number of iterations of job submission in our method only. QDT_correlated: True if want qubits corrlected in QDT method. file_address: file address, string ends with '/' if not empty Returns: None """ with open(file_address + 'interested_qubits.csv', mode='w', newline='') as sgm: param_writer = csv.writer(sgm, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) param_writer.writerow(interested_qubits) # Record data for filters (ourmethod) print('Our method') collect_filter_data(backend, itr=itr, shots=8192, if_monitor_job=True, if_write=True, file_address=file_address) # Qiskit Method print('Qiskit Method') qr = QuantumRegister(len(interested_qubits)) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') for i in range(len(meas_calibs)): meas_calibs[i] = transpile(meas_calibs[i], backend, initial_layout=interested_qubits[::-1]) job = execute(meas_calibs, backend=backend, shots=8192, optimization_level=0) job_monitor(job) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter cal_matrix = meas_fitter.cal_matrix with open(file_address + 'cal_matrix.csv', mode='w', newline='') as sgm: param_writer = csv.writer(sgm, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in cal_matrix: param_writer.writerow(row) with open(file_address + 'state_labels.csv', mode='w', newline='') as sgm: param_writer = csv.writer(sgm, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) param_writer.writerow(state_labels) # QDT print('QDT, correlation = ', QDT_correlated) if QDT_correlated: qdt_qubit_indices = interested_qubits qdt_probe_kets = povmtools.pauli_probe_eigenkets qdt_calibration_circuits = detector_tomography_circuits( qdt_qubit_indices, qdt_probe_kets) print('Number of Circuits needed is ', len(qdt_calibration_circuits)) # We then execute them on backend prepared earlier. shots_number = 8192 # Perform a noisy simulation job = execute(qdt_calibration_circuits, backend=backend, shots=shots_number, optimization_level=0) job_monitor(job) result = job.result() dtf = DetectorTomographyFitter() calibration_setup = QDTCalibrationSetup.from_qiskit_results( [result], qdt_probe_kets) ml_povm_estimator = dtf.get_maximum_likelihood_povm_estimator( calibration_setup) mitigator = QDTErrorMitigator() mitigator.prepare_mitigator(ml_povm_estimator) trans_mat = mitigator.transition_matrix with open(file_address + 'trans_matrix.csv', mode='w', newline='') as sgm: param_writer = csv.writer(sgm, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in trans_mat: param_writer.writerow(row) else: for q in interested_qubits: qdt_qubit_indices = [q] qdt_probe_kets = povmtools.pauli_probe_eigenkets qdt_calibration_circuits = detector_tomography_circuits( qdt_qubit_indices, qdt_probe_kets) print('Number of Circuits needed is ', len(qdt_calibration_circuits)) # We then execute them on backend prepared earlier. shots_number = 8192 # Perform a noisy simulation job = execute(qdt_calibration_circuits, backend=backend, shots=shots_number, optimization_level=0) job_monitor(job) result = job.result() # Create Mitigator dtf = DetectorTomographyFitter() calibration_setup = QDTCalibrationSetup.from_qiskit_results( [result], qdt_probe_kets) ml_povm_estimator = dtf.get_maximum_likelihood_povm_estimator( calibration_setup) mitigator = QDTErrorMitigator() mitigator.prepare_mitigator(ml_povm_estimator) trans_mat = mitigator.transition_matrix with open(file_address + 'trans_matrix' + str(q) + '.csv', mode='w', newline='') as sgm: param_writer = csv.writer(sgm, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in trans_mat: param_writer.writerow(row) # Data for Standard Bayesian # Read data to for measurement error while input is |0> print('Write data for standard Bayesian') prop_dict = backend.properties().to_dict() with open(file_address + 'given_params.csv', mode='w', newline='') as sgm: param_writer = csv.writer(sgm, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for q in interested_qubits: p0m0 = 1 - prop_dict['qubits'][q][5]['value'] if p0m0 == 1 or p0m0 < 0.7: p0m0 = 0.9 p1m1 = 1 - prop_dict['qubits'][q][4]['value'] if p1m1 == 1 or p1m1 < 0.7: p1m1 = 0.9 param_writer.writerow([p0m0, p1m1]) with open(file_address + 'Filter_data.csv', mode='r') as measfile: reader = csv.reader(measfile) cali01 = np.asarray([row for row in reader][0]) Data = cali01 for q in interested_qubits: y = getData0(Data, itr * int(8192 / shots_per_point), q) with open(file_address + 'Qubit{}.csv'.format(q), mode='w', newline='') as sgr: read_writer = csv.writer(sgr, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) read_writer.writerow(['x', 'y']) for i in range(len(y)): read_writer.writerow([0.5, y[i]])
print('\nOptimization level must be an integer between 0 and 3, inclusive. Higher levels generate more optimized circuits, at the expense of longer transpilation time.\n') exit(1) else: opt_level = 1 U_f = get_U_f(func_in, n) list_y = [] circuit = simon_program(U_f, n) circuit.measure(range(n), range(n)) # Calibration Matrix meas_calibs, state_labels = complete_meas_cal(qubit_list=range(n), circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=8192) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') start = time.time() circuit = transpile(circuit, backend, optimization_level=opt_level) transpiletime = time.time() - start if trials*n > 2048: trial_list = [8192]*((trials*n)//2048) + [(4*trials*n)%8192] else: trial_list = [4*trials*n] job = [] for t in trial_list: job.append(execute(circuit, backend, optimization_level=0, shots=t)) result = []
def test_ideal_meas_cal(self): """Test ideal execution, without noise.""" for nq in self.nq_list: print("Testing %d qubit measurement calibration" % nq) for pattern_type in range(1, 2**nq): # Generate the quantum register according to the pattern qubits, weight = self.choose_calibration(nq, pattern_type) # Generate the calibration circuits meas_calibs, state_labels = \ complete_meas_cal(qubit_list=qubits, circlabel='test') # Perform an ideal execution on the generated circuits backend = Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots) cal_results = job.result() # Make a calibration matrix meas_cal = CompleteMeasFitter(cal_results, state_labels, circlabel='test') # Assert that the calibration matrix is equal to identity IdentityMatrix = np.identity(2**weight) self.assertListEqual( meas_cal.cal_matrix.tolist(), IdentityMatrix.tolist(), 'Error: the calibration matrix is \ not equal to identity') # Assert that the readout fidelity is equal to 1 self.assertEqual( meas_cal.readout_fidelity(), 1.0, 'Error: the average fidelity \ is not equal to 1') # Generate ideal (equally distributed) results results_dict, results_list = \ self.generate_ideal_results(state_labels, weight) # Output the filter meas_filter = meas_cal.filter # Apply the calibration matrix to results # in list and dict forms using different methods results_dict_1 = meas_filter.apply(results_dict, method='least_squares') results_dict_0 = meas_filter.apply(results_dict, method='pseudo_inverse') results_list_1 = meas_filter.apply(results_list, method='least_squares') results_list_0 = meas_filter.apply(results_list, method='pseudo_inverse') # Assert that the results are equally distributed self.assertListEqual(results_list, results_list_0.tolist()) self.assertListEqual(results_list, np.round(results_list_1).tolist()) self.assertDictEqual(results_dict, results_dict_0) round_results = {} for key, val in results_dict_1.items(): round_results[key] = np.round(val) self.assertDictEqual(results_dict, round_results)
# Generates measurement calibration circuits for running measurement error # mitigation. q_register = QuantumRegister(5) calibration_circuits, state_labels = complete_meas_cal(qubit_list=[2, 3, 4], qr=q_register) # Executes calibration circuits. qasm_backend = Aer.get_backend("qasm_simulator") # simulates circuit job = qiskit.execute(calibration_circuits, backend=qasm_backend, shots=1000, noise_model=aer_noise_model) calibration_results = job.result() # Makes calibration matrix. measure_fitter = CompleteMeasFitter(calibration_results, state_labels) # Makes a 3-qubit GHZ state (a particular entangled state, at least 3 qubits). # 1. applies Hadamard, putting qubit into superposition # 2. applies CX (CNOT), putting qubits into Bell state # 3. applies CX (CNOT), putting qubits into GHZ state c_register = ClassicalRegister(3) ghz = QuantumCircuit(q_register, c_register) ghz.h(q_register[2]) # ghz.h(qubit); Hadamard gate ghz.cx(q_register[2], q_register[3]) # ghz.cx(control_qubit, target_qubit); CNOT ghz.cx(q_register[3], q_register[4]) ghz.measure(q_register[2], c_register[0]) # ghz.measure(qubit, cbit): # qubit: quantum register, # cbit: classical register, # measures qubit into classical bit
flip_drive = True backend_sim = qiskit.providers.aer.PulseSimulator() # experiments10 = cr_drive_experiments(drive_idx, target_idx, flip_drive) # compute frequencies from the Hamiltonian # qubit_lo_freq10 = two_qubit_model.hamiltonian.get_qubit_lo_from_drift() #assemble qobj 1 rabifit_result = RabiFitter(result1, amps1, qubits, fit_p0 = [0.5,0.5,0.6,1.5]) if l == trainidx[0] and i == 0: #if flag != 1: # Generate the calibration circuits qr = qiskit.QuantumRegister(2) qubit_list = [0,1] meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') job = qiskit.execute(meas_calibs, backend=backend, shots=10, noise_model=noise_model) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) # meas_fitter.cal_matrix = np.kron(meas_fitter.cal_matrices[1],meas_fitter.cal_matricesc[0]) meas_fitter.cal_matrix plt.figure(figsize=(15, 10)) for qubit in qubits: ax = plt.subplot(2, 2, qubit + 1) #Xvmin, Xvmax = ax.xaxis.get_data_interval() #Yvmin, Yvmax = ax.yaxis.get_data_interval() #print(Xvmin, Xvmax,Yvmin, Yvmax) Xvmin = multiplier * np.floor(0.1 / multiplier) Xvmax = multiplier * np.ceil(0.5 / multiplier) ax.set_xlim([Xvmin, Xvmax]) rabifit_result.plot(qubit, ax=ax) print('Q1 Pi Amp: %f'%rabifit_result.pi_amplitude(qubit)) # analysis on multi-shots averaged result # Results without mitigation
result2 = job2.result() plot_histogram(result2.get_counts(circuit3)) # #Mitigation grover 2 from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter) cal_circuits, state_labels = complete_meas_cal(qr = circuit2.qregs[0], circlabel = 'measerrormitigationcal') cal_circuits[2].draw(output='mpl') # cal_job = execute(cal_circuits, backend = qcomp, shots = 1024, optimization_level = 0) print(cal_job.job_id()) job_monitor(cal_job) cal_results = cal_job.result() # plot_histogram(cal_results.get_counts(cal_circuits[3])) # meas_fitter = CompleteMeasFitter(cal_results, state_labels) meas_fitter.plot_calibration() # meas_filter = meas_fitter.filter mitigated_result = meas_filter.apply(result) device_counts = result.get_counts(circuit2) mitigated_counts = mitigated_result.get_counts(circuit2) plot_histogram([device_counts, mitigated_counts], legend=['device, noisy', 'device, mitigated']) # #Mitigation grover 3 cal_circuits2, state_labels2 = complete_meas_cal(qr = circuit3.qregs[0], circlabel = 'measerrormitigationcal') cal_circuits2[2].draw(output='mpl') # cal_job2 = execute(cal_circuits2, backend = qcomp, shots = 1024, optimization_level = 0) print(cal_job2.job_id()) job_monitor(cal_job2)