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 init_params(self, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: input instance """ if algo_input is not None: raise AlgorithmError("Unexpected Input instance.") oracle_params = params.get(QuantumAlgorithm.SECTION_KEY_ORACLE) oracle = get_oracle_instance(oracle_params['name']) oracle.init_params(oracle_params) self.init_args(oracle)
def init_params(self, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: input instance """ if algo_input is not None: raise AlgorithmError("Unexpected Input instance.") grover_params = params.get(QuantumAlgorithm.SECTION_KEY_ALGORITHM) num_iterations = grover_params.get(Grover.PROP_NUM_ITERATIONS) oracle_params = params.get(QuantumAlgorithm.SECTION_KEY_ORACLE) oracle = get_oracle_instance(oracle_params['name']) oracle.init_params(oracle_params) self.init_args(oracle, num_iterations=num_iterations)
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)