Exemplo n.º 1
0
    def test_normInf(self):
        # Constant argument.
        p = Problem(Minimize(normInf(-2)))
        result = p.solve()
        self.assertAlmostEqual(result, 2)

        # Scalar arguments.
        p = Problem(Minimize(normInf(self.a)), [self.a >= 2])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertAlmostEqual(self.a.value, 2)

        p = Problem(Minimize(3 * normInf(self.a + 2 * self.b) + self.c),
                    [self.a >= 2, self.b <= -1, self.c == 3])
        result = p.solve()
        self.assertAlmostEqual(result, 3)
        self.assertAlmostEqual(self.a.value + 2 * self.b.value, 0)
        self.assertAlmostEqual(self.c.value, 3)

        # Maximize
        p = Problem(Maximize(-normInf(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, -2)
        self.assertAlmostEqual(self.a.value, -2)

        # Vector arguments.
        p = Problem(Minimize(normInf(self.x - self.z) + 5),
                    [self.x >= [2, 3], self.z <= [-1, -4]])
        result = p.solve()
        self.assertAlmostEqual(float(result), 12)
        self.assertAlmostEqual(
            float(list(self.x.value)[1] - list(self.z.value)[1]), 7)
Exemplo n.º 2
0
    def test_dual_variables(self):
        p = Problem(Minimize( norm1(self.x + self.z) ),
            [self.x >= [2,3],
             [[1,2],[3,4]]*self.z == [-1,-4],
             norm2(self.x + self.z) <= 100])
        result = p.solve()
        self.assertAlmostEqual(result, 4)
        self.assertItemsAlmostEqual(self.x.value, [4,3])
        self.assertItemsAlmostEqual(self.z.value, [-4,1])
        # Dual values
        self.assertItemsAlmostEqual(p.constraints[0].dual_value, [0, 1])
        self.assertItemsAlmostEqual(p.constraints[1].dual_value, [-1, 0.5])
        self.assertAlmostEqual(p.constraints[2].dual_value, 0)

        T = matrix(2, (2, 3))
        c = matrix([3,4])
        p = Problem(Minimize(1),
            [self.A >= T*self.C,
             self.A == self.B,
             self.C == T.T])
        result = p.solve()
        # Dual values
        self.assertItemsAlmostEqual(p.constraints[0].dual_value, 4*[0])
        self.assertItemsAlmostEqual(p.constraints[1].dual_value, 4*[0])
        self.assertItemsAlmostEqual(p.constraints[2].dual_value, 6*[0])
Exemplo n.º 3
0
    def test_norm2(self):
        # Constant argument.
        p = Problem(Minimize(norm2(-2)))
        result = p.solve()
        self.assertAlmostEqual(result, 2)

        # Scalar arguments.
        p = Problem(Minimize(norm2(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertAlmostEqual(self.a.value, -2)

        # Maximize
        p = Problem(Maximize(-norm2(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, -2)
        self.assertAlmostEqual(self.a.value, -2)

        # Vector arguments.
        p = Problem(Minimize(norm2(self.x - self.z) + 5),
                    [self.x >= [2, 3], self.z <= [-1, -4]])
        result = p.solve()
        self.assertAlmostEqual(result, 12.61577)
        self.assertItemsAlmostEqual(self.x.value, [2, 3])
        self.assertItemsAlmostEqual(self.z.value, [-1, -4])

        # Row  arguments.
        p = Problem(Minimize(norm2((self.x - self.z).T) + 5),
                    [self.x >= [2, 3], self.z <= [-1, -4]])
        result = p.solve()
        self.assertAlmostEqual(result, 12.61577)
        self.assertItemsAlmostEqual(self.x.value, [2, 3])
        self.assertItemsAlmostEqual(self.z.value, [-1, -4])
Exemplo n.º 4
0
    def test_norm1(self):
        # Constant argument.
        p = Problem(Minimize(norm1(-2)))
        result = p.solve()
        self.assertAlmostEqual(result, 2)

        # Scalar arguments.
        p = Problem(Minimize(norm1(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertAlmostEqual(self.a.value, -2)

        # Maximize
        p = Problem(Maximize(-norm1(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, -2)
        self.assertAlmostEqual(self.a.value, -2)

        # Vector arguments.
        p = Problem(Minimize(norm1(self.x - self.z) + 5),
                    [self.x >= [2, 3], self.z <= [-1, -4]])
        result = p.solve()
        self.assertAlmostEqual(float(result), 15)
        self.assertAlmostEqual(
            float(list(self.x.value)[1] - list(self.z.value)[1]), 7)
Exemplo n.º 5
0
    def test_verbose(self):
        # From http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python
        # setup the environment
        outputs = {True: [], False: []}
        backup = sys.stdout

        # ####
        for verbose in [True, False]:
            for solver in s.SOLVERS:
                sys.stdout = StringIO()     # capture output
                p = Problem(Minimize(self.a + self.x[0]), [self.a >= 2, self.x >= 2])
                if solver in s.MIP_CAPABLE:
                    p.constraints.append(BoolVar() == 0)
                p.solve(verbose=verbose, solver=solver)
                if solver in s.EXP_CAPABLE:
                    p = Problem(Minimize(self.a), [log(self.a) >= 2])
                    p.solve(verbose=verbose, solver=solver)
                out = sys.stdout.getvalue() # release output
                outputs[verbose].append(out.upper())
        # ####

        sys.stdout.close()  # close the stream
        sys.stdout = backup # restore original stdout

        for output in outputs[True]:
            assert len(output) > 0
        for output in outputs[False]:
            print output
            assert len(output) == 0
Exemplo n.º 6
0
    def test_quad_form(self):
        with self.assertRaises(Exception) as cm:
            Problem(Minimize(quad_form(self.x, self.A))).solve()
        self.assertEqual(
            str(cm.exception),
            "At least one argument to quad_form must be constant.")

        with self.assertRaises(Exception) as cm:
            Problem(Minimize(quad_form(1, self.A))).solve()
        self.assertEqual(str(cm.exception),
                         "Invalid dimensions for arguments.")

        with self.assertRaises(Exception) as cm:
            Problem(Minimize(quad_form(self.x, [[-1, 0], [0, 9]]))).solve()
        self.assertEqual(str(cm.exception),
                         "P has both positive and negative eigenvalues.")

        P = [[4, 0], [0, 9]]
        p = Problem(Minimize(quad_form(self.x, P)), [self.x >= 1])
        result = p.solve()
        self.assertAlmostEqual(result, 13, places=3)

        c = [1, 2]
        p = Problem(Minimize(quad_form(c, self.A)), [self.A >= 1])
        result = p.solve()
        self.assertAlmostEqual(result, 9)

        c = [1, 2]
        P = [[4, 0], [0, 9]]
        p = Problem(Minimize(quad_form(c, P)))
        result = p.solve()
        self.assertAlmostEqual(result, 40)
Exemplo n.º 7
0
    def test_indexing(self):
        # Vector variables
        p = Problem(Maximize(self.x[0, 0]),
                    [self.x[0, 0] <= 2, self.x[1, 0] == 3])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertItemsAlmostEqual(self.x.value, [2, 3])

        n = 10
        A = matrix(range(n * n), (n, n))
        x = Variable(n, n)
        p = Problem(Minimize(sum_entries(x)), [x == A])
        result = p.solve()
        answer = n * n * (n * n + 1) / 2 - n * n
        self.assertAlmostEqual(result, answer)

        # Matrix variables
        p = Problem(
            Maximize(sum(self.A[i, i] + self.A[i, 1 - i] for i in range(2))),
            [self.A <= [[1, -2], [-3, 4]]])
        result = p.solve()
        self.assertAlmostEqual(result, 0)
        self.assertItemsAlmostEqual(self.A.value, [1, -2, -3, 4])

        # Indexing arithmetic expressions.
        exp = [[1, 2], [3, 4]] * self.z + self.x
        p = Problem(Minimize(exp[1, 0]), [self.x == self.z, self.z == [1, 2]])
        result = p.solve()
        self.assertAlmostEqual(result, 12)
        self.assertItemsAlmostEqual(self.x.value, self.z.value)
Exemplo n.º 8
0
    def test_duplicate_constraints(self):
        eq = (self.x == 2)
        le = (self.x <= 2)
        obj = 0

        def test(self):
            objective, constraints = self.canonicalize()
            sym_data = SymData(objective, constraints, SOLVERS[s.ECOS])
            return (len(sym_data.constr_map[s.EQ]),
                    len(sym_data.constr_map[s.LEQ]))

        Problem.register_solve("test", test)
        p = Problem(Minimize(obj), [eq, eq, le, le])
        result = p.solve(method="test")
        self.assertEqual(result, (1, 1))

        # Internal constraints.
        X = Semidef(2)
        obj = sum_entries(X + X)
        p = Problem(Minimize(obj))
        result = p.solve(method="test")
        self.assertEqual(result, (0, 1))

        # Duplicates from non-linear constraints.
        exp = norm(self.x, 2)
        prob = Problem(Minimize(0), [exp <= 1, exp <= 2])
        result = prob.solve(method="test")
        self.assertEqual(result, (0, 4))
Exemplo n.º 9
0
    def test_verbose(self):
        # From http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python
        # setup the environment
        outputs = {True: [], False: []}
        backup = sys.stdout

        # ####
        for verbose in [True, False]:
            for solver in ["ecos", "cvxopt"]:
                sys.stdout = StringIO()     # capture output
                p = Problem(Minimize(self.a), [self.a >= 2])
                p.solve(verbose=verbose, solver=solver)
                p = Problem(Minimize(self.a), [log(self.a) >= 2])
                p.solve(verbose=verbose, solver=solver)
                out = sys.stdout.getvalue() # release output
                outputs[verbose].append(out.upper())
        # ####

        sys.stdout.close()  # close the stream
        sys.stdout = backup # restore original stdout

        for output in outputs[True]:
            assert len(output) > 0
        for output in outputs[False]:
            assert len(output) == 0
Exemplo n.º 10
0
    def test_duplicate_constraints(self):
        eq = (self.x == 2)
        le = (self.x <= 2)
        obj = 0
        def test(self):
            objective, constr_map  = self.canonicalize()
            self._presolve(objective, constr_map)
            print len(constr_map[s.SOC])
            dims = self._format_for_solver(constr_map, s.ECOS)
            return (len(constr_map[s.EQ]),len(constr_map[s.LEQ]))
        Problem.register_solve("test", test)
        p = Problem(Minimize(obj),[eq,eq,le,le])
        result = p.solve(method="test")
        self.assertEqual(result, (1, 1))

        # Internal constraints.
        X = Semidef(2)
        obj = sum_entries(X + X)
        p = Problem(Minimize(obj))
        result = p.solve(method="test")
        self.assertEqual(result, (1, 1))

        # Duplicates from non-linear constraints.
        exp = norm(self.x, 2)
        prob = Problem(Minimize(0), [exp <= 1, exp <= 2])
        result = prob.solve(method="test")
        self.assertEqual(result, (0, 4))
Exemplo n.º 11
0
    def test_vstack(self):
        c = matrix(1, (1, 5))
        p = Problem(Minimize(c * vstack(self.x, self.y)),
                    [self.x == [1, 2], self.y == [3, 4, 5]])
        result = p.solve()
        self.assertAlmostEqual(result, 15)

        c = matrix(1, (1, 4))
        p = Problem(Minimize(c * vstack(self.x, self.x)), [self.x == [1, 2]])
        result = p.solve()
        self.assertAlmostEqual(result, 6)

        c = matrix(1, (2, 2))
        p = Problem(Minimize(sum(vstack(self.A, self.C))),
                    [self.A >= 2 * c, self.C == -2])
        result = p.solve()
        self.assertAlmostEqual(result, -4)

        c = matrix(1, (1, 2))
        p = Problem(Minimize(sum(vstack(c * self.A, c * self.B))),
                    [self.A >= 2, self.B == -2])
        result = p.solve()
        self.assertAlmostEqual(result, 0)

        c = matrix([1, -1])
        p = Problem(Minimize(c.T * vstack(square(self.a), sqrt(self.b))),
                    [self.a == 2, self.b == 16])
        result = p.solve()
        self.assertAlmostEqual(result, 0)
Exemplo n.º 12
0
    def test_quad_form(self):
        with self.assertRaises(Exception) as cm:
            Problem(Minimize(quad_form(self.x, self.A))).solve()
        self.assertEqual(str(cm.exception), "At least one argument to quad_form must be constant.")

        with self.assertRaises(Exception) as cm:
            Problem(Minimize(quad_form(1, self.A))).solve()
        self.assertEqual(str(cm.exception), "Invalid dimensions for arguments.")

        with self.assertRaises(Exception) as cm:
            Problem(Minimize(quad_form(self.x, [[-1, 0], [0, 9]]))).solve()
        self.assertEqual(str(cm.exception), "P has both positive and negative eigenvalues.")

        P = [[4, 0], [0, 9]]
        p = Problem(Minimize(quad_form(self.x, P)), [self.x >= 1])
        result = p.solve()
        self.assertAlmostEqual(result, 13, places=3)

        c = [1,2]
        p = Problem(Minimize(quad_form(c, self.A)), [self.A >= 1])
        result = p.solve()
        self.assertAlmostEqual(result, 9)

        c = [1,2]
        P = [[4, 0], [0, 9]]
        p = Problem(Minimize(quad_form(c, P)))
        result = p.solve()
        self.assertAlmostEqual(result, 40)
Exemplo n.º 13
0
    def test_norm2(self):
        # Constant argument.
        p = Problem(Minimize(norm2(-2)))
        result = p.solve()
        self.assertAlmostEqual(result, 2)

        # Scalar arguments.
        p = Problem(Minimize(norm2(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertAlmostEqual(self.a.value, -2)

        # Maximize
        p = Problem(Maximize(-norm2(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, -2)
        self.assertAlmostEqual(self.a.value, -2)

        # Vector arguments.
        p = Problem(Minimize(norm2(self.x - self.z) + 5),
            [self.x >= [2,3], self.z <= [-1,-4]])
        result = p.solve()
        self.assertAlmostEqual(result, 12.61577)
        self.assertItemsAlmostEqual(self.x.value, [2,3])
        self.assertItemsAlmostEqual(self.z.value, [-1,-4])
Exemplo n.º 14
0
    def test_duplicate_constraints(self):
        eq = (self.x == 2)
        le = (self.x <= 2)
        obj = 0

        def test(self):
            objective, constr_map = self.canonicalize()
            print len(constr_map[s.SOC])
            dims = self._format_for_solver(constr_map, s.ECOS)
            return (len(constr_map[s.EQ]), len(constr_map[s.LEQ]))

        Problem.register_solve("test", test)
        p = Problem(Minimize(obj), [eq, eq, le, le])
        result = p.solve(method="test")
        self.assertEqual(result, (1, 1))

        # Internal constraints.
        z = hstack(self.x, self.x)
        obj = sum_entries(z[:, 0] + z[:, 1])
        p = Problem(Minimize(obj))
        result = p.solve(method="test")
        self.assertEqual(result, (2, 0))

        # Duplicates from non-linear constraints.
        exp = norm(self.x, 2)
        prob = Problem(Minimize(0), [exp <= 1, exp <= 2])
        result = prob.solve(method="test")
        self.assertEqual(result, (0, 4))
Exemplo n.º 15
0
    def test_verbose(self):
        # From http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python
        # setup the environment
        outputs = {True: [], False: []}
        backup = sys.stdout

        # ####
        for verbose in [True, False]:
            for solver in [s.ECOS, s.CVXOPT, s.SCS]:
                sys.stdout = StringIO()  # capture output
                p = Problem(Minimize(self.a + self.x[0]),
                            [self.a >= 2, self.x >= 2])
                p.solve(verbose=verbose, solver=solver)
                if solver != s.ECOS:
                    p = Problem(Minimize(self.a), [log(self.a) >= 2])
                    p.solve(verbose=verbose, solver=solver)
                out = sys.stdout.getvalue()  # release output
                outputs[verbose].append(out.upper())
        # ####

        sys.stdout.close()  # close the stream
        sys.stdout = backup  # restore original stdout

        for output in outputs[True]:
            assert len(output) > 0
        for output in outputs[False]:
            assert len(output) == 0
Exemplo n.º 16
0
    def test_duplicate_constraints(self):
        eq = (self.x == 2)
        le = (self.x <= 2)
        obj = 0
        def test(self):
            objective, constraints = self.canonicalize()
            sym_data = SymData(objective, constraints, SOLVERS[s.CVXOPT])
            return (len(sym_data.constr_map[s.EQ]),
                    len(sym_data.constr_map[s.LEQ]))
        Problem.register_solve("test", test)
        p = Problem(Minimize(obj),[eq,eq,le,le])
        result = p.solve(method="test")
        self.assertEqual(result, (1, 1))

        # Internal constraints.
        X = Semidef(2)
        obj = sum_entries(X + X)
        p = Problem(Minimize(obj))
        result = p.solve(method="test")
        self.assertEqual(result, (0, 1))

        # Duplicates from non-linear constraints.
        exp = norm(self.x, 2)
        prob = Problem(Minimize(0), [exp <= 1, exp <= 2])
        result = prob.solve(method="test")
        self.assertEqual(result, (0, 4))
Exemplo n.º 17
0
    def test_pnorm(self):
        import numpy as np

        x = Variable(3, name='x')

        a = np.array([1.0, 2, 3])

        # todo: add -1, .5, .3, -2.3 and testing positivity constraints

        for p in (1, 1.6, 1.3, 2, 1.99, 3, 3.7, np.inf):
            prob = Problem(Minimize(pnorm(x, p=p)), [x.T*a >= 1])
            prob.solve()

            # formula is true for any a >= 0 with p > 1
            if p == np.inf:
                x_true = np.ones_like(a)/sum(a)
            elif p == 1:
                # only works for the particular a = [1,2,3]
                x_true = np.array([0, 0, 1.0/3])
            else:
                x_true = a**(1.0/(p-1))/a.dot(a**(1.0/(p-1)))

            x_alg = np.array(x.value).flatten()
            self.assertTrue(np.allclose(x_alg, x_true, 1e-3), 'p = {}'.format(p))
            self.assertTrue(np.allclose(prob.value, np.linalg.norm(x_alg, p)))
            self.assertTrue(np.allclose(np.linalg.norm(x_alg, p), pnorm(x_alg, p).value))
Exemplo n.º 18
0
    def test_dual_variables(self):
        p = Problem(Minimize( norm1(self.x + self.z) ),
            [self.x >= [2,3],
             [[1,2],[3,4]]*self.z == [-1,-4],
             norm2(self.x + self.z) <= 100])
        result = p.solve()
        self.assertAlmostEqual(result, 4)
        self.assertItemsAlmostEqual(self.x.value, [4,3])
        self.assertItemsAlmostEqual(self.z.value, [-4,1])
        # Dual values
        self.assertItemsAlmostEqual(p.constraints[0].dual_value, [0, 1])
        self.assertItemsAlmostEqual(p.constraints[1].dual_value, [-1, 0.5])
        self.assertAlmostEqual(p.constraints[2].dual_value, 0)

        T = matrix(2,(2,3))
        c = matrix([3,4])
        p = Problem(Minimize(1),
            [self.A >= T*self.C,
             self.A == self.B,
             self.C == T.T])
        result = p.solve()
        # Dual values
        self.assertItemsAlmostEqual(p.constraints[0].dual_value, 4*[0])
        self.assertItemsAlmostEqual(p.constraints[1].dual_value, 4*[0])
        self.assertItemsAlmostEqual(p.constraints[2].dual_value, 6*[0])
Exemplo n.º 19
0
    def test_vstack(self):
        c = matrix(1, (1,5))
        p = Problem(Minimize(c * vstack(self.x, self.y)),
            [self.x == [1,2],
            self.y == [3,4,5]])
        result = p.solve()
        self.assertAlmostEqual(result, 15)

        c = matrix(1, (1,4))
        p = Problem(Minimize(c * vstack(self.x, self.x)),
            [self.x == [1,2]])
        result = p.solve()
        self.assertAlmostEqual(result, 6)


        c = matrix(1, (2,2))
        p = Problem( Minimize( sum(vstack(self.A, self.C)) ),
            [self.A >= 2*c,
            self.C == -2])
        result = p.solve()
        self.assertAlmostEqual(result, -4)

        c = matrix(1, (1,2))
        p = Problem( Minimize( sum(vstack(c*self.A, c*self.B)) ),
            [self.A >= 2,
            self.B == -2])
        result = p.solve()
        self.assertAlmostEqual(result, 0)

        c = matrix([1,-1])
        p = Problem( Minimize( c.T * vstack(square(self.a), sqrt(self.b))),
            [self.a == 2,
             self.b == 16])
        result = p.solve()
        self.assertAlmostEqual(result, 0)
Exemplo n.º 20
0
    def test_indexing(self):
        # Vector variables
        p = Problem(Maximize(self.x[0,0]), [self.x[0,0] <= 2, self.x[1,0] == 3])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertItemsAlmostEqual(self.x, [2,3])

        n = 10
        A = matrix(range(n*n), (n,n))
        x = Variable(n,n)
        p = Problem(Minimize(sum(x)), [x == A])
        result = p.solve()
        answer = n*n*(n*n+1)/2 - n*n
        self.assertAlmostEqual(result, answer)

        # Matrix variables
        import __builtin__
        p = Problem(Maximize( __builtin__.sum(self.A[i,i] + self.A[i,1-i] for i in range(2)) ),
                             [self.A <= [[1,-2],[-3,4]]])
        result = p.solve()
        self.assertAlmostEqual(result, 0)
        self.assertItemsAlmostEqual(self.A.value, [1,-2,-3,4])

        # Indexing arithmetic expressions.
        exp = [[1,2],[3,4]]*self.z + self.x
        p = Problem(Minimize(exp[1,0]), [self.x == self.z, self.z == [1,2]])
        result = p.solve()
        self.assertAlmostEqual(result, 12)
        self.assertItemsAlmostEqual(self.x.value, self.z.value)
Exemplo n.º 21
0
    def test_mul_elemwise(self):
        """Tests problems with mul_elemwise.
        """
        c = [[1, -1], [2, -2]]
        expr = mul_elemwise(c, self.A)
        obj = Minimize(normInf(expr))
        p = Problem(obj, [self.A == 5])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])

        # Test with a sparse matrix.
        import cvxopt
        interface = intf.get_matrix_interface(cvxopt.spmatrix)
        c = interface.const_to_matrix([1,2])
        expr = mul_elemwise(c, self.x)
        obj = Minimize(normInf(expr))
        p = Problem(obj, [self.x == 5])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(expr.value, [5, 10])

        # Test promotion.
        c = [[1, -1], [2, -2]]
        expr = mul_elemwise(c, self.a)
        obj = Minimize(normInf(expr))
        p = Problem(obj, [self.a == 5])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])
Exemplo n.º 22
0
    def test_normInf(self):
        # Constant argument.
        p = Problem(Minimize(normInf(-2)))
        result = p.solve()
        self.assertAlmostEqual(result, 2)

        # Scalar arguments.
        p = Problem(Minimize(normInf(self.a)), [self.a >= 2])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertAlmostEqual(self.a.value, 2)

        p = Problem(Minimize(3*normInf(self.a + 2*self.b) + self.c),
            [self.a >= 2, self.b <= -1, self.c == 3])
        result = p.solve()
        self.assertAlmostEqual(result, 3)
        self.assertAlmostEqual(self.a.value + 2*self.b.value, 0)
        self.assertAlmostEqual(self.c.value, 3)

        # Maximize
        p = Problem(Maximize(-normInf(self.a)), [self.a <= -2])
        result = p.solve()
        self.assertAlmostEqual(result, -2)
        self.assertAlmostEqual(self.a.value, -2)

        # Vector arguments.
        p = Problem(Minimize(normInf(self.x - self.z) + 5),
            [self.x >= [2,3], self.z <= [-1,-4]])
        result = p.solve()
        self.assertAlmostEqual(result, 12)
        self.assertAlmostEqual(list(self.x.value)[1] - list(self.z.value)[1], 7)
Exemplo n.º 23
0
    def test_mul_elemwise(self):
        """Tests problems with mul_elemwise.
        """
        c = [[1, -1], [2, -2]]
        expr = mul_elemwise(c, self.A)
        obj = Minimize(normInf(expr))
        p = Problem(obj, [self.A == 5])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])

        # Test with a sparse matrix.
        import cvxopt
        interface = intf.get_matrix_interface(cvxopt.spmatrix)
        c = interface.const_to_matrix([1, 2])
        expr = mul_elemwise(c, self.x)
        obj = Minimize(normInf(expr))
        p = Problem(obj, [self.x == 5])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(expr.value, [5, 10])

        # Test promotion.
        c = [[1, -1], [2, -2]]
        expr = mul_elemwise(c, self.a)
        obj = Minimize(normInf(expr))
        p = Problem(obj, [self.a == 5])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])
Exemplo n.º 24
0
    def test_pnorm(self):
        import numpy as np

        x = Variable(3, name='x')

        a = np.array([1.0, 2, 3])

        for p in (1, 1.6, 1.2, 2, 1.99, 3, 3.7, np.inf):
            prob = Problem(Minimize(pnorm(x, p=p)), [x.T * a >= 1])
            prob.solve()

            # formula is true for any a >= 0 with p > 1
            if p == np.inf:
                x_true = np.ones_like(a) / sum(a)
            elif p == 1:
                # only works for the particular a = [1,2,3]
                x_true = np.array([0, 0, 1.0 / 3])
            else:
                x_true = a**(1.0 / (p - 1)) / a.dot(a**(1.0 / (p - 1)))

            x_alg = np.array(x.value).flatten()
            self.assertTrue(np.allclose(x_alg, x_true, 1e-3))
            self.assertTrue(np.allclose(prob.value, np.linalg.norm(x_alg, p)))
            self.assertTrue(
                np.allclose(np.linalg.norm(x_alg, p),
                            pnorm(x_alg, p).value))
Exemplo n.º 25
0
 def test_cvxopt_errors(self):
     """Tests that cvxopt errors are caught as solver_error.
     """
     # For some reason CVXOPT can't handle this problem.
     expr = 500 * self.a + square(self.a)
     prob = Problem(Minimize(expr))
     prob.solve(solver=s.CVXOPT)
     self.assertEqual(prob.status, s.SOLVER_ERROR)
Exemplo n.º 26
0
 def test_power(self):
     x = Variable()
     prob = Problem(
         Minimize(power(x, 1.7) + power(x, -2.3) - power(x, .45)))
     prob.solve()
     x = x.value
     self.assertTrue(__builtins__['abs'](1.7 * x**.7 - 2.3 * x**-3.3 -
                                         .45 * x**-.55) <= 1e-3)
Exemplo n.º 27
0
 def test_cvxopt_errors(self):
     """Tests that cvxopt errors are caught as solver_error.
     """
     # For some reason CVXOPT can't handle this problem.
     expr = 500*self.a + square(self.a)
     prob = Problem(Minimize(expr))
     prob.solve(solver=s.CVXOPT)
     self.assertEqual(prob.status, s.SOLVER_ERROR)
Exemplo n.º 28
0
 def test_sdp(self):
     """Test a problem with semidefinite cones.
     """
     a = sp.rand(100, 100, .1, random_state=1)
     a = a.todense()
     X = Variable(100, 100)
     obj = at.norm(X, "nuc") + at.norm(X - a, 'fro')
     p = Problem(Minimize(obj))
     p.solve(solver="SCS")
Exemplo n.º 29
0
 def test_sdp(self):
     """Test a problem with semidefinite cones.
     """
     a = sp.rand(100,100,.1, random_state=1)
     a = a.todense()
     X = Variable(100,100)
     obj = at.norm(X, "nuc") + at.norm(X-a,'fro')
     p = Problem(Minimize(obj))
     p.solve(solver="SCS")
Exemplo n.º 30
0
    def test_slicing(self):
        p = Problem(Maximize(sum(self.C)), [self.C[1:3, :] <= 2, self.C[0, :] == 1])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(self.C, 2 * [1, 2, 2])

        p = Problem(Maximize(sum(self.C[0:3:2, 1])), [self.C[1:3, :] <= 2, self.C[0, :] == 1])
        result = p.solve()
        self.assertAlmostEqual(result, 3)
        self.assertItemsAlmostEqual(self.C.value[0:3:2, 1], [1, 2])

        p = Problem(
            Maximize(sum((self.C[0:2, :] + self.A)[:, 0:2])),
            [
                self.C[1:3, :] <= 2,
                self.C[0, :] == 1,
                (self.A + self.B)[:, 0] == 3,
                (self.A + self.B)[:, 1] == 2,
                self.B == 1,
            ],
        )
        result = p.solve()
        self.assertAlmostEqual(result, 12)
        self.assertItemsAlmostEqual(self.C.value[0:2, :], [1, 2, 1, 2])
        self.assertItemsAlmostEqual(self.A.value, [2, 2, 1, 1])

        p = Problem(
            Maximize([[3], [4]] * (self.C[0:2, :] + self.A)[:, 0]),
            [
                self.C[1:3, :] <= 2,
                self.C[0, :] == 1,
                [[1], [2]] * (self.A + self.B)[:, 0] == 3,
                (self.A + self.B)[:, 1] == 2,
                self.B == 1,
                3 * self.A[:, 0] <= 3,
            ],
        )
        result = p.solve()
        self.assertAlmostEqual(result, 12)
        self.assertItemsAlmostEqual(self.C.value[0:2, 0], [1, 2])
        self.assertItemsAlmostEqual(self.A.value, [1, -0.5, 1, 1])

        p = Problem(
            Minimize(norm2((self.C[0:2, :] + self.A)[:, 0])),
            [
                self.C[1:3, :] <= 2,
                self.C[0, :] == 1,
                (self.A + self.B)[:, 0] == 3,
                (self.A + self.B)[:, 1] == 2,
                self.B == 1,
            ],
        )
        result = p.solve()
        self.assertAlmostEqual(result, 3)
        self.assertItemsAlmostEqual(self.C.value[0:2, 0], [1, -2])
        self.assertItemsAlmostEqual(self.A.value, [2, 2, 1, 1])
Exemplo n.º 31
0
 def test_sdp(self) -> None:
     """Test a problem with semidefinite cones.
     """
     self.skipTest("Too slow.")
     a = sp.rand(100, 100, .1, random_state=1)
     a = a.todense()
     X = Variable((100, 100))
     obj = at.norm(X, "nuc") + at.norm(X - a, 'fro')
     p = Problem(cp.Minimize(obj))
     p.solve(solver="SCS")
Exemplo n.º 32
0
    def test_is_dcp(self):
        p = Problem(Minimize(normInf(self.a)))
        self.assertEqual(p.is_dcp(), True)

        p = Problem(Maximize(normInf(self.a)))
        self.assertEqual(p.is_dcp(), False)
        with self.assertRaises(Exception) as cm:
            p.solve()
        self.assertEqual(str(cm.exception), "Problem does not follow DCP rules.")
        p.solve(ignore_dcp=True)
Exemplo n.º 33
0
    def test_is_dcp(self):
        p = Problem(Minimize(normInf(self.a)))
        self.assertEqual(p.is_dcp(), True)

        p = Problem(Maximize(normInf(self.a)))
        self.assertEqual(p.is_dcp(), False)
        with self.assertRaises(Exception) as cm:
            p.solve()
        self.assertEqual(str(cm.exception), "Problem does not follow DCP rules.")
        p.solve(ignore_dcp=True)
Exemplo n.º 34
0
    def test_reshape(self):
        """Tests problems with reshape.
        """
        # Test on scalars.
        self.assertEqual(reshape(1, 1, 1).value, 1)

        # Test vector to matrix.
        x = Variable(4)
        mat = matrix([[1, -1], [2, -2]])
        vec = matrix([1, 2, 3, 4])
        vec_mat = matrix([[1, 2], [3, 4]])
        expr = reshape(x, 2, 2)
        obj = Minimize(sum_entries(mat * expr))
        prob = Problem(obj, [x == vec])
        result = prob.solve()
        self.assertAlmostEqual(result, sum(mat * vec_mat))

        # Test on matrix to vector.
        c = [1, 2, 3, 4]
        expr = reshape(self.A, 4, 1)
        obj = Minimize(expr.T * c)
        constraints = [self.A == [[-1, -2], [3, 4]]]
        prob = Problem(obj, constraints)
        result = prob.solve()
        self.assertAlmostEqual(result, 20)
        self.assertItemsAlmostEqual(expr.value, [-1, -2, 3, 4])
        self.assertItemsAlmostEqual(reshape(expr, 2, 2).value, [-1, -2, 3, 4])

        # Test matrix to matrix.
        expr = reshape(self.C, 2, 3)
        mat = numpy.matrix([[1, -1], [2, -2]])
        C_mat = numpy.matrix([[1, 4], [2, 5], [3, 6]])
        obj = Minimize(sum_entries(mat * expr))
        prob = Problem(obj, [self.C == C_mat])
        result = prob.solve()
        reshaped = numpy.reshape(C_mat, (2, 3), 'F')
        self.assertAlmostEqual(result, (mat.dot(reshaped)).sum())
        self.assertItemsAlmostEqual(expr.value, C_mat)

        # Test promoted expressions.
        c = matrix([[1, -1], [2, -2]])
        expr = reshape(c * self.a, 1, 4)
        obj = Minimize(expr * [1, 2, 3, 4])
        prob = Problem(obj, [self.a == 2])
        result = prob.solve()
        self.assertAlmostEqual(result, -6)
        self.assertItemsAlmostEqual(expr.value, 2 * c)

        expr = reshape(c * self.a, 4, 1)
        obj = Minimize(expr.T * [1, 2, 3, 4])
        prob = Problem(obj, [self.a == 2])
        result = prob.solve()
        self.assertAlmostEqual(result, -6)
        self.assertItemsAlmostEqual(expr.value, 2 * c)
Exemplo n.º 35
0
    def test_reshape(self):
        """Tests problems with reshape.
        """
        # Test on scalars.
        self.assertEqual(reshape(1, 1, 1).value, 1)

        # Test vector to matrix.
        x = Variable(4)
        mat = matrix([[1,-1], [2, -2]])
        vec = matrix([1, 2, 3, 4])
        vec_mat = matrix([[1, 2], [3, 4]])
        expr = reshape(x, 2, 2)
        obj = Minimize(sum_entries(mat*expr))
        prob = Problem(obj, [x == vec])
        result = prob.solve()
        self.assertAlmostEqual(result, sum(mat*vec_mat))

        # Test on matrix to vector.
        c = [1, 2, 3, 4]
        expr = reshape(self.A, 4, 1)
        obj = Minimize(expr.T*c)
        constraints = [self.A == [[-1, -2], [3, 4]]]
        prob = Problem(obj, constraints)
        result = prob.solve()
        self.assertAlmostEqual(result, 20)
        self.assertItemsAlmostEqual(expr.value, [-1, -2, 3, 4])
        self.assertItemsAlmostEqual(reshape(expr, 2, 2).value, [-1, -2, 3, 4])

        # Test matrix to matrix.
        expr = reshape(self.C, 2, 3)
        mat = numpy.matrix([[1,-1], [2, -2]])
        C_mat = numpy.matrix([[1, 4], [2, 5], [3, 6]])
        obj = Minimize(sum_entries(mat*expr))
        prob = Problem(obj, [self.C == C_mat])
        result = prob.solve()
        reshaped = numpy.reshape(C_mat, (2, 3), 'F')
        self.assertAlmostEqual(result, (mat.dot(reshaped)).sum())
        self.assertItemsAlmostEqual(expr.value, C_mat)

        # Test promoted expressions.
        c = matrix([[1,-1], [2, -2]])
        expr = reshape(c*self.a, 1, 4)
        obj = Minimize(expr*[1, 2, 3, 4])
        prob = Problem(obj, [self.a == 2])
        result = prob.solve()
        self.assertAlmostEqual(result, -6)
        self.assertItemsAlmostEqual(expr.value, 2*c)

        expr = reshape(c*self.a, 4, 1)
        obj = Minimize(expr.T*[1, 2, 3, 4])
        prob = Problem(obj, [self.a == 2])
        result = prob.solve()
        self.assertAlmostEqual(result, -6)
        self.assertItemsAlmostEqual(expr.value, 2*c)
Exemplo n.º 36
0
    def test_verbose(self):
        import sys
        # From http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python
        # setup the environment
        outputs = {True: [], False: []}
        backup = sys.stdout
        # ####
        for verbose in [True, False]:
            for solver in installed_solvers():
                # Don't test GLPK because there's a race
                # condition in setting CVXOPT solver options.
                if solver in ["GLPK", "GLPK_MI"]:
                    continue
                # if solver == "GLPK":
                #     # GLPK's stdout is separate from python,
                #     # so we have to do this.
                #     # Note: This probably breaks (badly) on Windows.
                #     import os
                #     import tempfile

                #     stdout_fd = 1
                #     tmp_handle = tempfile.TemporaryFile(bufsize = 0)
                #     os.dup2(tmp_handle.fileno(), stdout_fd)
                # else:
                sys.stdout = StringIO()  # capture output

                p = Problem(Minimize(self.a + self.x[0]),
                            [self.a >= 2, self.x >= 2])
                if SOLVERS[solver].MIP_CAPABLE:
                    p.constraints.append(Bool() == 0)
                p.solve(verbose=verbose, solver=solver)
                if SOLVERS[solver].EXP_CAPABLE:
                    p = Problem(Minimize(self.a), [log(self.a) >= 2])
                    p.solve(verbose=verbose, solver=solver)

                # if solver == "GLPK":
                #     # GLPK's stdout is separate from python,
                #     # so we have to do this.
                #     tmp_handle.seek(0)
                #     out = tmp_handle.read()
                #     tmp_handle.close()
                # else:
                out = sys.stdout.getvalue()  # release output

                outputs[verbose].append((out, solver))
        # ####
        sys.stdout.close()  # close the stream
        sys.stdout = backup  # restore original stdout
        for output, solver in outputs[True]:
            print(solver)
            assert len(output) > 0
        for output, solver in outputs[False]:
            print(solver)
            assert len(output) == 0
Exemplo n.º 37
0
    def test_verbose(self):
        import sys
        # From http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python
        # setup the environment
        outputs = {True: [], False: []}
        backup = sys.stdout
        # ####
        for verbose in [True, False]:
            for solver in installed_solvers():
                # Don't test GLPK because there's a race
                # condition in setting CVXOPT solver options.
                if solver in ["GLPK", "GLPK_MI"]:
                    continue
                # if solver == "GLPK":
                #     # GLPK's stdout is separate from python,
                #     # so we have to do this.
                #     # Note: This probably breaks (badly) on Windows.
                #     import os
                #     import tempfile

                #     stdout_fd = 1
                #     tmp_handle = tempfile.TemporaryFile(bufsize = 0)
                #     os.dup2(tmp_handle.fileno(), stdout_fd)
                # else:
                sys.stdout = StringIO() # capture output

                p = Problem(Minimize(self.a + self.x[0]),
                                     [self.a >= 2, self.x >= 2])
                if SOLVERS[solver].MIP_CAPABLE:
                    p.constraints.append(Bool() == 0)
                p.solve(verbose=verbose, solver=solver)
                if SOLVERS[solver].EXP_CAPABLE:
                    p = Problem(Minimize(self.a), [log(self.a) >= 2])
                    p.solve(verbose=verbose, solver=solver)

                # if solver == "GLPK":
                #     # GLPK's stdout is separate from python,
                #     # so we have to do this.
                #     tmp_handle.seek(0)
                #     out = tmp_handle.read()
                #     tmp_handle.close()
                # else:
                out = sys.stdout.getvalue() # release output

                outputs[verbose].append((out, solver))
        # ####
        sys.stdout.close()  # close the stream
        sys.stdout = backup # restore original stdout
        for output, solver in outputs[True]:
            print(solver)
            assert len(output) > 0
        for output, solver in outputs[False]:
            print(solver)
            assert len(output) == 0
Exemplo n.º 38
0
 def test_large_sdp(self):
     """Test for bug where large SDP caused integer overflow in CVXcanon.
     """
     SHAPE = (256, 256)
     rows = SHAPE[0]
     cols = SHAPE[1]
     X = Variable(*SHAPE)
     Z = Variable(rows+cols, rows+cols)
     prob = Problem(Minimize(0.5*at.trace(Z)),
         [X[0,0] >= 1, Z[0:rows,rows:rows+cols] == X, Z >> 0, Z == Z.T])
     prob.solve(solver="SCS")
     self.assertAlmostEqual(prob.value, 1.0)
Exemplo n.º 39
0
    def test_redundant_constraints(self):
        obj = Minimize(sum_entries(self.x))
        constraints = [self.x == 2, self.x == 2, self.x.T == 2, self.x[0] == 2]
        p = Problem(obj, constraints)
        result = p.solve(solver=s.CVXOPT)
        self.assertAlmostEqual(result, 4)

        obj = Minimize(sum_entries(square(self.x)))
        constraints = [self.x == self.x]
        p = Problem(obj, constraints)
        result = p.solve(solver=s.CVXOPT)
        self.assertAlmostEqual(result, 0)
Exemplo n.º 40
0
 def test_large_sdp(self):
     """Test for bug where large PSD caused integer overflow in cvxcore.
     """
     SHAPE = (256, 256)
     rows = SHAPE[0]
     cols = SHAPE[1]
     X = Variable(SHAPE)
     Z = Variable((rows+cols, rows+cols))
     prob = Problem(Minimize(0.5*at.trace(Z)),
                    [X[0, 0] >= 1, Z[0:rows, rows:rows+cols] == X, Z >> 0, Z == Z.T])
     prob.solve(solver="SCS")
     self.assertAlmostEqual(prob.value, 1.0)
Exemplo n.º 41
0
    def test_redundant_constraints(self):
        obj = Minimize(sum(self.x))
        constraints = [self.x == 2, self.x == 2, self.x.T == 2, self.x[0] == 2]
        p = Problem(obj, constraints)
        result = p.solve(solver=s.CVXOPT)
        self.assertAlmostEqual(result, 4)

        obj = Minimize(sum(square(self.x)))
        constraints = [self.x == self.x]
        p = Problem(obj, constraints)
        result = p.solve(solver=s.CVXOPT)
        self.assertAlmostEqual(result, 0)
Exemplo n.º 42
0
    def grad(self):
        """Gives the (sub/super)gradient of the expression w.r.t. each variable.

        Matrix expressions are vectorized, so the gradient is a matrix.
        None indicates variable values unknown or outside domain.

        Returns:
            A map of variable to SciPy CSC sparse matrix or None.
        """
        # Subgrad of g(y) = min f_0(x,y)
        #                   s.t. f_i(x,y) <= 0, i = 1,..,p
        #                        h_i(x,y) == 0, i = 1,...,q
        # Given by Df_0(x^*,y) + \sum_i Df_i(x^*,y) \lambda^*_i
        #          + \sum_i Dh_i(x^*,y) \nu^*_i
        # where x^*, \lambda^*_i, \nu^*_i are optimal primal/dual variables.
        # Add PSD constraints in same way.

        # Short circuit for constant.
        if self.is_constant():
            return u.grad.constant_grad(self)

        old_vals = {var.id: var.value for var in self.variables()}
        fix_vars = []
        for var in self.dont_opt_vars:
            if var.value is None:
                return u.grad.error_grad(self)
            else:
                fix_vars += [var == var.value]
        prob = Problem(self.args[0].objective,
                       fix_vars + self.args[0].constraints)
        prob.solve(verbose=True)
        # Compute gradient.
        if prob.status in s.SOLUTION_PRESENT:
            sign = self.is_convex() - self.is_concave()
            # Form Lagrangian.
            lagr = self.args[0].objective.args[0]
            for constr in self.args[0].constraints:
                # TODO: better way to get constraint expressions.
                lagr_multiplier = self.cast_to_const(sign*constr.dual_value)
                prod = lagr_multiplier.T*constr.expr
                if prod.is_scalar():
                    lagr += sum(prod)
                else:
                    lagr += trace(prod)
            grad_map = lagr.grad
            result = {var: grad_map[var] for var in self.dont_opt_vars}
        else:  # Unbounded, infeasible, or solver error.
            result = u.grad.error_grad(self)
        # Restore the original values to the variables.
        for var in self.variables():
            var.value = old_vals[var.id]
        return result
Exemplo n.º 43
0
Arquivo: spoc.py Projeto: stat-ml/SPOC
    def _get_Theta(self, U, F):
        """
        Function to find Theta from U and F via convex optimization in cvxpy
        or euclidean_proj_simplex

        Parameters
        ---------
        U: array-like with shape (n_nodes, n_clusters)

        F: nd.array with shape (n_clusters, n_clusters)
            with coordinates of k pretenders to be pure nodes


        Returns
        -------
        Theta: nd.array with shape (n_nodes, n_clusters)

        where n_nodes == U.shape[0], n_clusters == U.shape[1]


        Requires
        --------
        cvxpy (http://www.cvxpy.org/en/latest/)
        """

        assert U.shape[1] == F.shape[0] == F.shape[1], \
            "U.shape[1] != F.shape"

        n_nodes = U.shape[0]
        n_clusters = U.shape[1]

        if self.use_cvxpy:
            Theta = Variable(rows=n_nodes, cols=n_clusters)
            constraints = [
                sum_entries(Theta[i, :]) == 1 for i in range(n_nodes)
            ]
            constraints += [
                Theta[i, j] >= 0 for i in range(n_nodes)
                for j in range(n_clusters)
            ]
            obj = Minimize(norm(U - Theta * F, 'fro'))
            prob = Problem(obj, constraints)
            prob.solve()
            return np.array(Theta.value)
        else:
            projector = F.T.dot(np.linalg.inv(F.dot(F.T)))
            theta = U.dot(projector)
            theta_simplex_proj = np.array([
                self._euclidean_proj_simplex(x) for x in theta
            ])
            return theta_simplex_proj
Exemplo n.º 44
0
    def test_parameter_expressions(self):
        """Test that expressions with parameters are updated properly.
        """
        x = Variable()
        y = Variable()
        x0 = Parameter()
        xSquared = x0 * x0 + 2 * x0 * (x - x0)

        # initial guess for x
        x0.value = 2

        # make the constraint x**2 - y == 0
        g = xSquared - y

        # set up the problem
        obj = abs(x - 1)
        prob = Problem(Minimize(obj), [g == 0])
        prob.solve()
        x0.value = 1
        prob.solve()
        self.assertAlmostEqual(g.value, 0)

        # Test multiplication.
        prob = Problem(Minimize(x0 * x), [x == 1])
        x0.value = 2
        prob.solve()
        x0.value = 1
        prob.solve()
        self.assertAlmostEqual(prob.value, 1)
Exemplo n.º 45
0
    def test_parameter_expressions(self):
        """Test that expressions with parameters are updated properly.
        """
        x = Variable()
        y = Variable()
        x0 = Parameter()
        xSquared = x0*x0 + 2*x0*(x - x0)

        # initial guess for x
        x0.value = 2

        # make the constraint x**2 - y == 0
        g = xSquared - y

        # set up the problem
        obj = abs(x - 1)
        prob = Problem( Minimize( obj ), [ g == 0 ] )
        prob.solve()
        x0.value = 1
        prob.solve()
        self.assertAlmostEqual(g.value, 0)

        # Test multiplication.
        prob = Problem( Minimize( x0*x ), [ x == 1 ] )
        x0.value = 2
        prob.solve()
        x0.value = 1
        prob.solve()
        self.assertAlmostEqual(prob.value, 1)
Exemplo n.º 46
0
    def grad(self):
        """Gives the (sub/super)gradient of the expression w.r.t. each variable.

        Matrix expressions are vectorized, so the gradient is a matrix.
        None indicates variable values unknown or outside domain.

        Returns:
            A map of variable to SciPy CSC sparse matrix or None.
        """
        # Subgrad of g(y) = min f_0(x,y)
        #                   s.t. f_i(x,y) <= 0, i = 1,..,p
        #                        h_i(x,y) == 0, i = 1,...,q
        # Given by Df_0(x^*,y) + \sum_i Df_i(x^*,y) \lambda^*_i
        #          + \sum_i Dh_i(x^*,y) \nu^*_i
        # where x^*, \lambda^*_i, \nu^*_i are optimal primal/dual variables.
        # Add PSD constraints in same way.

        # Short circuit for constant.
        if self.is_constant():
            return u.grad.constant_grad(self)

        old_vals = {var.id:var.value for var in self.variables()}
        fix_vars = []
        for var in self.variables():
            if var.value is None:
                return u.grad.error_grad(self)
            else:
                fix_vars += [var == var.value]
        obj_arg = self._prob.objective.args[0]
        prob = Problem(self.args[0].objective.copy(obj_arg),
                       fix_vars + self._prob.constraints)
        prob.solve()
        # Compute gradient.
        if prob.status in s.SOLUTION_PRESENT:
            sign = self.is_convex() - self.is_concave()
            # Form Lagrangian.
            lagr = self._prob.objective.args[0]
            for constr in self._prob.constraints:
                # TODO: better way to get constraint expressions.
                lagr_multiplier = self.cast_to_const(sign*constr.dual_value)
                lagr += trace(lagr_multiplier.T*constr._expr)
            grad_map = lagr.grad
            result = {var:grad_map[var] for var in self.variables()}
        else: # Unbounded, infeasible, or solver error.
            result = u.grad.error_grad(self)
        # Restore the original values to the variables.
        for var in self.variables():
            var.value = old_vals[var.id]
        return result
Exemplo n.º 47
0
    def test_presolve_parameters(self):
        """Test presolve with parameters.
        """
        # Test with parameters.
        gamma = Parameter(sign="positive")
        x = Variable()
        obj = Minimize(x)
        prob = Problem(obj, [gamma == 1, x >= 0])
        gamma.value = 0
        prob.solve(solver=s.SCS)
        self.assertEqual(prob.status, s.INFEASIBLE)

        gamma.value = 1
        prob.solve(solver=s.CVXOPT)
        self.assertEqual(prob.status, s.OPTIMAL)
Exemplo n.º 48
0
    def test_presolve_parameters(self):
        """Test presolve with parameters.
        """
        # Test with parameters.
        gamma = Parameter(sign="positive")
        x = Variable()
        obj = Minimize(x)
        prob = Problem(obj, [gamma == 1, x >= 0])
        gamma.value = 0
        prob.solve(solver=s.SCS)
        self.assertEqual(prob.status, s.INFEASIBLE)

        gamma.value = 1
        prob.solve(solver=s.CVXOPT)
        self.assertEqual(prob.status, s.OPTIMAL)
Exemplo n.º 49
0
    def test_variable_promotion(self):
        p = Problem(Minimize(self.a), [self.x <= self.a, self.x == [1, 2]])
        result = p.solve()
        self.assertAlmostEqual(result, 2)
        self.assertAlmostEqual(self.a.value, 2)

        p = Problem(Minimize(self.a), [self.A <= self.a, self.A == [[1, 2], [3, 4]]])
        result = p.solve()
        self.assertAlmostEqual(result, 4)
        self.assertAlmostEqual(self.a.value, 4)

        # Promotion must happen before the multiplication.
        p = Problem(Minimize([[1], [1]] * (self.x + self.a + 1)), [self.a + self.x >= [1, 2]])
        result = p.solve()
        self.assertAlmostEqual(result, 5)
Exemplo n.º 50
0
    def test_register_solve(self):
        Problem.register_solve("test",lambda self: 1)
        p = Problem(Minimize(1))
        result = p.solve(method="test")
        self.assertEqual(result, 1)

        def test(self, a, b=2):
            return (a,b)
        Problem.register_solve("test", test)
        p = Problem(Minimize(0))
        result = p.solve(1,b=3,method="test")
        self.assertEqual(result, (1,3))
        result = p.solve(1,method="test")
        self.assertEqual(result, (1,2))
        result = p.solve(1,method="test",b=4)
        self.assertEqual(result, (1,4))
Exemplo n.º 51
0
 def test_div(self):
     """Tests a problem with division.
     """
     obj = Minimize(normInf(self.A / 5))
     p = Problem(obj, [self.A >= 5])
     result = p.solve()
     self.assertAlmostEqual(result, 1)
Exemplo n.º 52
0
    def test_register_solve(self):
        Problem.register_solve("test",lambda self: 1)
        p = Problem(Minimize(1))
        result = p.solve(method="test")
        self.assertEqual(result, 1)

        def test(self, a, b=2):
            return (a,b)
        Problem.register_solve("test", test)
        p = Problem(Minimize(0))
        result = p.solve(1,b=3,method="test")
        self.assertEqual(result, (1,3))
        result = p.solve(1,method="test")
        self.assertEqual(result, (1,2))
        result = p.solve(1,method="test",b=4)
        self.assertEqual(result, (1,4))
Exemplo n.º 53
0
 def test_div(self):
     """Tests a problem with division.
     """
     obj = Minimize(normInf(self.A/5))
     p = Problem(obj, [self.A >= 5])
     result = p.solve()
     self.assertAlmostEqual(result, 1)
Exemplo n.º 54
0
 def test_variable_name_conflict(self):
     var = Variable(name='a')
     p = Problem(Maximize(self.a + var), [var == 2 + self.a, var <= 3])
     result = p.solve()
     self.assertAlmostEqual(result, 4.0)
     self.assertAlmostEqual(self.a.value, 1)
     self.assertAlmostEqual(var.value, 3)
Exemplo n.º 55
0
 def test_variable_name_conflict(self):
     var = Variable(name='a')
     p = Problem(Maximize(self.a + var), [var == 2 + self.a, var <= 3])
     result = p.solve()
     self.assertAlmostEqual(result, 4.0)
     self.assertAlmostEqual(self.a.value, 1)
     self.assertAlmostEqual(var.value, 3)
Exemplo n.º 56
0
    def test_chebyshev_center(self):
        # The goal is to find the largest Euclidean ball (i.e. its center and
        # radius) that lies in a polyhedron described by linear inequalites in this
        # fashion: P = {x : a_i'*x <= b_i, i=1,...,m} where x is in R^2

        # Generate the input data
        a1 = np.matrix("2; 1")
        a2 = np.matrix(" 2; -1")
        a3 = np.matrix("-1;  2")
        a4 = np.matrix("-1; -2")
        b = np.ones([4,1])

        # Create and solve the model
        r = Variable(name='r')
        x_c = Variable(2,name='x_c')
        obj = Maximize(r)
        constraints = [ #TODO have atoms compute values for constants.
            a1.T*x_c + np.linalg.norm(a1)*r <= b[0],
            a2.T*x_c + np.linalg.norm(a2)*r <= b[1],
            a3.T*x_c + np.linalg.norm(a3)*r <= b[2],
            a4.T*x_c + np.linalg.norm(a4)*r <= b[3],
        ]
        
        p = Problem(obj, constraints)
        result = p.solve()
        self.assertAlmostEqual(result, 0.4472)
        self.assertAlmostEqual(r.value, result)
        self.assertAlmostEqual(x_c.value, [0,0])
Exemplo n.º 57
0
    def test_transpose(self):
        p = Problem(Minimize(sum_entries(self.x)),
                    [self.x.T >= matrix([1, 2]).T])
        result = p.solve()
        self.assertAlmostEqual(result, 3)
        self.assertItemsAlmostEqual(self.x.value, [1, 2])

        p = Problem(Minimize(sum_entries(self.C)),
                    [matrix([1, 1]).T * self.C.T >= matrix([0, 1, 2]).T])
        result = p.solve()
        value = self.C.value

        constraints = [
            1 * self.C[i, 0] + 1 * self.C[i, 1] >= i for i in range(3)
        ]
        p = Problem(Minimize(sum_entries(self.C)), constraints)
        result2 = p.solve()
        self.assertAlmostEqual(result, result2)
        self.assertItemsAlmostEqual(self.C.value, value)

        p = Problem(Minimize(self.A[0, 1] - self.A.T[1, 0]),
                    [self.A == [[1, 2], [3, 4]]])
        result = p.solve()
        self.assertAlmostEqual(result, 0)

        exp = (-self.x).T
        print exp.size
        p = Problem(Minimize(sum_entries(self.x)), [(-self.x).T <= 1])
        result = p.solve()
        self.assertAlmostEqual(result, -2)

        c = matrix([1, -1])
        p = Problem(Minimize(max_elemwise(c.T, 2, 2 + c.T)[1]))
        result = p.solve()
        self.assertAlmostEqual(result, 2)

        c = matrix([[1, -1, 2], [1, -1, 2]])
        p = Problem(Minimize(sum_entries(max_elemwise(c, 2, 2 + c).T[:, 0])))
        result = p.solve()
        self.assertAlmostEqual(result, 6)

        c = matrix([[1, -1, 2], [1, -1, 2]])
        p = Problem(Minimize(sum_entries(square(c.T).T[:, 0])))
        result = p.solve()
        self.assertAlmostEqual(result, 6)

        # Slice of transpose.
        p = Problem(Maximize(sum_entries(self.C)),
                    [self.C.T[:, 1:3] <= 2, self.C.T[:, 0] == 1])
        result = p.solve()
        self.assertAlmostEqual(result, 10)
        self.assertItemsAlmostEqual(self.C.value, 2 * [1, 2, 2])
Exemplo n.º 58
0
    def test_sdp_symmetry(self):
        # TODO should these raise exceptions?
        # with self.assertRaises(Exception) as cm:
        #     lambda_max([[1,2],[3,4]])
        # self.assertEqual(str(cm.exception), "lambda_max called on non-symmetric matrix.")

        # with self.assertRaises(Exception) as cm:
        #     lambda_min([[1,2],[3,4]])
        # self.assertEqual(str(cm.exception), "lambda_min called on non-symmetric matrix.")

        p = Problem(Minimize(lambda_max(self.A)), [self.A >= 2])
        result = p.solve()
        self.assertItemsAlmostEqual(self.A.value, self.A.value.T)

        p = Problem(Minimize(lambda_max(self.A)), [self.A == [[1, 2], [3, 4]]])
        result = p.solve()
        self.assertEqual(p.status, s.INFEASIBLE)
Exemplo n.º 59
0
    def test_sdp_symmetry(self):
        # TODO should these raise exceptions?
        # with self.assertRaises(Exception) as cm:
        #     lambda_max([[1,2],[3,4]])
        # self.assertEqual(str(cm.exception), "lambda_max called on non-symmetric matrix.")

        # with self.assertRaises(Exception) as cm:
        #     lambda_min([[1,2],[3,4]])
        # self.assertEqual(str(cm.exception), "lambda_min called on non-symmetric matrix.")

        p = Problem(Minimize(lambda_max(self.A)), [self.A >= 2])
        result = p.solve()
        self.assertItemsAlmostEqual(self.A.value, self.A.value.T)

        p = Problem(Minimize(lambda_max(self.A)), [self.A == [[1,2],[3,4]]])
        result = p.solve()
        self.assertEqual(p.status, s.INFEASIBLE)
Exemplo n.º 60
0
 def test_ecos_noineq(self):
     """Test ECOS with no inequality constraints.
     """
     T = matrix(1, (2, 2))
     p = Problem(Minimize(1), [self.A == T])
     result = p.solve(solver=s.ECOS)
     self.assertAlmostEqual(result, 1)
     self.assertItemsAlmostEqual(self.A.value, T)