How to use the cvxpy.sum 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
coeffs[tuple(self.A[1:,i])] += self.b[i]
			#create lookup table: vector -> index
			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)
github cvxgrp / cvxportfolio / cvxportfolio / policies.py View on Github external
t : pd.timestamp
            Timestamp for the optimization.
        """

        if t is None:
            t = dt.datetime.today()

        value = sum(portfolio)
        w = portfolio / value
        z = cvx.Variable(w.size)  # TODO pass index
        wplus = w.values + z

        if isinstance(self.return_forecast, BaseReturnsModel):
            alpha_term = self.return_forecast.weight_expr(t, wplus)
        else:
            alpha_term = cvx.sum(cvx.multiply(
                values_in_time(self.return_forecast, t).values,
                wplus))

        assert(alpha_term.is_concave())

        costs, constraints = [], []

        for cost in self.costs:
            cost_expr, const_expr = cost.weight_expr(t, wplus, z, value)
            costs.append(cost_expr)
            constraints += const_expr

        constraints += [item for item in (con.weight_expr(t, wplus, z, value)
                                          for con in self.constraints)]

        for el in costs:
github SCIP-Interfaces / PySCIPOpt / Poem / polynomial_opt.py View on Github external
t0 = datetime.now()
		#define short notation
		A = self.A[1:,:]
		n,t = A.shape

		b_relax = self.b.copy()
		b_relax[self.monomial_squares] = abs(self.b[self.monomial_squares])
		b_relax[self.non_squares] = -abs(self.b[self.non_squares])

		X = cvx.Variable(shape = (t,t), name = 'X', nonneg = True)
		#lamb[k,i]: barycentric coordinate, using A[:,i] to represent A[:,k]
		lamb = cvx.Variable(shape = (t,t), name = 'lambda', nonneg = True)
		#we use both variables only for k >= monomial_squares

		constraints = []
		constraints += [b_relax[i] == -2*X[i,i] + cvx.sum(X[:,i]) for i in self.non_squares]
		constraints += [b_relax[i] == cvx.sum(X[:,i]) for i in self.monomial_squares[1:]]
		constraints += [2*lamb[k,k] == cvx.sum(lamb[k,:]) for k in self.non_squares]
		constraints += [cvx.sum([A[:,i] * lamb[k,i] for i in range(t) if i != k]) == A[:,k]*lamb[k,k] for k in self.non_squares]
		constraints += [cvx.sum(cvx.kl_div(lamb[k,:], X[k,:])[[i for i in range(t) if i != k]]) <= -2*X[k,k] + cvx.sum(X[k,:]) for k in self.non_squares]

		objective = cvx.Minimize(cvx.sum(X[:,0]))
		self.prob_sage = cvx.Problem(objective, constraints)

		self.sage_problem_creation_time = aux.dt2sec(datetime.now() - t0)
github cvxgrp / cvxpy / examples / communications / optimal_power_Gaussian_channel_BV4.62.py View on Github external
print('alpha and beta vectors must have same length!')
    return 'failed',np.nan,np.nan,np.nan
  P=cvx.Variable(n)
  W=cvx.Variable(n)
  alpha=cvx.Parameter(n)
  beta =cvx.Parameter(n)
  alpha.value=np.array(a_val)
  beta.value =np.array(b_val)
  # This function will be used as the objective so must be DCP; i.e. element-wise multiplication must occur inside kl_div, not outside otherwise the solver does not know if it is DCP...
  R=cvx.kl_div(cvx.multiply(alpha, W),
               cvx.multiply(alpha, W + cvx.multiply(beta, P))) - \
    cvx.multiply(alpha, cvx.multiply(beta, P))
  objective=cvx.Minimize(cvx.sum(R))
  constraints=[P>=0.0,
               W>=0.0,
               cvx.sum(P)-P_tot==0.0,
               cvx.sum(W)-W_tot==0.0]
  prob=cvx.Problem(objective, constraints)
  prob.solve()
  return prob.status,-prob.value,P.value,W.value
github locuslab / lml / lml.py View on Github external
import sys
    from IPython.core import ultratb
    sys.excepthook = ultratb.FormattedTB(mode='Verbose',
        color_scheme='Linux', call_pdb=1)

    m = 10
    n = 2

    npr.seed(0)
    x = npr.random(m)

    import cvxpy as cp
    import numdifftools as nd

    y = cp.Variable(m)
    obj = cp.Minimize(-x*y - cp.sum(cp.entr(y)) - cp.sum(cp.entr(1.-y)))
    cons = [0 <= y, y <= 1, cp.sum(y) == n]
    prob = cp.Problem(obj, cons)
    prob.solve(cp.SCS, verbose=True)
    assert 'optimal' in prob.status
    y_cp = y.value

    x = Variable(torch.from_numpy(x), requires_grad=True)
    x = torch.stack([x,x])
    y = LML(N=n)(x)

    np.testing.assert_almost_equal(y[0].data.numpy(), y_cp, decimal=3)

    dy0, = grad(y[0,0], x)
    dy0 = dy0.squeeze()

    def f(x):
github cvxgrp / cvxportfolio / cvxportfolio / policies.py View on Github external
cost_expr, const_expr = cost.weight_expr(t, wplus, z, value)
            costs.append(cost_expr)
            constraints += const_expr

        constraints += [item for item in (con.weight_expr(t, wplus, z, value)
                                          for con in self.constraints)]

        for el in costs:
            assert (el.is_convex())

        for el in constraints:
            assert (el.is_dcp())

        self.prob = cvx.Problem(
            cvx.Maximize(alpha_term - sum(costs)),
            [cvx.sum(z) == 0] + constraints)
        try:
            self.prob.solve(solver=self.solver, **self.solver_opts)

            if self.prob.status == 'unbounded':
                logging.error(
                    'The problem is unbounded. Defaulting to no trades')
                return self._nulltrade(portfolio)

            if self.prob.status == 'infeasible':
                logging.error(
                    'The problem is infeasible. Defaulting to no trades')
                return self._nulltrade(portfolio)

            return pd.Series(index=portfolio.index, data=(z.value * value))
        except cvx.SolverError:
            logging.error(
github cvxgrp / cvxpy / examples / communications / water_filling_BVex5.2.py View on Github external
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
github SCIP-Interfaces / PySCIPOpt / Poem / polynomial_opt.py View on Github external
t0 = datetime.now()

		#default: evenly distribute the non-squares
		self._set_coefficient_distribution(B)
		b = np.array(self.b, dtype = np.float)

		X = cvx.Variable((len(self.cover), self.A.shape[1]))

		constraints = []
		for i in self.monomial_squares[1:]:
			indices = [k for k in range(len(self.cover)) if i in self.cover[k]]
			if indices != []:
				constraints.append(cvx.log_sum_exp(X[indices, i]) <= np.log(abs(b[i])))
		for k in range(len(self.cover)):
			lamb = self.lamb[k,self.cover[k][:-1]]
			constraints.append(np.log(abs(self.coefficient_distribution[k, self.cover[k][-1]])) == cvx.sum(cvx.multiply(lamb, X[k, self.cover[k][:-1]]) - (lamb * np.log(lamb))))

		if any([0 in c for c in self.cover]):
			objective = cvx.Minimize(cvx.log_sum_exp(X[[k for k in range(len(self.cover)) if 0 in self.cover[k]],0]))
		else:
			objective = cvx.Minimize(0)
		self.prob_sonc = cvx.Problem(objective, constraints)

		self.sonc_problem_creation_time = aux.dt2sec(datetime.now() - t0) + self.cover_time