def test_group_paulis(self): """ qiskit.tools.apps.optimization.group_paulis function""" ham_name = self._get_resource_path("../performance/H2/H2Equilibrium.txt") zz = np.array([0, 0]) oo = np.array([1, 1]) pauli_list = Hamiltonian_from_file(ham_name) pauli_list_grouped = group_paulis(pauli_list) self.assertEqual(len(pauli_list_grouped), 2) r0 = [i[0] for i in pauli_list_grouped] r1 = [i[1] for i in pauli_list_grouped] self.assertEqual(len(r0), 2) r00 = [i[0] for i in r0] r01 = [i[1] for i in r0] e01 = [Pauli(oo, zz), Pauli(zz, oo)] self.assertEqual([0, 0], r00) self.assertEqual(e01, r01) self.assertEqual(len(r1), 2) r10 = [i[0] for i in r1] r11 = [i[1] for i in r1] e11 = [Pauli(oo, zz), Pauli(zz, oo)] self.assertEqual([0.011279956224107712, 0.18093133934472627], r10) self.assertEqual(e11, r11) expected_stout = ("Post Rotations of TPB set 0:\nZZ\n0\n\nZZ\n0.0112800\n" "II\n-1.0523761\nZI\n0.3979357\nIZ\n" "0.3979357\n\n\nPost Rotations of TPB set 1:\nXX\n0\n\n" "XX\n0.1809313") with patch('sys.stdout', new=StringIO()) as fakeOutput: print_pauli_list_grouped(pauli_list_grouped) self.assertMultiLineEqual(fakeOutput.getvalue().strip(), expected_stout)
def test_group_paulis(self): """ qiskit.tools.apps.optimization.group_paulis function""" ham_name = self._get_resource_path("../performance/H2/H2Equilibrium.txt") zz = np.array([0, 0]) oo = np.array([1, 1]) pauli_list = Hamiltonian_from_file(ham_name) pauli_list_grouped = group_paulis(pauli_list) self.assertEqual(len(pauli_list_grouped), 2) r0 = [i[0] for i in pauli_list_grouped] r1 = [i[1] for i in pauli_list_grouped] self.assertEqual(len(r0), 2) r00 = [i[0] for i in r0] r01 = [i[1] for i in r0] e01 = [Pauli(oo, zz), Pauli(zz, oo)] self.assertEqual([0, 0], r00) self.assertEqual(e01, r01) self.assertEqual(len(r1), 2) r10 = [i[0] for i in r1] r11 = [i[1] for i in r1] e11 = [Pauli(oo, zz), Pauli(zz, oo)] self.assertEqual([0.011279956224107712, 0.18093133934472627], r10) self.assertEqual(e11, r11) expected_stout = ("Post Rotations of TPB set 0:\nZZ\n0\n\nZZ\n0.0112800\n" "II\n-1.0523761\nZI\n0.3979357\nIZ\n" "0.3979357\n\n\nPost Rotations of TPB set 1:\nXX\n0\n\n" "XX\n0.1809313") with patch('sys.stdout', new=StringIO()) as fakeOutput: print_pauli_list_grouped(pauli_list_grouped) self.assertMultiLineEqual(fakeOutput.getvalue().strip(), expected_stout)
def vqe(molecule='H2', depth=6, max_trials=200, shots=1): if molecule == 'H2': n_qubits = 2 Z1 = 1 Z2 = 1 min_distance = 0.2 max_distance = 4 elif molecule == 'LiH': n_qubits = 4 Z1 = 1 Z2 = 3 min_distance = 0.5 max_distance = 5 else: raise QISKitError("Unknown molecule for VQE.") # Read Hamiltonian ham_name = os.path.join(os.path.dirname(__file__), molecule + '/' + molecule + 'Equilibrium.txt') pauli_list = Hamiltonian_from_file(ham_name) H = make_Hamiltonian(pauli_list) # Exact Energy exact = np.amin(la.eig(H)[0]).real print('The exact ground state energy is: {}'.format(exact)) # Optimization device = 'qasm_simulator' if shots == 1: device = 'statevector_simulator' if 'statevector' not in device: H = group_paulis(pauli_list) entangler_map = get_backend(device).configuration()['coupling_map'] if entangler_map == 'all-to-all': entangler_map = {i: [j for j in range(n_qubits) if j != i] for i in range(n_qubits)} else: entangler_map = mapper.coupling_list2dict(entangler_map) initial_theta = np.random.randn(2 * n_qubits * depth) # initial angles initial_c = 0.01 # first theta perturbations target_update = 2 * np.pi * 0.1 # aimed update on first trial save_step = 20 # print optimization trajectory cost = partial(cost_function, H, n_qubits, depth, entangler_map, shots, device) SPSA_params, circuits_cal = SPSA_calibration(cost, initial_theta, initial_c, target_update, stat=25) output, circuits_opt = SPSA_optimization(cost, initial_theta, SPSA_params, max_trials, save_step, last_avg=1) return circuits_cal + circuits_opt
def vqe(molecule='H2', depth=6, max_trials=200, shots=1): if molecule == 'H2': n_qubits = 2 Z1 = 1 Z2 = 1 min_distance = 0.2 max_distance = 4 elif molecule == 'LiH': n_qubits = 4 Z1 = 1 Z2 = 3 min_distance = 0.5 max_distance = 5 else: raise QISKitError("Unknown molecule for VQE.") # Read Hamiltonian ham_name = os.path.join(os.path.dirname(__file__), molecule + '/' + molecule + 'Equilibrium.txt') pauli_list = Hamiltonian_from_file(ham_name) H = make_Hamiltonian(pauli_list) # Exact Energy exact = np.amin(la.eig(H)[0]).real print('The exact ground state energy is: {}'.format(exact)) # Optimization device = 'local_qasm_simulator' qp = QuantumProgram() if shots != 1: H = group_paulis(pauli_list) entangler_map = qp.get_backend_configuration(device)['coupling_map'] if entangler_map == 'all-to-all': entangler_map = {i: [j for j in range(n_qubits) if j != i] for i in range(n_qubits)} else: entangler_map = mapper.coupling_list2dict(entangler_map) initial_theta = np.random.randn(2 * n_qubits * depth) # initial angles initial_c = 0.01 # first theta perturbations target_update = 2 * np.pi * 0.1 # aimed update on first trial save_step = 20 # print optimization trajectory cost = partial(cost_function, qp, H, n_qubits, depth, entangler_map, shots, device) SPSA_params = SPSA_calibration(cost, initial_theta, initial_c, target_update, stat=25) output = SPSA_optimization(cost, initial_theta, SPSA_params, max_trials, save_step, last_avg=1) return qp
def vqe_for_qiskit(q_device, sample_number, pauli_list, timeout_seconds, json_stream_file): def expectation_estimation(current_params, report): timestamp_before_ee = time.time() timestamp_before_q_run = timestamp_before_ee # no point in taking consecutive timestamps ansatz_circuit = ansatz_function(current_params) global fun_evaluation_counter # Trying to recover from a timed-out run assuming it to be a temporary glitch: # for attempt in range(1, 8): try: complex_energy, q_run_seconds = eval_hamiltonian( pauli_list_grouped, ansatz_circuit, sample_number, q_device) #complex_energy, q_run_seconds = eval_hamiltonian(pauli_list_grouped, ansatz_circuit, sample_number, q_device) energy = complex_energy.real break except QISKitError as e: print( "{}, trying again -- attempt number {}, timeout: {} seconds" .format(e, attempt, timeout_seconds)) if len(q_run_seconds) > 0: # got the real measured q time total_q_run_seconds = sum(q_run_seconds) measured = 'remotely' else: # have to assume total_q_run_seconds = time.time() - timestamp_before_q_run q_run_seconds = [total_q_run_seconds] measured = 'locally' q_runs = len(q_run_seconds) total_q_run_shots = sample_number * q_runs q_run_shots = [sample_number] * q_runs report_this_iteration = { 'total_q_seconds_per_c_iteration': total_q_run_seconds, 'seconds_per_individual_q_run': q_run_seconds, 'total_q_shots_per_c_iteration': total_q_run_shots, 'shots_per_individual_q_run': q_run_shots, 'energy': energy, 'measured': measured, } if report != 'TestMode': report['iterations'].append(report_this_iteration) report['total_q_seconds'] += report_this_iteration[ 'total_q_seconds_per_c_iteration'] # total_q_time += total report['total_q_shots'] += report_this_iteration[ 'total_q_shots_per_c_iteration'] fun_evaluation_counter += 1 report_this_iteration['total_seconds_per_c_iteration'] = time.time( ) - timestamp_before_ee print(report_this_iteration, "\n") json_stream_file.write( json.dumps(report_this_iteration, cls=NumpyEncoder) + "\n") json_stream_file.flush() return energy # Groups a list of (coeff,Pauli) tuples into tensor product basis (tpb) sets pauli_list_grouped = group_paulis(pauli_list) report = {'total_q_seconds': 0, 'total_q_shots': 0, 'iterations': []} # Initial objective function value fun_initial = expectation_estimation(start_params, 'TestMode') print('Initial guess at start_params is: {:.4f}'.format(fun_initial)) timestamp_before_optimizer = time.time() optimizer_output = minimizer_function(expectation_estimation, start_params, my_args=(report), my_options=minimizer_options) report['total_seconds'] = time.time() - timestamp_before_optimizer # Also generate and provide a validated function value at the optimal point fun_validated = expectation_estimation(optimizer_output['x'], 'TestMode') print('Validated value at solution is: {:.4f}'.format(fun_validated)) # Exact (noiseless) calculation of the energy at the given point: complex_energy, _ = eval_hamiltonian( pauli_list, ansatz_function(optimizer_output['x']), 1, Aer.get_backend('statevector_simulator')) optimizer_output['fun_exact'] = complex_energy.real optimizer_output['fun_validated'] = fun_validated print('Total Q seconds = %f' % report['total_q_seconds']) print('Total Q shots = %d' % report['total_q_shots']) print('Total seconds = %f' % report['total_seconds']) return (optimizer_output, report)
best_distance_quantum, best_theta, cost_plus, cost_minus,_,_ = SPSA_optimization(obj_funct_partial, initial_theta, SPSA_parameters, max_trials, save_step) """ def cost_function(Q_program,H,n,m,entangler_map,shots,device,theta): return eval_hamiltonian(Q_program,H,trial_circuit_ry(n,m,theta,entangler_map,None,False),shots,device).real initial_c=0.1 target_update=2*np.pi*0.1 save_step = 1 if shots !=1: H=group_paulis(pauli_list) SPSA_params = SPSA_calibration(partial(cost_function,Q_program,H,n,m,entangler_map, shots,backend),initial_theta,initial_c,target_update,25) best_distance_quantum, best_theta, cost_plus, cost_minus, _, _ = SPSA_optimization(partial(cost_function,Q_program,H,n,m,entangler_map,shots,backend), initial_theta,SPSA_params,max_trials,save_step,1); plt.plot(np.arange(0, max_trials,save_step), cost_plus,label='C(theta_plus)') plt.plot(np.arange(0, max_trials,save_step),cost_minus,label='C(theta_minus)') plt.plot(np.arange(0, max_trials,save_step),np.ones(max_trials//save_step)*best_distance_quantum, label='Final Optimized Cost') plt.plot(np.arange(0, max_trials,save_step),np.ones(max_trials//save_step)*exact, label='Exact Cost') plt.legend()