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


Python cvxpy.Minimize方法代码示例

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


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

示例1: sys_norm_h2_LMI

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [as 别名]
def sys_norm_h2_LMI(Acl, Bdisturbance, C):
    #doesn't work very well, if problem poorly scaled Riccati works better.
    #Dullerud p 210
    n = Acl.shape[0]
    X = cvxpy.Semidef(n)
    Y = cvxpy.Semidef(n)

    constraints = [ Acl*X + X*Acl.T + Bdisturbance*Bdisturbance.T == -Y,
                  ]

    obj = cvxpy.Minimize(cvxpy.trace(Y))

    prob = cvxpy.Problem(obj, constraints)
    
    prob.solve()
    eps = 1e-16
    if np.max(np.linalg.eigvals((-Acl*X - X*Acl.T - Bdisturbance*Bdisturbance.T).value)) > -eps:
        print('Acl*X + X*Acl.T +Bdisturbance*Bdisturbance.T is not neg def.')
        return np.Inf

    if np.min(np.linalg.eigvals(X.value)) < eps:
        print('X is not pos def.')
        return np.Inf

    return np.sqrt(np.trace(C*X.value*C.T)) 
开发者ID:markwmuller,项目名称:controlpy,代码行数:27,代码来源:test_analysis.py

示例2: get_objective

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [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_inpaint_func_tv

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [as 别名]
def get_inpaint_func_tv():
    def inpaint_func(image, mask):
        """Total variation inpainting"""
        inpainted = np.zeros_like(image)
        for c in range(image.shape[2]):
            image_c = image[:, :, c]
            mask_c = mask[:, :, c]
            if np.min(mask_c) > 0:
                # if mask is all ones, no need to inpaint
                inpainted[:, :, c] = image_c
            else:
                h, w = image_c.shape
                inpainted_c_var = cvxpy.Variable(h, w)
                obj = cvxpy.Minimize(cvxpy.tv(inpainted_c_var))
                constraints = [cvxpy.mul_elemwise(mask_c, inpainted_c_var) == cvxpy.mul_elemwise(mask_c, image_c)]
                prob = cvxpy.Problem(obj, constraints)
                # prob.solve(solver=cvxpy.SCS, max_iters=100, eps=1e-2)  # scs solver
                prob.solve()  # default solver
                inpainted[:, :, c] = inpainted_c_var.value
        return inpainted
    return inpaint_func 
开发者ID:AshishBora,项目名称:ambient-gan,代码行数:23,代码来源:measure_utils.py

示例4: ball_con

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

    n = 2

    A = cp.Parameter((n, n))
    z = cp.Parameter(n)
    p = cp.Parameter(n)
    x = cp.Variable(n)
    t = cp.Variable(n)
    obj = cp.Minimize(0.5 * cp.sum_squares(x - p))
    # TODO automate introduction of variables.
    cons = [0.5 * cp.sum_squares(A * t) <= 1, t == (x - z)]
    prob = cp.Problem(obj, cons)

    L = npr.randn(n, n)
    A.value = L.T
    z.value = npr.randn(n)
    p.value = npr.randn(n)

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

示例5: relu

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

    n = 4
    _x = cp.Parameter(n)
    _y = cp.Variable(n)
    obj = cp.Minimize(cp.sum_squares(_y - _x))
    cons = [_y >= 0]
    prob = cp.Problem(obj, cons)

    _x.value = npr.randn(n)

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

示例6: running_example

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [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

示例7: test_lml

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [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

示例8: test_example

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [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

示例9: fit

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [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: _mk_monotonic_average

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [as 别名]
def _mk_monotonic_average(xs, ys, intervals, method="increasing", **kwargs):
    """
    Creates smoothed averages of `ys` at the intervals given by `intervals`.
    :param xs: all the datapoints of a feature (represents the x-axis)
    :param ys: all the datapoints what we'd like to predict (represents the y-axis)
    :param intervals: the intervals at which we'd like to get a good average value
    :param method: the method that is used for smoothing, can be either `increasing` or `decreasing`.
    :return:
        An array as long as `intervals` that represents the average `y`-values at those intervals,
        keeping the constraint in mind.
    """
    x_internal = np.array([xs >= i for i in intervals]).T.astype(np.float)
    betas = cp.Variable(x_internal.shape[1])
    objective = cp.Minimize(cp.sum_squares(x_internal * betas - ys))
    if method == "increasing":
        constraints = [betas[i + 1] >= 0 for i in range(betas.shape[0] - 1)]
    elif method == "decreasing":
        constraints = [betas[i + 1] <= 0 for i in range(betas.shape[0] - 1)]
    else:
        raise ValueError(
            f"method must be either `increasing` or `decreasing`, got: {method}"
        )
    prob = cp.Problem(objective, constraints)
    prob.solve()
    return betas.value.cumsum() 
开发者ID:koaning,项目名称:scikit-lego,代码行数:27,代码来源:intervalencoder.py

示例11: _generate_cvxpy_problem

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

        x = cvxpy.Variable(self.n)
        y = cvxpy.Variable(self.m)
        t = cvxpy.Variable(self.n)

        # Create parameeter and assign value
        lambda_cvxpy = cvxpy.Parameter()
        lambda_cvxpy.value = self.lambda_param

        objective = cvxpy.Minimize(cvxpy.quad_form(y, spa.eye(self.m))
                                   + self.lambda_param * (np.ones(self.n) * t))
        constraints = [y == self.Ad * x - self.bd,
                       -t <= x, x <= t]
        problem = cvxpy.Problem(objective, constraints)

        return problem, (x, y, t), lambda_cvxpy 
开发者ID:oxfordcontrol,项目名称:osqp_benchmarks,代码行数:22,代码来源:suitesparse_lasso.py

示例12: _generate_cvxpy_problem

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

        n = self.n
        m = self.m
        x = cvxpy.Variable(n)
        t = cvxpy.Variable(m)

        objective = cvxpy.Minimize(.5 * cvxpy.quad_form(x, spa.eye(n))
                                   + .5 * self.gamma * np.ones(m) * t)
        constraints = [t >= spa.diags(self.b_svm).dot(self.A_svm) * x + 1,
                       t >= 0]

        problem = cvxpy.Problem(objective, constraints)

        return problem, (x, t) 
开发者ID:oxfordcontrol,项目名称:osqp_benchmarks,代码行数:20,代码来源:svm.py

示例13: _generate_cvxpy_problem

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [as 别名]
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 
开发者ID:oxfordcontrol,项目名称:osqp_benchmarks,代码行数:23,代码来源:portfolio.py

示例14: _generate_cvxpy_problem

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [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

示例15: _check_for_sdp_solver

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Minimize [as 别名]
def _check_for_sdp_solver(cls):
        """Check if CVXPY solver is available"""
        if cls._HAS_SDP_SOLVER is None:
            if _HAS_CVX:
                # pylint:disable=import-error
                import cvxpy
                solvers = cvxpy.installed_solvers()
                if 'CVXOPT' in solvers:
                    cls._HAS_SDP_SOLVER = True
                    return
                if 'SCS' in solvers:
                    # Try example problem to see if built with BLAS
                    # SCS solver cannot solver larger than 2x2 matrix
                    # problems without BLAS
                    try:
                        var = cvxpy.Variable((4, 4), PSD=True)
                        obj = cvxpy.Minimize(cvxpy.norm(var))
                        cvxpy.Problem(obj).solve(solver='SCS')
                        cls._HAS_SDP_SOLVER = True
                        return
                    except cvxpy.error.SolverError:
                        pass
            cls._HAS_SDP_SOLVER = False 
开发者ID:Qiskit,项目名称:qiskit-ignis,代码行数:25,代码来源:base_fitter.py


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