How to use the cvxpy.Minimize 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 / cvxpy / cvxpy / performance_tests / test_warmstart.py View on Github external
"""
        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
            prob.solve(solver=cp.SCS, warm_start=True, use_indirect=True)
            # Use expr.value to get the numerical value of
            # an expression in the problem.
            sq_penalty.append(error.value)
            l1_penalty.append(cp.norm(x, 1).value)
github hungpham2511 / toppra / toppra / solverwrapper / cvxpy_solverwrapper.py View on Github external
+ cvxpy.norm(P[i, j].T[:, :2] * ux + P[i, j].T[:, 2])
                            <= 0
                        )

                if ubound is not None:
                    cvxpy_constraints.append(max(-CVXPY_MAXU, ubound[i, 0]) <= u)
                    cvxpy_constraints.append(u <= min(CVXPY_MAXU, ubound[i, 1]))

                if xbound is not None:
                    cvxpy_constraints.append(xbound[i, 0] <= x)
                    cvxpy_constraints.append(x <= min(CVXPY_MAXX, xbound[i, 1]))

        if H is None:
            H = np.zeros((self.get_no_vars(), self.get_no_vars()))

        objective = cvxpy.Minimize(0.5 * cvxpy.quad_form(ux, H) + g * ux)
        problem = cvxpy.Problem(objective, constraints=cvxpy_constraints)
        try:
            problem.solve(verbose=False)
        except cvxpy.SolverError:
            # solve fail
            pass
        if (
            problem.status == cvxpy.OPTIMAL
            or problem.status == cvxpy.OPTIMAL_INACCURATE
        ):
            return np.array(ux.value).flatten()
        else:
            res = np.empty(self.get_no_vars())
            res[:] = np.nan
            return res
github oxfordcontrol / osqp_benchmarks / problem_classes / huber.py View on Github external
'''
        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)
github DeniseCaiLab / minian / minian / cnmf.py View on Github external
cons.append(s >= 0)  # spike train non-negativity
    # noise constraints
    cons_noise = [noise[i] <= thres_sn[i] for i in range(thres_sn.shape[0])]
    try:
        obj = cvx.Minimize(cvx.sum(cvx.norm(s, 1, axis=1)))
        prob = cvx.Problem(obj, cons + cons_noise)
        if use_cons:
            _ = prob.solve(solver='ECOS')
        if not (prob.status == 'optimal'
                or prob.status == 'optimal_inaccurate'):
            if use_cons:
                warnings.warn("constrained version of problem infeasible")
            raise ValueError
    except (ValueError, cvx.SolverError):
        lam = sn * sparse_penal / sn.shape[0] # hacky correction for near-linear relationship between sparsity and number of concurrently updated units
        obj = cvx.Minimize(cvx.sum(cvx.sum(noise, axis=1) + lam * cvx.norm(s, 1, axis=1)))
        prob = cvx.Problem(obj, cons)
        try:
            _ = prob.solve(solver='ECOS', max_iters=max_iters)
            if prob.status in ["infeasible", "unbounded", None]:
                raise ValueError
        except (cvx.SolverError, ValueError):
            try:
                if scs:
                    _ = prob.solve(solver='SCS', max_iters=200)
                if prob.status in ["infeasible", "unbounded", None]:
                    raise ValueError
            except (cvx.SolverError, ValueError):
                warnings.warn(
                    "problem status is {}, returning null".format(prob.status),
                    RuntimeWarning)
                return np.full((5, c.shape[0], c.shape[1]), np.nan).squeeze()
github microsoft / AirSim-NeurIPS2019-Drone-Racing / baselines / gtp.py View on Github external
leader_term = np.dot(p_rel, t[k, :]);
                gamma = 0.0
                if (leader_term > 0):
                    gamma = 1.0/(leader_term * leader_term)/(k + 1);
                else:
                    gamma = 0.0
                # add blocking cost function
                blocking_obj += gamma  * blocking_objective_exp**k * cp.quad_form(p[k, :] - p_opp, np.outer(n[k, :], n[k, :]))
        
        # === "Win the Race" Objective ===
        # Take the tangent t at the last trajectory point
        # This serves as an approximation to the total track progress
        obj = -t[-1, :].T @ p[-1, :]

        # create the problem in cxvpy and solve it
        prob = cp.Problem(cp.Minimize(obj + self.nc_weight * nc_obj + self.blocking_weight * blocking_obj), dyn_constraints + track_constraints + nc_constraints)

        # try to solve proposed problem
        trajectory_result = np.array((self.n_steps, 3))
        try:
            prob.solve()
            # relax track constraints if problem is infeasible
            if np.isinf(prob.value):    
                print("WARN: relaxing track constraints")
                # If the problem is not feasible, relax track constraints
                # Assert it is indeed an infeasible problem and not unbounded (in which case value is -inf).
                # (The dynamical constraints keep the problem bounded.)
                assert prob.value >= 0.0

                # Solve relaxed problem (track constraint -> track objective)
                relaxed_prob = cp.Problem(cp.Minimize(obj + self.nc_weight * nc_obj + self.track_relax_weight * track_obj),
                                        dyn_constraints + nc_constraints)
github AtsushiSakai / PyAdvancedControl / mpc_modeling / use_modeling_tool.py View on Github external
# mpc calculation
    x = cvxpy.Variable(nx, N + 1)
    u = cvxpy.Variable(nu, N)

    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]]

    costlist += 0.5 * cvxpy.quad_form(x[:, N], P)  # terminal cost

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

    prob.constraints += [x[:, 0] == x0]  # inital state constraints
    #  prob.constraints += [cvxpy.abs(u) <= umax]  # input constraints

    prob.solve(verbose=True)

    rx1 = np.array(x.value[0, :]).flatten()
    rx2 = np.array(x.value[1, :]).flatten()
    ru = np.array(u.value[0, :]).flatten()

    flg, ax = plt.subplots(1)
    plt.plot(rx1, label="x1")
    plt.plot(rx2, label="x2")
    plt.plot(ru, label="u")
    plt.legend()
    plt.grid(True)
github wudingcheng / TSAnalyzer / TSAnalyzer / algorithms / l1extensive.py View on Github external
w_term = cvx.norm(dw, 1)
    errs = y - x - w
    seasonal = None
    if periods:
        tpi_t = 2 * np.pi * t
        for period in periods:
            a = cvx.Variable()
            b = cvx.Variable()
            temp = a * np.sin(tpi_t / period) + b * np.cos(tpi_t / period)
            if seasonal is None:
                seasonal = temp
            else:
                seasonal += temp
        errs = errs - seasonal

    obj = cvx.Minimize(0.5 * cvx.sum_squares(errs) + lam * x_term + rho * w_term)
    prob = cvx.Problem(obj)
    prob.solve(solver=solver, verbose=verbose)
    if periods:
        return np.array(x.value), np.array(w.value), np.array(seasonal.value)
    else:
        return np.array(x.value), np.array(w.value), None
github cvxgrp / cvxpy / examples / extensions / mixed_integer / admm_problem.py View on Github external
def admm(self, rho=0.5, iterations=5, *args, **kwargs):
    noncvx_vars = []
    for var in self.variables():
        if getattr(var, "noncvx", False):
            noncvx_vars += [var]
    # Form ADMM problem.
    obj = self.objective.args[0]
    for var in noncvx_vars:
        obj = obj + (rho/2)*cvx.sum(cvx.square(var - var.z + var.u))
    prob = cvx.Problem(cvx.Minimize(obj), self.constraints)
    # ADMM loop
    for _ in range(iterations):
        result = prob.solve(*args, **kwargs)
        print("relaxation", result)
        for var in noncvx_vars:
            var.z.value = var.round(var.value + var.u.value)
            var.u.value += var.value - var.z.value
    return polish(self, noncvx_vars, *args, **kwargs)
github AtsushiSakai / PyOptSamples / OperationsResearch / minimal_cost_network_flow.py View on Github external
ni = [1, 1, 2, 3, 3, 4, 4, 5]
    nj = [2, 3, 3, 4, 5, 1, 5, 2]
    cij = np.array([4, 2, 1, 1, 2, 5, 2, 4])
    inf = 100000.0
    uij = [inf, inf, inf, inf, 1, inf, inf, inf]
    bi = [-5, 11, -1, -2, -3]
    ni = [1, 1, 2, 3, 3, 4, 4, 5]

    print("ni", ni)
    print("nj", nj)
    print("cij", cij)
    print("uij", uij)
    print("bi", bi)

    x = cvxpy.Variable(len(ni))
    objective = cvxpy.Minimize(cij.T * x)
    constraints = [0 <= x, x <= uij]
    for iin in range(1, len(bi) + 1):
        inp = sum([x[i - 1] for i in range(1, len(nj)) if ni[i - 1] == iin])
        out = sum([x[i - 1] for i in range(1, len(ni)) if nj[i - 1] == iin])
        print(iin, bi[iin - 1])
        constraints += [inp - out == bi[iin - 1]]

    prob = cvxpy.Problem(objective, constraints)

    result = prob.solve(solver=cvxpy.ECOS)
    print("Opt result:", result)
    print("optimal parameter:\n", [float(np.round(i)) for i in x.value])
    print("status:" + prob.status)
github AtsushiSakai / PyAdvancedControl / mpc_modeling / mpc_modeling_with_ECOS.py View on Github external
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]]

    constrlist += [x[:, 0] == x0[:, 0]]  # inital state constraints
    if umax is not None:
        constrlist += [u <= umax]  # input constraints
    if umin is not None:
        constrlist += [u >= umin]  # input constraints

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

    prob.solve(verbose=True)

    return x.value, u.value