Esempio n. 1
0
    def test_qaoa(self, w, prob, m, solutions):
        """ QAOA test """
        seed = 0
        aqua_globals.random_seed = seed
        self.log.debug('Testing %s-step QAOA with MaxCut on graph\n%s', prob,
                       w)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, offset = max_cut.get_operator(w)

        qaoa = QAOA(qubit_op, optimizer, prob, mixer=m)
        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)

        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result['eigvecs'][0])
        graph_solution = max_cut.get_graph_solution(x)
        self.log.debug('energy:             %s', result['energy'])
        self.log.debug('time:               %s', result['eval_time'])
        self.log.debug('maxcut objective:   %s', result['energy'] + offset)
        self.log.debug('solution:           %s', graph_solution)
        self.log.debug('solution objective: %s', max_cut.max_cut_value(x, w))
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
Esempio n. 2
0
    def test_set_packing_vqe(self):
        """ set packing vqe test """
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        algorithm_cfg = {'name': 'VQE', '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 = sample_most_likely(result['eigvecs'][0])
        ising_sol = set_packing.get_solution(x)
        oracle = self._brute_force()
        self.assertEqual(np.count_nonzero(ising_sol), oracle)
Esempio n. 3
0
 def test_tsp(self):
     """ TSP test """
     algo = NumPyMinimumEigensolver(self.qubit_op)
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     order = tsp.get_tsp_solution(x)
     np.testing.assert_array_equal(order, [1, 2, 0])
Esempio n. 4
0
 def test_tsp(self):
     """ TSP test """
     algo = ExactEigensolver(self.qubit_op, k=1)
     result = algo.run()
     x = sample_most_likely(result['eigvecs'][0])
     order = tsp.get_tsp_solution(x)
     np.testing.assert_array_equal(order, [1, 2, 0])
Esempio n. 5
0
    def test_vertex_cover_vqe(self):
        """ Vertex Cover VQE test """
        algorithm_cfg = {'name': 'VQE', 'max_evals_grouped': 2}

        optimizer_cfg = {'name': 'SPSA', 'max_trials': 200}

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

        params = {
            'problem': {
                'name': 'ising',
                'random_seed': self.seed
            },
            '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 = sample_most_likely(result['eigvecs'][0])
        sol = vertex_cover.get_graph_solution(x)
        oracle = self._brute_force()
        self.assertEqual(np.count_nonzero(sol), oracle)
Esempio n. 6
0
    def test_set_packing_vqe(self):
        """ set packing vqe test """
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        aqua_globals.random_seed = 50
        result = VQE(self.qubit_op,
                     RY(self.qubit_op.num_qubits,
                        depth=5,
                        entanglement='linear'),
                     SPSA(max_trials=200),
                     max_evals_grouped=2).run(
                         QuantumInstance(
                             Aer.get_backend('qasm_simulator'),
                             seed_simulator=aqua_globals.random_seed,
                             seed_transpiler=aqua_globals.random_seed))
        x = sample_most_likely(result['eigvecs'][0])
        ising_sol = set_packing.get_solution(x)
        oracle = self._brute_force()
        self.assertEqual(np.count_nonzero(ising_sol), oracle)
Esempio n. 7
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)
Esempio n. 8
0
    def test_clique_vqe(self):
        """ VQE Clique test """
        algorithm_cfg = {'name': 'VQE', '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 = sample_most_likely(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)
Esempio n. 9
0
    def test_graph_partition_vqe(self):
        """ Graph Partition VQE test """
        algorithm_cfg = {'name': 'VQE', 'max_evals_grouped': 2}

        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 = BasicAer.get_backend('statevector_simulator')
        result = run_algorithm(params, self.algo_input, backend=backend)
        x = sample_most_likely(result['eigvecs'][0])
        # check against the oracle
        ising_sol = graph_partition.get_graph_solution(x)
        np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1])
        oracle = self._brute_force()
        self.assertEqual(graph_partition.objective_value(x, self.w), oracle)
Esempio n. 10
0
 def test_partition_direct(self):
     """ Partition Direct test """
     algo = ExactEigensolver(self.algo_input.qubit_op,
                             k=1,
                             aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result['eigvecs'][0])
     np.testing.assert_array_equal(x, [0, 1, 0])
Esempio n. 11
0
 def test_vertex_cover(self):
     """ Vertex Cover test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     sol = vertex_cover.get_graph_solution(x)
     np.testing.assert_array_equal(sol, [0, 1, 1])
     oracle = self._brute_force()
     self.assertEqual(np.count_nonzero(sol), oracle)
Esempio n. 12
0
 def test_portfolio(self):
     """ portfolio test """
     algo = ExactEigensolver(self.qubit_op)
     result = algo.run()
     selection = sample_most_likely(result['eigvecs'][0])
     value = portfolio.portfolio_value(selection, self.muu, self.sigma,
                                       self.risk, self.budget, self.penalty)
     np.testing.assert_array_equal(selection, [1, 0, 0, 1])
     self.assertAlmostEqual(value, -0.0055989)
Esempio n. 13
0
 def test_clique_direct(self):
     """ Clique Direct test """
     algo = ExactEigensolver(self.qubit_op, k=1, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(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)
Esempio n. 14
0
 def test_set_packing(self):
     """ set packing test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     ising_sol = set_packing.get_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 1])
     oracle = self._brute_force()
     self.assertEqual(np.count_nonzero(ising_sol), oracle)
Esempio n. 15
0
 def test_vertex_cover_direct(self):
     """ Vertex Cover Direct test """
     algo = ExactEigensolver(self.qubit_op, k=1, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result['eigvecs'][0])
     sol = vertex_cover.get_graph_solution(x)
     np.testing.assert_array_equal(sol, [0, 1, 1])
     oracle = self._brute_force()
     self.assertEqual(np.count_nonzero(sol), oracle)
Esempio n. 16
0
 def test_set_packing_direct(self):
     """ set packing direct test """
     algo = ExactEigensolver(self.qubit_op, k=1, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result['eigvecs'][0])
     ising_sol = set_packing.get_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 1])
     oracle = self._brute_force()
     self.assertEqual(np.count_nonzero(ising_sol), oracle)
Esempio n. 17
0
 def test_stable_set(self):
     """ Stable set test """
     algo = ExactEigensolver(self.qubit_op, k=1, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result['eigvecs'][0])
     self.assertAlmostEqual(result['energy'], -29.5)
     self.assertAlmostEqual(result['energy'] + self.offset, -25.0)
     ising_sol = stable_set.get_graph_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 0, 1, 1, 1])
     self.assertEqual(stable_set.stable_set_value(x, self.w), (3.0, False))
Esempio n. 18
0
 def test_graph_partition_direct(self):
     """ Graph Partition Direct test """
     algo = ExactEigensolver(self.qubit_op, k=1, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result['eigvecs'][0])
     # check against the oracle
     ising_sol = graph_partition.get_graph_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1])
     oracle = self._brute_force()
     self.assertEqual(graph_partition.objective_value(x, self.w), oracle)
Esempio n. 19
0
 def test_graph_partition(self):
     """ Graph Partition test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     # check against the oracle
     ising_sol = graph_partition.get_graph_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1])
     oracle = self._brute_force()
     self.assertEqual(graph_partition.objective_value(x, self.w), oracle)
Esempio n. 20
0
 def test_clique(self):
     """ Clique test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     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)
Esempio n. 21
0
 def test_exact_cover_direct(self):
     """ Exact Cover Direct test """
     algo = ExactEigensolver(self.qubit_op, k=1, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result['eigvecs'][0])
     ising_sol = exact_cover.get_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0])
     oracle = self._brute_force()
     self.assertEqual(exact_cover.check_solution_satisfiability(ising_sol, self.list_of_subsets),
                      oracle)
Esempio n. 22
0
 def test_set_packing(self):
     """ set packing test """
     params = {
         'problem': {'name': 'ising'},
         'algorithm': {'name': 'ExactEigensolver'}
     }
     result = run_algorithm(params, self.algo_input)
     x = sample_most_likely(result['eigvecs'][0])
     ising_sol = set_packing.get_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 1])
     oracle = self._brute_force()
     self.assertEqual(np.count_nonzero(ising_sol), oracle)
    def _run_knapsack(values, weights, max_weight):
        qubit_op, _ = knapsack.get_operator(values, weights, max_weight)

        algo = NumPyMinimumEigensolver(qubit_op)
        result = algo.run()
        x = sample_most_likely(result.eigenstate)

        solution = knapsack.get_solution(x, values)
        value, weight = knapsack.knapsack_value_weight(solution, values,
                                                       weights)

        return solution, value, weight
Esempio n. 24
0
 def test_clique(self):
     """ Clique test """
     params = {
         'problem': {'name': 'ising'},
         'algorithm': {'name': 'ExactEigensolver'}
     }
     result = run_algorithm(params, EnergyInput(self.qubit_op))
     x = sample_most_likely(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)
Esempio n. 25
0
    def run_simulation(self, backend):
        #
        # Random 3-regular graph with 12 nodes
        #
        n = int(os.environ.get("N", "4"))
        graph = nx.random_regular_graph(3, n)
        for e in graph.edges():
            graph[e[0]][e[1]]['weight'] = 1.0

        # Compute the weight matrix from the graph
        w = np.zeros([n, n])
        for i in range(n):
            for j in range(n):
                temp = graph.get_edge_data(i, j, default=0)
                if temp != 0:
                    w[i, j] = temp["weight"]

        # Create an Ising Hamiltonian with docplex.
        mdl = Model(name="max_cut")
        mdl.node_vars = mdl.binary_var_list(list(range(n)), name="node")
        maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] *
                              (1 - mdl.node_vars[j]) for i in range(n)
                              for j in range(n))
        mdl.maximize(maxcut_func)
        qubit_op, offset = docplex.get_operator(mdl)

        # Run quantum algorithm QAOA on qasm simulator
        seed = int(os.environ.get("SEED", "40598"))
        aqua_globals.random_seed = seed

        spsa = SPSA(max_trials=250)
        qaoa = QAOA(qubit_op, spsa, p=5, max_evals_grouped=4)

        quantum_instance = QuantumInstance(backend,
                                           shots=1024,
                                           seed_simulator=seed,
                                           seed_transpiler=seed,
                                           optimization_level=0)
        result = qaoa.run(quantum_instance)

        x = sample_most_likely(result["eigvecs"][0])
        result["solution"] = max_cut.get_graph_solution(x)
        result["solution_objective"] = max_cut.max_cut_value(x, w)
        result["maxcut_objective"] = result["energy"] + offset
        """
        print("energy:", result["energy"])
        print("time:", result["eval_time"])
        print("max-cut objective:", result["energy"] + offset)
        print("solution:", max_cut.get_graph_solution(x))
        print("solution objective:", max_cut.max_cut_value(x, w))
        """
        return result
Esempio n. 26
0
    def test_vertex_cover(self):
        """ Vertex cover test """
        params = {
            'problem': {'name': 'ising'},
            'algorithm': {'name': 'ExactEigensolver'}
        }
        result = run_algorithm(params, EnergyInput(self.qubit_op))

        x = sample_most_likely(result['eigvecs'][0])
        sol = vertex_cover.get_graph_solution(x)
        np.testing.assert_array_equal(sol, [0, 1, 1])
        oracle = self._brute_force()
        self.assertEqual(np.count_nonzero(sol), oracle)
Esempio n. 27
0
 def test_exact_cover(self):
     """ Exact Cover test """
     params = {
         'problem': {'name': 'ising'},
         'algorithm': {'name': 'ExactEigensolver'}
     }
     result = run_algorithm(params, EnergyInput(self.qubit_op))
     x = sample_most_likely(result['eigvecs'][0])
     ising_sol = exact_cover.get_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0])
     oracle = self._brute_force()
     self.assertEqual(exact_cover.check_solution_satisfiability(ising_sol, self.list_of_subsets),
                      oracle)
Esempio n. 28
0
    def test_portfolio_qaoa(self):
        """ portfolio test with QAOA """
        qaoa = QAOA(self.qubit_op, COBYLA(maxiter=500))

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend=backend,
                                           seed_simulator=self.seed,
                                           seed_transpiler=self.seed)
        result = qaoa.run(quantum_instance)
        selection = sample_most_likely(result['eigvecs'][0])
        value = portfolio.portfolio_value(selection, self.muu, self.sigma,
                                          self.risk, self.budget, self.penalty)
        np.testing.assert_array_equal(selection, [1, 0, 0, 1])
        self.assertAlmostEqual(value, -0.0055989)
Esempio n. 29
0
    def test_partition(self):
        """ Partition test """
        params = {
            'problem': {
                'name': 'ising'
            },
            'algorithm': {
                'name': 'ExactEigensolver'
            }
        }
        result = run_algorithm(params, EnergyInput(self.qubit_op))

        x = sample_most_likely(result['eigvecs'][0])
        np.testing.assert_array_equal(x, [0, 1, 0])
Esempio n. 30
0
 def test_clique_vqe(self):
     """ VQE Clique test """
     aqua_globals.random_seed = 10598
     result = VQE(self.qubit_op,
                  RY(self.qubit_op.num_qubits, depth=5, entanglement='linear'),
                  COBYLA(),
                  max_evals_grouped=2).run(
                      QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                                      seed_simulator=aqua_globals.random_seed,
                                      seed_transpiler=aqua_globals.random_seed))
     x = sample_most_likely(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)