How to use the cvxpy.Problem 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 SCIP-Interfaces / PySCIPOpt / Poem / polynomial_opt.py View on Github external
lookup = {half_support[i] : i for i in range(len(half_support))}
			constraints = []
			for v,c in coeffs.items():
				if not any(v):
					#constant term gets special treatment
					constraints.append(C[0,0] == coeffs[v] + gamma)
					continue
				#list all (indices of) pairs in half_support, that add up to v
				l = []
				for u in half_support:
					diff = tuple(v[i] - u[i] for i in range(len(v)))
					if diff in half_support:
						l.append((lookup[u],lookup[diff]))
				constraints.append(cvx.Zero(cvx.sum([C[i,j] for i,j in l]) - cvx.expressions.constants.Constant(c)))
			#define the problem
			self.prob_sos_sparse = cvx.Problem(cvx.Minimize(gamma),constraints)
			self.prob_sos = self.prob_sos_sparse
		else:
			n = A.shape[0]
			d = self._degree // 2
			size = binomial(n + 2*d, n)

			#create complete list of monomials, all coefficients initialised with 0
			coeffs = [(list(aux._index_to_vector(i,n,2*d)),0) for i in range(size)]
			#setting the coefficients occurring in A
			for i in range(A.shape[1]):
				index = aux._vector_to_index(A[:,i], 2*d)
				coeffs[index] = (coeffs[index][0],coeffs[index][1] + self.b[i])
			#declare semidefinite matrix C, aim: Z^T * C * Z = p where Z is vector of all monomials
			C = cvx.Variable((binomial(n + d, n), binomial(n + d, n)), PSD = True)

			#construct the constraints
github jayanthkoushik / torch-gel / tests / test_gel.py View on Github external
device = A_j.device
    dtype = A_j.dtype
    r_j = r_j.cpu().numpy()
    A_j = A_j.cpu().numpy()

    # Create the b_j variable.
    b_j = cvx.Variable(A_j.shape[1])

    # Form the objective.
    q_j = r_j - A_j * b_j
    obj_fun = cvx.square(cvx.norm(q_j)) / (2.0 * m)
    obj_fun += a_1_j * cvx.norm(b_j) + (a_2_j / 2.0) * cvx.square(cvx.norm(b_j))

    # Build the optimization problem.
    obj = cvx.Minimize(obj_fun)
    problem = cvx.Problem(obj, constraints=None)

    problem.solve(solver="CVXOPT", verbose=False)
    b_j = np.asarray(b_j.value)
    return torch.from_numpy(b_j).to(device, dtype)
github cvxgrp / cvxpy / cvxpy / utilities / coeff_extractor.py View on Github external
def extract_quadratic_coeffs(self, affine_expr, quad_forms):
        """ Assumes quadratic forms all have variable arguments.
            Affine expressions can be anything.
        """
        assert affine_expr.is_dpp()
        # Extract affine data.
        affine_problem = cvxpy.Problem(Minimize(affine_expr), [])
        affine_inverse_data = InverseData(affine_problem)
        affine_id_map = affine_inverse_data.id_map
        affine_var_shapes = affine_inverse_data.var_shapes
        extractor = CoeffExtractor(affine_inverse_data)
        coeffs = extractor.affine(affine_problem.objective.expr)
        c = coeffs[:-1].A.flatten()
        b = coeffs[-1, 0]

        # Combine affine data with quadforms.
        coeffs = {}
        for var in affine_problem.variables():
            if var.id in quad_forms:
                var_id = var.id
                orig_id = quad_forms[var_id][2].args[0].id
                var_offset = affine_id_map[var_id][0]
                var_size = affine_id_map[var_id][1]
github ustunb / dcptree / dcptree / baselines.py View on Github external
obj += cp.sum_squares(w[1:]) * self.lam

            if self.loss_function == self.LOSS_LOGISTIC:
                obj += cp.sum(cp.logistic(cp.multiply(-y, X * w))) / float(n)

            elif self.loss_function == self.LOSS_SVM:
                obj += cp.sum(cp.maximum(0.0, 1.0 - cp.multiply(y, X * w))) / float(n)

        constraints = []
        if cons_type in self.VALID_PREFERED_CONSTRAINTS:
            constraints = self._stamp_preference_constraints(X, x_sensitive, w, cons_type, cons_params.get('s_val_to_cons_sum'))

        elif cons_type == self.CONSTRAINT_PARITY:
            constraints = self._stamp_disparate_impact_constraint(X, y, x_sensitive, w, cov_thresh = np.abs(0.0))

        prob = cp.Problem(cp.Minimize(obj), constraints)

        ### solve optimization problem
        if is_dccp(prob):
            print("solving disciplined convex-concave program (DCCP)")
        else:
            assert prob.is_dcp()
            print("solving disciplined convex program (DCP)")

        prob.solve(**solver_settings)

        print("solver stopped (status: %r)" % prob.status)
        if prob.status != cp.OPTIMAL:
            warnings.warn('solver did not recover optimal solution')

        # check that the fairness constraint is satisfied
        for f_c in constraints:
github cvxgrp / cvxpy / examples / geometry / convex_sets.py View on Github external
def contains(cvx_set, value):
    p = cvx.Problem(cvx.Minimize(0), [cvx_set == value])
    p.solve(solver=cvx.CVXOPT)
    return p.status == cvx.OPTIMAL
github hungpham2511 / toppra / examples / variable_stepsize_custom_constraints.py View on Github external
dsi = ss[i + 1] - ss[i]
    # Continuity constraints
    constraints.append(x_var[i] + 2 * dsi * u_var[i] == x_var[i + 1])

    # Path constraints
    constraints.append(u_var[i] * path_constraint.a[i]
                       + x_var[i] * path_constraint.b[i]
                       + path_constraint.c[i] <= 0)

    obj += 2 * dsi * cvx.power(cvx.sqrt(x_var[i]) + cvx.sqrt(x_var[i + 1]), -1)

constraints.append(x_var[0] == 0.2)
constraints.append(x_var[N] == 0)
obj = cvx.Minimize(obj)

prob = cvx.Problem(obj, constraints)
prob.solve()
xs_cvx = np.array(x_var.value).flatten()

cm = {
    'K': 'C0',
    'p1': 'C1', 'p2': 'C2', 'p3': 'C3',
    'MVC': 'C4'}

if PLOT_PROFILE:
    # Normal plot
    fig, axs = plt.subplots(1, 1)
    plots = []
    plot_MVC = axs.plot(ss, MVC, '--', lw=5, c=cm['MVC'])
    plot_Ks = axs.plot(ss, Ks, lw=5, c=cm['K'])
    plot_xs = axs.plot(ss, xs, lw=2.5, c=cm['p1'])
    plot_xs2 = axs.plot(ss, xs2, lw=2.5, c=cm['p3'])
github AtsushiSakai / PythonRobotics / PathPlanning / MixIntegerPathPlanning / mix_integer_path_planning.py View on Github external
# obstable avoidanse
        for io in range(nob):
            ind = io * 4
            constraints.append(sum(o[ind:ind + 4, t]) <= 3)
            constraints.append(s[0, t] <= ob[io, 0] + M * o[ind + 0, t])
            constraints.append(-s[0, t] <= -ob[io, 1] + M * o[ind + 1, t])
            constraints.append(s[1, t] <= ob[io, 2] + M * o[ind + 2, t])
            constraints.append(-s[1, t] <= -ob[io, 3] + M * o[ind + 3, t])

    for t in range(T - 1):
        constraints.append(s[:, t + 1] == A * s[:, t] + B * u[:, t])

    objective = cvxpy.Minimize(sum(obj))

    prob = cvxpy.Problem(objective, constraints)

    prob.solve(solver=cvxpy.GUROBI)

    s_p = s.value
    u_p = u.value
    print("status:" + prob.status)

    return s_p, u_p
github nipy / dipy / dipy / reconst / ivim_mix.py View on Github external
"""

        # Create four scalar optimization variables.
        fe = cvx.Variable(2)
        # Create four constraints.
        constraints = [cvx.sum(fe) == 1,
                       fe[0] >= 0.011,
                       fe[1] >= 0.011,
                       fe[0] <= 0.29,
                       fe[1] <= 0.89]

        # Form objective.
        obj = cvx.Minimize(cvx.sum(cvx.square(phi * fe - signal)))

        # Form and solve problem.
        prob = cvx.Problem(obj, constraints)
        prob.solve()  # Returns the optimal value.
        return np.array(fe.value)