예제 #1
0
    def test_grover(self, input_file, incremental=True, num_iterations=1):
        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(',')
        ]
        sat_oracle = get_oracle_instance('SAT')
        sat_oracle.init_args(buf)

        grover = get_algorithm_instance('Grover')
        grover.setup_quantum_backend(backend='qasm_simulator', shots=100)
        grover.init_args(sat_oracle,
                         num_iterations=num_iterations,
                         incremental=incremental)

        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))
        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.')
예제 #2
0
    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)
예제 #3
0
 def test_sat_oracle(self, cnf_str, sols):
     num_shots = 1024
     sat = get_oracle_instance('SAT')
     sat.init_args(cnf_str)
     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.measure(sat._qr_outcome, m)
         counts = q_execute(qc, 'local_qasm_simulator',
                            shots=num_shots).result().get_counts(qc)
         if assignment in sols:
             assert (counts['1'] == num_shots)
         else:
             assert (counts['0'] == num_shots)
예제 #4
0
    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)