How to use the cvxpy.Maximize function in cvxpy

To help you get started, we’ve selected a few cvxpy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github alnurali / cvxstoc / tests / test_chance_constr.py View on Github external
# 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)
github msmbuilder / msmbuilder / msmbuilder / decomposition / speigh.py View on Github external
def solve_sparse(self, y, w, x_mask):
        assert y.ndim == 1 and w.ndim == 1 and y.shape == w.shape
        assert w.shape[0] == self.n

        x = cp.Variable(np.count_nonzero(x_mask))

        term1 = x.T*y[x_mask] - self.c*cp.norm1(cp.diag(w[x_mask]) * x)
        constraints = [cp.quad_form(x, self.B[np.ix_(x_mask, x_mask)]) <= 1]
        problem = cp.Problem(cp.Maximize(term1), constraints)

        result = problem.solve(solver=cp.SCS)
        if problem.status not in (cp.OPTIMAL, cp.OPTIMAL_INACCURATE):
            raise ValueError(problem.status)
        return np.asarray(x.value).flatten()
github cvxgrp / qcqp / examples / maxcut.py View on Github external
n = 25
np.random.seed(1)

# Make adjacency matrix.
p = 0.2
W = np.asmatrix(np.random.uniform(low=0.0, high=1.0, size=(n, n)))
for i in range(n):
    W[i, i] = 1
    for j in range(i+1, n):
        W[j, i] = W[i, j]
W = (W < p).astype(float)

x = cvx.Variable(n)
obj = 0.25*(cvx.sum_entries(W) - cvx.quad_form(x, W))
cons = [cvx.square(x) == 1]
prob = cvx.Problem(cvx.Maximize(obj), cons)
qcqp = QCQP(prob)

# sample from the semidefinite relaxation
qcqp.suggest(SDR)
print("SDR-based upper bound: %.3f" % qcqp.sdr_bound)

f_cd, v_cd = qcqp.improve(COORD_DESCENT)
print("Coordinate descent: objective %.3f, violation %.3f" % (f_cd, v_cd))

# SDR solution is cached and not solved again
qcqp.suggest(SDR)
f_dccp, v_dccp = qcqp.improve(DCCP, tau=1)
print("Penalty CCP: objective %.3f, violation %.3f" % (f_dccp, v_dccp))

qcqp.suggest(SDR)
f_admm, v_admm = qcqp.improve(ADMM)
github replicahq / doppelganger / doppelganger / listbalancer.py View on Github external
)

        constraints = [
            x >= 0,
            x.T * hh_table == A,
        ]
        prob = cvx.Problem(objective, constraints)
        prob.solve(solver=cvx.SCS, verbose=verbose_solver)

        return x.value

    else:
        # With relaxation factors
        z = cvx.Variable(n_controls)

        objective = cvx.Maximize(
            cvx.sum_entries(cvx.entr(x) + cvx.mul_elemwise(cvx.log(w.T), x)) +
            cvx.sum_entries(mu * (cvx.entr(z)))
        )

        constraints = [
            x >= 0,
            z >= 0,
            x.T * hh_table == cvx.mul_elemwise(A, z.T),
        ]
        prob = cvx.Problem(objective, constraints)
        prob.solve(solver=cvx.SCS, verbose=verbose_solver)

        return x.value, z.value
github cvxgrp / dmcp / dmcp / bcd.py View on Github external
#Add proximal variables
    prob_variables = prob.variables()
    prob_variables.sort(key = lambda x:x.id)
    for var in prob_variables:
        # add quadratic terms for all variables that are not slacks
        if not var.id in slack_id:
            if prob.objective.NAME == 'minimize':
                new_cost = new_cost + cvx.square(cvx.norm(var - var.value,'fro'))/2/lambd
            else:
                new_cost = new_cost - cvx.square(cvx.norm(var - var.value,'fro'))/2/lambd

    # Define proximal problem
    if prob.objective.NAME == 'minimize':
        new_prob = cvx.Problem(cvx.Minimize(new_cost), new_constr)
    else: # maximize
        new_prob = cvx.Problem(cvx.Maximize(new_cost), new_constr)
    return new_prob
github cvxgrp / dccp / dccp / problem.py View on Github external
constr_new.append(dom)
                constr_new.append(newcon.expr <= var_slack[count_slack])
                constr_new.append(var_slack[count_slack] >= 0)
                count_slack = count_slack + 1
            else:
                constr_new.append(arg)

        # objective
        if self.objective.NAME == 'minimize':
            for var in var_slack:
                cost_new += tau*cvx.sum(var)
            obj_new = cvx.Minimize(cost_new)
        else:
            for var in var_slack:
                cost_new -= tau*cvx.sum(var)
            obj_new = cvx.Maximize(cost_new)

        # new problem
        prob_new = cvx.Problem(obj_new, constr_new)
        # keep previous value of variables
        variable_pres_value = []
        for var in self.variables():
            variable_pres_value.append(var.value)
        # solve
        if solver is None:
            prob_new_cost_value = prob_new.solve(**kwargs)
        else:
            prob_new_cost_value = prob_new.solve(solver=solver, **kwargs)
        if prob_new_cost_value is not None:
            logger.info("iteration=%d, cost value=%.5f, tau=%.5f, solver status=%s", it, prob_new_cost_value, tau, prob_new.status)
        else:
            logger.info("iteration=%d, cost value=%.5f, tau=%.5f, solver status=%s", it, np.nan, tau, prob_new.status)
github AaronJi / RL / python / RLutils / algorithm / scheduling_mp.py View on Github external
R_left = np.maximum(R - 0.0001 * np.ones((n, 1)), small*np.ones((n, 1))) # R_left should be positive
    Ru_left = np.maximum(np.reshape(Ru, (tau_max*n, 1), order='F') - 0.0001 * np.ones((n, tau_max)), small*np.ones((n, tau_max)))


    # Construct the problem.
    X_left = cvx.Variable(num_nonzero_M, 1)
    Y_left = cvx.Variable(num_nonzero_rep, 1)
    Z_left = cvx.Variable(P.shape[0], tau_max*n)

    obj_left = W_coeff*X_left - C_coeff*Y_left + cvx.sum(cvx.multiply(P, Z_left))

    cons_left = [R_left == row_sum_matrix_X*X_left + row_sum_matrix_Y*Y_left,
                  cvx.sum(Z_left, axis=0).T == col_sum_matrix_X * X_left + col_sum_matrix_Y * Y_left + Ru_left,
                  0 <= X_left, X_left <= M_coeff, 0 <= Y_left, 0 <= Z_left, Z_left <= PLen]

    prob_left = cvx.Problem(cvx.Maximize(obj_left), cons_left)

    # Solve
    if solver == 'ECOS_BB':
        prob_left.solve(solver=cvx.ECOS_BB) #, mi_max_iters=100
    else:
        prob_left.solve(solver=cvx.ECOS)

    dual_left = np.array(cons_left[0].dual_value)
    for i in range(n):
        lambda_left[i][0] = dual_left[i][0]
    dual_left = np.array(cons_left[1].dual_value)
    for tau in range(tau_max):
        for i in range(n):
            lambda_left[i][1+tau] = dual_left[tau*n+i][0]

    return Vopt, Xopt, Yopt, end_resource, lambda_right, lambda_left, prob_right.status, prob_left.status
github AaronJi / RL / python / RLutils / algorithm / scheduling_mp.py View on Github external
# R_right = R
    R_right = R + 0.0001*np.ones((n,1))
    Ru_right = np.reshape(Ru, (tau_max*n, 1), order='F') + 0.0001 * np.ones((tau_max * n, 1))

    # Construct the problem.
    X_right = cvx.Variable(num_nonzero_M, 1)
    Y_right = cvx.Variable(num_nonzero_rep, 1)
    Z_right = cvx.Variable(P.shape[0], tau_max*n)

    obj_right = W_coeff*X_right - C_coeff*Y_right + cvx.sum(cvx.multiply(P, Z_right))

    cons_right = [R_right == row_sum_matrix_X*X_right + row_sum_matrix_Y*Y_right,
                  cvx.sum(Z_right, axis=0).T == col_sum_matrix_X * X_right + col_sum_matrix_Y * Y_right + Ru_right,
                  0 <= X_right, X_right <= M_coeff, 0 <= Y_right, 0 <= Z_right, Z_right <= PLen]

    prob_right = cvx.Problem(cvx.Maximize(obj_right), cons_right)

    # Solve
    if solver == 'ECOS_BB':
        prob_right.solve(solver=cvx.ECOS_BB) #, mi_max_iters=100
    else:
        prob_right.solve(solver=cvx.ECOS)

    Vopt = prob_right.value
    Xval = np.array(X_right.value)
    Yval = np.array(Y_right.value)
    Zval = np.array(Z_right.value)

    if num_nonzero_M == 1:
        Xopt[M_row_num[0]][M_col_num[0]] = np.round(Xval)
    else:
        for i in range(num_nonzero_M):
github cvxgrp / qcqp / examples / maxcut_OLD.py View on Github external
n = 25
np.random.seed(1)

# Make adjacency matrix.
p = 0.2
W = np.asmatrix(np.random.uniform(low=0.0, high=1.0, size=(n, n)))
for i in range(n):
    W[i, i] = 1
    for j in range(i+1, n):
        W[j, i] = W[i, j]
W = (W < p).astype(float)

x = cvx.Variable(n)
obj = 0.25*(cvx.sum_entries(W) - cvx.quad_form(x, W))
cons = [cvx.square(x) == 1]
prob = cvx.Problem(cvx.Maximize(obj), cons)

# Objective function
f = lambda x: 0.25*(np.sum(W) - (x_round.T*W*x_round)[0, 0])
def violation(x):
    return np.max(np.abs(np.square(x) - 1))

# SDP-based upper bound
ub = prob.solve(method='sdp-relax', solver=cvx.MOSEK)
print ('Upper bound: %.3f' % ub)

# Lower bounds
print ('(objective, maximum violation):')
f_dccp = prob.solve(method='qcqp-dccp', use_sdp=False, solver=cvx.MOSEK, num_samples=10, tau=1)
print ('  Convex-concave programming: (%.3f, %.3f)' % (f_dccp, violation(x.value)))
x_round = np.sign(np.random.randn(n, 1))
f_simple = f(x_round)