How to use the cvxpy.Parameter 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 cvxgrp / cvxpylayers / cvxpylayers / tensorflow / test_cvxpylayer.py View on Github external
def test_too_many_variables(self):
        x = cp.Variable(1)
        y = cp.Variable(1)
        lam = cp.Parameter(1, nonneg=True)
        objective = lam * cp.norm(x, 1)
        prob = cp.Problem(cp.Minimize(objective))
        with self.assertRaisesRegex(ValueError, 'Argument `variables`.*'):
            CvxpyLayer(prob, [lam], [x, y])  # noqa: F841
github cvxgrp / cvxpy / cvxpy / performance_tests / test_warmstart.py View on Github external
def test_warmstart(self):
        """Testing warmstart LASSO with SCS.
        """
        import numpy

        # Problem data.
        n = 15
        m = 10
        numpy.random.seed(1)
        A = numpy.random.randn(n, m)
        b = numpy.random.randn(n)
        # gamma must be positive due to DCP rules.
        gamma = cp.Parameter(nonneg=True)

        # Construct the problem.
        x = cp.Variable(m)
        error = cp.sum_squares(A*x - b)
        obj = cp.Minimize(error + gamma*cp.norm(x, 1))
        prob = cp.Problem(obj)

        # Construct a trade-off curve of ||Ax-b||^2 vs. ||x||_1
        sq_penalty = []
        l1_penalty = []
        x_values = []
        gamma_vals = numpy.logspace(-4, 6, 10)

        start = time.time()
        for val in gamma_vals:
            gamma.value = val
github cvxgrp / cvxpylayers / cvxpylayers / tensorflow / test_cvxpylayer.py View on Github external
np.random.seed(243)
        N, n = 10, 2

        def sigmoid(z):
            return 1 / (1 + np.exp(-z))

        X_np = np.random.randn(N, n)
        a_true = np.random.randn(n, 1)
        y_np = np.round(sigmoid(X_np @ a_true + np.random.randn(N, 1) * 0.5))

        X_tf = tf.Variable(X_np)
        lam_tf = tf.Variable(1.0 * tf.ones(1))

        a = cp.Variable((n, 1))
        X = cp.Parameter((N, n))
        lam = cp.Parameter(1, nonneg=True)
        y = y_np

        log_likelihood = cp.sum(
            cp.multiply(y, X @ a) -
            cp.log_sum_exp(cp.hstack([np.zeros((N, 1)), X @ a]).T, axis=0,
                           keepdims=True).T
        )
        prob = cp.Problem(
            cp.Minimize(-log_likelihood + lam * cp.sum_squares(a)))
        fit_logreg = CvxpyLayer(prob, [X, lam], [a])

        with tf.GradientTape(persistent=True) as tape:
            weights = fit_logreg(X_tf, lam_tf, solver_args={'eps': 1e-8})[0]
            summed = tf.math.reduce_sum(weights)
        grad_X_tf, grad_lam_tf = tape.gradient(summed, [X_tf, lam_tf])
github oxfordcontrol / osqp_benchmarks / problem_classes / portfolio.py View on Github external
def _generate_cvxpy_problem(self):
        '''
        Generate QP problem
        '''

        x = cvxpy.Variable(self.n)
        y = cvxpy.Variable(self.k)

        # Create parameters m
        mu = cvxpy.Parameter(self.n)
        mu.value = self.mu

        objective = cvxpy.Minimize(cvxpy.quad_form(x, self.D) +
                                   cvxpy.quad_form(y, spa.eye(self.k)) +
                                   - 1 / self.gamma * (mu.T * x))
        constraints = [np.ones(self.n) * x == 1,
                       self.F.T * x == y,
                       0 <= x, x <= 1]
        problem = cvxpy.Problem(objective, constraints)

        return problem, mu
github cvxgrp / dmcp / examples / Markov.py View on Github external
__author__ = 'Xinyue'

import numpy as np
import cvxpy as cvx
import dmcp

n = 4
m = 3

theta = cvx.Variable(n)
theta.value = np.ones(n)/float(n)
a = cvx.Parameter(1)
x = cvx.Variable(m)
x.value = np.ones(m)/float(m)
P = cvx.Variable((m,m))
P.value = np.ones((m,m))
P0 = []
P0.append(np.matrix([[0.2,0.7,0.1],[0.3,0.3,0.4],[0.1,0.8,0.1]]))
P0.append(np.matrix([[0.25,0.35,0.4],[0.1,0.1,0.8],[0.45,0.05,0.5]]))
P0.append(np.matrix([[0.1,0.25,0.65],[0.2,0.1,0.7],[0.3,0.3,0.4]]))
P0.append(np.matrix([[0.23,0.67,0.1],[0.01,0.24,0.75],[0.2,0.45,0.35]]))

x0 = [0.25,0.3,0.45]
cost = cvx.norm(x-x0)
constr = [theta >= 0, cvx.sum(theta) == 1, x >= 0, cvx.sum(x) == 1, P*x == x]
right = 0
for i in range(n):
    right += theta[i]*np.transpose(P0[i])
github oxfordcontrol / osqp / interfaces / python / examples / scripts / portfolio / portfolio_example.py View on Github external
def gen_cvxpy_problem(self, qp):
        # Construct the problem
        #       minimize	x' D x + y' I y - (1/gamma) * mu' x
        #       subject to  1' x = 1
        #                   F' x = y
        #                   0 <= x <= 1

        # gamma parameter
        gamma = cvxpy.Parameter(sign="positive")

        n_var = qp.F.shape[0]
        m_var = qp.F.shape[1]
        x = cvxpy.Variable(n_var)
        y = cvxpy.Variable(m_var)

        objective = cvxpy.Minimize(cvxpy.quad_form(x, qp.D) +
                                   cvxpy.quad_form(y, spa.eye(m_var)) +
                                   - 1 / gamma * (qp.mu * x))
        constraints = [np.ones(n_var) * x == 1,
                       qp.F.T * x == y,
                       0 <= x, x <= 1]
        problem = cvxpy.Problem(objective, constraints)

        return problem, gamma, (x, y)
github cvxgrp / dmcp / dmcp / fix.py View on Github external
if var.value is not None:
                para.value = abs(var.value)
            else:
                para.value = np.zeros(var.shape)
            para.id = var.id
            param_list.append(para)
        elif var.sign == "NONPOSITIVE":
            para = cvx.Parameter(shape = var.shape, nonpos=True)
            if var.value is not None:
                para.value = -abs(var.value)
            else:
                para.value = np.zeros(var.shape)
            para.id = var.id
            param_list.append(para)
        elif var.attributes['PSD'] == True:
            para = cvx.Parameter(shape = var.shape, PSD=True)
            if var.value is not None:
                para.value = var.value
            else:
                para.value = np.zeros(var.shape)
            para.id = var.id
            param_list.append(para)
        else:
            para = cvx.Parameter(shape = var.shape)
            if var.value is not None:
                para.value = var.value
            else:
                para.value = np.zeros(var.shape)
            para.id = var.id
            param_list.append(para)
    
    param_list.sort(key = lambda x:x.id)
github oxfordcontrol / osqp / interfaces / python / examples / scripts / lasso / lasso_example.py View on Github external
def gen_cvxpy_problem(self, n, m, qp_matrices):

        lambda_i = cvxpy.Parameter(sign="positive")
        x = cvxpy.Variable(n)
        y = cvxpy.Variable(m)
        t = cvxpy.Variable(n)

        objective = cvxpy.Minimize(cvxpy.quad_form(y, spa.eye(m))
                                   + lambda_i * (np.ones(n) * t))
        constraints = [y == qp_matrices.A_lasso * x - qp_matrices.b_lasso,
                       -t <= x, x <= t]
        problem = cvxpy.Problem(objective, constraints)
        return problem, lambda_i, (x, y, t)
github mathildebadoual / energym / energym / envs / grid_scale / energy_market_env.py View on Github external
def build_opt_problem(self):
        # build parameters
        self._p_max = cvx.Parameter(self._num_agents)
        self._p_min = cvx.Parameter(self._num_agents)
        self._cost = cvx.Parameter(self._num_agents)
        self._demand = cvx.Parameter()

        # build variables
        self._p = cvx.Variable(self._num_agents)

        # build constraints
        constraint = [np.ones(self._num_agents).T * self._p == self._demand]
        for i in range(self._num_agents):
            constraint += [self._p[i] <= self._p_max[i]]
            constraint += [self._p_min[i] <= self._p[i]]

        # build the objective
        objective = cvx.Minimize(self._p.T * self._cost)

        # build objective
github cvxgrp / cvxpy / examples / communications / water_filling_BVex5.2.py View on Github external
def water_filling(n,a,sum_x=1):
  '''
Boyd and Vandenberghe, Convex Optimization, example 5.2 page 145
Water-filling.
  
This problem arises in information theory, in allocating power to a set of
n communication channels in order to maximise the total channel capacity.
The variable x_i represents the transmitter power allocated to the ith channel, 
and log(α_i+x_i) gives the capacity or maximum communication rate of the channel. 
The objective is to minimize  -∑log(α_i+x_i) subject to the constraint ∑x_i = 1 
  '''
  # Declare variables and parameters
  x = cvx.Variable(n)
  alpha = cvx.Parameter(n,nonneg=True)
  alpha.value = a
  #alpha.value = np.ones(n)
  # Choose objective function. Interpret as maximising the total communication rate of all the channels
  obj = cvx.Maximize(cvx.sum(cvx.log(alpha + x)))
  # Declare constraints
  constraints = [x >= 0, cvx.sum(x) - sum_x == 0]
  # Solve
  prob = cvx.Problem(obj, constraints)
  prob.solve()
  if(prob.status=='optimal'):
    return prob.status,prob.value,x.value
  else:
    return prob.status,np.nan,np.nan