示例#1
0
    def test_min_eigen_optimizer(self, config):
        """ Min Eigen Optimizer Test """

        # unpack configuration
        min_eigen_solver_name, backend, filename = config

        # get minimum eigen solver
        min_eigen_solver = self.min_eigen_solvers[min_eigen_solver_name]
        if backend:
            min_eigen_solver.quantum_instance = BasicAer.get_backend(backend)

        # construct minimum eigen optimizer
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)

        # load optimization problem
        problem = OptimizationProblem()
        problem.read(self.resource_path + filename)

        # solve problem with cplex
        cplex = CplexOptimizer()
        cplex_result = cplex.solve(problem)

        # solve problem
        result = min_eigen_optimizer.solve(problem)

        # analyze results
        self.assertAlmostEqual(cplex_result.fval, result.fval)
示例#2
0
 def test_auto_penalty(self):
     """ Test auto penalty function"""
     op = QuadraticProgram()
     op.binary_var('x')
     op.binary_var('y')
     op.binary_var('z')
     op.minimize(constant=3, linear={'x': 1}, quadratic={('x', 'y'): 2})
     op.linear_constraint(linear={
         'x': 1,
         'y': 1,
         'z': 1
     },
                          sense='EQ',
                          rhs=2,
                          name='xyz_eq')
     lineq2penalty = LinearEqualityToPenalty(penalty=1e5)
     lineq2penalty_auto = LinearEqualityToPenalty()
     qubo = lineq2penalty.convert(op)
     qubo_auto = lineq2penalty_auto.convert(op)
     exact_mes = NumPyMinimumEigensolver()
     exact = MinimumEigenOptimizer(exact_mes)
     result = exact.solve(qubo)
     result_auto = exact.solve(qubo_auto)
     self.assertEqual(result.fval, result_auto.fval)
     np.testing.assert_array_almost_equal(result.x, result_auto.x)
示例#3
0
    def test_linear_equality_to_penalty_decode(self):
        """ Test decode func of LinearEqualityToPenalty"""
        qprog = QuadraticProgram()
        qprog.binary_var('x')
        qprog.binary_var('y')
        qprog.binary_var('z')
        qprog.maximize(linear={'x': 3, 'y': 1, 'z': 1})
        qprog.linear_constraint(linear={'x': 1, 'y': 1, 'z': 1}, sense='EQ', rhs=2, name='xyz_eq')
        lineq2penalty = LinearEqualityToPenalty()
        qubo = lineq2penalty.convert(qprog)
        exact_mes = NumPyMinimumEigensolver()
        exact = MinimumEigenOptimizer(exact_mes)
        result = exact.solve(qubo)

        decoded_result = lineq2penalty.interpret(result)
        self.assertEqual(decoded_result.fval, 4)
        np.testing.assert_array_almost_equal(decoded_result.x, [1, 1, 0])
        self.assertEqual(decoded_result.status, OptimizationResultStatus.SUCCESS)
        self.assertListEqual(decoded_result.variable_names, ['x', 'y', 'z'])
        self.assertDictEqual(decoded_result.variables_dict, {'x': 1.0, 'y': 1.0, 'z': 0.0})

        infeasible_result = OptimizationResult(x=[1, 1, 1], fval=0, variables=qprog.variables,
                                               status=OptimizationResultStatus.SUCCESS)
        decoded_infeasible_result = lineq2penalty.interpret(infeasible_result)
        self.assertEqual(decoded_infeasible_result.fval, 5)
        np.testing.assert_array_almost_equal(decoded_infeasible_result.x, [1, 1, 1])
        self.assertEqual(decoded_infeasible_result.status, OptimizationResultStatus.INFEASIBLE)
        self.assertListEqual(infeasible_result.variable_names, ['x', 'y', 'z'])
        self.assertDictEqual(infeasible_result.variables_dict, {'x': 1.0, 'y': 1.0, 'z': 1.0})
示例#4
0
    def test_min_eigen_optimizer(self, config):
        """ Min Eigen Optimizer Test """
        try:
            # unpack configuration
            min_eigen_solver_name, backend, filename = config

            # get minimum eigen solver
            min_eigen_solver = self.min_eigen_solvers[min_eigen_solver_name]
            if backend:
                min_eigen_solver.quantum_instance = BasicAer.get_backend(backend)

            # construct minimum eigen optimizer
            min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)

            # load optimization problem
            problem = QuadraticProgram()
            problem.read_from_lp_file(self.resource_path + filename)

            # solve problem with cplex
            cplex = CplexOptimizer()
            cplex_result = cplex.solve(problem)

            # solve problem
            result = min_eigen_optimizer.solve(problem)

            # analyze results
            self.assertAlmostEqual(cplex_result.fval, result.fval)
        except RuntimeError as ex:
            msg = str(ex)
            if 'CPLEX' in msg:
                self.skipTest(msg)
            else:
                self.fail(msg)
示例#5
0
    def test_linear_equality_to_penalty_decode(self):
        """ Test decode func of LinearEqualityToPenalty"""
        qprog = QuadraticProgram()
        qprog.binary_var('x')
        qprog.binary_var('y')
        qprog.binary_var('z')
        qprog.maximize(linear={'x': 3, 'y': 1, 'z': 1})
        qprog.linear_constraint(linear={
            'x': 1,
            'y': 1,
            'z': 1
        },
                                sense='EQ',
                                rhs=2,
                                name='xyz_eq')
        lineq2penalty = LinearEqualityToPenalty()
        qubo = lineq2penalty.convert(qprog)
        exact_mes = NumPyMinimumEigensolver()
        exact = MinimumEigenOptimizer(exact_mes)
        result = exact.solve(qubo)

        new_x = lineq2penalty.interpret(result.x)
        np.testing.assert_array_almost_equal(new_x, [1, 1, 0])
        infeasible_x = lineq2penalty.interpret([1, 1, 1])
        np.testing.assert_array_almost_equal(infeasible_x, [1, 1, 1])
示例#6
0
    def _test_readme_sample(self):
        """ readme sample test """

        # pylint: disable=import-outside-toplevel,redefined-builtin

        def print(*args):
            """ overloads print to log values """
            if args:
                self.log.debug(args[0], *args[1:])

        # Fix the random seed of SPSA (Optional)
        from qiskit.aqua import aqua_globals
        aqua_globals.random_seed = 123

        # --- Exact copy of sample code ----------------------------------------

        import networkx as nx
        import numpy as np

        from qiskit.optimization import QuadraticProgram
        from qiskit.optimization.algorithms import MinimumEigenOptimizer

        from qiskit import BasicAer
        from qiskit.aqua.algorithms import QAOA
        from qiskit.aqua.components.optimizers import SPSA

        # Generate a graph of 4 nodes
        n = 4
        graph = nx.Graph()
        graph.add_nodes_from(np.arange(0, n, 1))
        elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0),
                 (2, 3, 1.0)]
        graph.add_weighted_edges_from(elist)

        # Compute the weight matrix from the graph
        w = nx.adjacency_matrix(graph)

        # Formulate the problem as quadratic program
        problem = QuadraticProgram()
        _ = [problem.binary_var('x{}'.format(i))
             for i in range(n)]  # create n binary variables
        linear = w.dot(np.ones(n))
        quadratic = -w
        problem.maximize(linear=linear, quadratic=quadratic)

        # Fix node 0 to be 1 to break the symmetry of the max-cut solution
        problem.linear_constraint([1, 0, 0, 0], '==', 1)

        # Run quantum algorithm QAOA on qasm simulator
        spsa = SPSA(maxiter=250)
        backend = BasicAer.get_backend('qasm_simulator')
        qaoa = QAOA(optimizer=spsa, p=5, quantum_instance=backend)
        algorithm = MinimumEigenOptimizer(qaoa)
        result = algorithm.solve(problem)
        print(result)  # prints solution, x=[1, 0, 1, 0], the cost, fval=4
        # ----------------------------------------------------------------------

        np.testing.assert_array_almost_equal(result.x, [1, 0, 1, 0])
        self.assertAlmostEqual(result.fval, 4.0)
示例#7
0
    def validate_results(self, problem, results):
        """Validate the results object returned by GroverOptimizer."""
        # Get expected value.
        solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
        comp_result = solver.solve(problem)

        # Validate results.
        self.assertTrue(comp_result.x == results.x)
        self.assertTrue(comp_result.fval == results.fval)
    def validate_results(self, problem, results):
        """Validate the results object returned by GroverOptimizer."""
        # Get expected value.
        solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
        comp_result = solver.solve(problem)

        # Validate results.
        np.testing.assert_array_almost_equal(comp_result.x, results.x)
        self.assertEqual(comp_result.fval, results.fval)
    def Qmax_cut(self, w: List[List[int]], ans_set)->List:
        qubitOp, offset = max_cut.get_operator(w)

        # mapping Ising Hamiltonian to Quadratic Program
        qp = QuadraticProgram()
        qp.from_ising(qubitOp, offset)
        qp.to_docplex()#.prettyprint()

        # solving Quadratic Program using exact classical eigensolver
        exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
        result = exact.solve(qp)

        return result
示例#10
0
    def calculate(self, G, cost_matrix, starting_node=0):

        # Create nodes array for the TSP solver in Qiskit
        coords = []
        for node in G.nodes:
            coords.append(G.nodes[node]['pos'])

        tsp_instance = tsp.TspData(name="TSP",
                                   dim=len(G.nodes),
                                   coord=coords,
                                   w=cost_matrix)

        qubitOp, offset = tsp.get_operator(tsp_instance)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend)

        optimizer = COBYLA(maxiter=300, rhobeg=3, tol=1.5)

        # Define Minimum Eigen Solvers
        minimum_eigen_solver = QAOA(quantum_instance=quantum_instance,
                                    optimizer=optimizer,
                                    operator=qubitOp)
        #minimum_eigen_solver = VQE(quantum_instance=quantum_instance, optimizer=optimizer, operator=qubitOp)
        exact_mes = NumPyMinimumEigensolver()

        # Create the optimizers so we can plug our Quadratic Program
        minimum_eigen_optimizer = MinimumEigenOptimizer(minimum_eigen_solver)
        #vqe = MinimumEigenOptimizer(vqe_mes)
        exact = MinimumEigenOptimizer(exact_mes)
        rqaoa = RecursiveMinimumEigenOptimizer(
            min_eigen_optimizer=minimum_eigen_optimizer,
            min_num_vars=1,
            min_num_vars_optimizer=exact)

        # Create QUBO based on qubitOp from the TSP
        qp = QuadraticProgram()
        qp.from_ising(qubitOp, offset, linear=True)

        result = rqaoa.solve(qp)

        if (tsp.tsp_feasible(result.x)):
            z = tsp.get_tsp_solution(result.x)
            print('solution:', z)
            return z
        else:
            print('no solution:', result.x)
            return []
示例#11
0
    def test_recursive_min_eigen_optimizer(self):
        """Test the recursive minimum eigen optimizer."""
        try:
            filename = 'op_ip1.lp'
            # get minimum eigen solver
            min_eigen_solver = NumPyMinimumEigensolver()

            # construct minimum eigen optimizer
            min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)
            recursive_min_eigen_optimizer = RecursiveMinimumEigenOptimizer(min_eigen_optimizer,
                                                                           min_num_vars=4)

            # load optimization problem
            problem = QuadraticProgram()
            lp_file = self.get_resource_path(path.join('resources', filename))
            problem.read_from_lp_file(lp_file)

            # solve problem with cplex
            cplex = CplexOptimizer()
            cplex_result = cplex.solve(problem)

            # solve problem
            result = recursive_min_eigen_optimizer.solve(problem)

            # analyze results
            self.assertAlmostEqual(cplex_result.fval, result.fval)
        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
示例#12
0
 def test_continuous_variable_decode(self):
     """ Test decode func of IntegerToBinaryConverter for continuous variables"""
     try:
         mdl = Model('test_continuous_varable_decode')
         c = mdl.continuous_var(lb=0, ub=10.9, name='c')
         x = mdl.binary_var(name='x')
         mdl.maximize(c + x * x)
         op = QuadraticProgram()
         op.from_docplex(mdl)
         converter = IntegerToBinary()
         op = converter.convert(op)
         admm_params = ADMMParameters()
         qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
         continuous_optimizer = CplexOptimizer()
         solver = ADMMOptimizer(
             qubo_optimizer=qubo_optimizer,
             continuous_optimizer=continuous_optimizer,
             params=admm_params,
         )
         result = solver.solve(op)
         result = converter.interpret(result)
         self.assertEqual(result.x[0], 10.9)
         self.assertListEqual(result.variable_names, ['c', 'x'])
         self.assertDictEqual(result.variables_dict, {'c': 10.9, 'x': 0})
     except NameError as ex:
         self.skipTest(str(ex))
示例#13
0
    def test_admm_maximization(self):
        """Tests a simple maximization problem using ADMM optimizer"""
        mdl = Model('test')
        c = mdl.continuous_var(lb=0, ub=10, name='c')
        x = mdl.binary_var(name='x')
        mdl.maximize(c + x * x)
        op = OptimizationProblem()
        op.from_docplex(mdl)
        self.assertIsNotNone(op)

        admm_params = ADMMParameters()

        qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
        continuous_optimizer = CplexOptimizer()

        solver = ADMMOptimizer(qubo_optimizer=qubo_optimizer,
                               continuous_optimizer=continuous_optimizer,
                               params=admm_params)
        solution: ADMMOptimizerResult = solver.solve(op)
        self.assertIsNotNone(solution)
        self.assertIsInstance(solution, ADMMOptimizerResult)

        self.assertIsNotNone(solution.x)
        np.testing.assert_almost_equal([10, 0], solution.x, 3)
        self.assertIsNotNone(solution.fval)
        np.testing.assert_almost_equal(10, solution.fval, 3)
        self.assertIsNotNone(solution.state)
        self.assertIsInstance(solution.state, ADMMState)
示例#14
0
    def test_admm_miskp_eigen(self):
        """ADMM Optimizer Test based on Mixed-Integer Setup Knapsack Problem
        using NumPy eigen optimizer"""
        miskp = Miskp(*self._get_miskp_problem_params())
        op: OptimizationProblem = miskp.create_problem()
        self.assertIsNotNone(op)

        admm_params = ADMMParameters()

        # use numpy exact diagonalization
        qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
        continuous_optimizer = CplexOptimizer()

        solver = ADMMOptimizer(qubo_optimizer=qubo_optimizer,
                               continuous_optimizer=continuous_optimizer,
                               params=admm_params)
        solution: ADMMOptimizerResult = solver.solve(op)
        self.assertIsNotNone(solution)
        self.assertIsInstance(solution, ADMMOptimizerResult)

        correct_solution = [
            0.009127, 0.009127, 0.009127, 0.009127, 0.009127, 0.009127,
            0.009127, 0.009127, 0.009127, 0.009127, 0.006151, 0.006151,
            0.006151, 0.006151, 0.006151, 0.006151, 0.006151, 0.006151,
            0.006151, 0.006151, 0., 0.
        ]
        correct_objective = -1.2113693

        self.assertIsNotNone(solution.x)
        np.testing.assert_almost_equal(correct_solution, solution.x, 3)
        self.assertIsNotNone(solution.fval)
        np.testing.assert_almost_equal(correct_objective, solution.fval, 3)
        self.assertIsNotNone(solution.state)
        self.assertIsInstance(solution.state, ADMMState)
示例#15
0
    def test_admm_maximization(self):
        """Tests a simple maximization problem using ADMM optimizer"""
        try:
            mdl = Model('simple-max')
            c = mdl.continuous_var(lb=0, ub=10, name='c')
            x = mdl.binary_var(name='x')
            mdl.maximize(c + x * x)
            op = QuadraticProgram()
            op.from_docplex(mdl)

            admm_params = ADMMParameters()

            qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
            # qubo_optimizer = CplexOptimizer()
            continuous_optimizer = CplexOptimizer()

            solver = ADMMOptimizer(qubo_optimizer=qubo_optimizer,
                                   continuous_optimizer=continuous_optimizer,
                                   params=admm_params)
            solution = solver.solve(op)
            self.assertIsNotNone(solution)
            self.assertIsInstance(solution, ADMMOptimizationResult)

            self.assertIsNotNone(solution.x)
            np.testing.assert_almost_equal([10, 0], solution.x, 3)
            self.assertIsNotNone(solution.fval)
            np.testing.assert_almost_equal(10, solution.fval, 3)
            self.assertIsNotNone(solution.state)
            self.assertIsInstance(solution.state, ADMMState)
        except NameError as ex:
            self.skipTest(str(ex))
示例#16
0
    def test_recursive_min_eigen_optimizer(self):
        """Test the recursive minimum eigen optimizer."""
        try:
            filename = 'op_ip1.lp'
            # get minimum eigen solver
            min_eigen_solver = NumPyMinimumEigensolver()

            # construct minimum eigen optimizer
            min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)
            recursive_min_eigen_optimizer = RecursiveMinimumEigenOptimizer(min_eigen_optimizer,
                                                                           min_num_vars=4)

            # load optimization problem
            problem = QuadraticProgram()
            problem.read_from_lp_file(self.resource_path + filename)

            # solve problem with cplex
            cplex = CplexOptimizer()
            cplex_result = cplex.solve(problem)

            # solve problem
            result = recursive_min_eigen_optimizer.solve(problem)

            # analyze results
            self.assertAlmostEqual(cplex_result.fval, result.fval)
        except RuntimeError as ex:
            msg = str(ex)
            if 'CPLEX' in msg:
                self.skipTest(msg)
            else:
                self.fail(msg)
示例#17
0
    def test_converter_list(self):
        """Test converter list"""
        op = QuadraticProgram()
        op.integer_var(0, 3, "x")
        op.binary_var('y')

        op.maximize(linear={'x': 1, 'y': 2})
        op.linear_constraint(linear={
            'x': 1,
            'y': 1
        },
                             sense='LE',
                             rhs=3,
                             name='xy_leq')
        min_eigen_solver = NumPyMinimumEigensolver()
        # a single converter
        qp2qubo = QuadraticProgramToQubo()
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver,
                                                    converters=qp2qubo)
        result = min_eigen_optimizer.solve(op)
        self.assertEqual(result.fval, 4)
        # a list of converters
        ineq2eq = InequalityToEquality()
        int2bin = IntegerToBinary()
        penalize = LinearEqualityToPenalty()
        converters = [ineq2eq, int2bin, penalize]
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver,
                                                    converters=converters)
        result = min_eigen_optimizer.solve(op)
        self.assertEqual(result.fval, 4)
        with self.assertRaises(TypeError):
            invalid = [qp2qubo, "invalid converter"]
            MinimumEigenOptimizer(min_eigen_solver, converters=invalid)
示例#18
0
    def test_min_eigen_optimizer_history(self):
        """Tests different options for history."""
        try:
            filename = 'op_ip1.lp'
            # load optimization problem
            problem = QuadraticProgram()
            lp_file = self.get_resource_path(path.join('resources', filename))
            problem.read_from_lp_file(lp_file)

            # get minimum eigen solver
            min_eigen_solver = NumPyMinimumEigensolver()

            # construct minimum eigen optimizer
            min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)

            # no history
            recursive_min_eigen_optimizer = \
                RecursiveMinimumEigenOptimizer(min_eigen_optimizer,
                                               min_num_vars=4,
                                               history=IntermediateResult.NO_ITERATIONS)
            result = recursive_min_eigen_optimizer.solve(problem)
            self.assertIsNotNone(result.replacements)
            self.assertIsNotNone(result.history)
            self.assertIsNotNone(result.history[0])
            self.assertEqual(len(result.history[0]), 0)
            self.assertIsNone(result.history[1])

            # only last iteration in the history
            recursive_min_eigen_optimizer = \
                RecursiveMinimumEigenOptimizer(min_eigen_optimizer,
                                               min_num_vars=4,
                                               history=IntermediateResult.LAST_ITERATION)
            result = recursive_min_eigen_optimizer.solve(problem)
            self.assertIsNotNone(result.replacements)
            self.assertIsNotNone(result.history)
            self.assertIsNotNone(result.history[0])
            self.assertEqual(len(result.history[0]), 0)
            self.assertIsNotNone(result.history[1])

            # full history
            recursive_min_eigen_optimizer = \
                RecursiveMinimumEigenOptimizer(min_eigen_optimizer,
                                               min_num_vars=4,
                                               history=IntermediateResult.ALL_ITERATIONS)
            result = recursive_min_eigen_optimizer.solve(problem)
            self.assertIsNotNone(result.replacements)
            self.assertIsNotNone(result.history)
            self.assertIsNotNone(result.history[0])
            self.assertGreater(len(result.history[0]), 1)
            self.assertIsNotNone(result.history[1])

        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
示例#19
0
    def validate_results(self, problem, results, max_iterations):
        """Validate the results object returned by GroverMinimumFinder."""
        # Get measured values.
        grover_results = results.results['grover_results']
        op_key = results.x
        op_value = results.fval
        iterations = len(grover_results.operation_counts)
        rot = grover_results.rotation_count
        func = grover_results.func_dict
        print("Function", func)
        print("Optimum Key:", op_key, "Optimum Value:", op_value, "Rotations:",
              rot, "\n")

        # Get expected value.
        solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
        comp_result = solver.solve(problem)
        max_rotations = int(np.ceil(100 * np.pi / 4))

        # Validate results.
        max_hit = max_rotations <= rot or max_iterations <= iterations
        self.assertTrue(comp_result.x == results.x or max_hit)
        self.assertTrue(comp_result.fval == results.fval or max_hit)
示例#20
0
 def test_linear_equality_to_penalty_decode(self):
     """ Test decode func of LinearEqualityToPenalty"""
     qprog = QuadraticProgram()
     qprog .binary_var('x')
     qprog .binary_var('y')
     qprog .binary_var('z')
     qprog .maximize(linear={'x': 3, 'y': 1, 'z': 1})
     qprog .linear_constraint(linear={'x': 1, 'y': 1, 'z': 1}, sense='EQ', rhs=2, name='xyz_eq')
     lineq2penalty = LinearEqualityToPenalty()
     qubo = lineq2penalty.encode(qprog)
     exact_mes = NumPyMinimumEigensolver()
     exact = MinimumEigenOptimizer(exact_mes)
     result = exact.solve(qubo)
     decoded_result = lineq2penalty.decode(result)
     self.assertEqual(decoded_result.fval, 4)
     self.assertListEqual(decoded_result.x, [1, 1, 0])
     self.assertEqual(decoded_result.status, OptimizationResultStatus.SUCCESS)
     infeasible_result = OptimizationResult(x=[1, 1, 1])
     decoded_infeasible_result = lineq2penalty.decode(infeasible_result)
     self.assertEqual(decoded_infeasible_result.fval, 5)
     self.assertListEqual(decoded_infeasible_result.x, [1, 1, 1])
     self.assertEqual(decoded_infeasible_result.status, OptimizationResultStatus.INFEASIBLE)
示例#21
0
    def test_min_eigen_optimizer_with_filter(self, config):
        """ Min Eigen Optimizer Test """
        try:
            # unpack configuration
            filename, lowerbound, fval, status = config

            # get minimum eigen solver
            min_eigen_solver = NumPyMinimumEigensolver()

            # set filter
            # pylint: disable=unused-argument
            def filter_criterion(x, v, aux):
                return v > lowerbound

            min_eigen_solver.filter_criterion = filter_criterion

            # construct minimum eigen optimizer
            min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)

            # load optimization problem
            problem = QuadraticProgram()
            lp_file = self.get_resource_path(path.join('resources', filename))
            problem.read_from_lp_file(lp_file)

            # solve problem
            result = min_eigen_optimizer.solve(problem)
            self.assertIsNotNone(result)

            # analyze results
            self.assertAlmostEqual(fval, result.fval)
            self.assertEqual(status, result.status)

            # check that eigensolver result is present
            self.assertIsNotNone(result.min_eigen_solver_result)
        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
        except RuntimeError as ex:
            self.fail(str(ex))
示例#22
0
    def test_min_eigen_optimizer(self, config):
        """ Min Eigen Optimizer Test """
        try:
            # unpack configuration
            min_eigen_solver_name, backend, filename = config

            # get minimum eigen solver
            min_eigen_solver = self.min_eigen_solvers[min_eigen_solver_name]
            if backend:
                min_eigen_solver.quantum_instance = BasicAer.get_backend(
                    backend)

            # construct minimum eigen optimizer
            min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)

            # load optimization problem
            problem = QuadraticProgram()
            lp_file = self.get_resource_path(path.join('resources', filename))
            problem.read_from_lp_file(lp_file)

            # solve problem with cplex
            cplex = CplexOptimizer()
            cplex_result = cplex.solve(problem)

            # solve problem
            result = min_eigen_optimizer.solve(problem)
            self.assertIsNotNone(result)

            # analyze results
            self.assertAlmostEqual(cplex_result.fval, result.fval)

            # check that eigensolver result is present
            self.assertIsNotNone(result.min_eigen_solver_result)
        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
        except RuntimeError as ex:
            self.fail(str(ex))
示例#23
0
    def calculate(self, G, cost_matrix, starting_node = 0):

        # Create nodes array for the TSP solver in Qiskit
        coords = []
        for node in G.nodes:
            coords.append(G.nodes[node]['pos'])

        tsp_instance = tsp.TspData(name = "TSP", dim = len(G.nodes), coord = coords, w = cost_matrix)

        qubitOp, offset = tsp.get_operator(tsp_instance)
        print("Qubits needed: ", qubitOp.num_qubits)
        #print(qubitOp.print_details())

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

        # Create QUBO based on qubitOp from the TSP
        qp = QuadraticProgram()
        qp.from_ising(qubitOp, offset, linear=True)

        admm_params = ADMMParameters(
                            rho_initial=1001,
                            beta=1000,
                            factor_c=900,
                            maxiter=100,
                            three_block=True, tol=1.e-6)

        qubo_optimizer = MinimumEigenOptimizer(QAOA(quantum_instance=backend))
        convex_optimizer = CobylaOptimizer()
        admm = ADMMOptimizer(params=admm_params,
                             qubo_optimizer=qubo_optimizer,
                             continuous_optimizer=convex_optimizer)

        quantum_instance = QuantumInstance(backend)

        result = admm.solve(qp)
        print(result)
示例#24
0
 def test_continuous_variable_decode(self):
     """ Test decode func of IntegerToBinaryConverter for continuous variables"""
     try:
         mdl = Model('test_continuous_varable_decode')
         c = mdl.continuous_var(lb=0, ub=10.9, name='c')
         x = mdl.binary_var(name='x')
         mdl.maximize(c + x * x)
         op = QuadraticProgram()
         op.from_docplex(mdl)
         converter = IntegerToBinary()
         op = converter.encode(op)
         admm_params = ADMMParameters()
         qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
         continuous_optimizer = CplexOptimizer()
         solver = ADMMOptimizer(
             qubo_optimizer=qubo_optimizer,
             continuous_optimizer=continuous_optimizer,
             params=admm_params,
         )
         solution = solver.solve(op)
         solution = converter.decode(solution)
         self.assertEqual(solution.x[0], 10.9)
     except NameError as ex:
         self.skipTest(str(ex))
from qiskit.optimization import QuadraticProgram
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from dwave.plugins.qiskit import DWaveMinimumEigensolver

# Specify the problem - in IBM language
qp = QuadraticProgram()
qp.binary_var('x')
qp.binary_var('y')
qp.binary_var('z')

g = 25
qp.minimize(linear={'x': 17 - 3*g, 'y': 21 - 3*g, 'z': 19 - 3*g}, quadratic={'zx': g*2, 'yx': g*2, 'zy': g*2})


dwave_mes = DWaveMinimumEigensolver()

optimizer = MinimumEigenOptimizer(dwave_mes)

result = optimizer.solve(qp)

print(result.samples)
示例#26
0
x0 = model.binary_var(name="x0")
x1 = model.binary_var(name="x1")
x2 = model.binary_var(name="x2")
model.minimize(-x0 + 2 * x1 - 3 * x2 - 2 * x0 * x2 - 1 * x1 * x2)
qp = QuadraticProgram()
qp.from_docplex(model)
print(qp.export_as_lp_string())

from qiskit.aqua import QuantumInstance

grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)
results = grover_optimizer.solve(qp)
print("x={}".format(results.x))
print("fval={}".format(results.fval))

exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qp)
print("x={}".format(exact_result.x))
print("fval={}".format(exact_result.fval))

# Since the `pytket` extension modules provide an interface to the widest variety of devices and simulators out of all major quantum software platforms, the simplest advantage to obtain through `pytket` is to try using some alternative backends.
#
# One such backend that becomes available is the Qulacs simulator, providing fast noiseless simulations, especially when exploiting an available GPU. We can wrap up the `QulacsBackend` (or `QulacsGPUBackend` if you have a GPU available) in a form that can be passed to any Qiskit Aqua algorithm.

from pytket.extensions.qulacs import QulacsBackend
from pytket.extensions.qiskit.tket_backend import TketBackend

qulacs = QulacsBackend()
backend = TketBackend(qulacs, qulacs.default_compilation_pass())

grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)
def qubo_optimization(position_candidates, method='classical'):
    qubo = QuadraticProgram()
    qubo.binary_var(name='x0')
    qubo.binary_var(name='x1')
    qubo.binary_var(name='x2')
    qubo.binary_var(name='x3')
    qubo.binary_var(name='x4')
    qubo.binary_var(name='x5')
    qubo.binary_var(name='y0')
    qubo.binary_var(name='y1')
    qubo.binary_var(name='y2')
    qubo.binary_var(name='y3')
    qubo.binary_var(name='y4')
    qubo.binary_var(name='y5')
    a = 0
    b = 0
    aa = 0
    bb = 0
    RR = 0
    for sensor in position_candidates:
        a = a + sensor[0]
        b = b + sensor[1]
        aa = aa + sensor[0] * sensor[0]
        bb = bb + sensor[1] * sensor[1]
    #   RR = RR + sensor[2] * sensor[2]

    #print('a=',a)
    #print('b=',b)
    #print('aa=',aa)
    #print('bb=',bb)
    #print('RR=',RR)

    N = len(position_candidates)
    #print('N=',N)

    #np.array
    #a=5
    #b=7
    #R=13
    lx0 = -2 * a
    lx1 = -4 * a
    lx2 = -8 * a
    lx3 = -16 * a
    lx4 = -32 * a
    lx5 = -64 * a
    ly0 = -2 * b
    ly1 = -4 * b
    ly2 = -8 * b
    ly3 = -16 * b
    ly4 = -32 * b
    ly5 = -64 * b
    #qubo.binary_var('y')
    #qubo.binary_var('z')
    qubo.minimize(
        constant=aa + bb,
        linear=[lx0, lx1, lx2, lx3, lx4, lx5, ly0, ly1, ly2, ly3, ly4, ly5],
        quadratic={
            ('x0', 'x0'): 1 * N,
            ('x1', 'x1'): 4 * N,
            ('x2', 'x2'): 16 * N,
            ('x3', 'x3'): 64 * N,
            ('x4', 'x4'): 256 * N,
            ('x5', 'x5'): 1024 * N,
            ('x0', 'x1'): 4 * N,
            ('x0', 'x2'): 8 * N,
            ('x0', 'x3'): 16 * N,
            ('x0', 'x4'): 32 * N,
            ('x0', 'x5'): 64 * N,
            ('x1', 'x2'): 16 * N,
            ('x1', 'x3'): 32 * N,
            ('x1', 'x4'): 64 * N,
            ('x1', 'x5'): 128 * N,
            ('x2', 'x3'): 64 * N,
            ('x2', 'x4'): 128 * N,
            ('x2', 'x5'): 256 * N,
            ('x3', 'x4'): 256 * N,
            ('x3', 'x5'): 512 * N,
            ('x4', 'x5'): 1024 * N,
            ('y0', 'y0'): 1 * N,
            ('y1', 'y1'): 4 * N,
            ('y2', 'y2'): 16 * N,
            ('y3', 'y3'): 64 * N,
            ('y4', 'y4'): 256 * N,
            ('y5', 'y5'): 1024 * N,
            ('y0', 'y1'): 4 * N,
            ('y0', 'y2'): 8 * N,
            ('y0', 'y3'): 16 * N,
            ('y0', 'y4'): 32 * N,
            ('y0', 'y5'): 64 * N,
            ('y1', 'y2'): 16 * N,
            ('y1', 'y3'): 32 * N,
            ('y1', 'y4'): 64 * N,
            ('y1', 'y5'): 128 * N,
            ('y2', 'y3'): 64 * N,
            ('y2', 'y4'): 128 * N,
            ('y2', 'y5'): 256 * N,
            ('y3', 'y4'): 256 * N,
            ('y3', 'y5'): 512 * N,
            ('y4', 'y5'): 1024 * N
        })
    if method == 'qaoa':
        qaoa_mes = QAOA(
            quantum_instance=BasicAer.get_backend('statevector_simulator'))
        qaoa = MinimumEigenOptimizer(qaoa_mes)  # using QAOA
        result = qaoa.solve(qubo)
    else:
        exact_mes = NumPyMinimumEigensolver()
        exact = MinimumEigenOptimizer(
            exact_mes)  # using the exact classical numpy minimum eigen solver
        result = exact.solve(qubo)

        dX = 0
        dY = 0
        for i, x in enumerate(result.x):
            if i < len(result.x) / 2:
                dX = dX + x * 2**(i % 6)
            else:
                dY = dY + x * 2**(i % 6)
    return dX, dY
示例#28
0
    def test_samples(self):
        """Test samples"""
        SUCCESS = OptimizationResultStatus.SUCCESS  # pylint: disable=invalid-name
        aqua_globals.random_seed = 123
        quantum_instance = QuantumInstance(
            backend=BasicAer.get_backend('qasm_simulator'),
            seed_simulator=123,
            seed_transpiler=123,
            shots=1000)

        # test minimize
        op = QuadraticProgram()
        op.integer_var(0, 3, 'x')
        op.binary_var('y')
        op.minimize(linear={'x': 1, 'y': 2})
        op.linear_constraint(linear={
            'x': 1,
            'y': 1
        },
                             sense='>=',
                             rhs=1,
                             name='xy')

        min_eigen_solver = NumPyMinimumEigensolver()
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)
        result = min_eigen_optimizer.solve(op)
        opt_sol = 1
        self.assertEqual(result.fval, opt_sol)
        self.assertEqual(len(result.samples), 1)
        np.testing.assert_array_almost_equal(result.samples[0].x, [1, 0])
        self.assertAlmostEqual(result.samples[0].fval, opt_sol)
        self.assertAlmostEqual(result.samples[0].probability, 1.0)
        self.assertEqual(result.samples[0].status, SUCCESS)
        self.assertEqual(len(result.raw_samples), 1)
        np.testing.assert_array_almost_equal(result.raw_samples[0].x,
                                             [1, 0, 0, 0, 0])
        self.assertAlmostEqual(result.raw_samples[0].fval, opt_sol)
        self.assertAlmostEqual(result.raw_samples[0].probability, 1.0)
        self.assertEqual(result.raw_samples[0].status, SUCCESS)

        qaoa = QAOA(quantum_instance=quantum_instance)
        min_eigen_optimizer = MinimumEigenOptimizer(qaoa)
        result = min_eigen_optimizer.solve(op)
        self.assertEqual(len(result.samples), 8)
        self.assertEqual(len(result.raw_samples), 32)
        self.assertAlmostEqual(sum(s.probability for s in result.samples), 1)
        self.assertAlmostEqual(sum(s.probability for s in result.raw_samples),
                               1)
        self.assertAlmostEqual(min(s.fval for s in result.samples), 0)
        self.assertAlmostEqual(
            min(s.fval for s in result.samples if s.status == SUCCESS),
            opt_sol)
        self.assertAlmostEqual(min(s.fval for s in result.raw_samples),
                               opt_sol)
        for sample in result.raw_samples:
            self.assertEqual(sample.status, SUCCESS)
        np.testing.assert_array_almost_equal(result.x, result.samples[0].x)
        self.assertAlmostEqual(result.fval, result.samples[0].fval)
        self.assertEqual(result.status, result.samples[0].status)

        # test maximize
        op = QuadraticProgram()
        op.integer_var(0, 3, 'x')
        op.binary_var('y')
        op.maximize(linear={'x': 1, 'y': 2})
        op.linear_constraint(linear={
            'x': 1,
            'y': 1
        },
                             sense='<=',
                             rhs=1,
                             name='xy')

        min_eigen_solver = NumPyMinimumEigensolver()
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)
        result = min_eigen_optimizer.solve(op)
        opt_sol = 2
        self.assertEqual(result.fval, opt_sol)
        self.assertEqual(len(result.samples), 1)
        np.testing.assert_array_almost_equal(result.samples[0].x, [0, 1])
        self.assertAlmostEqual(result.samples[0].fval, opt_sol)
        self.assertAlmostEqual(result.samples[0].probability, 1.0)
        self.assertEqual(result.samples[0].status, SUCCESS)
        self.assertEqual(len(result.raw_samples), 1)
        np.testing.assert_array_almost_equal(result.raw_samples[0].x,
                                             [0, 0, 1, 0])
        self.assertAlmostEqual(result.raw_samples[0].fval, opt_sol)
        self.assertAlmostEqual(result.raw_samples[0].probability, 1.0)
        self.assertEqual(result.raw_samples[0].status, SUCCESS)

        qaoa = QAOA(quantum_instance=quantum_instance)
        min_eigen_optimizer = MinimumEigenOptimizer(qaoa)
        result = min_eigen_optimizer.solve(op)
        self.assertEqual(len(result.samples), 8)
        self.assertEqual(len(result.raw_samples), 16)
        self.assertAlmostEqual(sum(s.probability for s in result.samples), 1)
        self.assertAlmostEqual(sum(s.probability for s in result.raw_samples),
                               1)
        self.assertAlmostEqual(max(s.fval for s in result.samples), 5)
        self.assertAlmostEqual(
            max(s.fval for s in result.samples if s.status == SUCCESS),
            opt_sol)
        self.assertAlmostEqual(max(s.fval for s in result.raw_samples),
                               opt_sol)
        for sample in result.raw_samples:
            self.assertEqual(sample.status, SUCCESS)
        np.testing.assert_array_almost_equal(result.x, result.samples[0].x)
        self.assertAlmostEqual(result.fval, result.samples[0].fval)
        self.assertEqual(result.status, result.samples[0].status)
示例#29
0
import matplotlib.axes as axes


def draw_graph(G, colors, pos):
    default_axes = plt.axes(frameon=True)
    nx.draw_networkx(G,
                     node_color=colors,
                     node_size=600,
                     alpha=.8,
                     ax=default_axes,
                     pos=pos)
    edge_labels = nx.get_edge_attributes(G, 'weight')
    nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)


exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
# setup aqua logging
# Generating a graph of 3 nodes
n = 3
num_qubits = n**2
ins = tsp.random_tsp(n, seed=123)
data = tsp.TspData()
print(data)
# Draw the graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, ins.dim, 1))
colors = ['r' for node in G.nodes()]

for i in range(0, ins.dim):
    for j in range(i + 1, ins.dim):
        G.add_edge(i, j, weight=ins.w[i, j])
from qiskit.circuit.library import RealAmplitudes
from qiskit.aqua.components.optimizers import COBYLA

qaoa_mes = QAOA(quantum_instance=BasicAer.get_backend('statevector_simulator'))

vqe_mes = VQE(
    quantum_instance=BasicAer.get_backend('statevector_simulator'),
    var_form=RealAmplitudes(3, reps=2),  # parametrized circuit to use 
    optimizer=COBYLA(maxiter=200))  # classical optimizer

exact_mes = NumPyMinimumEigensolver()

# In[9]:

qaoa = MinimumEigenOptimizer(qaoa_mes)  # using QAOA
vqe = MinimumEigenOptimizer(vqe_mes)  # using VQE
exact = MinimumEigenOptimizer(
    exact_mes)  # using the exact classical numpy minimum eigen solver

# In[10]:

exact_result = exact.solve(qubo)
print(exact_result)

# In[11]:

qaoa_result = qaoa.solve(qubo)
print(qaoa_result)

# In[12]: