当前位置: 首页>>代码示例>>Python>>正文


Python cvxpy.sum方法代码示例

本文整理汇总了Python中cvxpy.sum方法的典型用法代码示例。如果您正苦于以下问题:Python cvxpy.sum方法的具体用法?Python cvxpy.sum怎么用?Python cvxpy.sum使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cvxpy的用法示例。


在下文中一共展示了cvxpy.sum方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_boolean

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def test_boolean(self):
        x = Variable((5, 4))
        y = Boolean(5, 4)
        p = Problem(Minimize(sum(1-x) + sum(x)), [x == y])
        result = p.solve(method="NC-ADMM", solver=CVXOPT)
        self.assertAlmostEqual(result[0], 20)
        for i in range(x.shape[0]):
            for j in range(x.shape[1]):
                v = x.value[i, j]
                self.assertAlmostEqual(v*(1-v), 0)

        x = Variable()
        p = Problem(Minimize(sum(1-x) + sum(x)), [x == Boolean(5,4)[0,0]])
        result = p.solve(method="NC-ADMM", solver=CVXOPT)
        self.assertAlmostEqual(result[0], 1)
        self.assertAlmostEqual(x.value*(1-x.value), 0)

    # Test choose variable. 
开发者ID:cvxgrp,项目名称:ncvx,代码行数:20,代码来源:test_vars.py

示例2: get_objective

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def get_objective(self, X_v, U_v, X_last_p, U_last_p):
        """
        Get model specific objective to be minimized.

        :param X_v: cvx variable for current states
        :param U_v: cvx variable for current inputs
        :param X_last_p: cvx parameter for last states
        :param U_last_p: cvx parameter for last inputs
        :return: A cvx objective function.
        """

        slack = 0
        for j in range(len(self.obstacles)):
            slack += cvx.sum(self.s_prime[j])

        objective = cvx.Minimize(1e5 * slack)
        # objective += cvx.Minimize(cvx.sum(cvx.square(U_v)))
        return objective 
开发者ID:EmbersArc,项目名称:SCvx,代码行数:20,代码来源:diffdrive_2d.py

示例3: get_sudoku_matrix

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def get_sudoku_matrix(n):
    X = np.array([[cp.Variable(n**2) for i in range(n**2)] for j in range(n**2)])
    cons = ([x >= 0 for row in X for x in row] +
            [cp.sum(x) == 1 for row in X for x in row] +
            [sum(row) == np.ones(n**2) for row in X] +
            [sum([row[i] for row in X]) == np.ones(n**2) for i in range(n**2)] +
            [sum([sum(row[i:i+n]) for row in X[j:j+n]]) == np.ones(n**2) for i in range(0,n**2,n) for j in range(0, n**2, n)])
    f = sum([cp.sum(x) for row in X for x in row])
    prob = cp.Problem(cp.Minimize(f), cons)

    A = np.asarray(prob.get_problem_data(cp.ECOS)[0]["A"].todense())
    A0 = [A[0]]
    rank = 1
    for i in range(1,A.shape[0]):
        if np.linalg.matrix_rank(A0+[A[i]], tol=1e-12) > rank:
            A0.append(A[i])
            rank += 1

    return np.array(A0) 
开发者ID:locuslab,项目名称:optnet,代码行数:21,代码来源:models.py

示例4: softmax

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def softmax():
    # print(f'--- {sys._getframe().f_code.co_name} ---')
    print('softmax')
    npr.seed(0)

    d = 4
    _x = cp.Parameter((d, 1))
    _y = cp.Variable(d)
    obj = cp.Minimize(-_x.T * _y - cp.sum(cp.entr(_y)))
    cons = [sum(_y) == 1.]
    prob = cp.Problem(obj, cons)

    _x.value = npr.randn(d, 1)

    prob.solve(solver=cp.SCS)
    print(_y.value) 
开发者ID:cvxgrp,项目名称:cvxpylayers,代码行数:18,代码来源:cvxpy_examples.py

示例5: running_example

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def running_example():
    print("running example")
    m = 20
    n = 10
    x = cp.Variable((n, 1))
    F = cp.Parameter((m, n))
    g = cp.Parameter((m, 1))
    lambd = cp.Parameter((1, 1), nonneg=True)
    objective_fn = cp.norm(F @ x - g) + lambd * cp.norm(x)
    constraints = [x >= 0]
    problem = cp.Problem(cp.Minimize(objective_fn), constraints)
    assert problem.is_dcp()
    assert problem.is_dpp()
    print("is_dpp: ", problem.is_dpp())

    F_t = torch.randn(m, n, requires_grad=True)
    g_t = torch.randn(m, 1, requires_grad=True)
    lambd_t = torch.rand(1, 1, requires_grad=True)
    layer = CvxpyLayer(problem, parameters=[F, g, lambd], variables=[x])
    x_star, = layer(F_t, g_t, lambd_t)
    x_star.sum().backward()
    print("F_t grad: ", F_t.grad)
    print("g_t grad: ", g_t.grad) 
开发者ID:cvxgrp,项目名称:cvxpylayers,代码行数:25,代码来源:cvxpy_examples.py

示例6: test_lml

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def test_lml(self):
        tf.random.set_seed(0)
        k = 2
        x = cp.Parameter(4)
        y = cp.Variable(4)
        obj = -x * y - cp.sum(cp.entr(y)) - cp.sum(cp.entr(1. - y))
        cons = [cp.sum(y) == k]
        problem = cp.Problem(cp.Minimize(obj), cons)
        lml = CvxpyLayer(problem, [x], [y])
        x_tf = tf.Variable([1., -1., -1., -1.], dtype=tf.float64)

        with tf.GradientTape() as tape:
            y_opt = lml(x_tf, solver_args={'eps': 1e-10})[0]
            loss = -tf.math.log(y_opt[1])

        def f():
            problem.solve(solver=cp.SCS, eps=1e-10)
            return -np.log(y.value[1])

        grad = tape.gradient(loss, [x_tf])
        numgrad = numerical_grad(f, [x], [x_tf])
        np.testing.assert_almost_equal(grad, numgrad, decimal=3) 
开发者ID:cvxgrp,项目名称:cvxpylayers,代码行数:24,代码来源:test_cvxpylayer.py

示例7: test_example

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def test_example(self):
        n, m = 2, 3
        x = cp.Variable(n)
        A = cp.Parameter((m, n))
        b = cp.Parameter(m)
        constraints = [x >= 0]
        objective = cp.Minimize(0.5 * cp.pnorm(A @ x - b, p=1))
        problem = cp.Problem(objective, constraints)
        assert problem.is_dpp()

        cvxpylayer = CvxpyLayer(problem, parameters=[A, b], variables=[x])
        A_tch = torch.randn(m, n, requires_grad=True)
        b_tch = torch.randn(m, requires_grad=True)

        # solve the problem
        solution, = cvxpylayer(A_tch, b_tch)

        # compute the gradient of the sum of the solution with respect to A, b
        solution.sum().backward() 
开发者ID:cvxgrp,项目名称:cvxpylayers,代码行数:21,代码来源:test_cvxpylayer.py

示例8: __init__

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def __init__(self, m, k, n, complex=False):
        if not cvx_available:
            raise RuntimeError('Cannot initialize when cvxpy is not available.')
        # Initialize parameters and variables
        A = cvx.Parameter((m, k), complex=complex)
        B = cvx.Parameter((m, n), complex=complex)
        l = cvx.Parameter(nonneg=True)
        X = cvx.Variable((k, n), complex=complex)
        # Create the problem
        # CVXPY issue:
        #   cvx.norm does not work if axis is not 0.
        # Workaround:
        #   use cvx.norm(X.T, 2, axis=0) instead of cvx.norm(X, 2, axis=1)
        obj_func = 0.5 * cvx.norm(cvx.matmul(A, X) - B, 'fro')**2 + \
                   l * cvx.sum(cvx.norm(X.T, 2, axis=0))
        self._problem = cvx.Problem(cvx.Minimize(obj_func))
        self._A = A
        self._B = B
        self._l = l
        self._X = X 
开发者ID:morriswmz,项目名称:doatools.py,代码行数:22,代码来源:l1lsq.py

示例9: fit

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def fit(self, X, y):
        """
        Fit the model using X, y as training data.

        :param X: array-like, shape=(n_columns, n_samples, ) training data.
        :param y: array-like, shape=(n_samples, ) training data.
        :return: Returns an instance of self.
        """
        X, y = check_X_y(X, y, estimator=self, dtype=FLOAT_DTYPES)

        # Construct the problem.
        betas = cp.Variable(X.shape[1])
        objective = cp.Minimize(cp.sum_squares(X * betas - y))
        constraints = [sum(betas) == 1]
        if self.non_negative:
            constraints.append(0 <= betas)

        # Solve the problem.
        prob = cp.Problem(objective, constraints)
        prob.solve()
        self.coefs_ = betas.value
        return self 
开发者ID:koaning,项目名称:scikit-lego,代码行数:24,代码来源:linear_model.py

示例10: _generate_cvxpy_problem

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def _generate_cvxpy_problem(self):
        '''
        Generate QP problem
        '''

        # Construct the problem
        #       minimize    1/2 z.T * z + np.ones(m).T * (r + s)
        #       subject to  Ax - b - z = r - s
        #                   r >= 0
        #                   s >= 0
        # The problem reformulation follows from Eq. (24) of the following paper:
        # https://doi.org/10.1109/34.877518
        x = cvxpy.Variable(self.n)
        z = cvxpy.Variable(self.m)
        r = cvxpy.Variable(self.m)
        s = cvxpy.Variable(self.m)

        objective = cvxpy.Minimize(.5 * cvxpy.sum_squares(z) + cvxpy.sum(r + s))
        constraints = [self.Ad@x - self.bd - z == r - s,
                       r >= 0, s >= 0]
        problem = cvxpy.Problem(objective, constraints)

        return problem, (x, z, r, s) 
开发者ID:oxfordcontrol,项目名称:osqp_benchmarks,代码行数:25,代码来源:suitesparse_huber.py

示例11: _generate_cvxpy_problem

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def _generate_cvxpy_problem(self):
        '''
        Generate QP problem
        '''
        # Construct the problem
        #       minimize    1/2 z.T * z + np.ones(m).T * (r + s)
        #       subject to  Ax - b - z = r - s
        #                   r >= 0
        #                   s >= 0
        # The problem reformulation follows from Eq. (24) of the following paper:
        # https://doi.org/10.1109/34.877518
        x = cvxpy.Variable(self.n)
        z = cvxpy.Variable(self.m)
        r = cvxpy.Variable(self.m)
        s = cvxpy.Variable(self.m)

        objective = cvxpy.Minimize(.5 * cvxpy.sum_squares(z) + cvxpy.sum(r + s))
        constraints = [self.Ad@x - self.bd - z == r - s,
                       r >= 0, s >= 0]
        problem = cvxpy.Problem(objective, constraints)

        return problem, (x, z, r, s) 
开发者ID:oxfordcontrol,项目名称:osqp_benchmarks,代码行数:24,代码来源:huber.py

示例12: price

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def price(self):
        """Price associated with this net."""
        return self.constraints[0].dual_value
        #print([c.dual_value for c in self.constraints])
        # raise
        # if (len(self.constraints) == 1 and
        #        np.size(self.constraints[0].dual_value)) == 1:
        #    return self.constraints[0].dual_value
        # TODO(enzo) hardcoded 1/K probability
        # return np.sum(constr.dual_value
        # for constr in self.constraints)
        # if self.num_scenarios > 1:
        #    return np.matrix(np.sum([constr.dual_value[0]
        #                             for constr in self.constraints], 0))
        # return np.hstack(constr.dual_value.reshape(-1, 1)
        #                 for constr in self.constraints) 
开发者ID:cvxgrp,项目名称:cvxpower,代码行数:18,代码来源:network.py

示例13: __init__

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def __init__(self, g: DFGraph, budget: int):
        self.budget = budget
        self.g = g
        self.T = self.g.size

        self.R = cp.Variable((self.T, self.T), name="R")
        self.S = cp.Variable((self.T, self.T), name="S")
        self.Free_E = cp.Variable((self.T, len(self.g.edge_list)), name="FREE_E")
        self.U = cp.Variable((self.T, self.T), name="U")

        cpu_cost_vec = np.asarray([self.g.cost_cpu[i] for i in range(self.T)])[np.newaxis, :].T
        assert cpu_cost_vec.shape == (self.T, 1)
        objective = cp.Minimize(cp.sum(self.R @ cpu_cost_vec))
        constraints = self.make_constraints(budget)
        self.problem = cp.Problem(objective, constraints)
        self.num_vars = self.problem.size_metrics.num_scalar_variables
        self.num_constraints = self.problem.size_metrics.num_scalar_eq_constr + self.problem.size_metrics.num_scalar_leq_constr 
开发者ID:parasj,项目名称:checkmate,代码行数:19,代码来源:cvxpy_solver.py

示例14: __init__

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def __init__(self, rows, cols, col_sum, *args, **kwargs):
        assert rows >= cols
        assert rows == sum(col_sum)
        super(GroupAssign, self).__init__(rows=rows, cols=cols, *args, **kwargs)
        self.col_sum = col_sum 
开发者ID:cvxgrp,项目名称:ncvx,代码行数:7,代码来源:group_assign.py

示例15: init_z

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum [as 别名]
def init_z(self, random):
        if random:
            result = np.zeros(self.shape)
            num_entries = self.shape[0]*self.shape[1]
            weights = np.random.uniform(size=num_entries)
            weights /= weights.sum()
            for k in range(num_entries):
                assignment = np.random.permutation(self.shape[0])
                for j in range(self.shape[1]):
                    result[assignment[j], j] += weights[k]
            self.z.value = result
        else:
            self.z.value = np.ones(self.shape)/self.shape[1]

    # Compute projection with maximal weighted matching. 
开发者ID:cvxgrp,项目名称:ncvx,代码行数:17,代码来源:group_assign.py


注:本文中的cvxpy.sum方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。