'Test quad form with a singular matrix.'

def test_singular_quad_form(self):

    np.random.seed(1234)
    for n in (3, 4, 5):
        for i in range(5):
            v = np.exp(np.random.randn(n))
            v = (v / np.sum(v))
            A = np.random.randn(n, n)
            Q = np.dot(A, A.T)
            E = (np.identity(n) - (np.outer(v, v) / np.inner(v, v)))
            Q = np.dot(E, np.dot(Q, E.T))
            observed_rank = np.linalg.matrix_rank(Q)
            desired_rank = (n - 1)
            (yield (assert_equal, observed_rank, desired_rank))
            for action in ('minimize', 'maximize'):
                x = cvxpy.Variable(n)
                if (action == 'minimize'):
                    q = cvxpy.quad_form(x, Q)
                    objective = cvxpy.Minimize(q)
                elif (action == 'maximize'):
                    q = cvxpy.quad_form(x, (- Q))
                    objective = cvxpy.Maximize(q)
                constraints = [(0 <= x), (cvxpy.sum_entries(x) == 1)]
                p = cvxpy.Problem(objective, constraints)
                p.solve()
                xopt = x.value.A.flatten()
                yopt = np.dot(xopt, np.dot(Q, xopt))
                assert_allclose(yopt, 0, atol=0.001)
                assert_allclose(xopt, v, atol=0.001)
