Exemplo n.º 1
0
    def test_hhl_random_hermitian(self):
        self.log.debug('Testing HHL with random hermitian matrix')

        hermitian_params = self.params
        hermitian_params['eigs']['num_ancillae'] = 4

        n = 2
        np.random.seed(0)
        matrix = rmg.random_hermitian(n, eigrange=[0, 1])
        vector = random(n)

        algo_input = LinearSystemInput()
        algo_input.matrix = matrix
        algo_input.vector = vector

        # run ExactLSsolver
        ref_result = run_algorithm(self.els_params, algo_input)
        ref_solution = ref_result['solution']
        ref_normed = ref_solution / np.linalg.norm(ref_solution)
        # run hhl
        hhl_result = run_algorithm(hermitian_params, algo_input)
        hhl_solution = hhl_result['solution']
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare result
        fidelity = state_fidelity(ref_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=2)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(ref_normed))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            hhl_result["probability_result"]))
Exemplo n.º 2
0
    def test_hhl_negative_eigs(self):
        self.log.debug('Testing HHL with matrix with negative eigenvalues')

        neg_params = self.params
        neg_params['eigs']['num_ancillae'] = 4
        neg_params['eigs']['negative_evals'] = True
        neg_params['reciprocal']['negative_evals'] = True

        n = 2
        np.random.seed(0)
        matrix = rmg.random_diag(n, eigrange=[-1, 1])
        vector = random(n)

        algo_input = LinearSystemInput()
        algo_input.matrix = matrix
        algo_input.vector = vector

        # run ExactLSsolver
        ref_result = run_algorithm(self.els_params, algo_input)
        ref_solution = ref_result['solution']
        ref_normed = ref_solution / np.linalg.norm(ref_solution)
        # run hhl
        hhl_result = run_algorithm(neg_params, algo_input)
        hhl_solution = hhl_result["solution"]
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare results
        fidelity = state_fidelity(ref_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=3)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(ref_normed))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            hhl_result["probability_result"]))
Exemplo n.º 3
0
    def test_hhl_diagonal_other_dim(self, n, num_ancillary):
        self.log.debug('Testing HHL with matrix dimension other than 2**n')

        dim_params = self.params
        dim_params['eigs']['num_ancillae'] = num_ancillary
        dim_params['eigs']['negative_evals'] = True
        dim_params['reciprocal']['negative_evals'] = True

        np.random.seed(0)
        matrix = rmg.random_diag(n, eigrange=[0, 1])
        vector = random(n)

        algo_input = LinearSystemInput()
        algo_input.matrix = matrix
        algo_input.vector = vector

        # run ExactLSsolver
        ref_result = run_algorithm(self.els_params, algo_input)
        ref_solution = ref_result['solution']
        ref_normed = ref_solution / np.linalg.norm(ref_solution)
        # run hhl
        hhl_result = run_algorithm(dim_params, algo_input)
        hhl_solution = hhl_result['solution']
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare result
        fidelity = state_fidelity(ref_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=1)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(ref_solution))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            hhl_result["probability_result"]))
Exemplo n.º 4
0
    def test_hhl_diagonal_qasm(self, vector):
        self.log.debug('Testing HHL simple test with qasm simulator')

        qasm_params = self.params
        matrix = [[1, 0], [0, 1]]
        qasm_params['input'] = {
            'name': 'LinearSystemInput',
            'matrix': matrix,
            'vector': vector
        }
        qasm_params['reciprocal']['scale'] = 0.5
        qasm_params['backend']['name'] = 'qasm_simulator'
        qasm_params['backend']['shots'] = 1000

        # run ExactLSsolver
        self.els_params['input'] = qasm_params['input']
        ref_result = run_algorithm(self.els_params)
        ref_solution = ref_result['solution']
        ref_normed = ref_solution / np.linalg.norm(ref_solution)
        # run hhl
        hhl_result = run_algorithm(qasm_params)
        hhl_solution = hhl_result['solution']
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare results
        fidelity = state_fidelity(ref_normed, hhl_normed)
        self.assertGreater(fidelity, 0.8)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(ref_normed))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            hhl_result["probability_result"]))
Exemplo n.º 5
0
    def test_hhl_diagonal_longdivison(self, vector):
        self.log.debug('Testing HHL simple test in mode LongDivision and '
                       'statevector simulator')

        ld_params = self.params
        matrix = [[1, 0], [0, 1]]
        ld_params['input'] = {
            'name': 'LinearSystemInput',
            'matrix': matrix,
            'vector': vector
        }
        ld_params['reciprocal']['name'] = 'LongDivision'
        ld_params['reciprocal']['scale'] = 1.0

        # run ExactLSsolver
        self.els_params['input'] = ld_params['input']
        ref_result = run_algorithm(self.els_params)
        ref_solution = ref_result['solution']
        ref_normed = ref_solution / np.linalg.norm(ref_solution)
        # run hhl
        hhl_result = run_algorithm(ld_params)
        hhl_solution = hhl_result['solution']
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare results
        fidelity = state_fidelity(ref_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=5)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(ref_normed))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            hhl_result["probability_result"]))
Exemplo n.º 6
0
    def test_hhl_diagonal_negative(self, vector):
        self.log.debug('Testing HHL simple test in mode Lookup with '
                       'statevector simulator')

        neg_params = self.params
        matrix = [[1, 0], [0, 1]]
        neg_params['input'] = {
            'name': 'LinearSystemInput',
            'matrix': matrix,
            'vector': vector
        }
        neg_params['eigs']['negative_evals'] = True
        neg_params['reciprocal']['negative_evals'] = True
        neg_params['eigs']['num_ancillae'] = 4

        # run ExactLSsolver
        self.els_params['input'] = neg_params['input']
        ref_result = run_algorithm(self.els_params)
        ref_solution = ref_result['solution']
        ref_normed = ref_solution / np.linalg.norm(ref_solution)
        # run hhl
        hhl_result = run_algorithm(neg_params)
        hhl_solution = hhl_result['solution']
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare results
        fidelity = state_fidelity(ref_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=5)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(ref_normed))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            hhl_result["probability_result"]))
Exemplo n.º 7
0
 def test_qgan_training_run_algo_torch(self):
     try:
         algo_input = QGANInput(self._real_data, self._bounds)
         trained_statevector = run_algorithm(params=self._params_torch, algo_input=algo_input,
                                             backend=BasicAer.get_backend('statevector_simulator'))
         trained_qasm = run_algorithm(self._params_torch, algo_input, backend=BasicAer.get_backend('qasm_simulator'))
         self.assertAlmostEqual(trained_qasm['rel_entr'], trained_statevector['rel_entr'], delta=0.1)
     except Exception as e:
         self.skipTest("Torch may not be installed: '{}'".format(str(e)))
Exemplo n.º 8
0
 def test_qgan_training_run_algo_numpy(self):
     algo_input = QGANInput(self._real_data, self._bounds)
     trained_statevector = run_algorithm(
         params=self._params_numpy,
         algo_input=algo_input,
         backend=BasicAer.get_backend('statevector_simulator'))
     trained_qasm = run_algorithm(
         self._params_numpy,
         algo_input,
         backend=BasicAer.get_backend('qasm_simulator'))
     self.assertAlmostEqual(trained_qasm['rel_entr'],
                            trained_statevector['rel_entr'],
                            delta=0.1)
Exemplo n.º 9
0
    def test_hhl_diagonal_qasm(self, vector):
        self.log.debug('Testing HHL simple test with qasm simulator')

        qasm_params = self.params
        matrix = [[1, 0], [0, 1]]
        qasm_params['input'] = {
            'name': 'LinearSystemInput',
            'matrix': matrix,
            'vector': vector
        }
        qasm_params['backend']['name'] = 'qasm_simulator'
        qasm_params['backend']['shots'] = 600

        # run hhl
        result = run_algorithm(qasm_params)
        hhl_solution = result["solution_hhl"]
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)
        # linear algebra solution
        linalg_solution = np.linalg.solve(matrix, vector)
        linalg_normed = linalg_solution / np.linalg.norm(linalg_solution)

        # compare result
        fidelity = abs(linalg_normed.dot(hhl_normed.conj()))**2
        self.assertTrue(fidelity > 0.8)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(linalg_solution))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            result["probability_result"]))
Exemplo n.º 10
0
    def test_vqc_with_raw_feature_vector_on_wine(self):
        """ vqc with raw features vector on wine test """
        feature_dim = 4  # dimension of each data point
        training_dataset_size = 8
        testing_dataset_size = 4

        _, training_input, test_input, _ = _wine_data(
            training_size=training_dataset_size,
            test_size=testing_dataset_size,
            n=feature_dim
        )
        params = {
            'problem': {'name': 'classification',
                        'random_seed': self.seed,
                        'skip_qobj_validation': True
                        },
            'algorithm': {'name': 'VQC'},
            'backend': {'provider': 'qiskit.BasicAer', 'name': 'statevector_simulator'},
            'optimizer': {'name': 'COBYLA', 'maxiter': 100},
            'variational_form': {'name': 'RYRZ', 'depth': 3},
            'feature_map': {'name': 'RawFeatureVector', 'feature_dimension': feature_dim}
        }

        result = run_algorithm(params, ClassificationInput(training_input, test_input))
        self.log.debug(result['testing_accuracy'])

        self.assertGreater(result['testing_accuracy'], 0.8)
Exemplo n.º 11
0
    def test_vertex_cover_vqe(self):
        algorithm_cfg = {
            'name': 'VQE',
            'operator_mode': 'grouped_paulis',
            'max_evals_grouped': 2
        }

        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 = BasicAer.get_backend('qasm_simulator')
        result = run_algorithm(params, self.algo_input, backend=backend)
        x = vertex_cover.sample_most_likely(len(self.w), result['eigvecs'][0])
        sol = vertex_cover.get_graph_solution(x)
        oracle = self.brute_force()
        self.assertEqual(np.count_nonzero(sol), oracle)
Exemplo n.º 12
0
 def test_ee_via_run_algorithm(self):
     params = {'algorithm': {'name': 'ExactEigensolver'}}
     result = run_algorithm(params, self.algo_input)
     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])
Exemplo n.º 13
0
    def test_set_packing_vqe(self):
        try:
            from qiskit import Aer
        except Exception as e:
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(e)))
            return

        algorithm_cfg = {
            'name': 'VQE',
            'operator_mode': 'grouped_paulis',
            'max_evals_grouped': 2
        }

        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 = Aer.get_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)
Exemplo n.º 14
0
    def test_qsvm_variational_statevector_via_run_algorithm(self):
        np.random.seed(self.random_seed)
        params = {
            'problem': {
                'name': 'svm_classification',
                'random_seed': self.random_seed
            },
            'algorithm': {
                'name': 'QSVM.Variational'
            },
            'backend': {
                'provider': 'qiskit.BasicAer',
                'name': 'statevector_simulator'
            },
            'optimizer': {
                'name': 'COBYLA'
            },
            'variational_form': {
                'name': 'RYRZ',
                'depth': 3
            },
            'feature_map': {
                'name': 'SecondOrderExpansion',
                'depth': 2
            }
        }
        result = run_algorithm(params, self.svm_input)
        ref_train_loss = 0.1059404
        np.testing.assert_array_almost_equal(result['training_loss'],
                                             ref_train_loss,
                                             decimal=4)

        self.assertEqual(result['testing_accuracy'], 0.5)
Exemplo n.º 15
0
    def test_partition_vqe(self):
        algorithm_cfg = {
            'name': 'VQE',
            'operator_mode': 'grouped_paulis',
            'max_evals_grouped': 2
        }

        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 = BasicAer.get_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
Exemplo n.º 16
0
    def test_hhl_diagonal_sv(self, vector):
        self.log.debug('Testing HHL simple test in mode Lookup with '
                       'statevector simulator')

        matrix = [[1, 0], [0, 1]]
        self.params['input'] = {
            'name': 'LinearSystemInput',
            'matrix': matrix,
            'vector': vector
        }

        # run hhl
        result = run_algorithm(self.params)
        hhl_solution = result['solution_hhl']
        hhl_normed = hhl_solution/np.linalg.norm(hhl_solution)
        # linear algebra solution
        linalg_solution = np.linalg.solve(matrix, vector)
        linalg_normed = linalg_solution/np.linalg.norm(linalg_solution)

        # compare result
        fidelity = state_fidelity(linalg_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=5)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(linalg_solution))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.
                       format(result["probability_result"]))
 def test_portfolio_diversification(self):
     """ portfolio diversification test """
     # Something of an integration test
     # Solve the problem in a classical fashion via CPLEX and compare the solution
     # Note that CPLEX uses a completely different integer linear programming formulation.
     x = None
     try:
         classical_optimizer = ClassicalOptimizer(self.instance, self.n,
                                                  self.q)
         x, classical_cost = classical_optimizer.cplex_solution()
     except Exception:  # pylint: disable=broad-except
         # This test should not focus on the availability of CPLEX, so we just eat the exception.
         self.skipTest("CPLEX may be missing.")
     # Solve the problem using the exact eigensolver
     params = {
         'problem': {
             'name': 'ising'
         },
         'algorithm': {
             'name': 'ExactEigensolver'
         }
     }
     result = run_algorithm(params, self.algo_input)
     quantum_solution = get_portfoliodiversification_solution(
         self.instance, self.n, self.q, result)
     ground_level = get_portfoliodiversification_value(
         self.instance, self.n, self.q, quantum_solution)
     if x is not None:
         np.testing.assert_approx_equal(ground_level, classical_cost)
         np.testing.assert_array_almost_equal(quantum_solution, x, 5)
Exemplo n.º 18
0
    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 = BasicAer.get_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'])
Exemplo n.º 19
0
    def test_exact_cover_vqe(self):
        """ Exact Cover VQE test """
        algorithm_cfg = {'name': 'VQE', 'max_evals_grouped': 2}

        optimizer_cfg = {'name': 'COBYLA'}

        var_form_cfg = {'name': 'RYRZ', 'depth': 5}

        params = {
            'problem': {
                'name': 'ising',
                'random_seed': 10598
            },
            'algorithm': algorithm_cfg,
            'optimizer': optimizer_cfg,
            'variational_form': var_form_cfg
        }
        backend = BasicAer.get_backend('statevector_simulator')
        result = run_algorithm(params, self.algo_input, backend=backend)
        x = sample_most_likely(result['eigvecs'][0])
        ising_sol = exact_cover.get_solution(x)
        oracle = self._brute_force()
        self.assertEqual(
            exact_cover.check_solution_satisfiability(ising_sol,
                                                      self.list_of_subsets),
            oracle)
Exemplo n.º 20
0
    def test_clique_vqe(self):
        algorithm_cfg = {
            'name': 'VQE',
            'operator_mode': 'matrix',
            'max_evals_grouped': 2
        }

        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 = BasicAer.get_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)
Exemplo n.º 21
0
    def test_hhl_diagonal_longdivison_sv(self, vector):
        self.log.debug('Testing HHL simple test in mode LongDivision and '
                       'statevector simulator')

        ld_params = self.params
        matrix = [[1, 0], [0, 1]]
        ld_params['input'] = {
            'name': 'LinearSystemInput',
            'matrix': matrix,
            'vector': vector
        }
        ld_params['reciprocal']['name'] = 'LongDivision'
        ld_params['reciprocal']['scale'] = 1.0

        # run hhl
        result = run_algorithm(ld_params)
        hhl_solution = result["solution_hhl"]
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)
        # linear algebra solution
        linalg_solution = np.linalg.solve(matrix, vector)
        linalg_normed = linalg_solution / np.linalg.norm(linalg_solution)

        # compare result
        fidelity = abs(linalg_normed.dot(hhl_normed.conj()))**2
        np.testing.assert_approx_equal(fidelity, 1, significant=5)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(linalg_solution))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            result["probability_result"]))
Exemplo n.º 22
0
    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 = Aer.get_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)
Exemplo n.º 23
0
    def test_qsvm_variational_with_minibatching(self):
        np.random.seed(self.random_seed)
        params = {
            'problem': {'name': 'svm_classification', 'random_seed': self.random_seed},
            'algorithm': {'name': 'QSVM.Variational', 'minibatch_size': 2},
            'backend': {'provider': 'qiskit.BasicAer', 'name': 'qasm_simulator', 'shots': 1024},
            'optimizer': {'name': 'SPSA', 'max_trials': 30, 'save_steps': 1},
            'variational_form': {'name': 'RYRZ', 'depth': 3},
            'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2}
        }
        result = run_algorithm(params, self.svm_input)

        # The results will differ from the above even though the batch size is larger than the trainingset size due
        # to the shuffle during minibatching
        #  minibatching_ref_opt_params = np.asarray([-18.8965, -36.9197,   2.3568,  14.9087,  43.8633,   7.1394,
        #                                          12.1298,  23.7219,  36.5693,  21.0561,  37.5775, -22.4538,
        #                                          41.1386, -54.3177, -27.3063,  31.3858])
        minibatching_ref_opt_params = np.array([2.4271, -21.5146, 4.4769, 21.0945, 8.4016, -9.7612,
                                                13.9343, 42.8698, 16.8601, -22.8767, 19.5411, -27.62,
                                                3.423, -25.9107, 21.0475, 21.895])

        # minibatching_ref_train_loss = 1.02335933
        minibatching_ref_train_loss = 0.6519675

        np.testing.assert_array_almost_equal(result['opt_params'], minibatching_ref_opt_params, decimal=4)
        np.testing.assert_array_almost_equal(result['training_loss'], minibatching_ref_train_loss, decimal=8)

        # self.assertEqual(result['testing_accuracy'], .5)
        self.assertEqual(result['testing_accuracy'], 0.0)
Exemplo n.º 24
0
def classical_svm(train_input, test_input, class_labels, n):
    temp = [test_input[k] for k in test_input]
    total_array = np.concatenate(temp)

    # Select parameters based on number of classes in data
    if len(class_labels) > 2:
        aqua_dict = {
            'problem': {'name': 'classification', 'random_seed': 100},
            'algorithm': {
                'name': 'SVM'
            },
            'multiclass_extension': {'name': 'AllPairs'}
        }
    else:
        aqua_dict = {
            'problem': {'name': 'classification', 'random_seed': 100},
            'algorithm': {
                'name': 'SVM'
            }
        }

    algo_input = ClassificationInput
    algo_input.training_dataset = train_input
    algo_input.test_dataset = test_input
    algo_input.datapoints = total_array

    # Run the classical SVM algorithm
    result = run_algorithm(aqua_dict, algo_input)

    # Print model values
    #  for k,v in result.items():
    #      print("'{}' : {}".format(k, v))

    return result
Exemplo n.º 25
0
    def test_qsvm_kernel_multiclass_all_pairs(self):

        backend = BasicAer.get_backend('qasm_simulator')
        training_input = {'A': np.asarray([[0.6560706, 0.17605998], [0.25776033, 0.47628296],
                                           [0.8690704, 0.70847635]]),
                          'B': np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951],
                                           [0.49156185, -0.3660534]]),
                          'C': np.asarray([[-0.68088231, 0.46824423], [-0.56167659, 0.65270294],
                                           [-0.82139073, 0.29941512]])}

        test_input = {'A': np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544],
                                       [0.48142649, 0.15931707]]),
                      'B': np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828],
                                       [0.06183066, -0.53376975]]),
                      'C': np.asarray([[-0.74561108, 0.27047295], [-0.69942965, 0.11885162],
                                       [-0.66489165, 0.1181712]])}

        total_array = np.concatenate((test_input['A'], test_input['B'], test_input['C']))

        params = {
            'problem': {'name': 'svm_classification', 'random_seed': self.random_seed},
            'algorithm': {
                'name': 'QSVM.Kernel',
            },
            'backend': {'shots': self.shots},
            'multiclass_extension': {'name': 'AllPairs'},
            'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': [[0, 1]]}
        }

        algo_input = SVMInput(training_input, test_input, total_array)
        result = run_algorithm(params, algo_input, backend=backend)
        self.assertAlmostEqual(result['testing_accuracy'], 0.444444444, places=4,
                               msg='Please ensure you are using C++ simulator')
        self.assertEqual(result['predicted_classes'], ['A', 'A', 'C', 'A',
                                                       'A', 'A', 'A', 'C', 'C'])
Exemplo n.º 26
0
    def test_hhl_negative_eigs_sv(self):
        self.log.debug('Testing HHL with matrix with negative eigenvalues')

        neg_params = self.params
        neg_params['eigs']['num_ancillae'] = 4
        neg_params['eigs']['negative_evals'] = True
        neg_params['reciprocal']['negative_evals'] = True

        n = 2
        matrix = rmg.random_diag(n, eigrange=[-1, 1])
        vector = random(2)

        algo_input = LinearSystemInput()
        algo_input.matrix = matrix
        algo_input.vector = vector

        # run hhl
        result = run_algorithm(neg_params, algo_input)
        hhl_solution = result["solution_hhl"]
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)
        # linear algebra solution
        linalg_solution = np.linalg.solve(matrix, vector)
        linalg_normed = linalg_solution / np.linalg.norm(linalg_solution)

        # compare result
        fidelity = abs(linalg_normed.dot(hhl_normed.conj()))**2
        np.testing.assert_approx_equal(fidelity, 1, significant=3)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(linalg_solution))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            result["probability_result"]))
Exemplo n.º 27
0
    def test_vqe_via_run_algorithm(self):

        coupling_map = [[0, 1]]
        basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']

        params = {
            'algorithm': {
                'name': 'VQE'
            },
            'backend': {
                'name': 'statevector_simulator',
                'provider': 'qiskit.Aer',
                'shots': 1,
                'coupling_map': coupling_map,
                'basis_gates': basis_gates
            },
        }
        result = run_algorithm(params, self.algo_input)
        self.assertAlmostEqual(result['energy'], -1.85727503)
        np.testing.assert_array_almost_equal(result['eigvals'], [-1.85727503],
                                             5)
        np.testing.assert_array_almost_equal(result['opt_params'], [
            -0.58294401, -1.86141794, -1.97209632, -0.54796022, -0.46945572,
            2.60114794, -1.15637845, 1.40498879, 1.14479635, -0.48416694,
            -0.66608349, -1.1367579, -2.67097002, 3.10214631, 3.10000313,
            0.37235089
        ], 5)
        self.assertIn('eval_count', result)
        self.assertIn('eval_time', result)
Exemplo n.º 28
0
    def test_hhl_random_hermitian_sv(self):
        self.log.debug('Testing HHL with random hermitian matrix')

        hermitian_params = self.params
        hermitian_params['eigs']['num_ancillae'] = 4

        n = 2
        matrix = rmg.random_hermitian(n, eigrange=[0, 1])
        vector = random(2)

        algo_input = LinearSystemInput()
        algo_input.matrix = matrix
        algo_input.vector = vector

        # run hhl
        result = run_algorithm(hermitian_params, algo_input)
        hhl_solution = result["solution_hhl"]
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)
        # linear algebra solution
        linalg_solution = np.linalg.solve(matrix, vector)
        linalg_normed = linalg_solution / np.linalg.norm(linalg_solution)

        # compare result
        fidelity = abs(linalg_normed.dot(hhl_normed.conj()))**2
        np.testing.assert_approx_equal(fidelity, 1, significant=2)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(linalg_solution))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            result["probability_result"]))
Exemplo n.º 29
0
    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)
Exemplo n.º 30
0
    def test_hhl_diagonal_negative_sv(self, vector):
        self.log.debug('Testing HHL simple test in mode Lookup with '
                       'statevector simulator')

        neg_params = self.params
        matrix = [[1, 0], [0, 1]]
        neg_params['input'] = {
            'name': 'LinearSystemInput',
            'matrix': matrix,
            'vector': vector
        }
        neg_params['eigs']['negative_evals'] = True
        neg_params['reciprocal']['negative_evals'] = True
        neg_params['eigs']['num_ancillae'] = 4

        # run hhl
        result = run_algorithm(neg_params)
        hhl_solution = result["solution_hhl"]
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)
        # linear algebra solution
        linalg_solution = np.linalg.solve(matrix, vector)
        linalg_normed = linalg_solution / np.linalg.norm(linalg_solution)

        # compare result
        fidelity = abs(linalg_normed.dot(hhl_normed.conj()))**2
        np.testing.assert_approx_equal(fidelity, 1, significant=5)

        self.log.debug('HHL solution vector:       {}'.format(hhl_solution))
        self.log.debug('algebraic solution vector: {}'.format(linalg_solution))
        self.log.debug('fidelity HHL to algebraic: {}'.format(fidelity))
        self.log.debug('probability of result:     {}'.format(
            result["probability_result"]))