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 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)
plt.title('raw') plt.figure() plot_histogram(mitigated_counts[-1]) plt.title('mitigated') plt.figure() plt.bar(range(2),[r_counts,m_counts]), plt.xticks('01','10','00','11') plt.legend('raw','mitigated') plt.title('Q1 counts') # Plot the calibration matrix print('Q1 Calibration Matrix') meas_fitter.plot_calibration() plt.show() flag = 1 # What is the measurement fidelity of Q0? print("Average Measurement Fidelity of Q1: %f" % meas_fitter.readout_fidelity( label_list = [['00','01'],['10','11']])) if label1[l][i] == 0 and label2[l][i] == 1: drive_idx = 0 target_idx = 1 flip_drive = True backend_sim = qiskit.providers.aer.PulseSimulator() # qubit_lo_freq01 = two_qubit_model.hamiltonian.get_qubit_lo_from_drift() # experiments10 = cr_drive_experiments(drive_idx, target_idx, flip_drive) # compute frequencies from the Hamiltonian rabifit_result = RabiFitter(result0, amps0, qubits, fit_p0 = [0.5,0.5,0.6,1.5]) if l == trainidx[0] and i == 0: #if flag != 0: # Generate the calibration circuits qr = qiskit.QuantumRegister(2) qubit_list = [0,1]
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)
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)