本文整理汇总了Python中cvxpy.abs方法的典型用法代码示例。如果您正苦于以下问题:Python cvxpy.abs方法的具体用法?Python cvxpy.abs怎么用?Python cvxpy.abs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cvxpy
的用法示例。
在下文中一共展示了cvxpy.abs方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例2: get_constr_error
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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)
示例3: is_better
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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])
示例4: relax
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
def relax(self):
return [cvx.abs(self) <= self.M]
示例5: get_constraints
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例6: get_constraints
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例7: _constraints
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例8: fit
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例9: constraints
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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 []
示例10: _retrieve_imminent_reference
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例11: constraints
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例12: optimizeRelationships
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例13: optimizeRelationshipsSoft
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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
示例14: mixing_sp
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import abs [as 别名]
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)