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)
Exemple #2
0
    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)
Exemple #3
0
    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))
Exemple #4
0
def qc_solver(h_qop, num_spin_orbitals, num_particles, map_type, \
        qubit_reduction, aux_qops=None):
    # backends = Aer.backends()
    backends = IBMQ.backends(simulator=False)
    print(backends)
    # backend = IBMQ.get_backend('ibmq_qasm_simulator')
    # backend = IBMQ.get_backend('ibmq_16_melbourne')

    # backend = Aer.get_backend('statevector_simulator')
    backend = Aer.get_backend('qasm_simulator')

    # setup COBYLA optimizer
    max_eval = 1000
    cobyla = COBYLA(maxiter=max_eval)
    # setup hartreeFock state
    hf_state = HartreeFock(h_qop.num_qubits, num_spin_orbitals, num_particles,
            map_type, qubit_reduction)
    # setup UCCSD variational form
    var_form = UCCSD(h_qop.num_qubits, depth=1,
            num_orbitals=num_spin_orbitals, num_particles=num_particles,
            active_occupied=[0], active_unoccupied=[0],
            initial_state=hf_state, qubit_mapping=map_type,
            two_qubit_reduction=qubit_reduction, num_time_slices=1)

    # setup VQE
    vqe = VQE(h_qop, var_form, cobyla, operator_mode='matrix', \
            aux_operators=aux_qops)
    quantum_instance = QuantumInstance(backend=backend, shots=1024,
            max_credits=10)
    ret = vqe.run(quantum_instance)
    print(ret['aux_ops'])
    print('The computed ground state energy is: {:.12f}'.format(\
            ret['eigvals'][0]))
def solve_ibmqx_ising_qubo_nisq_ibmqx4(G, matrix_func, optimizer, p):
    backend = IBMQ.get_backend('ibmqx4')
    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_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_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
Exemple #8
0
 def test_vqe_direct(self, batch_mode):
     backend = Aer.get_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 run(self, quantum_instance=None, **kwargs):
        """Execute the algorithm with selected backend.

        Args:
            quantum_instance (QuantumInstance or BaseBackend): the experiemental setting.

        Returns:
            dict: results of an algorithm.
        """
        if not self.configuration.get('classical', False):
            if quantum_instance is None:
                AquaError(
                    "Quantum device or backend is needed since you are running quanutm algorithm."
                )
            if isinstance(quantum_instance, BaseBackend):
                quantum_instance = QuantumInstance(quantum_instance)
                quantum_instance.set_config(**kwargs)
            self._quantum_instance = quantum_instance
        return self._run()
Exemple #10
0
    def test_iqpe(self, distance):
        self.algorithm = 'IQPE'
        self.log.debug('Testing End-to-End with IQPE on H2 with '
                       'inter-atomic distance {}.'.format(distance))
        try:
            driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance),
                                 unit=UnitsType.ANGSTROM,
                                 charge=0,
                                 spin=0,
                                 basis='sto3g')
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')
        self.molecule = driver.run()
        qubit_mapping = 'parity'
        fer_op = FermionicOperator(h1=self.molecule.one_body_integrals, h2=self.molecule.two_body_integrals)
        self.qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10).two_qubit_reduced_operator(2)

        exact_eigensolver = ExactEigensolver(self.qubit_op, 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.qubit_op.num_qubits + (2 if two_qubit_reduction else 0)

        num_time_slices = 50
        num_iterations = 12
        state_in = HartreeFock(self.qubit_op.num_qubits, num_orbitals,
                               num_particles, qubit_mapping, two_qubit_reduction)
        iqpe = IQPE(self.qubit_op, state_in, num_time_slices, num_iterations,
                    paulis_grouping='random', expansion_mode='suzuki', expansion_order=2,
                    shallow_circuit_concat=True)
        backend = qiskit.Aer.get_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 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=num_iterations + 3,
            fractional_part_only=True
        )))

        np.testing.assert_approx_equal(result['energy'], self.reference_energy, significant=2)
Exemple #11
0
    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)
Exemple #12
0
    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_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.')
Exemple #14
0
    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.')
Exemple #15
0
 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'])
Exemple #16
0
    def test_qsvm_variational_directly(self):
        np.random.seed(self.random_seed)
        backend = Aer.get_backend('qasm_simulator')

        num_qubits = 2
        optimizer = SPSA(max_trials=10, c0=4.0, skip_calibration=True)
        optimizer.set_options(save_steps=1)
        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

        quantum_instance = QuantumInstance(backend, shots=1024, seed=self.random_seed, 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'], 0.0)
Exemple #17
0
    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)
Exemple #18
0
    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 = Aer.get_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)
Exemple #19
0
    if line.startswith('p'):
        # 8 is the size of the base rule set
        new_cnf = new_cnf + 'p cnf 9 ' + str(len(new_sat_lines) + 8) + '\n'
    else:
        # copy over comments or actual sat lines
        new_cnf = new_cnf + line + '\n'
for line in new_sat_lines:
    new_cnf = new_cnf + line + '\n'

print(new_cnf)

sat_oracle = SAT(new_cnf)
grover = Grover(sat_oracle)

backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=100)
result = grover.run(quantum_instance)
print(result['result'])

# potential moves are > 0 results
potential_moves = [x for x in result['result'] if x > 0]
if len(potential_moves) == 0:
    print("No move found! Choosing randomly")
elif 5 in potential_moves:
    print("Taking the centre! Move ", 4)
elif [x for x in potential_moves if x in [1, 3, 7, 9]]:
    print('Taking a corner! Choosing from ',
          [x for x in potential_moves if x in [1, 3, 7, 9]])
else:
    print('No special move, choosing from ', potential_moves)
backend = Aer.get_backend('statevector_simulator')
# setup COBYLA optimizer
max_eval = 200
cobyla = COBYLA(maxiter=max_eval)

# setup HartreeFock state
HF_state = HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles,
                       map_type, qubit_reduction)

# setup UCCSD variational form
var_form = UCCSD(qubitOp.num_qubits,
                 depth=1,
                 num_orbitals=num_spin_orbitals,
                 num_particles=num_particles,
                 active_occupied=[0],
                 active_unoccupied=[0, 1],
                 initial_state=HF_state,
                 qubit_mapping=map_type,
                 two_qubit_reduction=qubit_reduction,
                 num_time_slices=1)

# setup VQE
vqe = VQE(qubitOp, var_form, cobyla, 'matrix')
quantum_instance = QuantumInstance(backend=backend)
results = vqe.run(quantum_instance)
print('The computed ground state energy is: {:.12f}'.format(
    results['eigvals'][0]))
print('The total ground state energy is: {:.12f}'.format(
    results['eigvals'][0] + energy_shift + nuclear_repulsion_energy))
#print("Parameters: {}".format(results['opt_params']))
    def test_qsvm_kernel_binary_directly_statevector(self):

        ref_kernel_testing = np.array(
            [[0.1443953, 0.18170069, 0.47479649, 0.14691763],
             [0.33041779, 0.37663733, 0.02115561, 0.16106199]])

        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('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']

        np.testing.assert_array_almost_equal(result['kernel_matrix_testing'],
                                             ref_kernel_testing,
                                             decimal=4)

        self.assertEqual(len(result['svm']['support_vectors']), 4)
        np.testing.assert_array_almost_equal(result['svm']['support_vectors'],
                                             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'],
            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)

        np.testing.assert_array_almost_equal(
            loaded_svm.ret['kernel_matrix_testing'],
            ref_kernel_testing,
            decimal=4)

        if os.path.exists(file_path):
            try:
                os.remove(file_path)
            except:
                pass
Exemple #22
0
def run_algorithm(params, algo_input=None, json_output=False, backend=None):
    """
    Run algorithm as named in params, using params and algo_input as input data
    and returning a result dictionary

    Args:
        params (dict): Dictionary of params for algo and dependent objects
        algo_input (AlgorithmInput): Main input data for algorithm. Optional, an algo may run entirely from params
        json_output (bool): False for regular python dictionary return, True for json conversion
        backend (BaseBackend): Backend object to be used in place of backend name

    Returns:
        Result dictionary containing result of algorithm computation
    """
    _discover_on_demand()

    inputparser = InputParser(params)
    inputparser.parse()
    # before merging defaults attempts to find a provider for the backend in case no
    # provider was passed
    if backend is None and inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER) is None:
        backend_name = inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.NAME)
        if backend_name is not None:
            inputparser.set_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER, get_provider_from_backend(backend_name))

    inputparser.validate_merge_defaults()
    logger.debug('Algorithm Input: {}'.format(json.dumps(inputparser.get_sections(), sort_keys=True, indent=4)))

    algo_name = inputparser.get_section_property(PluggableType.ALGORITHM.value, JSONSchema.NAME)
    if algo_name is None:
        raise AquaError('Missing algorithm name')

    if algo_name not in local_pluggables(PluggableType.ALGORITHM):
        raise AquaError('Algorithm "{0}" missing in local algorithms'.format(algo_name))

    if algo_input is None:
        input_name = inputparser.get_section_property('input', JSONSchema.NAME)
        if input_name is not None:
            input_params = copy.deepcopy(inputparser.get_section_properties('input'))
            del input_params[JSONSchema.NAME]
            convert_json_to_dict(input_params)
            algo_input = get_pluggable_class(PluggableType.INPUT, input_name).from_params(input_params)

    algo_params = copy.deepcopy(inputparser.get_sections())
    algorithm = get_pluggable_class(PluggableType.ALGORITHM,
                                    algo_name).init_params(algo_params, algo_input)
    random_seed = inputparser.get_section_property(JSONSchema.PROBLEM, 'random_seed')
    algorithm.random_seed = random_seed
    quantum_instance = None
    # setup backend
    backend_provider = inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER)
    backend_name = inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.NAME)
    if backend_provider is not None and backend_name is not None:  # quantum algorithm
        backend_cfg = {k: v for k, v in inputparser.get_section(JSONSchema.BACKEND).items() if k not in [JSONSchema.PROVIDER, JSONSchema.NAME]}
        noise_params = backend_cfg.pop('noise_params', None)
        backend_cfg['config'] = {}
        backend_cfg['config']['noise_params'] = noise_params
        backend_cfg['seed'] = random_seed
        backend_cfg['seed_mapper'] = random_seed
        pass_manager = PassManager() if backend_cfg.pop('skip_transpiler', False) else None
        if pass_manager is not None:
            backend_cfg['pass_manager'] = pass_manager

        if backend is not None and isinstance(backend, BaseBackend):
            backend_cfg['backend'] = backend
        else:
            backend_cfg['backend'] = get_backend_from_provider(backend_provider, backend_name)

        quantum_instance = QuantumInstance(**backend_cfg)

    value = algorithm.run(quantum_instance)
    if isinstance(value, dict) and json_output:
        convert_dict_to_json(value)

    return value
    def test_qpe(self, distance):
        self.algorithm = 'QPE'
        self.log.debug(
            'Testing End-to-End with QPE on H2 with inter-atomic 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
        try:
            driver = cfg_mgr.get_driver_instance('PYSCF')
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')

        self.molecule = driver.run(section)
        qubit_mapping = 'parity'
        fer_op = FermionicOperator(h1=self.molecule.one_body_integrals,
                                   h2=self.molecule.two_body_integrals)
        self.qubit_op = fer_op.mapping(
            map_type=qubit_mapping,
            threshold=1e-10).two_qubit_reduced_operator(2)

        exact_eigensolver = ExactEigensolver(self.qubit_op, 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.qubit_op.num_qubits + \
            (2 if two_qubit_reduction else 0)

        num_time_slices = 50
        n_ancillae = 9

        state_in = HartreeFock(self.qubit_op.num_qubits, num_orbitals,
                               num_particles, qubit_mapping,
                               two_qubit_reduction)
        iqft = Standard(n_ancillae)

        qpe = QPE(self.qubit_op,
                  state_in,
                  iqft,
                  num_time_slices,
                  n_ancillae,
                  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 = qpe.run(quantum_instance)

        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)
Exemple #24
0
ansatz = RY(num_qubits, initial_state=init_state)

# operator from hamiltonian
qubit_op = Operator.load_from_dict(pauli_dict)

# get an optimizer
optimizer = COBYLA(maxiter=1000, disp=True)

# form the algorithm
vqe = VQE(qubit_op, ansatz, optimizer)

# get a backend
backend = get_aer_backend("statevector_simulator")

# get a quantum instance
qinstance = QuantumInstance(backend, shots=1024)

# ===================
# do the optimization
# ===================

result = vqe.run(qinstance)

# ================
# show the results
# ================

# output of the optimization
print(result)

# show the circuit
Exemple #25
0
    def test_qpe(self, qubitOp, simulator):
        self.algorithm = 'QPE'
        self.log.debug('Testing QPE')

        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
        n_ancillae = 6

        state_in = Custom(self.qubitOp.num_qubits,
                          state_vector=self.ref_eigenvec)
        iqft = Standard(n_ancillae)

        qpe = QPE(self.qubitOp,
                  state_in,
                  iqft,
                  num_time_slices,
                  n_ancillae,
                  paulis_grouping='random',
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = get_aer_backend(simulator)
        run_config = RunConfig(shots=100, max_credits=10, memory=False)
        quantum_instance = QuantumInstance(backend,
                                           run_config,
                                           pass_manager=PassManager())

        # run qpe
        result = qpe.run(quantum_instance)
        # self.log.debug('transformed operator paulis:\n{}'.format(self.qubitOp.print_operators('paulis')))

        # report result
        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.real + result['translation']) *
                result['stretch'],
                max_num_digits=n_ancillae + 3,
                fractional_part_only=True)))

        np.testing.assert_approx_equal(result['energy'],
                                       self.ref_eigenval.real,
                                       significant=2)
Exemple #26
0
    sol_found = False
    data_file = "QAOA_run2"
    seq_array = np.array(sequences)
    cost_array = np.array(costs)
    coeff_arr = np.array([1, Hamiltonian_penalty])
    insert_vals = np.array(inserts)

    times = []
    energies = []
    angle_arr = []
    states = []
    while not sol_found:
        print("Starting iteration p =", p)
        solver = QAOA(Hamilt, opt, p, initial_point=angles)
        simulator = Aer.get_backend(backend)  #IBMQ.get_backend(backend)
        instance = QuantumInstance(backend=simulator, shots=shots)
        start = time.time()
        result = solver.run(instance)
        run_time = time.time() - start

        state = result["eigvecs"][0]
        energy = result["eigvals"][0] + shift
        angles = list(result["opt_params"])
        states.append(state)
        energies.append(energy)
        angle_arr.append(angles)
        times.append(run_time)

        positions = MSA_column.sample_most_likely(state, rev_inds)
        for (key, value) in positions.items():
            print(key, value)