Ejemplo n.º 1
0
    def test_penalize_binary(self):
        """ Test PenalizeLinearEqualityConstraints with binary variables """
        op = QuadraticProgram()
        for i in range(3):
            op.binary_var(name='x{}'.format(i))
        # Linear constraints
        linear_constraint = {'x0': 1, 'x1': 1}
        op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
        linear_constraint = {'x1': 1, 'x2': -1}
        op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 2, 'x1x2')
        linear_constraint = {'x0': 1, 'x2': 3}
        op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 2, 'x0x2')
        self.assertEqual(op.get_num_linear_constraints(), 3)
        conv = LinearEqualityToPenalty()
        op2 = conv.convert(op)
        self.assertEqual(op2.get_num_linear_constraints(), 0)

        result = OptimizationResult(x=np.arange(3),
                                    fval=0,
                                    variables=op2.variables)
        new_result = conv.interpret(result)
        self.assertEqual(new_result.status,
                         OptimizationResultStatus.INFEASIBLE)
        np.testing.assert_array_almost_equal(new_result.x, np.arange(3))
        self.assertListEqual(result.variable_names, ['x0', 'x1', 'x2'])
        self.assertDictEqual(result.variables_dict, {
            'x0': 0,
            'x1': 1,
            'x2': 2
        })
Ejemplo n.º 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)
Ejemplo n.º 3
0
 def test_binary_to_integer(self):
     """ Test binary to integer """
     op = QuadraticProgram()
     for i in range(0, 2):
         op.binary_var(name='x{}'.format(i))
     op.integer_var(name='x2', lowerbound=0, upperbound=5)
     linear = {'x0': 1, 'x1': 2, 'x2': 1}
     op.maximize(0, linear, {})
     linear = {}
     for x in op.variables:
         linear[x.name] = 1
     op.linear_constraint(linear, Constraint.Sense.EQ, 6, 'x0x1x2')
     conv = IntegerToBinary()
     op2 = conv.convert(op)
     result = OptimizationResult(x=[0, 1, 1, 1, 1],
                                 fval=17,
                                 variables=op2.variables)
     new_result = conv.interpret(result)
     np.testing.assert_array_almost_equal(new_result.x, [0, 1, 5])
     self.assertEqual(new_result.fval, 17)
     self.assertListEqual(new_result.variable_names, ['x0', 'x1', 'x2'])
     self.assertDictEqual(new_result.variables_dict, {
         'x0': 0,
         'x1': 1,
         'x2': 5
     })
 def test_objective_handling(self):
     """test objective handling"""
     q_p = QuadraticProgram()
     q_p.binary_var('x')
     q_p.binary_var('y')
     q_p.binary_var('z')
     q_p.minimize()
     obj = q_p.objective
     self.assertEqual(obj.sense, QuadraticObjective.Sense.MINIMIZE)
     self.assertEqual(obj.constant, 0)
     self.assertDictEqual(obj.linear.to_dict(), {})
     self.assertDictEqual(obj.quadratic.to_dict(), {})
     q_p.maximize(1, {'y': 1}, {('z', 'x'): 1, ('y', 'y'): 1})
     obj = q_p.objective
     self.assertEqual(obj.sense, QuadraticObjective.Sense.MAXIMIZE)
     self.assertEqual(obj.constant, 1)
     self.assertDictEqual(obj.linear.to_dict(), {1: 1})
     self.assertDictEqual(obj.linear.to_dict(use_name=True), {'y': 1})
     self.assertListEqual(obj.linear.to_array().tolist(), [0, 1, 0])
     self.assertDictEqual(obj.quadratic.to_dict(), {(0, 2): 1, (1, 1): 1})
     self.assertDictEqual(obj.quadratic.to_dict(symmetric=True),
                          {(0, 2): 0.5, (2, 0): 0.5, (1, 1): 1})
     self.assertDictEqual(obj.quadratic.to_dict(use_name=True),
                          {('x', 'z'): 1, ('y', 'y'): 1})
     self.assertDictEqual(obj.quadratic.to_dict(use_name=True, symmetric=True),
                          {('x', 'z'): 0.5, ('z', 'x'): 0.5, ('y', 'y'): 1})
     self.assertListEqual(obj.quadratic.to_array().tolist(),
                          [[0, 0, 1], [0, 1, 0], [0, 0, 0]])
     self.assertListEqual(obj.quadratic.to_array(symmetric=True).tolist(),
                          [[0, 0, 0.5], [0, 1, 0], [0.5, 0, 0]])
Ejemplo n.º 5
0
    def test_optimizationproblem_to_ising_deprecated(self):
        """ Test optimization problem to operators"""
        op = QuadraticProgram()
        for i in range(4):
            op.binary_var(name='x{}'.format(i))
        linear = {}
        for x in op.variables:
            linear[x.name] = 1
        op.maximize(0, linear, {})
        linear = {}
        for i, x in enumerate(op.variables):
            linear[x.name] = i + 1
        op.linear_constraint(linear, Constraint.Sense.EQ, 3, 'sum1')
        penalize = LinearEqualityToPenalty(penalty=1e5)
        try:
            warnings.filterwarnings(action="ignore",
                                    category=DeprecationWarning)
            op2 = penalize.encode(op)
            conv = QuadraticProgramToIsing()
            qubitop, offset = conv.encode(op2)
        finally:
            warnings.filterwarnings(action="always",
                                    category=DeprecationWarning)

        self.assertEqual(qubitop, QUBIT_OP_MAXIMIZE_SAMPLE)
        self.assertEqual(offset, OFFSET_MAXIMIZE_SAMPLE)
Ejemplo n.º 6
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})
Ejemplo n.º 7
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])
Ejemplo n.º 8
0
    def test_optimizationproblem_to_ising(self):
        """ Test optimization problem to operators"""
        op = QuadraticProgram()
        for i in range(4):
            op.binary_var(name='x{}'.format(i))
        linear = {}
        for x in op.variables:
            linear[x.name] = 1
        op.maximize(0, linear, {})
        linear = {}
        for i, x in enumerate(op.variables):
            linear[x.name] = i + 1
        op.linear_constraint(linear, Constraint.Sense.EQ, 3, 'sum1')
        penalize = LinearEqualityToPenalty()
        op2ope = QuadraticProgramToIsing()
        op2 = penalize.encode(op)
        qubitop, offset = op2ope.encode(op2)

        # the encoder uses a dictionary, in which the order of items in Python 3.5 is not
        # maintained, therefore don't do a list compare but dictionary compare
        qubit_op_as_dict = dict(qubitop.paulis)
        for coeff, paulis in QUBIT_OP_MAXIMIZE_SAMPLE.paulis:
            self.assertEqual(paulis, qubit_op_as_dict[coeff])

        self.assertEqual(offset, OFFSET_MAXIMIZE_SAMPLE)
 def test_symmetric_set(self):
     """ test symmetric set """
     q_p = QuadraticProgram()
     q_p.binary_var('x')
     q_p.binary_var('y')
     q_p.binary_var('z')
     quad = QuadraticExpression(q_p, {('x', 'y'): -1, ('y', 'x'): 2, ('z', 'x'): 3})
     self.assertDictEqual(quad.to_dict(use_name=True), {('x', 'y'): 1, ('x', 'z'): 3})
     self.assertDictEqual(quad.to_dict(symmetric=True, use_name=True),
                          {('x', 'y'): 0.5, ('y', 'x'): 0.5, ('x', 'z'): 1.5, ('z', 'x'): 1.5})
Ejemplo n.º 10
0
 def test_inequality_mode_auto(self):
     """ Test auto mode of InequalityToEqualityConverter() """
     op = QuadraticProgram()
     for i in range(3):
         op.binary_var(name='x{}'.format(i))
     # Linear constraints
     linear_constraint = {'x0': 1, 'x1': 1}
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
     linear_constraint = {'x1': 1, 'x2': -1}
     op.linear_constraint(linear_constraint, Constraint.Sense.LE, 2, 'x1x2')
     linear_constraint = {'x0': 1.1, 'x2': 2.2}
     op.linear_constraint(linear_constraint, Constraint.Sense.GE, 3.3, 'x0x2')
     conv = InequalityToEquality(mode='auto')
     op2 = conv.convert(op)
     lst = [op2.variables[3].vartype, op2.variables[4].vartype]
     self.assertListEqual(lst, [Variable.Type.INTEGER, Variable.Type.CONTINUOUS])
Ejemplo n.º 11
0
 def test_penalize_sense(self):
     """ Test PenalizeLinearEqualityConstraints with senses """
     op = QuadraticProgram()
     for i in range(3):
         op.binary_var(name='x{}'.format(i))
     # Linear constraints
     linear_constraint = {'x0': 1, 'x1': 1}
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
     linear_constraint = {'x1': 1, 'x2': -1}
     op.linear_constraint(linear_constraint, Constraint.Sense.LE, 2, 'x1x2')
     linear_constraint = {'x0': 1, 'x2': 3}
     op.linear_constraint(linear_constraint, Constraint.Sense.GE, 2, 'x0x2')
     self.assertEqual(op.get_num_linear_constraints(), 3)
     conv = LinearEqualityToPenalty()
     with self.assertRaises(QiskitOptimizationError):
         conv.convert(op)
Ejemplo n.º 12
0
 def test_binary_to_integer(self):
     """ Test binary to integer """
     op = QuadraticProgram()
     for i in range(0, 2):
         op.binary_var(name='x{}'.format(i))
     op.integer_var(name='x2', lowerbound=0, upperbound=5)
     linear = {'x0': 1, 'x1': 2, 'x2': 1}
     op.maximize(0, linear, {})
     linear = {}
     for x in op.variables:
         linear[x.name] = 1
     op.linear_constraint(linear, Constraint.Sense.EQ, 6, 'x0x1x2')
     conv = IntegerToBinary()
     _ = conv.convert(op)
     new_x = conv.interpret([0, 1, 1, 1, 1])
     np.testing.assert_array_almost_equal(new_x, [0, 1, 5])
Ejemplo n.º 13
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)
 def test_clear(self):
     """ test clear """
     q_p = QuadraticProgram('test')
     q_p.binary_var('x')
     q_p.binary_var('y')
     q_p.minimize(constant=1, linear={'x': 1, 'y': 2}, quadratic={('x', 'x'): 1})
     q_p.linear_constraint({'x': 1}, '==', 1)
     q_p.quadratic_constraint({'x': 1}, {('y', 'y'): 2}, '<=', 1)
     q_p.clear()
     self.assertEqual(q_p.name, '')
     self.assertEqual(q_p.status, QuadraticProgram.Status.VALID)
     self.assertEqual(q_p.get_num_vars(), 0)
     self.assertEqual(q_p.get_num_linear_constraints(), 0)
     self.assertEqual(q_p.get_num_quadratic_constraints(), 0)
     self.assertEqual(q_p.objective.constant, 0)
     self.assertDictEqual(q_p.objective.linear.to_dict(), {})
     self.assertDictEqual(q_p.objective.quadratic.to_dict(), {})
Ejemplo n.º 15
0
 def test_integer_to_binary(self):
     """ Test integer to binary """
     op = QuadraticProgram()
     for i in range(0, 2):
         op.binary_var(name='x{}'.format(i))
     op.integer_var(name='x2', lowerbound=0, upperbound=5)
     linear = {}
     for i, x in enumerate(op.variables):
         linear[x.name] = i + 1
     op.maximize(0, linear, {})
     conv = IntegerToBinary()
     op2 = conv.encode(op)
     for x in op2.variables:
         self.assertEqual(x.vartype, Variable.Type.BINARY)
     dct = op2.objective.linear.to_dict()
     self.assertEqual(dct[2], 3)
     self.assertEqual(dct[3], 6)
     self.assertEqual(dct[4], 6)
Ejemplo n.º 16
0
 def test_optimizationproblem_to_ising(self):
     """ Test optimization problem to operators"""
     op = QuadraticProgram()
     for i in range(4):
         op.binary_var(name='x{}'.format(i))
     linear = {}
     for x in op.variables:
         linear[x.name] = 1
     op.maximize(0, linear, {})
     linear = {}
     for i, x in enumerate(op.variables):
         linear[x.name] = i + 1
     op.linear_constraint(linear, Constraint.Sense.EQ, 3, 'sum1')
     penalize = LinearEqualityToPenalty(penalty=1e5)
     op2 = penalize.convert(op)
     qubitop, offset = op2.to_ising()
     self.assertEqual(qubitop, QUBIT_OP_MAXIMIZE_SAMPLE)
     self.assertEqual(offset, OFFSET_MAXIMIZE_SAMPLE)
Ejemplo n.º 17
0
 def test_auto_penalty_warning(self):
     """ Test warnings of auto penalty function"""
     op = QuadraticProgram()
     op.binary_var('x')
     op.binary_var('y')
     op.binary_var('z')
     op.minimize(linear={'x': 1, 'y': 2})
     op.linear_constraint(linear={'x': 0.5, 'y': 0.5, 'z': 0.5}, sense='EQ', rhs=1, name='xyz')
     with self.assertLogs('qiskit.optimization', level='WARNING') as log:
         lineq2penalty = LinearEqualityToPenalty()
         _ = lineq2penalty.encode(op)
     warning = (
         'WARNING:qiskit.optimization.converters.linear_equality_to_penalty:'
         + 'Warning: Using 100000.000000 for the penalty coefficient because a float '
         + 'coefficient exists in constraints. \nThe value could be too small. If so, '
         + 'set the penalty coefficient manually.'
     )
     self.assertIn(warning, log.output)
Ejemplo n.º 18
0
 def test_integer_to_binary(self):
     """ Test integer to binary """
     op = QuadraticProgram()
     for i in range(0, 2):
         op.binary_var(name='x{}'.format(i))
     op.integer_var(name='x2', lowerbound=0, upperbound=5)
     linear = {}
     for i, x in enumerate(op.variables):
         linear[x.name] = i + 1
     op.maximize(0, linear, {})
     conv = IntegerToBinary()
     op2 = conv.convert(op)
     self.assertEqual(op2.get_num_vars(), 5)
     self.assertListEqual([x.vartype for x in op2.variables], [Variable.Type.BINARY] * 5)
     self.assertListEqual([x.name for x in op2.variables], ['x0', 'x1', 'x2@0', 'x2@1', 'x2@2'])
     dct = op2.objective.linear.to_dict()
     self.assertEqual(dct[2], 3)
     self.assertEqual(dct[3], 6)
     self.assertEqual(dct[4], 6)
Ejemplo n.º 19
0
    def test_penalize_binary(self):
        """ Test PenalizeLinearEqualityConstraints with binary variables """
        op = QuadraticProgram()
        for i in range(3):
            op.binary_var(name='x{}'.format(i))
        # Linear constraints
        linear_constraint = {'x0': 1, 'x1': 1}
        op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
        linear_constraint = {'x1': 1, 'x2': -1}
        op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 2, 'x1x2')
        linear_constraint = {'x0': 1, 'x2': 3}
        op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 2, 'x0x2')
        self.assertEqual(op.get_num_linear_constraints(), 3)
        conv = LinearEqualityToPenalty()
        op2 = conv.convert(op)
        self.assertEqual(op2.get_num_linear_constraints(), 0)

        new_x = conv.interpret(np.arange(3))
        np.testing.assert_array_almost_equal(new_x, np.arange(3))
    def test_write_to_lp_file(self):
        """test write problem"""
        q_p = QuadraticProgram('my problem')
        q_p.binary_var('x')
        q_p.integer_var(-1, 5, 'y')
        q_p.continuous_var(-1, 5, 'z')
        q_p.minimize(1, {'x': 1, 'y': -1, 'z': 10}, {('x', 'x'): 0.5, ('y', 'z'): -1})
        q_p.linear_constraint({'x': 1, 'y': 2}, '==', 1, 'lin_eq')
        q_p.linear_constraint({'x': 1, 'y': 2}, '<=', 1, 'lin_leq')
        q_p.linear_constraint({'x': 1, 'y': 2}, '>=', 1, 'lin_geq')
        q_p.quadratic_constraint({'x': 1, 'y': 1}, {('x', 'x'): 1, ('y', 'z'): -1, ('z', 'z'): 2},
                                 '==', 1, 'quad_eq')
        q_p.quadratic_constraint({'x': 1, 'y': 1}, {('x', 'x'): 1, ('y', 'z'): -1, ('z', 'z'): 2},
                                 '<=', 1, 'quad_leq')
        q_p.quadratic_constraint({'x': 1, 'y': 1}, {('x', 'x'): 1, ('y', 'z'): -1, ('z', 'z'): 2},
                                 '>=', 1, 'quad_geq')

        reference_file_name = self.get_resource_path(path.join('resources',
                                                               'test_quadratic_program.lp'))
        temp_output_file = tempfile.NamedTemporaryFile(mode='w+t', suffix='.lp')
        q_p.write_to_lp_file(temp_output_file.name)
        with open(reference_file_name) as reference:
            lines1 = temp_output_file.readlines()
            lines2 = reference.readlines()
            self.assertListEqual(lines1, lines2)

        temp_output_file.close()  # automatically deleted

        with tempfile.TemporaryDirectory() as temp_problem_dir:
            q_p.write_to_lp_file(temp_problem_dir)
            with open(path.join(temp_problem_dir, 'my_problem.lp')) as file1, open(
                    reference_file_name) as file2:
                lines1 = file1.readlines()
                lines2 = file2.readlines()
                self.assertListEqual(lines1, lines2)

        with self.assertRaises(OSError):
            q_p.write_to_lp_file('/cannot/write/this/file.lp')

        with self.assertRaises(DOcplexException):
            q_p.write_to_lp_file('')
Ejemplo n.º 21
0
 def test_binary_to_integer(self):
     """ Test binary to integer """
     op = QuadraticProgram()
     for i in range(0, 2):
         op.binary_var(name='x{}'.format(i))
     op.integer_var(name='x2', lowerbound=0, upperbound=5)
     linear = {}
     linear['x0'] = 1
     linear['x1'] = 2
     linear['x2'] = 1
     op.maximize(0, linear, {})
     linear = {}
     for x in op.variables:
         linear[x.name] = 1
     op.linear_constraint(linear, Constraint.Sense.EQ, 6, 'x0x1x2')
     conv = IntegerToBinary()
     _ = conv.encode(op)
     result = OptimizationResult(x=[0, 1, 1, 1, 1], fval=17)
     new_result = conv.decode(result)
     self.assertListEqual(new_result.x, [0, 1, 5])
     self.assertEqual(new_result.fval, 17)
Ejemplo n.º 22
0
 def test_penalize_binary(self):
     """ Test PenalizeLinearEqualityConstraints with binary variables """
     op = QuadraticProgram()
     for i in range(3):
         op.binary_var(name='x{}'.format(i))
     # Linear constraints
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x1'] = 1
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
     linear_constraint = {}
     linear_constraint['x1'] = 1
     linear_constraint['x2'] = -1
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 2, 'x1x2')
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x2'] = 3
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 2, 'x0x2')
     self.assertEqual(len(op.linear_constraints), 3)
     conv = LinearEqualityToPenalty()
     op2 = conv.encode(op)
     self.assertEqual(len(op2.linear_constraints), 0)
Ejemplo n.º 23
0
 def test_inequality_mode_integer(self):
     """ Test integer mode of InequalityToEqualityConverter() """
     op = QuadraticProgram()
     for i in range(3):
         op.binary_var(name='x{}'.format(i))
     # Linear constraints
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x1'] = 1
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
     linear_constraint = {}
     linear_constraint['x1'] = 1
     linear_constraint['x2'] = -1
     op.linear_constraint(linear_constraint, Constraint.Sense.LE, 2, 'x1x2')
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x2'] = 3
     op.linear_constraint(linear_constraint, Constraint.Sense.GE, 2, 'x0x2')
     conv = InequalityToEquality(mode='integer')
     op2 = conv.convert(op)
     lst = [op2.variables[3].vartype, op2.variables[4].vartype]
     self.assertListEqual(lst, [Variable.Type.INTEGER, Variable.Type.INTEGER])
Ejemplo n.º 24
0
 def test_penalize_sense(self):
     """ Test PenalizeLinearEqualityConstraints with senses """
     op = QuadraticProgram()
     for i in range(3):
         op.binary_var(name='x{}'.format(i))
     # Linear constraints
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x1'] = 1
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
     linear_constraint = {}
     linear_constraint['x1'] = 1
     linear_constraint['x2'] = -1
     op.linear_constraint(linear_constraint, Constraint.Sense.LE, 2, 'x1x2')
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x2'] = 3
     op.linear_constraint(linear_constraint, Constraint.Sense.GE, 2, 'x0x2')
     self.assertEqual(len(op.linear_constraints), 3)
     conv = LinearEqualityToPenalty()
     with self.assertRaises(QiskitOptimizationError):
         conv.encode(op)
Ejemplo n.º 25
0
 def test_inequality_mode_continuous(self):
     """ Test continuous mode of InequalityToEqualityConverter() """
     op = QuadraticProgram()
     for i in range(3):
         op.binary_var(name='x{}'.format(i))
     # Linear constraints
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x1'] = 1
     op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, 'x0x1')
     linear_constraint = {}
     linear_constraint['x1'] = 1
     linear_constraint['x2'] = -1
     op.linear_constraint(linear_constraint, Constraint.Sense.LE, 2, 'x1x2')
     linear_constraint = {}
     linear_constraint['x0'] = 1
     linear_constraint['x2'] = 3
     op.linear_constraint(linear_constraint, Constraint.Sense.GE, 2, 'x0x2')
     conv = InequalityToEquality()
     op2 = conv.encode(op, mode='continuous')
     lst = [op2.variables[3].vartype, op2.variables[4].vartype]
     self.assertListEqual(lst, [Variable.Type.CONTINUOUS, Variable.Type.CONTINUOUS])
Ejemplo n.º 26
0
 def test_0var_range_inequality(self):
     """ Test InequalityToEquality converter when the var_rang of the slack variable is 0"""
     op = QuadraticProgram()
     op.binary_var('x')
     op.binary_var('y')
     op.linear_constraint(linear={
         'x': 1,
         'y': 1
     },
                          sense='LE',
                          rhs=0,
                          name='xy_leq1')
     op.linear_constraint(linear={
         'x': 1,
         'y': 1
     },
                          sense='GE',
                          rhs=2,
                          name='xy_geq1')
     op.quadratic_constraint(quadratic={('x', 'x'): 1},
                             sense='LE',
                             rhs=0,
                             name='xy_leq2')
     op.quadratic_constraint(quadratic={('x', 'y'): 1},
                             sense='GE',
                             rhs=1,
                             name='xy_geq2')
     ineq2eq = InequalityToEquality()
     new_op = ineq2eq.convert(op)
     self.assertEqual(new_op.get_num_vars(), 2)
     self.assertTrue(
         all(l_const.sense == Constraint.Sense.EQ
             for l_const in new_op.linear_constraints))
     self.assertTrue(
         all(q_const.sense == Constraint.Sense.EQ
             for q_const in new_op.quadratic_constraints))
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)
Ejemplo n.º 28
0
    def test_substitute_variables(self):
        """test substitute variables"""
        q_p = QuadraticProgram('test')
        q_p.binary_var(name='x')
        q_p.integer_var(name='y', lowerbound=-2, upperbound=4)
        q_p.continuous_var(name='z', lowerbound=-1.5, upperbound=3.2)
        q_p.minimize(constant=1,
                     linear={
                         'x': 1,
                         'y': 2
                     },
                     quadratic={
                         ('x', 'y'): -1,
                         ('z', 'z'): 2
                     })
        q_p.linear_constraint({'x': 2, 'z': -1}, '==', 1)
        q_p.quadratic_constraint({'x': 2, 'z': -1}, {('y', 'z'): 3}, '<=', -1)

        q_p2 = q_p.substitute_variables(constants={'x': -1})
        self.assertEqual(q_p2.status, QuadraticProgram.Status.INFEASIBLE)
        q_p2 = q_p.substitute_variables(constants={'y': -3})
        self.assertEqual(q_p2.status, QuadraticProgram.Status.INFEASIBLE)
        q_p2 = q_p.substitute_variables(constants={'x': 1, 'z': 2})
        self.assertEqual(q_p2.status, QuadraticProgram.Status.INFEASIBLE)
        q_p2.clear()
        self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID)

        q_p2 = q_p.substitute_variables(constants={'x': 0})
        self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID)
        self.assertDictEqual(q_p2.objective.linear.to_dict(use_name=True),
                             {'y': 2})
        self.assertDictEqual(q_p2.objective.quadratic.to_dict(use_name=True),
                             {('z', 'z'): 2})
        self.assertEqual(q_p2.objective.constant, 1)
        self.assertEqual(len(q_p2.linear_constraints), 1)
        self.assertEqual(len(q_p2.quadratic_constraints), 1)

        cst = q_p2.linear_constraints[0]
        self.assertDictEqual(cst.linear.to_dict(use_name=True), {'z': -1})
        self.assertEqual(cst.sense.name, 'EQ')
        self.assertEqual(cst.rhs, 1)

        cst = q_p2.quadratic_constraints[0]
        self.assertDictEqual(cst.linear.to_dict(use_name=True), {'z': -1})
        self.assertDictEqual(cst.quadratic.to_dict(use_name=True),
                             {('y', 'z'): 3})
        self.assertEqual(cst.sense.name, 'LE')
        self.assertEqual(cst.rhs, -1)

        q_p2 = q_p.substitute_variables(constants={'z': -1})
        self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID)
        self.assertDictEqual(q_p2.objective.linear.to_dict(use_name=True), {
            'x': 1,
            'y': 2
        })
        self.assertDictEqual(q_p2.objective.quadratic.to_dict(use_name=True),
                             {('x', 'y'): -1})
        self.assertEqual(q_p2.objective.constant, 3)
        self.assertEqual(len(q_p2.linear_constraints), 2)
        self.assertEqual(len(q_p2.quadratic_constraints), 0)

        cst = q_p2.linear_constraints[0]
        self.assertDictEqual(cst.linear.to_dict(use_name=True), {'x': 2})
        self.assertEqual(cst.sense.name, 'EQ')
        self.assertEqual(cst.rhs, 0)

        cst = q_p2.linear_constraints[1]
        self.assertDictEqual(cst.linear.to_dict(use_name=True), {
            'x': 2,
            'y': -3
        })
        self.assertEqual(cst.sense.name, 'LE')
        self.assertEqual(cst.rhs, -2)

        q_p2 = q_p.substitute_variables(variables={'y': ('x', -0.5)})
        self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID)
        self.assertDictEqual(q_p2.objective.linear.to_dict(use_name=True), {})
        self.assertDictEqual(q_p2.objective.quadratic.to_dict(use_name=True), {
            ('x', 'x'): 0.5,
            ('z', 'z'): 2
        })
        self.assertEqual(q_p2.objective.constant, 1)
        self.assertEqual(len(q_p2.linear_constraints), 1)
        self.assertEqual(len(q_p2.quadratic_constraints), 1)

        cst = q_p2.linear_constraints[0]
        self.assertDictEqual(cst.linear.to_dict(use_name=True), {
            'x': 2,
            'z': -1
        })
        self.assertEqual(cst.sense.name, 'EQ')
        self.assertEqual(cst.rhs, 1)

        cst = q_p2.quadratic_constraints[0]
        self.assertDictEqual(cst.linear.to_dict(use_name=True), {
            'x': 2,
            'z': -1
        })
        self.assertDictEqual(cst.quadratic.to_dict(use_name=True),
                             {('x', 'z'): -1.5})
        self.assertEqual(cst.sense.name, 'LE')
        self.assertEqual(cst.rhs, -1)
Ejemplo n.º 29
0
    def test_docplex(self):
        """test from_docplex and to_docplex"""
        q_p = QuadraticProgram('test')
        q_p.binary_var(name='x')
        q_p.integer_var(name='y', lowerbound=-2, upperbound=4)
        q_p.continuous_var(name='z', lowerbound=-1.5, upperbound=3.2)
        q_p.minimize(constant=1,
                     linear={
                         'x': 1,
                         'y': 2
                     },
                     quadratic={
                         ('x', 'y'): -1,
                         ('z', 'z'): 2
                     })
        q_p.linear_constraint({'x': 2, 'z': -1}, '==', 1)
        q_p.quadratic_constraint({'x': 2, 'z': -1}, {('y', 'z'): 3}, '==', 1)
        q_p2 = QuadraticProgram()
        q_p2.from_docplex(q_p.to_docplex())
        self.assertEqual(q_p.export_as_lp_string(), q_p2.export_as_lp_string())

        mod = Model('test')
        x = mod.binary_var('x')
        y = mod.integer_var(-2, 4, 'y')
        z = mod.continuous_var(-1.5, 3.2, 'z')
        mod.minimize(1 + x + 2 * y - x * y + 2 * z * z)
        mod.add(2 * x - z == 1, 'c0')
        mod.add(2 * x - z + 3 * y * z == 1, 'q0')
        self.assertEqual(q_p.export_as_lp_string(), mod.export_as_lp_string())

        with self.assertRaises(QiskitOptimizationError):
            mod = Model()
            mod.semiinteger_var(lb=1, name='x')
            q_p.from_docplex(mod)

        with self.assertRaises(QiskitOptimizationError):
            mod = Model()
            x = mod.binary_var('x')
            mod.add_range(0, 2 * x, 1)
            q_p.from_docplex(mod)

        with self.assertRaises(QiskitOptimizationError):
            mod = Model()
            x = mod.binary_var('x')
            y = mod.binary_var('y')
            mod.add_indicator(x, x + y <= 1, 1)
            q_p.from_docplex(mod)

        with self.assertRaises(QiskitOptimizationError):
            mod = Model()
            x = mod.binary_var('x')
            y = mod.binary_var('y')
            mod.add_equivalence(x, x + y <= 1, 1)
            q_p.from_docplex(mod)

        with self.assertRaises(QiskitOptimizationError):
            mod = Model()
            x = mod.binary_var('x')
            y = mod.binary_var('y')
            mod.add(mod.not_equal_constraint(x, y + 1))
            q_p.from_docplex(mod)

        # test from_docplex without explicit variable names
        mod = Model()
        x = mod.binary_var()
        y = mod.continuous_var()
        z = mod.integer_var()
        mod.minimize(x + y + z + x * y + y * z + x * z)
        mod.add_constraint(x + y == z)  # linear EQ
        mod.add_constraint(x + y >= z)  # linear GE
        mod.add_constraint(x + y <= z)  # linear LE
        mod.add_constraint(x * y == z)  # quadratic EQ
        mod.add_constraint(x * y >= z)  # quadratic GE
        mod.add_constraint(x * y <= z)  # quadratic LE
        q_p = QuadraticProgram()
        q_p.from_docplex(mod)
        var_names = [v.name for v in q_p.variables]
        self.assertListEqual(var_names, ['x0', 'x1', 'x2'])
        senses = [
            Constraint.Sense.EQ, Constraint.Sense.GE, Constraint.Sense.LE
        ]
        for i, c in enumerate(q_p.linear_constraints):
            self.assertDictEqual(c.linear.to_dict(use_name=True), {
                'x0': 1,
                'x1': 1,
                'x2': -1
            })
            self.assertEqual(c.rhs, 0)
            self.assertEqual(c.sense, senses[i])
        for i, c in enumerate(q_p.quadratic_constraints):
            self.assertEqual(c.rhs, 0)
            self.assertDictEqual(c.linear.to_dict(use_name=True), {'x2': -1})
            self.assertDictEqual(c.quadratic.to_dict(use_name=True),
                                 {('x0', 'x1'): 1})
            self.assertEqual(c.sense, senses[i])
Ejemplo n.º 30
0
    def test_var_dict(self):
        """test {binary,integer,continuous}_var_dict"""
        q_p = QuadraticProgram()

        d_0 = q_p.continuous_var_dict(name='a', key_format='_{}', keys=3)
        self.assertSetEqual(set(d_0.keys()), {'a_0', 'a_1', 'a_2'})
        self.assertSetEqual({var.name
                             for var in q_p.variables}, {'a_0', 'a_1', 'a_2'})
        for var in q_p.variables:
            self.assertAlmostEqual(var.lowerbound, 0)
            self.assertAlmostEqual(var.upperbound, INFINITY)
            self.assertEqual(var.vartype, VarType.CONTINUOUS)
            self.assertTupleEqual(var.as_tuple(), d_0[var.name].as_tuple())

        d_1 = q_p.binary_var_dict(name='b', keys=5)
        self.assertSetEqual(set(d_1.keys()), {'b3', 'b4', 'b5', 'b6', 'b7'})
        self.assertSetEqual(
            {var.name
             for var in q_p.variables},
            {'a_0', 'a_1', 'a_2', 'b3', 'b4', 'b5', 'b6', 'b7'})
        for var in q_p.variables[-5:]:
            self.assertAlmostEqual(var.lowerbound, 0)
            self.assertAlmostEqual(var.upperbound, 1)
            self.assertEqual(var.vartype, VarType.BINARY)
            self.assertTupleEqual(var.as_tuple(), d_1[var.name].as_tuple())

        d_2 = q_p.integer_var_dict(keys=1,
                                   key_format='-{}',
                                   lowerbound=-4,
                                   upperbound=10)
        self.assertSetEqual(set(d_2.keys()), {'x-8'})
        self.assertSetEqual(
            {var.name
             for var in q_p.variables},
            {'a_0', 'a_1', 'a_2', 'b3', 'b4', 'b5', 'b6', 'b7', 'x-8'})
        for var in q_p.variables[-1:]:
            self.assertAlmostEqual(var.lowerbound, -4)
            self.assertAlmostEqual(var.upperbound, 10)
            self.assertEqual(var.vartype, VarType.INTEGER)
            self.assertTupleEqual(var.as_tuple(), d_2[var.name].as_tuple())

        d_3 = q_p.binary_var_dict(name='c', keys=range(3))
        self.assertSetEqual(set(d_3.keys()), {'c0', 'c1', 'c2'})
        self.assertSetEqual({var.name
                             for var in q_p.variables}, {
                                 'a_0', 'a_1', 'a_2', 'b3', 'b4', 'b5', 'b6',
                                 'b7', 'x-8', 'c0', 'c1', 'c2'
                             })
        for var in q_p.variables[-3:]:
            self.assertAlmostEqual(var.lowerbound, 0)
            self.assertAlmostEqual(var.upperbound, 1)
            self.assertEqual(var.vartype, VarType.BINARY)
            self.assertTupleEqual(var.as_tuple(), d_3[var.name].as_tuple())

        with self.assertRaises(QiskitOptimizationError):
            q_p.binary_var_dict(name='c', keys=range(3))

        d_4 = q_p.binary_var_dict(1, 'x', '_')
        self.assertSetEqual(set(d_4.keys()), {'x_'})
        self.assertSetEqual({var.name
                             for var in q_p.variables}, {
                                 'a_0', 'a_1', 'a_2', 'b3', 'b4', 'b5', 'b6',
                                 'b7', 'x-8', 'c0', 'c1', 'c2', 'x_'
                             })
        for var in q_p.variables[-1:]:
            self.assertAlmostEqual(var.lowerbound, 0)
            self.assertAlmostEqual(var.upperbound, 1)
            self.assertEqual(var.vartype, VarType.BINARY)
            self.assertTupleEqual(var.as_tuple(), d_4[var.name].as_tuple())

        with self.assertRaises(QiskitOptimizationError):
            q_p.binary_var_dict(1, 'x', '_')

        with self.assertRaises(QiskitOptimizationError):
            q_p.binary_var('x_')

        d_5 = q_p.continuous_var_dict(1, -1, 2, '', '')
        self.assertSetEqual(set(d_5.keys()), {''})
        self.assertSetEqual({var.name
                             for var in q_p.variables}, {
                                 'a_0', 'a_1', 'a_2', 'b3', 'b4', 'b5', 'b6',
                                 'b7', 'x-8', 'c0', 'c1', 'c2', 'x_', ''
                             })
        for var in q_p.variables[-1:]:
            self.assertAlmostEqual(var.lowerbound, -1)
            self.assertAlmostEqual(var.upperbound, 2)
            self.assertEqual(var.vartype, VarType.CONTINUOUS)
            self.assertTupleEqual(var.as_tuple(), d_5[var.name].as_tuple())

        with self.assertRaises(QiskitOptimizationError):
            q_p.binary_var_dict(1, '', '')

        with self.assertRaises(QiskitOptimizationError):
            q_p.integer_var(0, 1, '')

        with self.assertRaises(QiskitOptimizationError):
            q_p = QuadraticProgram()
            q_p.binary_var_dict(keys=1, key_format='{}{}')

        with self.assertRaises(QiskitOptimizationError):
            q_p = QuadraticProgram()
            q_p.binary_var_dict(keys=0)

        with self.assertRaises(QiskitOptimizationError):
            q_p = QuadraticProgram()
            q_p.binary_var_dict(keys=1, key_format='_{{}}')

        with self.assertRaises(QiskitOptimizationError):
            q_p = QuadraticProgram()
            q_p.binary_var_dict(keys=2, key_format='')

        with self.assertRaises(QiskitOptimizationError):
            q_p = QuadraticProgram()
            q_p.binary_var_dict(keys=range(2), key_format='')