class TestEnd2End(QiskitAquaChemistryTestCase): """End2End tests.""" def setUp(self): hdf5_cfg = OrderedDict([ ('hdf5_input', self._get_resource_path('test_driver_hdf5.hdf5')) ]) section = {'properties': hdf5_cfg} driver = HDF5Driver() self.qmolecule = driver.run(section) core = Hamiltonian(transformation='full', qubit_mapping='parity', two_qubit_reduction=True, freeze_core=False, orbital_reduction=[], max_workers=4) self.algo_input = core.run(self.qmolecule) self.reference_energy = -1.857275027031588 @parameterized.expand([ [ 'COBYLA_M', 'COBYLA', get_aer_backend('statevector_simulator'), 'matrix', 1 ], [ 'COBYLA_P', 'COBYLA', get_aer_backend('statevector_simulator'), 'paulis', 1 ], # ['SPSA_P', 'SPSA', 'qasm_simulator', 'paulis', 1024], # ['SPSA_GP', 'SPSA', 'qasm_simulator', 'grouped_paulis', 1024] ]) def test_end2end_h2(self, name, optimizer, backend, mode, shots): if optimizer == 'COBYLA': optimizer = COBYLA() optimizer.set_options(maxiter=1000) elif optimizer == 'SPSA': optimizer = SPSA(max_trials=2000) ryrz = RYRZ(self.algo_input.qubit_op.num_qubits, depth=3, entanglement='full') vqe = VQE(self.algo_input.qubit_op, ryrz, optimizer, mode, aux_operators=self.algo_input.aux_ops) quantum_instance = QuantumInstance(backend, shots=shots) results = vqe.run(quantum_instance) self.assertAlmostEqual(results['energy'], self.reference_energy, places=6)
def test_partition_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'grouped_paulis', 'batch_mode': True } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 200 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 100}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('qasm_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) self.assertNotEqual(x[0], x[1]) self.assertNotEqual(x[2], x[1]) # hardcoded oracle
def test_eoh(self): SIZE = 2 temp = np.random.random((2**SIZE, 2**SIZE)) h1 = temp + temp.T qubit_op = Operator(matrix=h1) temp = np.random.random((2**SIZE, 2**SIZE)) h1 = temp + temp.T evo_op = Operator(matrix=h1) state_in = Custom(SIZE, state='random') evo_time = 1 num_time_slices = 100 eoh = EOH(qubit_op, state_in, evo_op, 'paulis', evo_time, num_time_slices) backend = get_aer_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=1, pass_manager=PassManager()) # self.log.debug('state_out:\n\n') ret = eoh.run(quantum_instance) self.log.debug('Evaluation result: {}'.format(ret))
def test_vertex_cover_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'grouped_paulis', 'batch_mode': True } optimizer_cfg = {'name': 'SPSA', 'max_trials': 200} var_form_cfg = { 'name': 'RYRZ', 'depth': 3, } params = { 'problem': { 'name': 'ising', 'random_seed': 100 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('qasm_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = vertexcover.sample_most_likely(len(self.w), result['eigvecs'][0]) sol = vertexcover.get_graph_solution(x) oracle = self.brute_force() self.assertEqual(np.count_nonzero(sol), oracle)
def test_graph_partition_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix', 'batch_mode': True } optimizer_cfg = {'name': 'SPSA', 'max_trials': 300} var_form_cfg = {'name': 'RY', 'depth': 5, 'entanglement': 'linear'} params = { 'problem': { 'name': 'ising', 'random_seed': 10598 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('statevector_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = graphpartition.sample_most_likely(result['eigvecs'][0]) # check against the oracle ising_sol = graphpartition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 0, 0, 1]) oracle = self.brute_force() self.assertEqual(graphpartition.objective_value(x, self.w), oracle)
def test_clique_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix', 'batch_mode': True } optimizer_cfg = {'name': 'COBYLA'} var_form_cfg = {'name': 'RY', 'depth': 5, 'entanglement': 'linear'} params = { 'problem': { 'name': 'ising', 'random_seed': 10598 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('statevector_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = clique.sample_most_likely(len(self.w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 1, 1, 1, 1]) oracle = self.brute_force() self.assertEqual(clique.satisfy_or_not(ising_sol, self.w, self.K), oracle)
def test_set_packing_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'grouped_paulis', 'batch_mode': True } optimizer_cfg = {'name': 'SPSA', 'max_trials': 200} var_form_cfg = {'name': 'RY', 'depth': 5, 'entanglement': 'linear'} params = { 'problem': { 'name': 'ising', 'random_seed': 100 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('qasm_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = setpacking.sample_most_likely(len(self.list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) oracle = self.brute_force() self.assertEqual(np.count_nonzero(ising_sol), oracle)
def test_qsvm_kernel_binary_directly(self): backend = get_aer_backend('qasm_simulator') num_qubits = 2 feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2, entangler_map={0: [1]}) svm = QSVMKernel(feature_map, self.training_data, self.testing_data, None) svm.random_seed = self.random_seed quantum_instance = QuantumInstance(backend, shots=self.shots, seed=self.random_seed, seed_mapper=self.random_seed) result = svm.run(quantum_instance) # np.testing.assert_array_almost_equal( # result['kernel_matrix_training'], self.ref_kernel_matrix_training, decimal=4) # np.testing.assert_array_almost_equal( # result['kernel_matrix_testing'], self.ref_kernel_matrix_testing, decimal=4) self.assertEqual(len(result['svm']['support_vectors']), 4) np.testing.assert_array_almost_equal(result['svm']['support_vectors'], self.ref_support_vectors, decimal=4) # np.testing.assert_array_almost_equal(result['svm']['alphas'], self.ref_alpha, decimal=4) # np.testing.assert_array_almost_equal(result['svm']['bias'], self.ref_bias, decimal=4) self.assertEqual(result['testing_accuracy'], 0.5)
def test_vqe_var_forms(self, name, places): backend = get_aer_backend('statevector_simulator') params = { 'algorithm': {'name': 'VQE'}, 'variational_form': {'name': name}, 'backend': {'shots': 1} } result = run_algorithm(params, self.algo_input, backend=backend) self.assertAlmostEqual(result['energy'], -1.85727503, places=places)
def test_qsvm_kernel_binary_directly(self): ref_kernel_training = np.array( [[1., 0.85366667, 0.12341667, 0.36408333], [0.85366667, 1., 0.11141667, 0.45491667], [0.12341667, 0.11141667, 1., 0.667], [0.36408333, 0.45491667, 0.667, 1.]]) ref_kernel_testing = np.array( [[0.14316667, 0.18208333, 0.4785, 0.14441667], [0.33608333, 0.3765, 0.02316667, 0.15858333]]) ref_alpha = np.array([0.36064489, 1.49204209, 0.0264953, 1.82619169]) ref_bias = np.array([-0.03380763]) ref_support_vectors = np.array([[2.95309709, 2.51327412], [3.14159265, 4.08407045], [4.08407045, 2.26194671], [4.46106157, 2.38761042]]) backend = get_aer_backend('qasm_simulator') num_qubits = 2 feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2, entangler_map={0: [1]}) svm = QSVMKernel(feature_map, self.training_data, self.testing_data, None) svm.random_seed = self.random_seed run_config = RunConfig(shots=self.shots, max_credits=10, memory=False, seed=self.random_seed) quantum_instance = QuantumInstance(backend, run_config, seed_mapper=self.random_seed) result = svm.run(quantum_instance) np.testing.assert_array_almost_equal(result['kernel_matrix_training'], ref_kernel_training, decimal=1) np.testing.assert_array_almost_equal(result['kernel_matrix_testing'], ref_kernel_testing, decimal=1) self.assertEqual(len(result['svm']['support_vectors']), 4) np.testing.assert_array_almost_equal(result['svm']['support_vectors'], ref_support_vectors, decimal=4) np.testing.assert_array_almost_equal(result['svm']['alphas'], ref_alpha, decimal=4) np.testing.assert_array_almost_equal(result['svm']['bias'], ref_bias, decimal=4) self.assertEqual(result['testing_accuracy'], 0.5)
def test_vqe_optimizers(self, name, places, batch_mode): backend = get_aer_backend('statevector_simulator') params = { 'algorithm': {'name': 'VQE', 'batch_mode': batch_mode}, 'optimizer': {'name': name}, 'backend': {'shots': 1} } result = run_algorithm(params, self.algo_input, backend=backend) self.assertAlmostEqual(result['energy'], -1.85727503, places=places)
def solve_ibmqx_ising_qubo(G, matrix_func, optimizer, p): backend = get_aer_backend('qasm_simulator') w = matrix_func(G) ops = get_qubitops(w) qaoa = QAOA(ops, optimizer, p, operator_mode='paulis') quantum_instance = QuantumInstance(backend) result = qaoa.run(quantum_instance) x = sample_most_likely(result['eigvecs'][0]) return x
def test_qsvm_variational_directly(self): np.random.seed(self.random_seed) backend = get_aer_backend('qasm_simulator') num_qubits = 2 optimizer = SPSA(max_trials=10, save_steps=1, c0=4.0, skip_calibration=True) feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2) var_form = RYRZ(num_qubits=num_qubits, depth=3) svm = QSVMVariational(optimizer, feature_map, var_form, self.training_data, self.testing_data) svm.random_seed = self.random_seed run_config = RunConfig(shots=1024, max_credits=10, memory=False, seed=self.random_seed) quantum_instance = QuantumInstance(backend, run_config, seed_mapper=self.random_seed) result = svm.run(quantum_instance) np.testing.assert_array_almost_equal(result['opt_params'], self.ref_opt_params, decimal=4) np.testing.assert_array_almost_equal(result['training_loss'], self.ref_train_loss, decimal=8) self.assertEqual(result['testing_accuracy'], 1.0) file_path = self._get_resource_path('qsvm_variational_test.npz') svm.save_model(file_path) self.assertTrue(os.path.exists(file_path)) loaded_svm = QSVMVariational(optimizer, feature_map, var_form, self.training_data, None) loaded_svm.load_model(file_path) np.testing.assert_array_almost_equal(loaded_svm.ret['opt_params'], self.ref_opt_params, decimal=4) loaded_test_acc = loaded_svm.test(svm.test_dataset[0], svm.test_dataset[1], quantum_instance) self.assertEqual(result['testing_accuracy'], loaded_test_acc) if os.path.exists(file_path): try: os.remove(file_path) except: pass
def test_vqe_2_iqpe(self): backend = get_aer_backend('qasm_simulator') num_qbits = self.algo_input.qubit_op.num_qubits var_form = RYRZ(num_qbits, 3) optimizer = SPSA(max_trials=10) # optimizer.set_options(**{'max_trials': 500}) algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'paulis') quantum_instance = QuantumInstance(backend) result = algo.run(quantum_instance) self.log.debug('VQE result: {}.'.format(result)) self.ref_eigenval = -1.85727503 num_time_slices = 50 num_iterations = 11 state_in = VarFormBased(var_form, result['opt_params']) iqpe = IQPE(self.algo_input.qubit_op, state_in, num_time_slices, num_iterations, paulis_grouping='random', expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) quantum_instance = QuantumInstance(backend, shots=100, pass_manager=PassManager(), seed=self.random_seed, seed_mapper=self.random_seed) result = iqpe.run(quantum_instance) self.log.debug('top result str label: {}'.format( result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format( result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format( result['stretch'])) self.log.debug('translation: {}'.format( result['translation'])) self.log.debug('final eigenvalue from QPE: {}'.format( result['energy'])) self.log.debug('reference eigenvalue: {}'.format( self.ref_eigenval)) self.log.debug('ref eigenvalue (transformed): {}'.format( (self.ref_eigenval + result['translation']) * result['stretch'])) self.log.debug('reference binary str label: {}'.format( decimal_to_binary((self.ref_eigenval + result['translation']) * result['stretch'], max_num_digits=num_iterations + 3, fractional_part_only=True))) np.testing.assert_approx_equal(self.ref_eigenval, result['energy'], significant=2)
def test_vqe_direct(self, batch_mode): backend = get_aer_backend('statevector_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 3, initial_state=init_state) optimizer = L_BFGS_B() algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'matrix', batch_mode=batch_mode) quantum_instance = QuantumInstance(backend) result = algo.run(quantum_instance) self.assertAlmostEqual(result['energy'], -1.85727503)
def test_iqpe(self, qubitOp): self.algorithm = 'IQPE' self.log.debug('Testing IQPE') self.qubitOp = qubitOp exact_eigensolver = ExactEigensolver(self.qubitOp, k=1) results = exact_eigensolver.run() w = results['eigvals'] v = results['eigvecs'] self.qubitOp.to_matrix() np.testing.assert_almost_equal( self.qubitOp.matrix @ v[0], w[0] * v[0] ) np.testing.assert_almost_equal( expm(-1.j * sparse.csc_matrix(self.qubitOp.matrix)) @ v[0], np.exp(-1.j * w[0]) * v[0] ) self.ref_eigenval = w[0] self.ref_eigenvec = v[0] self.log.debug('The exact eigenvalue is: {}'.format(self.ref_eigenval)) self.log.debug('The corresponding eigenvector: {}'.format(self.ref_eigenvec)) num_time_slices = 50 num_iterations = 12 state_in = Custom(self.qubitOp.num_qubits, state_vector=self.ref_eigenvec) iqpe = IQPE(self.qubitOp, state_in, num_time_slices, num_iterations, paulis_grouping='random', expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = get_aer_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=100, pass_manager=PassManager()) result = iqpe.run(quantum_instance) self.log.debug('top result str label: {}'.format(result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format(result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format(result['stretch'])) self.log.debug('translation: {}'.format(result['translation'])) self.log.debug('final eigenvalue from IQPE: {}'.format(result['energy'])) self.log.debug('reference eigenvalue: {}'.format(self.ref_eigenval)) self.log.debug('ref eigenvalue (transformed): {}'.format( (self.ref_eigenval + result['translation']) * result['stretch']) ) self.log.debug('reference binary str label: {}'.format(decimal_to_binary( (self.ref_eigenval.real + result['translation']) * result['stretch'], max_num_digits=num_iterations + 3, fractional_part_only=True ))) np.testing.assert_approx_equal(result['energy'], self.ref_eigenval.real, significant=2)
def test_real_eval(self): depth = 1 var_form = RYRZ(self.qubitOp.num_qubits, depth) circuit = var_form.construct_circuit(np.array(np.random.randn(var_form.num_parameters))) # self.qubitOp.coloring = None run_config_ref = {'shots': 1} run_config = {'shots': 10000} reference = self.qubitOp.eval('matrix', circuit, get_aer_backend( 'statevector_simulator'), run_config=run_config_ref)[0] reference = reference.real backend = get_aer_backend('qasm_simulator') paulis_mode = self.qubitOp.eval('paulis', circuit, backend, run_config=run_config) grouped_paulis_mode = self.qubitOp.eval('grouped_paulis', circuit, backend, run_config=run_config) paulis_mode_p_3sigma = paulis_mode[0] + 3 * paulis_mode[1] paulis_mode_m_3sigma = paulis_mode[0] - 3 * paulis_mode[1] grouped_paulis_mode_p_3sigma = grouped_paulis_mode[0] + 3 * grouped_paulis_mode[1] grouped_paulis_mode_m_3sigma = grouped_paulis_mode[0] - 3 * grouped_paulis_mode[1] self.assertLessEqual(reference, paulis_mode_p_3sigma.real) self.assertGreaterEqual(reference, paulis_mode_m_3sigma.real) self.assertLessEqual(reference, grouped_paulis_mode_p_3sigma.real) self.assertGreaterEqual(reference, grouped_paulis_mode_m_3sigma.real) run_config = {'shots': 10000} compile_config = {'pass_manager': PassManager()} paulis_mode = self.qubitOp.eval('paulis', circuit, backend, run_config=run_config, compile_config=compile_config) grouped_paulis_mode = self.qubitOp.eval('grouped_paulis', circuit, backend, run_config=run_config, compile_config=compile_config) paulis_mode_p_3sigma = paulis_mode[0] + 3 * paulis_mode[1] paulis_mode_m_3sigma = paulis_mode[0] - 3 * paulis_mode[1] grouped_paulis_mode_p_3sigma = grouped_paulis_mode[0] + 3 * grouped_paulis_mode[1] grouped_paulis_mode_m_3sigma = grouped_paulis_mode[0] - 3 * grouped_paulis_mode[1] self.assertLessEqual(reference, paulis_mode_p_3sigma.real, "Without any pass manager") self.assertGreaterEqual(reference, paulis_mode_m_3sigma.real, "Without any pass manager") self.assertLessEqual(reference, grouped_paulis_mode_p_3sigma.real, "Without any pass manager") self.assertGreaterEqual(reference, grouped_paulis_mode_m_3sigma.real, "Without any pass manager")
def test_grover(self, input_file, incremental=True, num_iterations=1, cnx_mode='basic'): input_file = self._get_resource_path(input_file) # get ground-truth with open(input_file) as f: buf = f.read() if incremental: self.log.debug( 'Testing incremental Grover search on SAT problem instance: \n{}' .format(buf, )) else: self.log.debug( 'Testing Grover search with {} iteration(s) on SAT problem instance: \n{}' .format( num_iterations, buf, )) header = buf.split('\n')[0] self.assertGreaterEqual(header.find('solution'), 0, 'Ground-truth info missing.') self.groundtruth = [ ''.join([ '1' if i > 0 else '0' for i in sorted( [int(v) for v in s.strip().split() if v != '0'], key=abs) ])[::-1] for s in header.split('solutions:' if header.find( 'solutions:') >= 0 else 'solution:')[-1].split(',') ] backend = get_aer_backend('qasm_simulator') sat_oracle = SAT(buf) grover = Grover(sat_oracle, num_iterations=num_iterations, incremental=incremental, cnx_mode=cnx_mode) quantum_instance = QuantumInstance(backend, shots=100) ret = grover.run(quantum_instance) self.log.debug('Ground-truth Solutions: {}.'.format(self.groundtruth)) self.log.debug('Measurement result: {}.'.format( ret['measurements'])) top_measurement = max(ret['measurements'].items(), key=operator.itemgetter(1))[0] self.log.debug('Top measurement: {}.'.format(top_measurement)) if ret['oracle_evaluation']: self.assertIn(top_measurement, self.groundtruth) self.log.debug('Search Result: {}.'.format(ret['result'])) else: self.assertEqual(self.groundtruth, ['']) self.log.debug('Nothing found.')
def test_qsvm_kernel_binary_directly_statevector(self): backend = get_aer_backend('statevector_simulator') num_qubits = 2 feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2, entangler_map={0: [1]}) svm = QSVMKernel(feature_map, self.training_data, self.testing_data, None) svm.random_seed = self.random_seed quantum_instance = QuantumInstance(backend, seed=self.random_seed, seed_mapper=self.random_seed) result = svm.run(quantum_instance) ori_alphas = result['svm']['alphas'] self.assertEqual(len(result['svm']['support_vectors']), 4) np.testing.assert_array_almost_equal(result['svm']['support_vectors'], self.ref_support_vectors, decimal=4) self.assertEqual(result['testing_accuracy'], 0.5) file_path = self._get_resource_path('qsvm_kernel_test.npz') svm.save_model(file_path) self.assertTrue(os.path.exists(file_path)) loaded_svm = QSVMKernel(feature_map, self.training_data, None, None) loaded_svm.load_model(file_path) np.testing.assert_array_almost_equal( loaded_svm.ret['svm']['support_vectors'], self.ref_support_vectors, decimal=4) np.testing.assert_array_almost_equal(loaded_svm.ret['svm']['alphas'], ori_alphas, decimal=4) loaded_test_acc = loaded_svm.test(svm.test_dataset[0], svm.test_dataset[1], quantum_instance) self.assertEqual(result['testing_accuracy'], loaded_test_acc) if os.path.exists(file_path): try: os.remove(file_path) except: pass
def test_expected_value(self, simulator): # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = ((r - 0.5 * vol ** 2) * T + np.log(S)) 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 value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct circuit factory for uncertainty model uncertainty_model = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma, low=low, high=high) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.5 # construct circuit factory for payoff function european_call = EuropeanCallExpectedValue( uncertainty_model, strike_price=strike_price, c_approx=c_approx ) # set number of evaluation qubits (samples) m = 3 # construct amplitude estimation ae = AmplitudeEstimation(m, european_call) # run simulation result = ae.run(quantum_instance=get_aer_backend(simulator)) # compare to precomputed solution self.assertEqual(0.0, np.round(result['estimation'] - 0.045705353233, decimals=4))
def test_grover(self, input_file, incremental, num_iterations, mct_mode, simulator): input_file = self._get_resource_path(input_file) # get ground-truth with open(input_file) as f: buf = f.read() if incremental: self.log.debug( 'Testing incremental Grover search on SAT problem instance: \n{}' .format(buf, )) else: self.log.debug( 'Testing Grover search with {} iteration(s) on SAT problem instance: \n{}' .format( num_iterations, buf, )) header = buf.split('\n')[0] self.assertGreaterEqual(header.find('solution'), 0, 'Ground-truth info missing.') self.groundtruth = [ ''.join([ '1' if i > 0 else '0' for i in sorted( [int(v) for v in s.strip().split() if v != '0'], key=abs) ])[::-1] for s in header.split('solutions:' if header.find( 'solutions:') >= 0 else 'solution:')[-1].split(',') ] backend = get_aer_backend(simulator) sat_oracle = SAT(buf) grover = Grover(sat_oracle, num_iterations=num_iterations, incremental=incremental, mct_mode=mct_mode) run_config = RunConfig(shots=100, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config) ret = grover.run(quantum_instance) self.log.debug('Ground-truth Solutions: {}.'.format(self.groundtruth)) self.log.debug('Top measurement: {}.'.format( ret['top_measurement'])) if ret['oracle_evaluation']: self.assertIn(ret['top_measurement'], self.groundtruth) self.log.debug('Search Result: {}.'.format(ret['result'])) else: self.assertEqual(self.groundtruth, ['']) self.log.debug('Nothing found.')
def test_create_from_matrix(self): """Test with matrix initialization.""" for num_qubits in range(1, 3): m_size = np.power(2, num_qubits) matrix = np.random.rand(m_size, m_size) op = Operator(matrix=matrix) depth = 1 var_form = RYRZ(op.num_qubits, depth) circuit = var_form.construct_circuit(np.array(np.random.randn(var_form.num_parameters))) backend = get_aer_backend('statevector_simulator') run_config = {'shots': 1} non_matrix_mode = op.eval('paulis', circuit, backend, run_config=run_config)[0] matrix_mode = op.eval('matrix', circuit, backend, run_config=run_config)[0] self.assertAlmostEqual(matrix_mode, non_matrix_mode, 6)
def test_create_from_paulis_0(self): """Test with single paulis.""" num_qubits = 3 for pauli_label in itertools.product('IXYZ', repeat=num_qubits): coeff = np.random.random(1)[0] pauli_term = [coeff, Pauli.from_label(pauli_label)] op = Operator(paulis=[pauli_term]) depth = 1 var_form = RYRZ(op.num_qubits, depth) circuit = var_form.construct_circuit(np.array(np.random.randn(var_form.num_parameters))) run_config = {'shots': 1} backend = get_aer_backend('statevector_simulator') non_matrix_mode = op.eval('paulis', circuit, backend, run_config=run_config)[0] matrix_mode = op.eval('matrix', circuit, backend, run_config=run_config)[0] self.assertAlmostEqual(matrix_mode, non_matrix_mode, 6)
def test_exact_eval(self): depth = 1 var_form = RYRZ(self.qubitOp.num_qubits, depth) circuit = var_form.construct_circuit(np.array(np.random.randn(var_form.num_parameters))) run_config = {'shots': 1} backend = get_aer_backend('statevector_simulator') matrix_mode = self.qubitOp.eval('matrix', circuit, backend, run_config=run_config)[0] non_matrix_mode = self.qubitOp.eval('paulis', circuit, backend, run_config=run_config)[0] diff = abs(matrix_mode - non_matrix_mode) self.assertLess(diff, 0.01, "Values: ({} vs {})".format(matrix_mode, non_matrix_mode)) run_config = {'shots': 1} compile_config = {'pass_manager': PassManager()} non_matrix_mode = self.qubitOp.eval('paulis', circuit, backend, run_config=run_config, compile_config=compile_config)[0] diff = abs(matrix_mode - non_matrix_mode) self.assertLess(diff, 0.01, "Without any pass manager, Values: ({} vs {})".format(matrix_mode, non_matrix_mode))
def test_mct(self, num_controls): c = QuantumRegister(num_controls, name='c') o = QuantumRegister(1, name='o') allsubsets = list( chain(*[ combinations(range(num_controls), ni) for ni in range(num_controls + 1) ])) for subset in allsubsets: for mode in ['basic', 'advanced']: qc = QuantumCircuit(o, c) if mode == 'basic': if num_controls <= 2: num_ancillae = 0 else: num_ancillae = num_controls - 2 else: if num_controls <= 4: num_ancillae = 0 else: num_ancillae = 1 if num_ancillae > 0: a = QuantumRegister(num_ancillae, name='a') qc.add_register(a) for idx in subset: qc.x(c[idx]) qc.cnx([c[i] for i in range(num_controls)], o[0], [a[i] for i in range(num_ancillae)], mode=mode) for idx in subset: qc.x(c[idx]) vec = np.asarray( q_execute(qc, get_aer_backend( 'statevector_simulator')).result().get_statevector( qc, decimals=16)) vec_o = [0, 1] if len(subset) == num_controls else [1, 0] # print(vec, np.array(vec_o + [0] * (2 ** (num_controls + num_ancillae + 1) - 2))) f = state_fidelity( vec, np.array(vec_o + [0] * (2**(num_controls + num_ancillae + 1) - 2))) self.assertAlmostEqual(f, 1) return
def test_qsvm_kernel_binary_via_run_algorithm(self): training_input = { 'A': np.asarray([[0.6560706, 0.17605998], [0.14154948, 0.06201424], [0.80202323, 0.40582692], [0.46779595, 0.39946754], [0.57660199, 0.21821317]]), 'B': np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951], [-0.30119743, -0.11221681], [-0.16479252, -0.08640519], [0.49156185, -0.3660534]]) } test_input = { 'A': np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544], [0.08791134, 0.11515506], [0.45988094, 0.32854319], [0.53015085, 0.41539212]]), 'B': np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828], [-0.17323832, -0.49535592], [0.14043268, -0.87869109], [-0.15046837, -0.47340207]]) } total_array = np.concatenate((test_input['A'], test_input['B'])) params = { 'problem': { 'name': 'svm_classification', 'random_seed': self.random_seed }, 'backend': { 'shots': self.shots }, 'algorithm': { 'name': 'QSVM.Kernel' } } backend = get_aer_backend('qasm_simulator') algo_input = SVMInput(training_input, test_input, total_array) result = run_algorithm(params, algo_input, backend=backend) self.assertEqual(result['testing_accuracy'], 0.6) self.assertEqual(result['predicted_classes'], ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'A', 'A', 'A'])
def test_vqe_caching_direct(self, batch_mode): backend = get_aer_backend('statevector_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 3, initial_state=init_state) optimizer = L_BFGS_B() algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'matrix', batch_mode=batch_mode) circuit_cache = CircuitCache(skip_qobj_deepcopy=True) quantum_instance_caching = QuantumInstance(backend, circuit_cache=circuit_cache, skip_qobj_validation=True) result_caching = algo.run(quantum_instance_caching) self.assertAlmostEqual( self.reference_vqe_result['statevector_simulator']['energy'], result_caching['energy'])
def test_sat_oracle(self, cnf_str, sols): num_shots = 1024 for cnx_mode in ['basic', 'advanced']: sat = SAT(cnf_str, cnx_mode=cnx_mode) sat_circuit = sat.construct_circuit() m = ClassicalRegister(1, name='m') for assignment in itertools.product([True, False], repeat=len(sat.variable_register())): qc = QuantumCircuit(m, sat.variable_register()) for idx, tf in enumerate(assignment): if tf: qc.x(sat.variable_register()[idx]) qc += sat_circuit qc.barrier(sat._qr_outcome) qc.measure(sat._qr_outcome, m) counts = q_execute(qc, get_aer_backend( 'qasm_simulator'), shots=num_shots).result().get_counts(qc) if assignment in sols: assert(counts['1'] == num_shots) else: assert(counts['0'] == num_shots)
def test_expected_value(self, simulator): # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution u = MultivariateNormalDistribution(num_qubits, low, high, mu, sigma) # specify cash flow cf = [1.0, 2.0] # specify approximation factor c_approx = 0.125 # get fixed income circuit appfactory fixed_income = FixedIncomeExpectedValue(u, A, b, cf, c_approx) # set number of evaluation qubits (samples) m = 5 # construct amplitude estimation ae = AmplitudeEstimation(m, fixed_income) # run simulation result = ae.run(quantum_instance=get_aer_backend('statevector_simulator')) # compare to precomputed solution self.assertEqual(0.0, np.round(result['estimation'] - 2.4600, decimals=4))
def test_qaoa(self, w, p, solutions): self.log.debug('Testing {}-step QAOA with MaxCut on graph\n{}'.format( p, w)) np.random.seed(0) backend = get_aer_backend('statevector_simulator') optimizer = COBYLA() qubitOp, offset = maxcut.get_maxcut_qubitops(w) qaoa = QAOA(qubitOp, optimizer, p, operator_mode='matrix') quantum_instance = QuantumInstance(backend) result = qaoa.run(quantum_instance) x = maxcut.sample_most_likely(result['eigvecs'][0]) graph_solution = maxcut.get_graph_solution(x) self.log.debug('energy: {}'.format(result['energy'])) self.log.debug('time: {}'.format(result['eval_time'])) self.log.debug('maxcut objective: {}'.format(result['energy'] + offset)) self.log.debug('solution: {}'.format(graph_solution)) self.log.debug('solution objective: {}'.format( maxcut.maxcut_value(x, w))) self.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions)