예제 #1
0
 def test_diag_prob(self):
     """Test a problem with diag.
     """
     C = Variable(3, 3)
     obj = Maximize(C[0, 2])
     constraints = [
         diag(C) == 1, C[0, 1] == 0.6, C[1, 2] == -0.3, C == Semidef(3)
     ]
     prob = Problem(obj, constraints)
     result = prob.solve()
     self.assertAlmostEqual(result, 0.583151)
예제 #2
0
 def test_large_sum(self):
     """Test large number of variables summed.
     """
     for n in [10, 20, 30, 40, 50]:
         A = matrix(range(n * n), (n, n))
         x = Variable(n, n)
         p = Problem(Minimize(at.sum_entries(x)), [x >= A])
         result = p.solve()
         answer = n * n * (n * n + 1) / 2 - n * n
         print(result - answer)
         self.assertAlmostEqual(result, answer)
예제 #3
0
    def test_var_copy(self):
        """Test the copy function for variable types.
        """
        x = Variable(3, 4, name="x")
        y = x.copy()
        self.assertEqual(y.size, (3, 4))
        self.assertEqual(y.name(), "x")

        x = Semidef(5, name="x")
        y = x.copy()
        self.assertEqual(y.size, (5, 5))
예제 #4
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)
예제 #5
0
 def test_quadratic_form(self):
     x = Variable(5)
     P = np.asmatrix(np.random.randn(5, 5))
     q = np.asmatrix(np.random.randn(5, 1))
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         s = x.T*P*x + q.T*x
     self.assertFalse(s.is_constant())
     self.assertFalse(s.is_affine())
     self.assertTrue(s.is_quadratic())
     self.assertFalse(s.is_dcp())
예제 #6
0
파일: test_atoms.py 프로젝트: ctb/cvxpy
 def test_index(self):
     """Test the copy function for index.
     """
     # Test copy with args=None
     size = (5, 4)
     A = Variable(*size)
     atom = A[0:2, 0:1]
     copy = atom.copy()
     self.assertTrue(type(copy) is type(atom))
     # A new object is constructed, so copy.args == atom.args but copy.args
     # is not atom.args.
     self.assertEqual(copy.args, atom.args)
     self.assertFalse(copy.args is atom.args)
     self.assertEqual(copy.get_data(), atom.get_data())
     # Test copy with new args
     B = Variable(4, 5)
     copy = atom.copy(args=[B])
     self.assertTrue(type(copy) is type(atom))
     self.assertTrue(copy.args[0] is B)
     self.assertEqual(copy.get_data(), atom.get_data())
예제 #7
0
    def test_min_entries(self):
        """Test min_entries.
        """
        # One arg, test sign.
        self.assertEqual(min_entries(1).sign, s.POSITIVE)
        self.assertEqual(min_entries(-2).sign, s.NEGATIVE)
        self.assertEqual(min_entries(Variable()).sign, s.UNKNOWN)
        self.assertEqual(min_entries(0).sign, s.ZERO)

        # Test with axis argument.
        self.assertEqual(min_entries(Variable(2), axis=0).size, (1, 1))
        self.assertEqual(min_entries(Variable(2), axis=1).size, (2, 1))
        self.assertEqual(min_entries(Variable(2, 3), axis=0).size, (1, 3))
        self.assertEqual(min_entries(Variable(2, 3), axis=1).size, (2, 1))

        # Invalid axis.
        with self.assertRaises(Exception) as cm:
            min_entries(self.x, axis=4)
        self.assertEqual(str(cm.exception),
                         "Invalid argument for axis.")
예제 #8
0
파일: test_grad.py 프로젝트: McCabeJM/cvxpy
    def test_affine(self):
        """Test grad for affine atoms.
        """
        expr = -self.a
        self.a.value = 2
        self.assertAlmostEqual(expr.grad[self.a], -1)

        expr = 2 * self.a
        self.a.value = 2
        self.assertAlmostEqual(expr.grad[self.a], 2)

        expr = self.a / 2
        self.a.value = 2
        self.assertAlmostEqual(expr.grad[self.a], 0.5)

        expr = -(self.x)
        self.x.value = [3, 4]
        val = np.zeros((2, 2)) - np.diag([1, 1])
        self.assertItemsAlmostEqual(expr.grad[self.x].todense(), val)

        expr = -(self.A)
        self.A.value = [[1, 2], [3, 4]]
        val = np.zeros((4, 4)) - np.diag([1, 1, 1, 1])
        self.assertItemsAlmostEqual(expr.grad[self.A].todense(), val)

        expr = self.A[0, 1]
        self.A.value = [[1, 2], [3, 4]]
        val = np.zeros((4, 1))
        val[2] = 1
        self.assertItemsAlmostEqual(expr.grad[self.A].todense(), val)

        z = Variable(3)
        expr = vstack(self.x, z)
        self.x.value = [1, 2]
        z.value = [1, 2, 3]
        val = np.zeros((2, 5))
        val[:, 0:2] = np.eye(2)
        self.assertItemsAlmostEqual(expr.grad[self.x].todense(), val)

        val = np.zeros((3, 5))
        val[:, 2:] = np.eye(3)
        self.assertItemsAlmostEqual(expr.grad[z].todense(), val)

        # cumsum
        expr = cumsum(self.x)
        self.x.value = [1, 2]
        val = np.ones((2, 2))
        val[1, 0] = 0
        self.assertItemsAlmostEqual(expr.grad[self.x].todense(), val)

        expr = cumsum(self.x, axis=1)
        self.x.value = [1, 2]
        val = np.eye(2)
        self.assertItemsAlmostEqual(expr.grad[self.x].todense(), val)
예제 #9
0
 def test_presolve_constant_constraints(self):
     """Test that the presolver removes constraints with no variables.
     """
     x = Variable()
     obj = Maximize(sqrt(x))
     prob = Problem(obj)
     c, G, h, dims, A, b = prob.get_problem_data(s.ECOS)
     for row in range(A.shape[0]):
         assert A[row, :].nnz > 0
     for row in range(G.shape[0]):
         assert G[row, :].nnz > 0
예제 #10
0
파일: test_domain.py 프로젝트: anto6715/svm
    def setUp(self):
        self.a = Variable(name='a')

        self.x = Variable(2, name='x')
        self.y = Variable(2, name='y')
        self.z = Variable(3, name='z')

        self.A = Variable(2, 2, name='A')
        self.B = Variable(2, 2, name='B')
        self.C = Variable(3, 2, name='C')
예제 #11
0
    def test_sum_smallest(self):
        """Test the sum_smallest atom and related atoms.
        """
        with self.assertRaises(Exception) as cm:
            sum_smallest(self.x, -1)
        self.assertEqual(str(cm.exception),
            "Second argument must be a positive integer.")

        with self.assertRaises(Exception) as cm:
            lambda_sum_smallest(Variable(2,2), 2.4)
        self.assertEqual(str(cm.exception),
            "Second argument must be a positive integer.")
예제 #12
0
    def test_partial_optimize_eval_1norm(self):
        # Evaluate the 1-norm in the usual way (i.e., in epigraph form).
        dims = 3
        x, t = Variable(dims), Variable(dims)
        xval = [-5]*dims
        p1 = Problem(Minimize(sum_entries(t)), [-t<=xval, xval<=t])
        p1.solve()

        # Minimize the 1-norm via partial_optimize.
        p2 = Problem(Minimize(sum_entries(t)), [-t<=x, x<=t])
        g = partial_optimize(p2, [t], [x])
        p3 = Problem(Minimize(g), [x == xval])
        p3.solve()
        self.assertAlmostEqual(p1.value, p3.value)

        # Try leaving out args.

        # Minimize the 1-norm via partial_optimize.
        g = partial_optimize(p2, opt_vars=[t])
        p3 = Problem(Minimize(g), [x == xval])
        p3.solve()
        self.assertAlmostEqual(p1.value, p3.value)

        # Minimize the 1-norm via partial_optimize.
        g = partial_optimize(p2, dont_opt_vars=[x])
        p3 = Problem(Minimize(g), [x == xval])
        p3.solve()
        self.assertAlmostEqual(p1.value, p3.value)

        with self.assertRaises(Exception) as cm:
            g = partial_optimize(p2)
        self.assertEqual(str(cm.exception),
            "partial_optimize called with neither opt_vars nor dont_opt_vars.")

        with self.assertRaises(Exception) as cm:
            g = partial_optimize(p2, [], [x])
        self.assertEqual(str(cm.exception),
            ("If opt_vars and new_opt_vars are both specified, "
             "they must contain all variables in the problem.")
        )
예제 #13
0
    def test_neg_indices(self):
        """Test negative indices.
        """
        c = Constant([[1, 2], [3, 4]])
        exp = c[-1, -1]
        self.assertEqual(exp.value, 4)
        self.assertEqual(exp.size, (1, 1))
        self.assertEqual(exp.curvature, s.CONSTANT)

        c = Constant([1, 2, 3, 4])
        exp = c[1:-1]
        self.assertItemsAlmostEqual(exp.value, [2, 3])
        self.assertEqual(exp.size, (2, 1))
        self.assertEqual(exp.curvature, s.CONSTANT)

        c = Constant([1, 2, 3, 4])
        exp = c[::-1]
        self.assertItemsAlmostEqual(exp.value, [4, 3, 2, 1])
        self.assertEqual(exp.size, (4, 1))
        self.assertEqual(exp.curvature, s.CONSTANT)

        x = Variable(4)
        Problem(Minimize(0), [x[::-1] == c]).solve()
        self.assertItemsAlmostEqual(x.value, [4, 3, 2, 1])
        self.assertEqual(x[::-1].size, (4, 1))

        x = Variable(2)
        self.assertEqual(x[::-1].size, (2, 1))

        x = Variable(100, name="x")
        self.assertEqual("x[:-1, 0]", str(x[:-1]))

        c = Constant([[1, 2], [3, 4]])
        expr = c[0, 2:0:-1]
        self.assertEqual(expr.size, (1, 1))
        self.assertAlmostEqual(expr.value, 3)

        expr = c[0, 2::-1]
        self.assertEqual(expr.size, (1, 2))
        self.assertItemsAlmostEqual(expr.value, [3, 1])
예제 #14
0
    def setUp(self):
        self.a = Variable(name='a')

        self.x = Variable(2, name='x')
        self.y = Variable(3, name='y')
        self.z = Variable(2, name='z')

        self.A = Variable(2, 2, name='A')
        self.B = Variable(2, 2, name='B')
        self.C = Variable(3, 2, name='C')
        self.intf = intf.DEFAULT_INTERFACE
예제 #15
0
    def test_power(self):
        from fractions import Fraction

        for size in (1, 1), (3, 1), (2, 3):
            x = Variable(*size)
            y = Variable(*size)
            exp = x + y

            for p in 0, 1, 2, 3, 2.7, .67, -1, -2.3, Fraction(4, 5):
                atom = power(exp, p)

                self.assertEquals(atom.size, size)

                if p > 1 or p < 0:
                    self.assertEquals(atom.curvature, u.Curvature.CONVEX_KEY)
                elif p == 1:
                    self.assertEquals(atom.curvature, u.Curvature.AFFINE_KEY)
                elif p == 0:
                    self.assertEquals(atom.curvature, u.Curvature.CONSTANT_KEY)
                else:
                    self.assertEquals(atom.curvature, u.Curvature.CONCAVE_KEY)

                if p != 1:
                    self.assertEquals(atom.sign, u.Sign.POSITIVE_KEY)

                # Test copy with args=None
                copy = atom.copy()
                self.assertTrue(type(copy) is type(atom))
                # A new object is constructed, so copy.args == atom.args but copy.args
                # is not atom.args.
                self.assertEqual(copy.args, atom.args)
                self.assertFalse(copy.args is atom.args)
                self.assertEqual(copy.get_data(), atom.get_data())
                # Test copy with new args
                copy = atom.copy(args=[self.y])
                self.assertTrue(type(copy) is type(atom))
                self.assertTrue(copy.args[0] is self.y)
                self.assertEqual(copy.get_data(), atom.get_data())
예제 #16
0
    def test_power(self):
        from fractions import Fraction

        for size in (1, 1), (3, 1), (2, 3):
            x = Variable(*size)
            y = Variable(*size)
            exp = x + y

            for p in 0, 1, 2, 3, 2.7, .67, -1, -2.3, Fraction(4, 5):
                atom = power(exp, p)

                self.assertEquals(atom.size, size)

                if p > 1 or p < 0:
                    self.assertEquals(atom.curvature, u.Curvature.CONVEX_KEY)
                elif p == 1:
                    self.assertEquals(atom.curvature, u.Curvature.AFFINE_KEY)
                elif p == 0:
                    self.assertEquals(atom.curvature, u.Curvature.CONSTANT_KEY)
                else:
                    self.assertEquals(atom.curvature, u.Curvature.CONCAVE_KEY)

                if p != 1:
                    self.assertEquals(atom.sign, u.Sign.POSITIVE_KEY)
예제 #17
0
    def test_assign_var_value(self):
        """Test assigning a value to a variable.
        """
        # Scalar variable.
        a = Variable()
        a.value = 1
        self.assertEqual(a.value, 1)
        with self.assertRaises(Exception) as cm:
            a.value = [2, 1]
        self.assertEqual(str(cm.exception),
                         "Invalid dimensions (2, 1) for Variable value.")

        # Test assigning None.
        a.value = 1
        a.value = None
        assert a.value is None

        # Vector variable.
        x = Variable(2)
        x.value = [2, 1]
        self.assertItemsAlmostEqual(x.value, [2, 1])
        # Matrix variable.
        A = Variable(3, 2)
        A.value = np.ones((3, 2))
        self.assertItemsAlmostEqual(A.value, np.ones((3, 2)))

        # Test assigning negative val to nonnegative variable.
        x = NonNegative()
        with self.assertRaises(Exception) as cm:
            x.value = -2
        self.assertEqual(str(cm.exception),
                         "Invalid sign for NonNegative value.")

        # Small negative values are rounded to 0.
        x.value = -1e-8
        self.assertEqual(x.value, 0)
예제 #18
0
    def test_sum_largest(self):
        """Test the sum_largest atom and related atoms.
        """
        with self.assertRaises(Exception) as cm:
            sum_largest(self.x, -1)
        self.assertEqual(str(cm.exception),
            "Second argument must be a positive integer.")

        with self.assertRaises(Exception) as cm:
            lambda_sum_largest(self.x, 2.4)
        self.assertEqual(str(cm.exception),
            "First argument must be a square matrix.")

        with self.assertRaises(Exception) as cm:
            lambda_sum_largest(Variable(2, 2), 2.4)
        self.assertEqual(str(cm.exception),
            "Second argument must be a positive integer.")

        # Test copy with args=None
        atom = sum_largest(self.x, 2)
        copy = atom.copy()
        self.assertTrue(type(copy) is type(atom))
        # A new object is constructed, so copy.args == atom.args but copy.args
        # is not atom.args.
        self.assertEqual(copy.args, atom.args)
        self.assertFalse(copy.args is atom.args)
        self.assertEqual(copy.get_data(), atom.get_data())
        # Test copy with new args
        copy = atom.copy(args=[self.y])
        self.assertTrue(type(copy) is type(atom))
        self.assertTrue(copy.args[0] is self.y)
        self.assertEqual(copy.get_data(), atom.get_data())
        # Test copy with lambda_sum_largest, which is in fact an AddExpression
        atom = lambda_sum_largest(Variable(2, 2), 2)
        copy = atom.copy()
        self.assertTrue(type(copy) is type(atom))
예제 #19
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)
예제 #20
0
    def test_yield_constr_cost_min(self):
        # Create problem data.
        n = 10
        c = numpy.random.randn(n)
        P, q, r = numpy.eye(n), numpy.random.randn(n), numpy.random.randn()
        mu, Sigma = numpy.zeros(n), 0.1 * numpy.eye(n)
        omega = NormalRandomVariable(mu, Sigma)
        m, eta = 100, 0.95

        # Create and solve optimization problem.
        x = Variable(n)
        yield_constr = prob(
            quad_form(x + omega, P) + (x + omega).T * q + r >= 0, m) <= 1 - eta
        p = Problem(Minimize(x.T * c), [yield_constr])
        p.solve()
        self.assert_feas(p)
예제 #21
0
    def test_matrix_frac(self):
        """Test for the matrix_frac atom.
        """
        atom = matrix_frac(self.x, self.A)
        self.assertEqual(atom.size, (1, 1))
        self.assertEqual(atom.curvature, s.CONVEX)
        # Test matrix_frac size validation.
        with self.assertRaises(Exception) as cm:
            matrix_frac(self.x, self.C)
        self.assertEqual(str(cm.exception),
                         "The second argument to matrix_frac must be a square matrix.")

        with self.assertRaises(Exception) as cm:
            matrix_frac(Variable(3), self.A)
        self.assertEqual(str(cm.exception),
                         "The arguments to matrix_frac have incompatible dimensions.")
예제 #22
0
    def test_geo_mean(self):
        import numpy as np

        x = Variable(2)
        cost = geo_mean(x)
        prob = Problem(Maximize(cost), [x <= 1])
        prob.solve()
        self.assertAlmostEqual(prob.value, 1)

        prob = Problem(Maximize(cost), [sum(x) <= 1])
        prob.solve()
        self.assertItemsAlmostEqual(x.value, [.5, .5])

        x = Variable(3, 3)
        self.assertRaises(ValueError, geo_mean, x)

        x = Variable(3, 1)
        g = geo_mean(x)
        self.assertSequenceEqual(g.w, [Fraction(1, 3)] * 3)

        x = Variable(1, 5)
        g = geo_mean(x)
        self.assertSequenceEqual(g.w, [Fraction(1, 5)] * 5)

        # check that we get the right answer for
        # max geo_mean(x) s.t. sum(x) <= 1
        p = np.array([.07, .12, .23, .19, .39])

        def short_geo_mean(x, p):
            p = np.array(p) / sum(p)
            x = np.array(x)
            return np.prod(x**p)

        x = Variable(5)
        prob = Problem(Maximize(geo_mean(x, p)), [sum(x) <= 1])
        prob.solve()
        x = np.array(x.value).flatten()
        x_true = p / sum(p)

        self.assertTrue(np.allclose(prob.value, geo_mean(list(x), p).value))
        self.assertTrue(np.allclose(prob.value, short_geo_mean(x, p)))
        self.assertTrue(np.allclose(x, x_true, 1e-3))

        # check that we get the right answer for
        # max geo_mean(x) s.t. norm(x) <= 1
        x = Variable(5)
        prob = Problem(Maximize(geo_mean(x, p)), [norm(x) <= 1])
        prob.solve()
        x = np.array(x.value).flatten()
        x_true = np.sqrt(p / sum(p))

        self.assertTrue(np.allclose(prob.value, geo_mean(list(x), p).value))
        self.assertTrue(np.allclose(prob.value, short_geo_mean(x, p)))
        self.assertTrue(np.allclose(x, x_true, 1e-3))
예제 #23
0
    def test_cvar(self):
        # Create problem data.
        n = 10
        pbar, Sigma = numpy.random.randn(n), numpy.eye(n)
        p = RandomVariableFactory().create_normal_rv(pbar, Sigma)
        u, eta, m = numpy.random.rand(), 0.95, 100

        # Create optimization variables.
        x, beta = NonNegative(n), Variable()

        # Create and solve optimization problem.
        cvar = expectation(pos(-x.T * p - beta), m)
        cvar = beta + 1 / (1 - eta) * cvar
        prob = Problem(Minimize(expectation(-x.T * p, m)),
                       [x.T * numpy.ones((n, 1)) == 1, cvar <= u])
        prob.solve()

        self.assert_feas(prob)
예제 #24
0
    def test_scale(self):
        """
        Note: everything works fine with num_samples <= 100,000 and n <= 10.
        """
        num_samples = 10
        n = 1

        mu = numpy.zeros(n)
        Sigma = numpy.eye(n)
        c = RandomVariableFactory().create_normal_rv(mu, Sigma)

        x = Variable(n)

        p = Problem(Minimize(expectation(x.T * c, num_samples)),
                    [x >= -1, x <= 1])
        p.solve()

        self.assert_feas(p)
예제 #25
0
    def test_min_elemwise_sign(self):
        # Two args.
        self.assertEqual(min_elemwise(1, 2).sign, s.POSITIVE)
        self.assertEqual(min_elemwise(1, Variable()).sign, s.UNKNOWN)
        self.assertEqual(min_elemwise(1, -2).sign, s.NEGATIVE)
        self.assertEqual(min_elemwise(1, 0).sign, s.ZERO)

        self.assertEqual(min_elemwise(Variable(), 0).sign, s.NEGATIVE)
        self.assertEqual(min_elemwise(Variable(), Variable()).sign, s.UNKNOWN)
        self.assertEqual(min_elemwise(Variable(), -2).sign, s.NEGATIVE)

        self.assertEqual(min_elemwise(0, 0).sign, s.ZERO)
        self.assertEqual(min_elemwise(0, -2).sign, s.NEGATIVE)

        self.assertEqual(min_elemwise(-3, -2).sign, s.NEGATIVE)

        # Many args.
        self.assertEqual(
            min_elemwise(-2, Variable(), 0, -1, Variable(), 1).sign,
            s.NEGATIVE)

        # Promotion.
        self.assertEqual(min_elemwise(-1, Variable(2)).sign, s.NEGATIVE)
        self.assertEqual(min_elemwise(-1, Variable(2)).size, (2, 1))
예제 #26
0
    def test_min_elemwise_sign(self):
        # Two args.
        self.assertEquals(min_elemwise(1, 2).sign, u.Sign.POSITIVE_KEY)
        self.assertEquals(min_elemwise(1, Variable()).sign, u.Sign.UNKNOWN_KEY)
        self.assertEquals(min_elemwise(1, -2).sign, u.Sign.NEGATIVE_KEY)
        self.assertEquals(min_elemwise(1, 0).sign, u.Sign.ZERO_KEY)

        self.assertEquals(min_elemwise(Variable(), 0).sign, u.Sign.NEGATIVE_KEY)
        self.assertEquals(min_elemwise(Variable(), Variable()).sign, u.Sign.UNKNOWN_KEY)
        self.assertEquals(min_elemwise(Variable(), -2).sign, u.Sign.NEGATIVE_KEY)

        self.assertEquals(min_elemwise(0, 0).sign, u.Sign.ZERO_KEY)
        self.assertEquals(min_elemwise(0, -2).sign, u.Sign.NEGATIVE_KEY)

        self.assertEquals(min_elemwise(-3, -2).sign, u.Sign.NEGATIVE_KEY)

        # Many args.
        self.assertEquals(min_elemwise(-2, Variable(), 0, -1, Variable(), 1).sign,
                          u.Sign.NEGATIVE_KEY)
예제 #27
0
    def test_simple_problem(self):
        # Create problem data.
        n = numpy.random.randint(1, 10)
        eta = 0.95
        num_samples = 10

        c = numpy.random.rand(n, 1)

        mu = numpy.zeros(n)
        Sigma = numpy.eye(n)
        a = NormalRandomVariable(mu, Sigma)

        b = numpy.random.randn()

        # Create and solve optimization problem.
        x = Variable(n)
        p = Problem(
            Maximize(x.T * c),
            [prob(max_entries(x.T * a - b) >= 0, num_samples) <= 1 - eta])
        p.solve()
        self.assert_feas(p)
예제 #28
0
    def test_add_expression(self):
        # Vectors
        c = Constant([2, 2])
        exp = self.x + c
        self.assertEqual(exp.curvature, u.Curvature.AFFINE_KEY)
        self.assertEqual(exp.sign, u.Sign.UNKNOWN_KEY)
        self.assertEqual(exp.canonical_form[0].size, (2, 1))
        self.assertEqual(exp.canonical_form[1], [])
        # self.assertEqual(exp.name(), self.x.name() + " + " + c.name())
        self.assertEqual(exp.size, (2, 1))

        z = Variable(2, name='z')
        exp = exp + z + self.x

        with self.assertRaises(Exception) as cm:
            (self.x + self.y)
        self.assertEqual(str(cm.exception),
                         "Incompatible dimensions (2, 1) (3, 1)")

        # Matrices
        exp = self.A + self.B
        self.assertEqual(exp.curvature, u.Curvature.AFFINE_KEY)
        self.assertEqual(exp.size, (2, 2))

        with self.assertRaises(Exception) as cm:
            (self.A + self.C)
        self.assertEqual(str(cm.exception),
                         "Incompatible dimensions (2, 2) (3, 2)")

        with self.assertRaises(Exception) as cm:
            AddExpression([self.A, self.C])
        self.assertEqual(str(cm.exception),
                         "Incompatible dimensions (2, 2) (3, 2)")

        # Test that sum is flattened.
        exp = self.x + c + self.x
        self.assertEqual(len(exp.args), 3)

        # Test repr.
        self.assertEqual(repr(exp), "Expression(AFFINE, UNKNOWN, (2, 1))")
예제 #29
0
    def test_sum_entries(self):
        """Test the sum_entries atom.
        """
        self.assertEqual(sum_entries(1).sign, s.POSITIVE)
        self.assertEqual(sum_entries([1, -1]).sign, s.UNKNOWN)
        self.assertEqual(sum_entries([1, -1]).curvature, s.CONSTANT)
        self.assertEqual(sum_entries(Variable(2)).sign, s.UNKNOWN)
        self.assertEqual(sum_entries(Variable(2)).size, (1, 1))
        self.assertEqual(sum_entries(Variable(2)).curvature, s.AFFINE)
        # Mixed curvature.
        mat = np.mat("1 -1")
        self.assertEqual(sum_entries(mat*square(Variable(2))).curvature, s.UNKNOWN)

        # Test with axis argument.
        self.assertEqual(sum_entries(Variable(2), axis=0).size, (1, 1))
        self.assertEqual(sum_entries(Variable(2), axis=1).size, (2, 1))
        self.assertEqual(sum_entries(Variable(2, 3), axis=0).size, (1, 3))
        self.assertEqual(sum_entries(Variable(2, 3), axis=1).size, (2, 1))

        # Invalid axis.
        with self.assertRaises(Exception) as cm:
            sum_entries(self.x, axis=4)
        self.assertEqual(str(cm.exception),
                         "Invalid argument for axis.")
예제 #30
0
    def test_consistency(self):
        """Test that variables and constraints keep a consistent order.
        """
        import itertools
        num_solves = 4
        vars_lists = []
        ineqs_lists = []
        var_ids_order_created = []
        for k in range(num_solves):
            sum = 0
            constraints = []
            var_ids = []
            for i in range(100):
                var = Variable(name=str(i))
                var_ids.append(var.id)
                sum += var
                constraints.append(var >= i)
            var_ids_order_created.append(var_ids)
            obj = Minimize(sum)
            p = Problem(obj, constraints)
            objective, constr_map = p.canonicalize()
            all_ineq = itertools.chain(constr_map[s.EQ], constr_map[s.LEQ])
            var_offsets, var_sizes, x_length = p._get_var_offsets(
                objective, all_ineq)
            # Sort by offset.
            vars_ = sorted(var_offsets.items(),
                           key=lambda (var_id, offset): offset)
            vars_ = [var_id for (var_id, offset) in vars_]
            vars_lists.append(vars_)
            ineqs_lists.append(constr_map[s.LEQ])

        # Verify order of variables is consistent.
        for i in range(num_solves):
            self.assertEqual(var_ids_order_created[i], vars_lists[i])
        for i in range(num_solves):
            for idx, constr in enumerate(ineqs_lists[i]):
                var_id, _ = lu.get_expr_vars(constr.expr)[0]
                self.assertEqual(var_ids_order_created[i][idx], var_id)