def test_evolution(self): SIZE = 2 #SPARSITY = 0 #X = [[0, 1], [1, 0]] #Y = [[0, -1j], [1j, 0]] Z = [[1, 0], [0, -1]] I = [[1, 0], [0, 1]] h1 = np.kron( I, Z ) # + 0.5 * np.kron(Y, X)# + 0.3 * np.kron(Z, X) + 0.4 * np.kron(Z, Y) # np.random.seed(2) temp = np.random.random((2**SIZE, 2**SIZE)) h1 = temp + temp.T qubitOp = Operator(matrix=h1) temp = np.random.random((2**SIZE, 2**SIZE)) h1 = temp + temp.T evoOp = Operator(matrix=h1) state_in = get_initial_state_instance('CUSTOM') state_in.init_args(SIZE, state='random') evo_time = 1 num_time_slices = 100 dynamics = get_algorithm_instance('Dynamics') dynamics.setup_quantum_backend() # self.log.debug('state_out:\n\n') dynamics.init_args(qubitOp, 'paulis', state_in, evoOp, evo_time, num_time_slices) ret = dynamics.run() self.log.debug('Evaluation result: {}'.format(ret))
def test_evolution(self): SIZE = 2 temp = np.random.random((2**SIZE, 2**SIZE)) h1 = temp + temp.T qubitOp = Operator(matrix=h1) temp = np.random.random((2**SIZE, 2**SIZE)) h1 = temp + temp.T evoOp = Operator(matrix=h1) state_in = get_initial_state_instance('CUSTOM') state_in.init_args(SIZE, state='random') evo_time = 1 num_time_slices = 100 dynamics = get_algorithm_instance('Dynamics') dynamics.setup_quantum_backend(skip_transpiler=True) # self.log.debug('state_out:\n\n') dynamics.init_args(qubitOp, 'paulis', state_in, evoOp, evo_time, num_time_slices) ret = dynamics.run() self.log.debug('Evaluation result: {}'.format(ret))
def test_grover(self, input_file, num_iterations=1): self.log.debug('Testing Grover search with {} iteration(s) on SAT problem instance: \n{}'.format( num_iterations, open(input_file).read(), )) # get ground-truth with open(input_file) as f: header = f.readline() 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(',') ] sat_oracle = get_oracle_instance('SAT') with open(input_file) as f: sat_oracle.init_args(f.read()) grover = get_algorithm_instance('Grover') grover.setup_quantum_backend(backend='local_qasm_simulator', shots=100) grover.init_args(sat_oracle, num_iterations=num_iterations) ret = grover.run() 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)) self.log.debug('Search Result: {}.'.format(ret['result'])) self.assertIn(top_measurement, self.groundtruth)
def test_ee_direct(self): algo = get_algorithm_instance('ExactEigensolver') algo.init_args(self.algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() self.assertAlmostEqual(result['energy'], -1.85727503) np.testing.assert_array_almost_equal(result['energies'], [-1.85727503]) np.testing.assert_array_almost_equal(result['eigvals'], [-1.85727503 + 0j])
def test_ee_direct_k4(self): algo = get_algorithm_instance('ExactEigensolver') algo.init_args(self.algo_input.qubit_op, k=4, aux_operators=[]) result = algo.run() self.assertAlmostEqual(result['energy'], -1.85727503) self.assertEqual(len(result['eigvals']), 4) self.assertEqual(len(result['eigvecs']), 4) np.testing.assert_array_almost_equal( result['energies'], [-1.85727503, -1.24458455, -0.88272215, -0.22491125])
def test_grover(self): sat_oracle = get_oracle_instance('SAT') with open(self.input_file) as f: sat_oracle.init_args(f.read()) grover = get_algorithm_instance('Grover') grover.setup_quantum_backend(backend='local_qasm_simulator', shots=100) grover.init_args(sat_oracle, num_iterations=2) ret = grover.run() 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)) self.log.debug('Search Result: {}.'.format(ret['result'])) self.assertIn(top_measurement, self.groundtruth)
def test_qaoa(self, w, p, solutions): self.log.debug('Testing {}-step QAOA with MaxCut on graph\n{}'.format( p, w)) optimizer = get_optimizer_instance('COBYLA') qubitOp, offset = maxcut.get_maxcut_qubitops(w) qaoa = get_algorithm_instance('QAOA') qaoa.init_args(qubitOp, 'matrix', p, optimizer) qaoa.setup_quantum_backend(backend='local_statevector_simulator', shots=100) result = qaoa.run() 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)
def test_svm_qkernel_directly(self): svm = get_algorithm_instance("SVM_QKernel") svm.setup_quantum_backend(backend='local_qasm_simulator', shots=1024) svm.random_seed = self.random_seed svm.init_args(self.training_data, self.testing_data, None, print_info=False) result = svm.run() 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) self.assertEqual(result['test_success_ratio'], 0.5)
def test_qpe(self, qubitOp): self.algorithm = 'QPE' self.log.debug('Testing QPE') self.qubitOp = qubitOp exact_eigensolver = get_algorithm_instance('ExactEigensolver') exact_eigensolver.init_args(self.qubitOp, k=1) results = exact_eigensolver.run() w = results['eigvals'] v = results['eigvecs'] self.qubitOp._check_representation('matrix') np.testing.assert_almost_equal(self.qubitOp.matrix @ v[0], w[0] * v[0]) np.testing.assert_almost_equal( expm(-1.j * 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 iqpe = get_algorithm_instance('IQPE') iqpe.setup_quantum_backend(backend='local_qasm_simulator', shots=100, skip_transpiler=True) state_in = get_initial_state_instance('CUSTOM') state_in.init_args(self.qubitOp.num_qubits, state_vector=self.ref_eigenvec) iqpe.init_args( self.qubitOp, state_in, num_time_slices, num_iterations, paulis_grouping='random', expansion_mode='suzuki', expansion_order=2, ) result = iqpe.run() # self.log.debug('operator paulis:\n{}'.format(self.qubitOp.print_operators('paulis'))) # self.log.debug('qpe circuit:\n\n{}'.format(result['circuit']['complete'].qasm())) 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_qpe(self, distance): self.algorithm = 'QPE' self.log.debug( 'Testing End-to-End with QPE on H2 with interatomic distance {}.'. format(distance)) cfg_mgr = ConfigurationManager() pyscf_cfg = OrderedDict([('atom', 'H .0 .0 .0; H .0 .0 {}'.format(distance)), ('unit', 'Angstrom'), ('charge', 0), ('spin', 0), ('basis', 'sto3g')]) section = {} section['properties'] = pyscf_cfg driver = cfg_mgr.get_driver_instance('PYSCF') self.molecule = driver.run(section) ferOp = FermionicOperator(h1=self.molecule._one_body_integrals, h2=self.molecule._two_body_integrals) self.qubitOp = ferOp.mapping( map_type='PARITY', threshold=1e-10).two_qubit_reduced_operator(2) exact_eigensolver = get_algorithm_instance('ExactEigensolver') exact_eigensolver.init_args(self.qubitOp, k=1) results = exact_eigensolver.run() self.reference_energy = results['energy'] self.log.debug('The exact ground state energy is: {}'.format( results['energy'])) num_particles = self.molecule._num_alpha + self.molecule._num_beta two_qubit_reduction = True num_orbitals = self.qubitOp.num_qubits + (2 if two_qubit_reduction else 0) qubit_mapping = 'parity' num_time_slices = 50 n_ancillae = 9 qpe = get_algorithm_instance('QPE') qpe.setup_quantum_backend(backend='local_qasm_simulator', shots=100) state_in = get_initial_state_instance('HartreeFock') state_in.init_args(self.qubitOp.num_qubits, num_orbitals, qubit_mapping, two_qubit_reduction, num_particles) iqft = get_iqft_instance('STANDARD') iqft.init_args(n_ancillae) qpe.init_args(self.qubitOp, state_in, iqft, num_time_slices, n_ancillae, paulis_grouping='random', expansion_mode='suzuki', expansion_order=2, use_basis_gates=True) result = qpe.run() self.log.debug('measurement results: {}'.format( result['measurements'])) 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 energy from QPE: {}'.format(result['energy'])) self.log.debug('reference energy: {}'.format( self.reference_energy)) self.log.debug('ref energy (transformed): {}'.format( (self.reference_energy + result['translation']) * result['stretch'])) self.log.debug('ref binary str label: {}'.format( decimal_to_binary((self.reference_energy + result['translation']) * result['stretch'], max_num_digits=n_ancillae + 3, fractional_part_only=True))) np.testing.assert_approx_equal(result['energy'], self.reference_energy, significant=2)