How to use the cvxpy.abs 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 Networks-Learning / discussion-complexity / code / cjr / models / lin_thres.py View on Github external
def _upvote_cstr(x, v, thres):
    return [CVX.abs(x - v) <= thres]
github koaning / scikit-lego / sklego / linear_model.py View on Github external
def constraints(self, y_hat, y_true, sensitive, n_obs):
        if self.covariance_threshold is not None:
            dec_boundary_cov = y_hat @ (sensitive - np.mean(sensitive, axis=0)) / n_obs
            return [cp.abs(dec_boundary_cov) <= self.covariance_threshold]
        else:
            return []
github stephane-caron / pymanoid / examples / vhip_stabilization.py View on Github external
# Cost function
        costs = []
        sq_costs = [(1., u[0]), (1., u[1]), (1e-3, u[2])]
        for weight, expr in sq_costs:
            costs.append((weight, cvxpy.sum_squares(expr)))
        cost = sum(weight * expr for (weight, expr) in costs)

        # Quadratic program
        prob = cvxpy.Problem(
            objective=cvxpy.Minimize(cost),
            constraints=[
                Delta_xid == lambda_d / omega_d * ((1 - k_p) * Delta_xi + u),
                Delta_omegad == omega_d * (1 - k_p) * Delta_omega,
                Delta_nu == Delta_r_world
                + gravity * Delta_lambda / lambda_d ** 2,
                cvxpy.abs(r_contact) <= self.r_contact_max,
                lambda_ <= lambda_max,
                lambda_ >= lambda_min,
                xi_z <= max_dcm_height,
                xi_z >= min_dcm_height,
                omega <= omega_max,
                omega >= omega_min])
        prob.solve()

        # Read outputs from solution
        Delta_lambda_opt = Delta_lambda.value
        Delta_r_opt = array(Delta_r.value).reshape((2,))
        self.omega = omega_d + Delta_omega.value
        self.dcm = self.pendulum.com.p \
            + self.pendulum.com.pd / self.omega
        return (Delta_r_opt, Delta_lambda_opt)
github okama-io / cifrum / yapo / _portfolio / optimal / basic.py View on Github external
start_period: pd.Period, end_period: pd.Period,
            currency: Currency) -> EfficientFrontier:
    asset_rors = [a.get_return().values for a in assets]
    mu = np.mean(asset_rors, axis=1)
    sigma = np.cov(asset_rors)

    efficient_frontier = EfficientFrontier(start_period=start_period, end_period=end_period, currency=currency)

    for idx, return_trg in enumerate(np.linspace(mu.min(), mu.max(), num=samples_count)):
        w = cvx.Variable(len(assets))
        ret = mu.T * w
        risk = cvx.quad_form(w, sigma)
        problem = cvx.Problem(objective=cvx.Minimize(risk),
                              constraints=[cvx.sum(w) == 1,
                                           w >= 0,
                                           cvx.abs(ret - return_trg) <= 1e-4,
                                           ])
        problem.solve(solver='ECOS_BB')

        ret_yearly = (ret.value + 1.) ** _MONTHS_PER_YEAR - 1.
        risk_yearly = \
            (risk.value ** 2 + (ret.value + 1.) ** 2) ** _MONTHS_PER_YEAR - (ret.value + 1.) ** (_MONTHS_PER_YEAR * 2)
        risk_yearly = np.sqrt(risk_yearly)
        point = EfficientFrontierPoint(weights=w.value,
                                       return_=ret.value,
                                       return_yearly=ret_yearly,
                                       risk_yearly=risk_yearly,
                                       risk=risk.value)
        efficient_frontier.add_point(point)

    return efficient_frontier
github charlesll / rampy / rampy / mixing.py View on Github external
obj = sum(abs(y_fit-(ref1*F1 + ref2*(1-F1))))

    Uses cvxpy to perform this calculation
    """

    try:
        import cvxpy
    except ImportError:
        print('ERROR: Install cvxpy>=1.0 to use this function.')

    ref1 = ref1.reshape(1,-1)
    ref2 = ref2.reshape(1,-1)
    
    F1 = cvxpy.Variable(shape=(y_fit.shape[1],1))

    objective = cvxpy.Minimize(cvxpy.sum(cvxpy.abs(F1*ref1 + (1-F1)*ref2 - y_fit.T))) 

    constraints = [0 <= F1, F1 <= 1]

    prob = cvxpy.Problem(objective, constraints)
    prob.solve()
    return np.asarray(F1.value).reshape(-1)
github cvxgrp / dccp / examples / circle_packing.py View on Github external
import matplotlib.pyplot as plt
import dccp
np.random.seed(0)
n = 4
r = np.linspace(1, 5, n)

c = cvx.Variable((n,2))
constr = []
for i in range(n-1):
    for j in range(i+1, n):
        constr.append(cvx.norm(cvx.vec(c[i,:]-c[j,:]), 2) >= r[i]+r[j])
prob = cvx.Problem(cvx.Minimize(cvx.max(cvx.max(cvx.abs(c), axis=1) + r)), constr)
#prob = cvx.Problem(cvx.Minimize(cvx.max(cvx.norm(c, "inf", axis=1) + r)), constr)
prob.solve(method = 'dccp', tau=0.000005, ccp_times = 1)

l = cvx.max(cvx.max(cvx.abs(c),axis=1)+r).value*2
pi = np.pi
ratio = pi*cvx.sum(cvx.square(r)).value/cvx.square(l).value
print "ratio =", ratio
print prob.status

# plot
plt.figure(figsize=(5,5))
circ = np.linspace(0,2*pi)
x_border = [-l/2, l/2, l/2, -l/2, -l/2]
y_border = [-l/2, -l/2, l/2, l/2, -l/2]
for i in xrange(n):
    plt.plot(c[i,0].value+r[i]*np.cos(circ),c[i,1].value+r[i]*np.sin(circ),'b')
plt.plot(x_border,y_border,'g')
plt.axes().set_aspect('equal')
plt.xlim([-l/2,l/2])
plt.ylim([-l/2,l/2])
github AtsushiSakai / PythonRobotics / PathTracking / model_predictive_speed_and_steer_control / model_predictive_speed_and_steer_control.py View on Github external
cost = 0.0
    constraints = []

    for t in range(T):
        cost += cvxpy.quad_form(u[:, t], R)

        if t != 0:
            cost += cvxpy.quad_form(xref[:, t] - x[:, t], Q)

        A, B, C = get_linear_model_matrix(
            xbar[2, t], xbar[3, t], dref[0, t])
        constraints += [x[:, t + 1] == A * x[:, t] + B * u[:, t] + C]

        if t < (T - 1):
            cost += cvxpy.quad_form(u[:, t + 1] - u[:, t], Rd)
            constraints += [cvxpy.abs(u[1, t + 1] - u[1, t]) <=
                            MAX_DSTEER * DT]

    cost += cvxpy.quad_form(xref[:, T] - x[:, T], Qf)

    constraints += [x[:, 0] == x0]
    constraints += [x[2, :] <= MAX_SPEED]
    constraints += [x[2, :] >= MIN_SPEED]
    constraints += [cvxpy.abs(u[0, :]) <= MAX_ACCEL]
    constraints += [cvxpy.abs(u[1, :]) <= MAX_STEER]

    prob = cvxpy.Problem(cvxpy.Minimize(cost), constraints)
    prob.solve(solver=cvxpy.ECOS, verbose=False)

    if prob.status == cvxpy.OPTIMAL or prob.status == cvxpy.OPTIMAL_INACCURATE:
        ox = get_nparray_from_matrix(x.value[0, :])
        oy = get_nparray_from_matrix(x.value[1, :])
github cvxgrp / cvxportfolio / cvxportfolio / returns.py View on Github external
def weight_expr(self, t, wplus, z=None, v=None):
        """Returns the estimated alpha.

        Args:
          t: time estimate is made.
          wplus: An expression for holdings.
          tau: time of alpha being estimated.

        Returns:
          An expression for the alpha.
        """
        alpha = cvx.multiply(
            time_locator(self.returns, t, as_numpy=True), wplus)
        alpha -= cvx.multiply(
            time_locator(self.delta, t, as_numpy=True), cvx.abs(wplus))
        return cvx.sum(alpha)
github cvxgrp / cvxportfolio / cvxportfolio / risks.py View on Github external
def _estimate(self, t, wplus, z, value):
        F = locator(self.exposures, t)
        f = (wplus.T * F.T).T
        Sigma_F = locator(self.factor_Sigma, t)
        D = locator(self.idiosync, t)
        self.expression = cvx.sum_squares(
            cvx.multiply(np.sqrt(D), wplus)) + \
            cvx.quad_form(f, Sigma_F) + \
            self.epsilon * (cvx.abs(f).T * np.sqrt(np.diag(Sigma_F)))**2

        return self.expression
github herobd / Visual-Template-Free-Form-Parsing / model / optimize.py View on Github external
constraint = [0]*len(gtNodeNeighbors)
    for i in range(len(gtNodeNeighbors)):
        relI=0
        for a,b in relNodes:
            j=None
            if a==i:
                j=b
            elif b==i:
                j=a
            if j is not None:
                constraint[i] += useRel[relI]
            relI+=1
        constraint[i] -= gtNodeNeighbors[i]
        #obj -= cvxpy.power(penalty,(cvxpy.abs(constraint[i]))) #this causes it to not miss on the same node more than once
        constraint[i] = cvxpy.abs(constraint[i])
        obj -= penalty*constraint[i]


    cs=[]
    for i in range(len(gtNodeNeighbors)):
        cs.append(constraint[i]<=1)
    problem = cvxpy.Problem(cvxpy.Maximize(obj),cs)
    #problem.solve(solver=cvxpy.GLPK_MI)
    problem.solve(solver=cvxpy.ECOS_BB)
    assert(useRel.value is not None)
    return useRel.value
def optimizeRelationshipsSoft(relPred,relNodes,predNodeNeighbors,penalty=1.2,threshold=0.5):