Python cvxpy.abs() Examples
The following are 16
code examples of cvxpy.abs().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cvxpy
, or try the search function
.
Example #1
Source File: diffdrive_2d.py From SCvx with MIT License | 6 votes |
def get_constraints(self, X_v, U_v, X_last_p, U_last_p): """ Get model specific constraints. :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 list of cvx constraints """ # Boundary conditions: constraints = [ X_v[:, 0] == self.x_init, X_v[:, -1] == self.x_final, U_v[:, 0] == 0, U_v[:, -1] == 0 ] # Input conditions: constraints += [ 0 <= U_v[0, :], U_v[0, :] <= self.v_max, cvx.abs(U_v[1, :]) <= self.w_max, ] # State conditions: constraints += [ X_v[0:2, :] <= self.upper_bound - self.robot_radius, X_v[0:2, :] >= self.lower_bound + self.robot_radius, ] # linearized obstacles for j, obst in enumerate(self.obstacles): p = obst[0] r = obst[1] + self.robot_radius lhs = [(X_last_p[0:2, k] - p) / (cvx.norm((X_last_p[0:2, k] - p)) + 1e-6) * (X_v[0:2, k] - p) for k in range(K)] constraints += [r - cvx.vstack(lhs) <= self.s_prime[j]] return constraints
Example #2
Source File: vhip_stabilization.py From pymanoid with GNU General Public License v3.0 | 6 votes |
def __init__(self, pendulum): super(Stabilizer, self).__init__() ref_com = pendulum.com.p + ref_offset n = pendulum.contact.normal lambda_ = -dot(n, gravity) / dot(n, ref_com - pendulum.contact.p) omega = sqrt(lambda_) ref_cop = ref_com + gravity / lambda_ assert abs(lambda_ - pendulum.lambda_) < 1e-5 self.contact = pendulum.contact self.dcm = ref_com self.omega = omega self.pendulum = pendulum self.ref_com = ref_com self.ref_comd = numpy.zeros(3) self.ref_cop = ref_cop self.ref_lambda = lambda_ self.ref_omega = omega
Example #3
Source File: admm_problem.py From ncvx with GNU General Public License v3.0 | 5 votes |
def get_constr_error(constr): if isinstance(constr, cvx.constraints.Equality): error = cvx.abs(constr.args[0] - constr.args[1]) elif isinstance(constr, cvx.constraints.Inequality): error = cvx.pos(constr.args[0] - constr.args[1]) elif isinstance(constr, cvx.constraints.PSD): mat = constr.args[0] - constr.args[1] error = cvx.neg(cvx.lambda_min(mat + mat.T)/2) return cvx.sum(error)
Example #4
Source File: admm_problem.py From ncvx with GNU General Public License v3.0 | 5 votes |
def is_better(noncvx_inf, opt_val, best_so_far, error): """Is the current result better than best_so_far? """ inf_diff = best_so_far[0] - noncvx_inf return (inf_diff > error) or \ (abs(inf_diff) <= error and opt_val < best_so_far[1])
Example #5
Source File: integer.py From ncvx with GNU General Public License v3.0 | 5 votes |
def relax(self): return [cvx.abs(self) <= self.M]
Example #6
Source File: rocket_landing_2d.py From SCvx with MIT License | 5 votes |
def get_constraints(self, X_v, U_v, X_last_p, U_last_p): """ Get model specific constraints. :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 list of cvx constraints """ constraints = [ # Boundary conditions: X_v[0:2, 0] == self.x_init[0:2], X_v[2:4, 0] == self.x_init[2:4], X_v[4, 0] == self.x_init[4], X_v[5, 0] == self.x_init[5], X_v[:, -1] == self.x_final, # State constraints: cvx.abs(X_v[4, :]) <= self.t_max, cvx.abs(X_v[5, :]) <= self.w_max, X_v[1, :] >= 0, # Control constraints: cvx.abs(U_v[0, :]) <= self.max_gimbal, U_v[1, :] >= self.T_min, U_v[1, :] <= self.T_max, ] return constraints
Example #7
Source File: nuclear_norm_minimization.py From ME-Net with MIT License | 5 votes |
def _constraints(self, X, missing_mask, S, error_tolerance): """ Parameters ---------- X : np.array Data matrix with missing values filled in missing_mask : np.array Boolean array indicating where missing values were S : cvxpy.Variable Representation of solution variable """ ok_mask = ~missing_mask masked_X = cvxpy.multiply(ok_mask, X) masked_S = cvxpy.multiply(ok_mask, S) abs_diff = cvxpy.abs(masked_S - masked_X) close_to_data = abs_diff <= error_tolerance constraints = [close_to_data] if self.require_symmetric_solution: constraints.append(S == S.T) if self.min_value is not None: constraints.append(S >= self.min_value) if self.max_value is not None: constraints.append(S <= self.max_value) return constraints
Example #8
Source File: nuclear_norm_minimization.py From fancyimpute with Apache License 2.0 | 5 votes |
def _constraints(self, X, missing_mask, S, error_tolerance): """ Parameters ---------- X : np.array Data matrix with missing values filled in missing_mask : np.array Boolean array indicating where missing values were S : cvxpy.Variable Representation of solution variable """ ok_mask = ~missing_mask masked_X = cvxpy.multiply(ok_mask, X) masked_S = cvxpy.multiply(ok_mask, S) abs_diff = cvxpy.abs(masked_S - masked_X) close_to_data = abs_diff <= error_tolerance constraints = [close_to_data] if self.require_symmetric_solution: constraints.append(S == S.T) if self.min_value is not None: constraints.append(S >= self.min_value) if self.max_value is not None: constraints.append(S <= self.max_value) return constraints
Example #9
Source File: linear_model.py From scikit-lego with MIT License | 5 votes |
def fit(self, X, y): X, y = check_X_y(X, y, estimator=self, dtype=FLOAT_DTYPES) if self.effect not in self.allowed_effects: raise ValueError(f"effect {self.effect} must be in {self.allowed_effects}") def deadzone(errors): if self.effect == "linear": return np.where(errors > self.threshold, errors, np.zeros(errors.shape)) if self.effect == "quadratic": return np.where( errors > self.threshold, errors ** 2, np.zeros(errors.shape) ) def training_loss(weights): diff = np.abs(np.dot(X, weights) - y) if self.relative: diff = diff / y return np.mean(deadzone(diff)) n, k = X.shape # Build a function that returns gradients of training loss using autograd. training_gradient_fun = grad(training_loss) # Check the gradients numerically, just to be safe. weights = np.random.normal(0, 1, k) if self.check_grad: check_grads(training_loss, modes=["rev"])(weights) # Optimize weights using gradient descent. self.loss_log_ = np.zeros(self.n_iter) self.wts_log_ = np.zeros((self.n_iter, k)) self.deriv_log_ = np.zeros((self.n_iter, k)) for i in range(self.n_iter): weights -= training_gradient_fun(weights) * self.stepsize self.wts_log_[i, :] = weights.ravel() self.loss_log_[i] = training_loss(weights) self.deriv_log_[i, :] = training_gradient_fun(weights).ravel() self.coefs_ = weights return self
Example #10
Source File: linear_model.py From scikit-lego with MIT License | 5 votes |
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 []
Example #11
Source File: linear_model.py From scikit-lego with MIT License | 5 votes |
def constraints(self, y_hat, y_true, sensitive, n_obs): if self.covariance_threshold is not None: n_obs = len(y_true[y_true == self.positive_target]) dec_boundary_cov = ( y_hat[y_true == self.positive_target] @ ( sensitive[y_true == self.positive_target] - np.mean(sensitive, axis=0) ) / n_obs ) return [cp.abs(dec_boundary_cov) <= self.covariance_threshold] else: return []
Example #12
Source File: mpc.py From pylot with Apache License 2.0 | 5 votes |
def _retrieve_imminent_reference(self): """ Retrieve the reference state and reference steer in the imminent horizon. :return: reference state and reference steer """ reference_state = np.zeros( (self.num_state, self.config['horizon'] + 1)) reference_steer = np.zeros((1, self.config['horizon'] + 1)) arc_displacement = 0.0 for t in range(self.config['horizon'] + 1): offset = int(round(arc_displacement / self.delta_s)) if (self.path_index + offset) < self.path_length: reference_state[0, t] = \ self.reference.x_list[self.path_index + offset] reference_state[1, t] = \ self.reference.y_list[self.path_index + offset] reference_state[2, t] = \ self.reference.vel_list[self.path_index + offset] reference_state[3, t] = \ self.reference.yaw_list[self.path_index + offset] else: reference_state[0, t] = \ self.reference.x_list[self.path_length - 1] reference_state[1, t] = \ self.reference.y_list[self.path_length - 1] reference_state[2, t] = \ self.reference.vel_list[self.path_length - 1] reference_state[3, t] = \ self.reference.yaw_list[self.path_length - 1] arc_displacement = \ arc_displacement + abs(self.vehicle.vel) * self.delta_t return reference_state, reference_steer
Example #13
Source File: devices.py From cvxpower with GNU General Public License v3.0 | 5 votes |
def constraints(self): p1 = self.terminals[0].power_var p2 = self.terminals[1].power_var constrs = [] if self.alpha > 0: constrs += [p1 + p2 >= self.alpha * cvx.square((p1 - p2) / 2)] if self.power_max is not None: constrs += [2 * self.alpha * self.power_max**2 >= p1 + p2] else: constrs += [p1 + p2 == 0] if self.power_max is not None: constrs += [cvx.abs((p1 - p2) / 2) <= self.power_max] return constrs
Example #14
Source File: optimize.py From Visual-Template-Free-Form-Parsing with GNU General Public License v3.0 | 5 votes |
def optimizeRelationships(relPred,relNodes,gtNodeNeighbors,penalty=490): #if 'cvxpy' not in sys.modules: import cvxpy useRel = cvxpy.Variable(relPred.size(0),boolean=True) obj =0 huh=0 for i in range(relPred.size(0)): obj += relPred[i].item()*useRel[i] huh +=useRel[i] 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
Example #15
Source File: optimize.py From Visual-Template-Free-Form-Parsing with GNU General Public License v3.0 | 5 votes |
def optimizeRelationshipsSoft(relPred,relNodes,predNodeNeighbors,penalty=1.2,threshold=0.5): #if 'cvxpy' not in sys.modules: import cvxpy useRel = cvxpy.Variable(relPred.size(0),boolean=True) obj =0 huh=0 for i in range(relPred.size(0)): obj += (relPred[i].item()-threshold)*useRel[i] huh +=useRel[i] difference = [0]*len(predNodeNeighbors) for i in range(len(predNodeNeighbors)): relI=0 for a,b in relNodes: j=None if a==i: j=b elif b==i: j=a if j is not None: difference[i] += useRel[relI] relI+=1 difference[i] -= predNodeNeighbors[i] #difference[i] = cvxpy.abs(difference[i]) #obj -= cvxpy.power(penalty,difference[i]) #this causes it to not miss on the same node more than once obj -= penalty*cvxpy.power(difference[i],2) #obj -= penalty*cvxpy.maximum(1,difference[i]) - penalty #double penalty if difference>1 #obj -= penalty*cvxpy.maximum(2,difference[i]) - 2*penalty #triple penalty if difference>2 cs=[] #for i in range(len(predNodeNeighbors)): # cs.append(difference[i]<=4) problem = cvxpy.Problem(cvxpy.Maximize(obj),cs) #problem.solve(solver=cvxpy.GLPK_MI) problem.solve(solver=cvxpy.ECOS_BB) return useRel.value
Example #16
Source File: mixing.py From rampy with GNU General Public License v2.0 | 4 votes |
def mixing_sp(y_fit,ref1,ref2): """mix two reference spectra to match the given ones Parameters ---------- y_fit : ndarray, shape m * n an array containing the signals with m datapoints and n experiments ref1 : ndarray, shape m an array containing the first reference signal ref2 : ndarray, shape m an array containing the second reference signal Returns ------- out : ndarray, shape n the fractions of ref1 in the mix Notes ----- Performs the calculation by minimizing the sum of the least absolute value of the objective function: 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)