How to use the cvxpy.quad_form 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 QuantConnect / Lean / Algorithm.Python / PythonPackageTestAlgorithm.py View on Github external
def cvxpy_test():
    numpy.random.seed(1)
    n = 10
    mu = numpy.abs(numpy.random.randn(n, 1))
    Sigma = numpy.random.randn(n, n)
    Sigma = Sigma.T.dot(Sigma)

    w = cvxpy.Variable(n)
    gamma = cvxpy.Parameter(sign='positive')
    ret = mu.T*w
    risk = cvxpy.quad_form(w, Sigma)
    print ("csvpy test >>> ", cvxpy.Problem(cvxpy.Maximize(ret - gamma*risk),
               [cvxpy.sum_entries(w) == 1,
                w >= 0]))
github sebp / scikit-survival / sksurv / svm / minlip.py View on Github external
def _fit_cvxpy(self, K, D, time):
        import cvxpy

        n_pairs = D.shape[0]

        a = cvxpy.Variable(shape=(n_pairs, 1))
        P = D.dot(D.dot(K).T).T
        q = D.dot(time)

        obj = cvxpy.Minimize(0.5 * cvxpy.quad_form(a, P) - a.T * q)
        assert obj.is_dcp()

        alpha = cvxpy.Parameter(nonneg=True, value=self.alpha)
        Dta = D.T.astype(P.dtype) * a  # cast constraints to correct type
        constraints = [a >= 0., -alpha <= Dta, Dta <= alpha]

        prob = cvxpy.Problem(obj, constraints)
        solver_opts = self._get_options_cvxpy()
        prob.solve(solver=cvxpy.settings.ECOS, **solver_opts)
        if prob.status != 'optimal':
            s = prob.solver_stats
            warnings.warn(('cvxpy solver {} did not converge after {} iterations: {}'.format(
                s.solver_name, s.num_iters, prob.status)),
                category=ConvergenceWarning,
                stacklevel=4)
github yangarbiter / adversarial-nonparametrics / nnattack / attacks / utils.py View on Github external
def solve_qp(Q, q, G, h, n, C=None, d=None, init_x=None, solver=cp.GUROBI):
    x = cp.Variable(shape=(n, 1))
    #obj = cp.Minimize(cp.sum(cp.square(x)) + q.T * x)
    obj = cp.Minimize((1/2)*cp.quad_form(x, Q) + q.T @ x)

    if C is not None and d is not None:
        constraints = [G*x <= h, C*x == d]
    else:
        constraints = [G*x <= h]
    prob = cp.Problem(obj, constraints)

    if init_x is not None:
        x.value = init_x

    try:
        prob.solve(solver=solver)
    except cp.error.SolverError:
        try:
            prob.solve(solver=solver)
        except cp.error.SolverError as e:
github dmalyuta / successive_rendezvous / rendezvous.py View on Github external
cost = cvx.Minimize(J+J_tr+J_vc)
    
    # constraints
    constraints = []
    constraints += [x[k+1]==A[k]*x[k]+B[k]*u[k]+r[k]+v[k] for k in range(N)]
    constraints += [xi[k+1]==xi[k]+sum(u[k]) for k in range(N)]
    constraints += [x[0]==state_init,x[-1]==state_final,xi[0]==0]
    constraints += [(x[k][:3]-data['lm']['p']).T*I_e>=
                    cvx.norm(x[k][:3]-data['lm']['p'])*
                    np.cos(np.deg2rad(data['gamma']))
                    for k in range(N+1)]
    constraints += [u[k]<=data['t_pulse_max'] for k in range(N)]
    constraints += [u[k]>=u_lb[k] for k in range(N)]
    constraints += [u[k][i] == 0. for k in range(N) for i in range(n_u)
                    if i in data['thrusters_off']]
    constraints += [cvx.quad_form(x_hat[k+1]-x_prev_hat[k+1],np.eye(n_x))
                    <=eta_hat[k] for k in range(N)]
    constraints += [stc_lb[k][i]*u[k][i]==0
                    for k in range(N) for i in range(n_u)]
    constraints += [stc_q[k]*u[k][i]==0 for k in range(N)
                    for i in range(n_u) if 'p_f' in csm.i2thruster[i]]
    constraints += [stc_q[k+1]*
                    (tools.rqpmat(data['xf']['q'])[0].dot(np.diag([1,-1,-1,-1]))
                     *x[k][6:10]-np.cos(0.5*np.deg2rad(data['ang_app'])))<=0
                    for k in range(N)]

    data['lrtop'] = cvx.Problem(cost,constraints)
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 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 arex18 / rocket-lander / control_and_ai / mpc.py View on Github external
:param target:
        :param time_horizon:
        :param verbose:
        :return:
        """
        assert len(initial_state) == self.state_len
        # Create variables
        x = opt.Variable(self.state_len, time_horizon + 1, name='states')
        u = opt.Variable(self.action_len, time_horizon, name='actions')

        # Loop through the entire time_horizon and append costs
        cost_function = []

        for t in range(time_horizon):
            # _cost = opt.norm(x[2, t + 1],2)*50 + opt.norm(x[3, t + 1],2)*50 + opt.quad_form(target[:, t + 1] - x[:, t + 1], Q) + opt.quad_form(u[:, t], R) + opt.quad_form(u[:, t]-u[:, t-1], R*0.1)
            _cost = opt.quad_form(target[:, t + 1] - x[:, t + 1], Q) + opt.quad_form(u[:, t], R) + opt.quad_form(
                u[:, t] - u[:, t - 1], R * 0.1)
            _constraints = [x[:, t + 1] == A * x[:, t] + B * u[:, t],
                            u[0, t] >= MAIN_ENGINE_POWER/1.8, u[0, t] <= MAIN_ENGINE_POWER / 1.05,
                            u[1, t] >= -SIDE_ENGINE_POWER, u[1, t] <= SIDE_ENGINE_POWER,
                            u[2, t] >= -self.angle_limit, u[2, t] <= self.angle_limit,
                            opt.norm(target[:, t + 1] - x[:, t + 1], 1) <= 0.01]

            cost_function.append(opt.Problem(opt.Minimize(_cost), constraints=_constraints))

        # Add final cost
        problem = sum(cost_function)
        problem.constraints += [opt.norm(target[:, time_horizon] - x[:, time_horizon], 1) <= 0.001,
                                x[:, 0] == initial_state]
        # Minimize Problem
        problem.solve(verbose=verbose, solver=opt.SCS)
        # u[0, :].value.A.flatten()
github oxfordcontrol / osqp_benchmarks / problem_classes / svm.py View on Github external
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)
github oxfordcontrol / osqp / interfaces / python / examples / scripts / mpc / mpc_example.py View on Github external
def gen_cvxpy_problem(self, qp):
        (nx, nu) = self.problem.B.shape
        N = qp.n

        # Initial state
        x0 = cvxpy.Parameter(nx)

        # Problem
        p = self.problem

        # variables
        x = cvxpy.Variable(nx, N + 1)
        u = cvxpy.Variable(nu, N)

        # Objective
        cost = .5 * cvxpy.quad_form((x[:, N] - p.xr), p.QN)  # Final stage cost
        for i in range(N):
            cost += .5 * cvxpy.quad_form((x[:, i] - p.xr), p.Q)  # State cost
            cost += .5 * cvxpy.quad_form(u[:, i], p.R)  # Inpout cost
        objective = cvxpy.Minimize(cost)

        # Constraints
        constr = []
        # Linear Dynamics
        constr += [x[:, 0] == x0]
        for i in range(0, N):
            constr += [x[:, i+1] == p.A * x[:, i] + p.B * u[:, i]]

        # Terminal constraints
        if p.tmin is not None:
            constr += [p.tmin <= p.T * x[:, N], p.T * x[:, N] <= p.tmax]
github AtsushiSakai / PyAdvancedControl / mpc_modeling / mpc_modeling.py View on Github external
costlist = 0.0
    constrlist = []

    for t in range(N):
        costlist += 0.5 * cvxpy.quad_form(x[:, t], Q)
        costlist += 0.5 * cvxpy.quad_form(u[:, t], R)

        constrlist += [x[:, t + 1] == A * x[:, t] + B * u[:, t]]

        if xmin is not None:
            constrlist += [x[:, t] >= xmin[:, 0]]
        if xmax is not None:
            constrlist += [x[:, t] <= xmax[:, 0]]

    costlist += 0.5 * cvxpy.quad_form(x[:, N], P)  # terminal cost
    if xmin is not None:
        constrlist += [x[:, N] >= xmin[:, 0]]
    if xmax is not None:
        constrlist += [x[:, N] <= xmax[:, 0]]

    if umax is not None:
        constrlist += [u <= umax]  # input constraints
    if umin is not None:
        constrlist += [u >= umin]  # input constraints

    constrlist += [x[:, 0] == x0[:, 0]]  # inital state constraints

    prob = cvxpy.Problem(cvxpy.Minimize(costlist), constrlist)

    prob.solve(verbose=True)