def test_linear_inequality_to_penalty4(self):
        """Test special constraint to penalty x1+x2+x3+... <= 1 -> P(x1*x2+x1*x3+...)"""

        op = QuadraticProgram()
        lip = LinearInequalityToPenalty()

        op.binary_var(name="x")
        op.binary_var(name="y")
        op.binary_var(name="z")
        # Linear constraints
        linear_constraint = {"x": 1, "y": 1, "z": 1}
        op.linear_constraint(linear_constraint, Constraint.Sense.LE, 1,
                             "P(xy+yz+zx)")

        # Test with no max/min
        with self.subTest("No max/min"):
            self.assertEqual(op.get_num_linear_constraints(), 1)
            penalty = 1
            quadratic = {
                ("x", "y"): penalty,
                ("x", "z"): penalty,
                ("y", "z"): penalty
            }
            op2 = lip.convert(op)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)

        # Test maximize
        op = QuadraticProgram()
        op.binary_var_list(5)
        linear2 = [1, 1, 0, 0, 0]
        op.maximize(linear=linear2)
        op.linear_constraint([1, 1, 1, 1, 1], Constraint.Sense.LE, 1, "")

        with self.subTest("Maximum"):
            self.assertEqual(op.get_num_linear_constraints(), 1)
            lip.penalty = 5
            quadratic2 = [
                [0, 1, 1, 1, 1],
                [0, 0, 1, 1, 1],
                [0, 0, 0, 1, 1],
                [0, 0, 0, 0, 1],
                [0, 0, 0, 0, 0],
            ]
            op2 = lip.convert(op)
            ldct2 = op2.objective.linear.to_array()
            qdct2 = op2.objective.quadratic.to_array() / lip.penalty * -1
            self.assertEqual(ldct2.tolist(), linear2)
            self.assertEqual(qdct2.tolist(), quadratic2)
            self.assertEqual(op2.get_num_linear_constraints(), 0)
Exemple #2
0
 def test_integer_to_binary2(self):
     """Test integer to binary variables 2"""
     mod = QuadraticProgram()
     mod.integer_var(name="x", lowerbound=0, upperbound=1)
     mod.integer_var(name="y", lowerbound=0, upperbound=1)
     mod.minimize(1, {"x": 1}, {("x", "y"): 2})
     mod.linear_constraint({"x": 1}, "==", 1)
     mod.quadratic_constraint({"x": 1}, {("x", "y"): 2}, "==", 1)
     mod2 = IntegerToBinary().convert(mod)
     self.assertListEqual([e.name + "@0" for e in mod.variables],
                          [e.name for e in mod2.variables])
     self.assertDictEqual(mod.objective.linear.to_dict(),
                          mod2.objective.linear.to_dict())
     self.assertDictEqual(mod.objective.quadratic.to_dict(),
                          mod2.objective.quadratic.to_dict())
     self.assertEqual(mod.get_num_linear_constraints(),
                      mod2.get_num_linear_constraints())
     for cst, cst2 in zip(mod.linear_constraints, mod2.linear_constraints):
         self.assertDictEqual(cst.linear.to_dict(), cst2.linear.to_dict())
     self.assertEqual(mod.get_num_quadratic_constraints(),
                      mod2.get_num_quadratic_constraints())
     for cst, cst2 in zip(mod.quadratic_constraints,
                          mod2.quadratic_constraints):
         self.assertDictEqual(cst.linear.to_dict(), cst2.linear.to_dict())
         self.assertDictEqual(cst.quadratic.to_dict(),
                              cst2.quadratic.to_dict())
    def test_linear_inequality_to_penalty3(self):
        """Test special constraint to penalty x1+x2+x3+... >= n-1 -> P(x1*x2+x1*x3+...)"""

        op = QuadraticProgram()
        lip = LinearInequalityToPenalty()
        op.binary_var_list(5)

        # Linear constraints
        n = 5
        op.linear_constraint([1, 1, 1, 1, 1], Constraint.Sense.GE, n - 1, "")

        # Test with no max/min
        with self.subTest("No max/min"):
            self.assertEqual(op.get_num_linear_constraints(), 1)
            penalty = 5
            lip.penalty = penalty

            constant = 10
            linear = [n - 1, n - 1, n - 1, n - 1, n - 1]
            quadratic = [
                [0, 1, 1, 1, 1],
                [0, 0, 1, 1, 1],
                [0, 0, 0, 1, 1],
                [0, 0, 0, 0, 1],
                [0, 0, 0, 0, 0],
            ]
            op2 = lip.convert(op)
            cnst2 = op2.objective.constant / penalty
            ldct2 = op2.objective.linear.to_array() / penalty * -1
            qdct2 = op2.objective.quadratic.to_array() / penalty
            self.assertEqual(cnst2, constant)
            self.assertEqual(ldct2.tolist(), linear)
            self.assertEqual(qdct2.tolist(), quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)
Exemple #4
0
    def test_ising_to_quadraticprogram_quadratic(self):
        """Test optimization problem to operators with linear=False"""
        op = QUBIT_OP_MAXIMIZE_SAMPLE
        offset = OFFSET_MAXIMIZE_SAMPLE

        quadratic = QuadraticProgram()
        quadratic.from_ising(op, offset, linear=False)

        self.assertEqual(quadratic.get_num_vars(), 4)
        self.assertEqual(quadratic.get_num_linear_constraints(), 0)
        self.assertEqual(quadratic.get_num_quadratic_constraints(), 0)
        self.assertEqual(quadratic.objective.sense,
                         quadratic.objective.Sense.MINIMIZE)
        self.assertAlmostEqual(quadratic.objective.constant, 900000)

        quadratic_matrix = np.zeros((4, 4))
        quadratic_matrix[0, 0] = -500001
        quadratic_matrix[0, 1] = 400000
        quadratic_matrix[0, 2] = 600000
        quadratic_matrix[0, 3] = 800000
        quadratic_matrix[1, 1] = -800001
        quadratic_matrix[1, 2] = 1200000
        quadratic_matrix[1, 3] = 1600000
        quadratic_matrix[2, 2] = -900001
        quadratic_matrix[2, 3] = 2400000
        quadratic_matrix[3, 3] = -800001

        np.testing.assert_array_almost_equal(
            quadratic.objective.quadratic.coefficients.toarray(),
            quadratic_matrix)
Exemple #5
0
 def test_constructor(self):
     """test constructor"""
     quadratic_program = QuadraticProgram()
     self.assertEqual(quadratic_program.name, "")
     self.assertEqual(quadratic_program.status, QuadraticProgram.Status.VALID)
     self.assertEqual(quadratic_program.get_num_vars(), 0)
     self.assertEqual(quadratic_program.get_num_linear_constraints(), 0)
     self.assertEqual(quadratic_program.get_num_quadratic_constraints(), 0)
     self.assertEqual(quadratic_program.objective.constant, 0)
     self.assertDictEqual(quadratic_program.objective.linear.to_dict(), {})
     self.assertDictEqual(quadratic_program.objective.quadratic.to_dict(), {})
    def test_linear_inequality_to_penalty7(self):
        """Test special constraint to penalty 6 x-y >= 0 -> P(y-x*y)"""

        op = QuadraticProgram()
        lip = LinearInequalityToPenalty()

        op.binary_var(name="x")
        op.binary_var(name="y")
        # Linear constraints
        linear_constraint = {"x": 1, "y": -1}
        op.linear_constraint(linear_constraint, Constraint.Sense.GE, 0,
                             "P(y-xy)")

        # Test with no max/min
        with self.subTest("No max/min"):
            self.assertEqual(op.get_num_linear_constraints(), 1)
            penalty = 1
            linear = {"y": penalty}
            quadratic = {("x", "y"): -1 * penalty}
            op2 = lip.convert(op)
            ldct = op2.objective.linear.to_dict(use_name=True)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(ldct, linear)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)

        # Test maximize
        with self.subTest("Maximize"):
            linear = {"x": 2, "y": 1}
            op.maximize(linear=linear)
            penalty = 4
            linear["y"] = linear["y"] - penalty
            quadratic = {("x", "y"): penalty}
            op2 = lip.convert(op)
            ldct = op2.objective.linear.to_dict(use_name=True)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(ldct, linear)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)

        # Test minimize
        with self.subTest("Minimize"):
            linear = {"x": 2, "y": 1}
            op.minimize(linear={"x": 2, "y": 1})
            penalty = 4
            linear["y"] = linear["y"] + penalty
            quadratic = {("x", "y"): -1 * penalty}
            op2 = lip.convert(op)
            ldct = op2.objective.linear.to_dict(use_name=True)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(ldct, linear)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)
Exemple #7
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)
Exemple #8
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(), {})
Exemple #9
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))
Exemple #10
0
    def test_penalize_integer(self):
        """Test PenalizeLinearEqualityConstraints with integer variables"""
        op = QuadraticProgram()
        for i in range(3):
            op.integer_var(name="x{}".format(i), lowerbound=-3, upperbound=3)
        # 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": -1}
        op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1, "x0x2")
        op.minimize(constant=3, linear={"x0": 1}, quadratic={("x1", "x2"): 2})
        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([0, 1, -1])
        np.testing.assert_array_almost_equal(new_x, [0, 1, -1])
 def test_integer_to_binary_quadratic(self):
     """Test integer to binary variables with quadratic expressions"""
     mod = QuadraticProgram()
     mod.integer_var(name="x", lowerbound=10, upperbound=13)
     mod.minimize(quadratic={("x", "x"): 1})
     mod2 = IntegerToBinary().convert(mod)
     self.assertListEqual([e.name for e in mod2.variables], ["x@0", "x@1"])
     self.assertEqual(mod.get_num_linear_constraints(), 0)
     self.assertEqual(mod.get_num_quadratic_constraints(), 0)
     self.assertAlmostEqual(mod2.objective.constant, 100)
     self.assertDictEqual(mod2.objective.linear.to_dict(use_name=True), {
         "x@0": 20,
         "x@1": 40
     })
     self.assertDictEqual(
         mod2.objective.quadratic.to_dict(use_name=True),
         {
             ("x@0", "x@0"): 1,
             ("x@1", "x@1"): 4,
             ("x@0", "x@1"): 4
         },
     )
 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(), {})
    def test_init(self):
        """ test init. """

        quadratic_program = QuadraticProgram()
        for _ in range(5):
            quadratic_program.continuous_var()
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 0)

        coefficients = np.array(range(5))

        # equality constraints
        quadratic_program.linear_constraint(sense='==')
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 1)
        self.assertEqual(quadratic_program.linear_constraints[0].name, 'c0')
        self.assertEqual(
            len(quadratic_program.linear_constraints[0].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[0].sense,
                         Constraint.Sense.EQ)
        self.assertEqual(quadratic_program.linear_constraints[0].rhs, 0.0)
        self.assertEqual(quadratic_program.linear_constraints[0],
                         quadratic_program.get_linear_constraint('c0'))
        self.assertEqual(quadratic_program.linear_constraints[0],
                         quadratic_program.get_linear_constraint(0))

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name='c0')

        quadratic_program.linear_constraint(coefficients, '==', 1.0, 'c1')
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 2)
        self.assertEqual(quadratic_program.linear_constraints[1].name, 'c1')
        self.assertTrue(
            (quadratic_program.linear_constraints[1].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[1].sense,
                         Constraint.Sense.EQ)
        self.assertEqual(quadratic_program.linear_constraints[1].rhs, 1.0)
        self.assertEqual(quadratic_program.linear_constraints[1],
                         quadratic_program.get_linear_constraint('c1'))
        self.assertEqual(quadratic_program.linear_constraints[1],
                         quadratic_program.get_linear_constraint(1))

        # geq constraints
        quadratic_program.linear_constraint(sense='>=')
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 3)
        self.assertEqual(quadratic_program.linear_constraints[2].name, 'c2')
        self.assertEqual(
            len(quadratic_program.linear_constraints[2].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[2].sense,
                         Constraint.Sense.GE)
        self.assertEqual(quadratic_program.linear_constraints[2].rhs, 0.0)
        self.assertEqual(quadratic_program.linear_constraints[2],
                         quadratic_program.get_linear_constraint('c2'))
        self.assertEqual(quadratic_program.linear_constraints[2],
                         quadratic_program.get_linear_constraint(2))

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name='c2', sense='>=')

        quadratic_program.linear_constraint(coefficients, '>=', 1.0, 'c3')
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 4)
        self.assertEqual(quadratic_program.linear_constraints[3].name, 'c3')
        self.assertTrue(
            (quadratic_program.linear_constraints[3].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[3].sense,
                         Constraint.Sense.GE)
        self.assertEqual(quadratic_program.linear_constraints[3].rhs, 1.0)
        self.assertEqual(quadratic_program.linear_constraints[3],
                         quadratic_program.get_linear_constraint('c3'))
        self.assertEqual(quadratic_program.linear_constraints[3],
                         quadratic_program.get_linear_constraint(3))

        # leq constraints
        quadratic_program.linear_constraint(sense='<=')
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 5)
        self.assertEqual(quadratic_program.linear_constraints[4].name, 'c4')
        self.assertEqual(
            len(quadratic_program.linear_constraints[4].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[4].sense,
                         Constraint.Sense.LE)
        self.assertEqual(quadratic_program.linear_constraints[4].rhs, 0.0)
        self.assertEqual(quadratic_program.linear_constraints[4],
                         quadratic_program.get_linear_constraint('c4'))
        self.assertEqual(quadratic_program.linear_constraints[4],
                         quadratic_program.get_linear_constraint(4))

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name='c4', sense='<=')

        quadratic_program.linear_constraint(coefficients, '<=', 1.0, 'c5')
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 6)
        self.assertEqual(quadratic_program.linear_constraints[5].name, 'c5')
        self.assertTrue(
            (quadratic_program.linear_constraints[5].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[5].sense,
                         Constraint.Sense.LE)
        self.assertEqual(quadratic_program.linear_constraints[5].rhs, 1.0)
        self.assertEqual(quadratic_program.linear_constraints[5],
                         quadratic_program.get_linear_constraint('c5'))
        self.assertEqual(quadratic_program.linear_constraints[5],
                         quadratic_program.get_linear_constraint(5))
Exemple #14
0
class TestLinearConstraint(QiskitOptimizationTestCase):
    """Test LinearConstraint."""
    def setUp(self) -> None:
        super().setUp()
        self.quadratic_program = QuadraticProgram()
        self.quadratic_program.binary_var_list(3, name="x")
        self.quadratic_program.linear_constraint({"x0": 1, "x1": -2}, "<=", 1)
        self.quadratic_program.linear_constraint({"x0": 1, "x1": -2}, "<", 1)
        self.quadratic_program.linear_constraint({"x0": 1, "x1": -2}, "LE", 1)
        self.quadratic_program.linear_constraint({"x0": 1, "x1": -2}, "L", 1)
        self.quadratic_program.linear_constraint({"x0": -1, "x1": 2}, "==", 2)
        self.quadratic_program.linear_constraint({"x0": -1, "x1": 2}, "=", 2)
        self.quadratic_program.linear_constraint({"x0": -1, "x1": 2}, "EQ", 2)
        self.quadratic_program.linear_constraint({"x0": -1, "x1": 2}, "E", 2)
        self.quadratic_program.linear_constraint({"x1": 2, "x2": -1}, ">=", 3)
        self.quadratic_program.linear_constraint({"x1": 2, "x2": -1}, ">", 3)
        self.quadratic_program.linear_constraint({"x1": 2, "x2": -1}, "GE", 3)
        self.quadratic_program.linear_constraint({"x1": 2, "x2": -1}, "G", 3)

    def test_init(self):
        """test init."""

        quadratic_program = QuadraticProgram()
        for _ in range(5):
            quadratic_program.continuous_var()
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 0)

        coefficients = np.array(range(5))

        # equality constraints
        quadratic_program.linear_constraint(sense="==")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 1)
        self.assertEqual(quadratic_program.linear_constraints[0].name, "c0")
        self.assertEqual(
            len(quadratic_program.linear_constraints[0].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[0].sense,
                         Constraint.Sense.EQ)
        self.assertEqual(quadratic_program.linear_constraints[0].rhs, 0.0)
        self.assertEqual(
            quadratic_program.linear_constraints[0],
            quadratic_program.get_linear_constraint("c0"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[0],
            quadratic_program.get_linear_constraint(0),
        )

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name="c0")

        quadratic_program.linear_constraint(coefficients, "==", 1.0, "c1")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 2)
        self.assertEqual(quadratic_program.linear_constraints[1].name, "c1")
        self.assertTrue(
            (quadratic_program.linear_constraints[1].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[1].sense,
                         Constraint.Sense.EQ)
        self.assertEqual(quadratic_program.linear_constraints[1].rhs, 1.0)
        self.assertEqual(
            quadratic_program.linear_constraints[1],
            quadratic_program.get_linear_constraint("c1"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[1],
            quadratic_program.get_linear_constraint(1),
        )

        # geq constraints
        quadratic_program.linear_constraint(sense=">=")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 3)
        self.assertEqual(quadratic_program.linear_constraints[2].name, "c2")
        self.assertEqual(
            len(quadratic_program.linear_constraints[2].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[2].sense,
                         Constraint.Sense.GE)
        self.assertEqual(quadratic_program.linear_constraints[2].rhs, 0.0)
        self.assertEqual(
            quadratic_program.linear_constraints[2],
            quadratic_program.get_linear_constraint("c2"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[2],
            quadratic_program.get_linear_constraint(2),
        )

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name="c2", sense=">=")

        quadratic_program.linear_constraint(coefficients, ">=", 1.0, "c3")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 4)
        self.assertEqual(quadratic_program.linear_constraints[3].name, "c3")
        self.assertTrue(
            (quadratic_program.linear_constraints[3].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[3].sense,
                         Constraint.Sense.GE)
        self.assertEqual(quadratic_program.linear_constraints[3].rhs, 1.0)
        self.assertEqual(
            quadratic_program.linear_constraints[3],
            quadratic_program.get_linear_constraint("c3"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[3],
            quadratic_program.get_linear_constraint(3),
        )

        # leq constraints
        quadratic_program.linear_constraint(sense="<=")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 5)
        self.assertEqual(quadratic_program.linear_constraints[4].name, "c4")
        self.assertEqual(
            len(quadratic_program.linear_constraints[4].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[4].sense,
                         Constraint.Sense.LE)
        self.assertEqual(quadratic_program.linear_constraints[4].rhs, 0.0)
        self.assertEqual(
            quadratic_program.linear_constraints[4],
            quadratic_program.get_linear_constraint("c4"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[4],
            quadratic_program.get_linear_constraint(4),
        )

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name="c4", sense="<=")

        quadratic_program.linear_constraint(coefficients, "<=", 1.0, "c5")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 6)
        self.assertEqual(quadratic_program.linear_constraints[5].name, "c5")
        self.assertTrue(
            (quadratic_program.linear_constraints[5].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[5].sense,
                         Constraint.Sense.LE)
        self.assertEqual(quadratic_program.linear_constraints[5].rhs, 1.0)
        self.assertEqual(
            quadratic_program.linear_constraints[5],
            quadratic_program.get_linear_constraint("c5"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[5],
            quadratic_program.get_linear_constraint(5),
        )

    def test_str(self):
        """Test str"""
        self.assertEqual(self.quadratic_program.get_num_linear_constraints(),
                         12)
        for i in range(0, 4):
            self.assertEqual(
                str(self.quadratic_program.get_linear_constraint(i)),
                f"x0 - 2*x1 <= 1 'c{i}'")
        for i in range(4, 8):
            self.assertEqual(
                str(self.quadratic_program.get_linear_constraint(i)),
                f"-x0 + 2*x1 == 2 'c{i}'")
        for i in range(8, 12):
            self.assertEqual(
                str(self.quadratic_program.get_linear_constraint(i)),
                f"2*x1 - x2 >= 3 'c{i}'")

    def test_repr(self):
        """Test repr"""
        self.assertEqual(self.quadratic_program.get_num_linear_constraints(),
                         12)
        for i in range(0, 4):
            self.assertEqual(
                repr(self.quadratic_program.get_linear_constraint(i)),
                f"<LinearConstraint: x0 - 2*x1 <= 1 'c{i}'>",
            )
        for i in range(4, 8):
            self.assertEqual(
                repr(self.quadratic_program.get_linear_constraint(i)),
                f"<LinearConstraint: -x0 + 2*x1 == 2 'c{i}'>",
            )
        for i in range(8, 12):
            self.assertEqual(
                repr(self.quadratic_program.get_linear_constraint(i)),
                f"<LinearConstraint: 2*x1 - x2 >= 3 'c{i}'>",
            )
    def test_linear_inequality_to_penalty1(self):
        """Test special constraint to penalty x+y <= 1 -> P(x*y)"""

        op = QuadraticProgram()
        lip = LinearInequalityToPenalty()

        op.binary_var(name="x")
        op.binary_var(name="y")
        # Linear constraints
        linear_constraint = {"x": 1, "y": 1}
        op.linear_constraint(linear_constraint, Constraint.Sense.LE, 1,
                             "P(xy)")

        # Test with no max/min
        with self.subTest("No max/min"):
            self.assertEqual(op.get_num_linear_constraints(), 1)
            lip.penalty = 1
            quadratic = {("x", "y"): lip.penalty}
            op2 = lip.convert(op)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)

        # Test maximize
        with self.subTest("Maximize"):
            linear = {"x": 2, "y": 1}
            op.maximize(linear=linear)
            lip.penalty = 5
            quadratic = {("x", "y"): -1 * lip.penalty}
            op2 = lip.convert(op)
            ldct = op2.objective.linear.to_dict(use_name=True)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(ldct, linear)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)

        # Test minimize
        with self.subTest("Minimize"):
            linear = {"x": 2, "y": 1}
            op.minimize(linear=linear)
            lip.penalty = 5
            quadratic = {("x", "y"): lip.penalty}
            op2 = lip.convert(op)
            ldct = op2.objective.linear.to_dict(use_name=True)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(ldct, linear)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 0)

        # Test combination
        with self.subTest("Combination"):
            op = QuadraticProgram()
            lip = LinearInequalityToPenalty()

            op.binary_var(name="x")
            op.binary_var(name="y")
            op.binary_var(name="z")
            op.binary_var(name="w")
            linear = {"x": 2, "y": 1, "z": -1, "w": 1}
            quadratic = {("y", "z"): -2, ("w", "w"): 1}
            op.minimize(linear=linear, quadratic=quadratic)

            linear_constraint = {"x": 1, "w": 1}
            op.linear_constraint(linear_constraint, Constraint.Sense.LE, 1,
                                 "P(xw)")
            linear_constraint = {"y": 1, "z": 1}
            op.linear_constraint(linear_constraint, Constraint.Sense.LE, 1,
                                 "P(yz)")
            linear_constraint = {"y": 2, "z": 1}
            op.linear_constraint(linear_constraint, Constraint.Sense.EQ, 1,
                                 "None 1")
            quadratic_constraint = {("x", "x"): -2, ("y", "w"): 1}
            op.quadratic_constraint(linear_constraint, quadratic_constraint,
                                    Constraint.Sense.LE, 1, "None 2")

            lip.penalty = 5
            op2 = lip.convert(op)
            quadratic[("x", "w")] = lip.penalty
            quadratic[("y", "z")] = quadratic[("y", "z")] + lip.penalty
            ldct = op2.objective.linear.to_dict(use_name=True)
            qdct = op2.objective.quadratic.to_dict(use_name=True)
            self.assertEqual(ldct, linear)
            self.assertEqual(qdct, quadratic)
            self.assertEqual(op2.get_num_linear_constraints(), 1)
            self.assertEqual(op2.get_num_quadratic_constraints(), 1)
    def test_integer_to_binary_zero_range_variable(self):
        """Test integer to binary variables with zero range variables"""

        with self.subTest(
                "zero range variable in a linear expression of the objective"):
            mod = QuadraticProgram()
            mod.integer_var(name="x", lowerbound=10, upperbound=10)
            mod.minimize(linear={"x": 1})
            mod2 = IntegerToBinary().convert(mod)
            self.assertListEqual([e.name for e in mod2.variables], ["x@0"])
            self.assertEqual(mod.get_num_linear_constraints(), 0)
            self.assertEqual(mod.get_num_quadratic_constraints(), 0)
            self.assertAlmostEqual(mod2.objective.constant, 10)
            self.assertDictEqual(mod2.objective.linear.to_dict(), {})
            self.assertDictEqual(mod2.objective.quadratic.to_dict(), {})

        with self.subTest(
                "zero range variable in a quadratic expression of the objective"
        ):
            mod = QuadraticProgram()
            mod.integer_var(name="x", lowerbound=10, upperbound=10)
            mod.minimize(quadratic={("x", "x"): 1})
            mod2 = IntegerToBinary().convert(mod)
            self.assertListEqual([e.name for e in mod2.variables], ["x@0"])
            self.assertEqual(mod.get_num_linear_constraints(), 0)
            self.assertEqual(mod.get_num_quadratic_constraints(), 0)
            self.assertAlmostEqual(mod2.objective.constant, 100)
            self.assertDictEqual(mod2.objective.linear.to_dict(), {})
            self.assertDictEqual(mod2.objective.quadratic.to_dict(), {})

        with self.subTest("zero range variable in a linear constraint"):
            mod = QuadraticProgram()
            mod.integer_var(name="x", lowerbound=10, upperbound=10)
            mod.binary_var(name="y")
            mod.linear_constraint({"x": 1, "y": 1}, "<=", 100)
            mod2 = IntegerToBinary().convert(mod)
            self.assertListEqual([e.name for e in mod2.variables],
                                 ["x@0", "y"])
            self.assertEqual(mod.get_num_linear_constraints(), 1)
            self.assertEqual(mod.get_num_quadratic_constraints(), 0)
            self.assertAlmostEqual(mod2.objective.constant, 0)
            self.assertDictEqual(mod2.objective.linear.to_dict(), {})
            self.assertDictEqual(mod2.objective.quadratic.to_dict(), {})
            cst = mod2.get_linear_constraint(0)
            self.assertDictEqual(cst.linear.to_dict(use_name=True), {"y": 1})
            self.assertEqual(cst.sense, Constraint.Sense.LE)
            self.assertAlmostEqual(cst.rhs, 90)
            self.assertEqual(cst.name, "c0")

        with self.subTest("zero range variable in a quadratic constraint"):
            mod = QuadraticProgram()
            mod.integer_var(name="x", lowerbound=10, upperbound=10)
            mod.binary_var(name="y")
            mod.quadratic_constraint({"x": 1}, {
                ("x", "x"): 2,
                ("x", "y"): 3
            }, ">=", 100)
            mod2 = IntegerToBinary().convert(mod)
            self.assertListEqual([e.name for e in mod2.variables],
                                 ["x@0", "y"])
            self.assertEqual(mod.get_num_linear_constraints(), 0)
            self.assertEqual(mod.get_num_quadratic_constraints(), 1)
            self.assertAlmostEqual(mod2.objective.constant, 0)
            self.assertDictEqual(mod2.objective.linear.to_dict(), {})
            self.assertDictEqual(mod2.objective.quadratic.to_dict(), {})
            cst = mod2.get_quadratic_constraint(0)
            self.assertDictEqual(cst.linear.to_dict(use_name=True), {"y": 30})
            self.assertEqual(cst.sense, Constraint.Sense.GE)
            self.assertAlmostEqual(cst.rhs, -110)
            self.assertEqual(cst.name, "q0")
Exemple #17
0
    def test_linear_constraints_handling(self):
        """test linear constraints handling"""
        q_p = QuadraticProgram()
        q_p.binary_var("x")
        q_p.binary_var("y")
        q_p.binary_var("z")
        q_p.linear_constraint({"x": 1}, "==", 1)
        q_p.linear_constraint({"y": 1}, "<=", 1)
        q_p.linear_constraint({"z": 1}, ">=", 1)
        self.assertEqual(q_p.get_num_linear_constraints(), 3)
        lin = q_p.linear_constraints
        self.assertEqual(len(lin), 3)

        self.assertDictEqual(lin[0].linear.to_dict(), {0: 1})
        self.assertDictEqual(lin[0].linear.to_dict(use_name=True), {"x": 1})
        self.assertListEqual(lin[0].linear.to_array().tolist(), [1, 0, 0])
        self.assertEqual(lin[0].sense, Constraint.Sense.EQ)
        self.assertEqual(lin[0].rhs, 1)
        self.assertEqual(lin[0].name, "c0")
        self.assertEqual(q_p.get_linear_constraint(0).name, "c0")
        self.assertEqual(q_p.get_linear_constraint("c0").name, "c0")

        self.assertDictEqual(lin[1].linear.to_dict(), {1: 1})
        self.assertDictEqual(lin[1].linear.to_dict(use_name=True), {"y": 1})
        self.assertListEqual(lin[1].linear.to_array().tolist(), [0, 1, 0])
        self.assertEqual(lin[1].sense, Constraint.Sense.LE)
        self.assertEqual(lin[1].rhs, 1)
        self.assertEqual(lin[1].name, "c1")
        self.assertEqual(q_p.get_linear_constraint(1).name, "c1")
        self.assertEqual(q_p.get_linear_constraint("c1").name, "c1")

        self.assertDictEqual(lin[2].linear.to_dict(), {2: 1})
        self.assertDictEqual(lin[2].linear.to_dict(use_name=True), {"z": 1})
        self.assertListEqual(lin[2].linear.to_array().tolist(), [0, 0, 1])
        self.assertEqual(lin[2].sense, Constraint.Sense.GE)
        self.assertEqual(lin[2].rhs, 1)
        self.assertEqual(lin[2].name, "c2")
        self.assertEqual(q_p.get_linear_constraint(2).name, "c2")
        self.assertEqual(q_p.get_linear_constraint("c2").name, "c2")

        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(name="c0")
        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(name="c1")
        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(name="c2")
        with self.assertRaises(IndexError):
            q_p.get_linear_constraint(4)
        with self.assertRaises(KeyError):
            q_p.get_linear_constraint("c3")

        q_p.remove_linear_constraint("c1")
        lin = q_p.linear_constraints
        self.assertEqual(len(lin), 2)
        self.assertDictEqual(lin[1].linear.to_dict(), {2: 1})
        self.assertDictEqual(lin[1].linear.to_dict(use_name=True), {"z": 1})
        self.assertListEqual(lin[1].linear.to_array().tolist(), [0, 0, 1])
        self.assertEqual(lin[1].sense, Constraint.Sense.GE)
        self.assertEqual(lin[1].rhs, 1)
        self.assertEqual(lin[1].name, "c2")
        self.assertEqual(q_p.get_linear_constraint(1).name, "c2")
        self.assertEqual(q_p.get_linear_constraint("c2").name, "c2")

        with self.assertRaises(KeyError):
            q_p.remove_linear_constraint("c1")
        with self.assertRaises(IndexError):
            q_p.remove_linear_constraint(9)

        q_p.linear_constraint(sense="E")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.EQ)
        q_p.linear_constraint(sense="G")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.GE)
        q_p.linear_constraint(sense="L")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.LE)
        q_p.linear_constraint(sense="EQ")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.EQ)
        q_p.linear_constraint(sense="GE")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.GE)
        q_p.linear_constraint(sense="LE")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.LE)
        q_p.linear_constraint(sense="=")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.EQ)
        q_p.linear_constraint(sense=">")
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.GE)
        q_p.linear_constraint(sense="<")

        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(sense="=>")
    def test_init(self):
        """test init."""

        quadratic_program = QuadraticProgram()
        for _ in range(5):
            quadratic_program.continuous_var()
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 0)

        coefficients = np.array(range(5))

        # equality constraints
        quadratic_program.linear_constraint(sense="==")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 1)
        self.assertEqual(quadratic_program.linear_constraints[0].name, "c0")
        self.assertEqual(
            len(quadratic_program.linear_constraints[0].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[0].sense,
                         Constraint.Sense.EQ)
        self.assertEqual(quadratic_program.linear_constraints[0].rhs, 0.0)
        self.assertEqual(
            quadratic_program.linear_constraints[0],
            quadratic_program.get_linear_constraint("c0"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[0],
            quadratic_program.get_linear_constraint(0),
        )

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name="c0")

        quadratic_program.linear_constraint(coefficients, "==", 1.0, "c1")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 2)
        self.assertEqual(quadratic_program.linear_constraints[1].name, "c1")
        self.assertTrue(
            (quadratic_program.linear_constraints[1].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[1].sense,
                         Constraint.Sense.EQ)
        self.assertEqual(quadratic_program.linear_constraints[1].rhs, 1.0)
        self.assertEqual(
            quadratic_program.linear_constraints[1],
            quadratic_program.get_linear_constraint("c1"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[1],
            quadratic_program.get_linear_constraint(1),
        )

        # geq constraints
        quadratic_program.linear_constraint(sense=">=")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 3)
        self.assertEqual(quadratic_program.linear_constraints[2].name, "c2")
        self.assertEqual(
            len(quadratic_program.linear_constraints[2].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[2].sense,
                         Constraint.Sense.GE)
        self.assertEqual(quadratic_program.linear_constraints[2].rhs, 0.0)
        self.assertEqual(
            quadratic_program.linear_constraints[2],
            quadratic_program.get_linear_constraint("c2"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[2],
            quadratic_program.get_linear_constraint(2),
        )

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name="c2", sense=">=")

        quadratic_program.linear_constraint(coefficients, ">=", 1.0, "c3")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 4)
        self.assertEqual(quadratic_program.linear_constraints[3].name, "c3")
        self.assertTrue(
            (quadratic_program.linear_constraints[3].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[3].sense,
                         Constraint.Sense.GE)
        self.assertEqual(quadratic_program.linear_constraints[3].rhs, 1.0)
        self.assertEqual(
            quadratic_program.linear_constraints[3],
            quadratic_program.get_linear_constraint("c3"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[3],
            quadratic_program.get_linear_constraint(3),
        )

        # leq constraints
        quadratic_program.linear_constraint(sense="<=")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 5)
        self.assertEqual(quadratic_program.linear_constraints[4].name, "c4")
        self.assertEqual(
            len(quadratic_program.linear_constraints[4].linear.to_dict()), 0)
        self.assertEqual(quadratic_program.linear_constraints[4].sense,
                         Constraint.Sense.LE)
        self.assertEqual(quadratic_program.linear_constraints[4].rhs, 0.0)
        self.assertEqual(
            quadratic_program.linear_constraints[4],
            quadratic_program.get_linear_constraint("c4"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[4],
            quadratic_program.get_linear_constraint(4),
        )

        with self.assertRaises(QiskitOptimizationError):
            quadratic_program.linear_constraint(name="c4", sense="<=")

        quadratic_program.linear_constraint(coefficients, "<=", 1.0, "c5")
        self.assertEqual(quadratic_program.get_num_linear_constraints(), 6)
        self.assertEqual(quadratic_program.linear_constraints[5].name, "c5")
        self.assertTrue(
            (quadratic_program.linear_constraints[5].linear.to_array() ==
             coefficients).all())
        self.assertEqual(quadratic_program.linear_constraints[5].sense,
                         Constraint.Sense.LE)
        self.assertEqual(quadratic_program.linear_constraints[5].rhs, 1.0)
        self.assertEqual(
            quadratic_program.linear_constraints[5],
            quadratic_program.get_linear_constraint("c5"),
        )
        self.assertEqual(
            quadratic_program.linear_constraints[5],
            quadratic_program.get_linear_constraint(5),
        )
    def test_read_from_lp_file(self):
        """test read lp file"""
        try:
            q_p = QuadraticProgram()
            with self.assertRaises(FileNotFoundError):
                q_p.read_from_lp_file('')
            with self.assertRaises(FileNotFoundError):
                q_p.read_from_lp_file('no_file.txt')
            lp_file = self.get_resource_path(
                path.join('resources', 'test_quadratic_program.lp'))
            q_p.read_from_lp_file(lp_file)
            self.assertEqual(q_p.name, 'my problem')
            self.assertEqual(q_p.get_num_vars(), 3)
            self.assertEqual(q_p.get_num_binary_vars(), 1)
            self.assertEqual(q_p.get_num_integer_vars(), 1)
            self.assertEqual(q_p.get_num_continuous_vars(), 1)
            self.assertEqual(q_p.get_num_linear_constraints(), 3)
            self.assertEqual(q_p.get_num_quadratic_constraints(), 3)

            self.assertEqual(q_p.variables[0].name, 'x')
            self.assertEqual(q_p.variables[0].vartype, Variable.Type.BINARY)
            self.assertEqual(q_p.variables[0].lowerbound, 0)
            self.assertEqual(q_p.variables[0].upperbound, 1)
            self.assertEqual(q_p.variables[1].name, 'y')
            self.assertEqual(q_p.variables[1].vartype, Variable.Type.INTEGER)
            self.assertEqual(q_p.variables[1].lowerbound, -1)
            self.assertEqual(q_p.variables[1].upperbound, 5)
            self.assertEqual(q_p.variables[2].name, 'z')
            self.assertEqual(q_p.variables[2].vartype,
                             Variable.Type.CONTINUOUS)
            self.assertEqual(q_p.variables[2].lowerbound, -1)
            self.assertEqual(q_p.variables[2].upperbound, 5)

            self.assertEqual(q_p.objective.sense,
                             QuadraticObjective.Sense.MINIMIZE)
            self.assertEqual(q_p.objective.constant, 1)
            self.assertDictEqual(q_p.objective.linear.to_dict(use_name=True), {
                'x': 1,
                'y': -1,
                'z': 10
            })
            self.assertDictEqual(
                q_p.objective.quadratic.to_dict(use_name=True), {
                    ('x', 'x'): 0.5,
                    ('y', 'z'): -1
                })

            cst = q_p.linear_constraints
            self.assertEqual(cst[0].name, 'lin_eq')
            self.assertDictEqual(cst[0].linear.to_dict(use_name=True), {
                'x': 1,
                'y': 2
            })
            self.assertEqual(cst[0].sense, Constraint.Sense.EQ)
            self.assertEqual(cst[0].rhs, 1)
            self.assertEqual(cst[1].name, 'lin_leq')
            self.assertDictEqual(cst[1].linear.to_dict(use_name=True), {
                'x': 1,
                'y': 2
            })
            self.assertEqual(cst[1].sense, Constraint.Sense.LE)
            self.assertEqual(cst[1].rhs, 1)
            self.assertEqual(cst[2].name, 'lin_geq')
            self.assertDictEqual(cst[2].linear.to_dict(use_name=True), {
                'x': 1,
                'y': 2
            })
            self.assertEqual(cst[2].sense, Constraint.Sense.GE)
            self.assertEqual(cst[2].rhs, 1)

            cst = q_p.quadratic_constraints
            self.assertEqual(cst[0].name, 'quad_eq')
            self.assertDictEqual(cst[0].linear.to_dict(use_name=True), {
                'x': 1,
                'y': 1
            })
            self.assertDictEqual(cst[0].quadratic.to_dict(use_name=True), {
                ('x', 'x'): 1,
                ('y', 'z'): -1,
                ('z', 'z'): 2
            })
            self.assertEqual(cst[0].sense, Constraint.Sense.EQ)
            self.assertEqual(cst[0].rhs, 1)
            self.assertEqual(cst[1].name, 'quad_leq')
            self.assertDictEqual(cst[1].linear.to_dict(use_name=True), {
                'x': 1,
                'y': 1
            })
            self.assertDictEqual(cst[1].quadratic.to_dict(use_name=True), {
                ('x', 'x'): 1,
                ('y', 'z'): -1,
                ('z', 'z'): 2
            })
            self.assertEqual(cst[1].sense, Constraint.Sense.LE)
            self.assertEqual(cst[1].rhs, 1)
            self.assertEqual(cst[2].name, 'quad_geq')
            self.assertDictEqual(cst[2].linear.to_dict(use_name=True), {
                'x': 1,
                'y': 1
            })
            self.assertDictEqual(cst[2].quadratic.to_dict(use_name=True), {
                ('x', 'x'): 1,
                ('y', 'z'): -1,
                ('z', 'z'): 2
            })
            self.assertEqual(cst[2].sense, Constraint.Sense.GE)
            self.assertEqual(cst[2].rhs, 1)
        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
        except RuntimeError as ex:
            self.fail(str(ex))
    def test_linear_constraints_handling(self):
        """test linear constraints handling"""
        q_p = QuadraticProgram()
        q_p.binary_var('x')
        q_p.binary_var('y')
        q_p.binary_var('z')
        q_p.linear_constraint({'x': 1}, '==', 1)
        q_p.linear_constraint({'y': 1}, '<=', 1)
        q_p.linear_constraint({'z': 1}, '>=', 1)
        self.assertEqual(q_p.get_num_linear_constraints(), 3)
        lin = q_p.linear_constraints
        self.assertEqual(len(lin), 3)

        self.assertDictEqual(lin[0].linear.to_dict(), {0: 1})
        self.assertDictEqual(lin[0].linear.to_dict(use_name=True), {'x': 1})
        self.assertListEqual(lin[0].linear.to_array().tolist(), [1, 0, 0])
        self.assertEqual(lin[0].sense, Constraint.Sense.EQ)
        self.assertEqual(lin[0].rhs, 1)
        self.assertEqual(lin[0].name, 'c0')
        self.assertEqual(q_p.get_linear_constraint(0).name, 'c0')
        self.assertEqual(q_p.get_linear_constraint('c0').name, 'c0')

        self.assertDictEqual(lin[1].linear.to_dict(), {1: 1})
        self.assertDictEqual(lin[1].linear.to_dict(use_name=True), {'y': 1})
        self.assertListEqual(lin[1].linear.to_array().tolist(), [0, 1, 0])
        self.assertEqual(lin[1].sense, Constraint.Sense.LE)
        self.assertEqual(lin[1].rhs, 1)
        self.assertEqual(lin[1].name, 'c1')
        self.assertEqual(q_p.get_linear_constraint(1).name, 'c1')
        self.assertEqual(q_p.get_linear_constraint('c1').name, 'c1')

        self.assertDictEqual(lin[2].linear.to_dict(), {2: 1})
        self.assertDictEqual(lin[2].linear.to_dict(use_name=True), {'z': 1})
        self.assertListEqual(lin[2].linear.to_array().tolist(), [0, 0, 1])
        self.assertEqual(lin[2].sense, Constraint.Sense.GE)
        self.assertEqual(lin[2].rhs, 1)
        self.assertEqual(lin[2].name, 'c2')
        self.assertEqual(q_p.get_linear_constraint(2).name, 'c2')
        self.assertEqual(q_p.get_linear_constraint('c2').name, 'c2')

        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(name='c0')
        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(name='c1')
        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(name='c2')
        with self.assertRaises(IndexError):
            q_p.get_linear_constraint(4)
        with self.assertRaises(KeyError):
            q_p.get_linear_constraint('c3')

        q_p.remove_linear_constraint('c1')
        lin = q_p.linear_constraints
        self.assertEqual(len(lin), 2)
        self.assertDictEqual(lin[1].linear.to_dict(), {2: 1})
        self.assertDictEqual(lin[1].linear.to_dict(use_name=True), {'z': 1})
        self.assertListEqual(lin[1].linear.to_array().tolist(), [0, 0, 1])
        self.assertEqual(lin[1].sense, Constraint.Sense.GE)
        self.assertEqual(lin[1].rhs, 1)
        self.assertEqual(lin[1].name, 'c2')
        self.assertEqual(q_p.get_linear_constraint(1).name, 'c2')
        self.assertEqual(q_p.get_linear_constraint('c2').name, 'c2')

        with self.assertRaises(KeyError):
            q_p.remove_linear_constraint('c1')
        with self.assertRaises(IndexError):
            q_p.remove_linear_constraint(9)

        q_p.linear_constraint(sense='E')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.EQ)
        q_p.linear_constraint(sense='G')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.GE)
        q_p.linear_constraint(sense='L')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.LE)
        q_p.linear_constraint(sense='EQ')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.EQ)
        q_p.linear_constraint(sense='GE')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.GE)
        q_p.linear_constraint(sense='LE')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.LE)
        q_p.linear_constraint(sense='=')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.EQ)
        q_p.linear_constraint(sense='>')
        self.assertEqual(q_p.linear_constraints[-1].sense, Constraint.Sense.GE)
        q_p.linear_constraint(sense='<')

        with self.assertRaises(QiskitOptimizationError):
            q_p.linear_constraint(sense='=>')
Exemple #21
0
    def test_read_from_lp_file(self):
        """test read lp file"""
        try:
            q_p = QuadraticProgram()
            with self.assertRaises(FileNotFoundError):
                q_p.read_from_lp_file("")
            with self.assertRaises(FileNotFoundError):
                q_p.read_from_lp_file("no_file.txt")
            lp_file = self.get_resource_path("test_quadratic_program.lp",
                                             "problems/resources")
            q_p.read_from_lp_file(lp_file)
            self.assertEqual(q_p.name, "my problem")
            self.assertEqual(q_p.get_num_vars(), 3)
            self.assertEqual(q_p.get_num_binary_vars(), 1)
            self.assertEqual(q_p.get_num_integer_vars(), 1)
            self.assertEqual(q_p.get_num_continuous_vars(), 1)
            self.assertEqual(q_p.get_num_linear_constraints(), 3)
            self.assertEqual(q_p.get_num_quadratic_constraints(), 3)

            self.assertEqual(q_p.variables[0].name, "x")
            self.assertEqual(q_p.variables[0].vartype, Variable.Type.BINARY)
            self.assertEqual(q_p.variables[0].lowerbound, 0)
            self.assertEqual(q_p.variables[0].upperbound, 1)
            self.assertEqual(q_p.variables[1].name, "y")
            self.assertEqual(q_p.variables[1].vartype, Variable.Type.INTEGER)
            self.assertEqual(q_p.variables[1].lowerbound, -1)
            self.assertEqual(q_p.variables[1].upperbound, 5)
            self.assertEqual(q_p.variables[2].name, "z")
            self.assertEqual(q_p.variables[2].vartype,
                             Variable.Type.CONTINUOUS)
            self.assertEqual(q_p.variables[2].lowerbound, -1)
            self.assertEqual(q_p.variables[2].upperbound, 5)

            self.assertEqual(q_p.objective.sense,
                             QuadraticObjective.Sense.MINIMIZE)
            self.assertEqual(q_p.objective.constant, 1)
            self.assertDictEqual(q_p.objective.linear.to_dict(use_name=True), {
                "x": 1,
                "y": -1,
                "z": 10
            })
            self.assertDictEqual(
                q_p.objective.quadratic.to_dict(use_name=True),
                {
                    ("x", "x"): 0.5,
                    ("y", "z"): -1
                },
            )

            cst = q_p.linear_constraints
            self.assertEqual(cst[0].name, "lin_eq")
            self.assertDictEqual(cst[0].linear.to_dict(use_name=True), {
                "x": 1,
                "y": 2
            })
            self.assertEqual(cst[0].sense, Constraint.Sense.EQ)
            self.assertEqual(cst[0].rhs, 1)
            self.assertEqual(cst[1].name, "lin_leq")
            self.assertDictEqual(cst[1].linear.to_dict(use_name=True), {
                "x": 1,
                "y": 2
            })
            self.assertEqual(cst[1].sense, Constraint.Sense.LE)
            self.assertEqual(cst[1].rhs, 1)
            self.assertEqual(cst[2].name, "lin_geq")
            self.assertDictEqual(cst[2].linear.to_dict(use_name=True), {
                "x": 1,
                "y": 2
            })
            self.assertEqual(cst[2].sense, Constraint.Sense.GE)
            self.assertEqual(cst[2].rhs, 1)

            cst = q_p.quadratic_constraints
            self.assertEqual(cst[0].name, "quad_eq")
            self.assertDictEqual(cst[0].linear.to_dict(use_name=True), {
                "x": 1,
                "y": 1
            })
            self.assertDictEqual(
                cst[0].quadratic.to_dict(use_name=True),
                {
                    ("x", "x"): 1,
                    ("y", "z"): -1,
                    ("z", "z"): 2
                },
            )
            self.assertEqual(cst[0].sense, Constraint.Sense.EQ)
            self.assertEqual(cst[0].rhs, 1)
            self.assertEqual(cst[1].name, "quad_leq")
            self.assertDictEqual(cst[1].linear.to_dict(use_name=True), {
                "x": 1,
                "y": 1
            })
            self.assertDictEqual(
                cst[1].quadratic.to_dict(use_name=True),
                {
                    ("x", "x"): 1,
                    ("y", "z"): -1,
                    ("z", "z"): 2
                },
            )
            self.assertEqual(cst[1].sense, Constraint.Sense.LE)
            self.assertEqual(cst[1].rhs, 1)
            self.assertEqual(cst[2].name, "quad_geq")
            self.assertDictEqual(cst[2].linear.to_dict(use_name=True), {
                "x": 1,
                "y": 1
            })
            self.assertDictEqual(
                cst[2].quadratic.to_dict(use_name=True),
                {
                    ("x", "x"): 1,
                    ("y", "z"): -1,
                    ("z", "z"): 2
                },
            )
            self.assertEqual(cst[2].sense, Constraint.Sense.GE)
            self.assertEqual(cst[2].rhs, 1)
        except RuntimeError as ex:
            self.fail(str(ex))