Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_basic_gp(self):
tf.random.set_seed(243)
x = cp.Variable(pos=True)
y = cp.Variable(pos=True)
z = cp.Variable(pos=True)
a = cp.Parameter(pos=True, value=2.0)
b = cp.Parameter(pos=True, value=1.0)
c = cp.Parameter(value=0.5)
objective_fn = 1/(x*y*z)
constraints = [a*(x*y + x*z + y*z) <= b, x >= y**c]
problem = cp.Problem(cp.Minimize(objective_fn), constraints)
problem.solve(cp.SCS, gp=True, eps=1e-12)
layer = CvxpyLayer(
problem, parameters=[a, b, c], variables=[x, y, z], gp=True)
a_tf = tf.Variable(2.0, dtype=tf.float64)
b_tf = tf.Variable(1.0, dtype=tf.float64)
"""Solve a group elastic net problem with cvx.
Arguments:
As: list of tensors.
y: tensor.
l_1, l_2: floats.
ns: iterable.
"""
# Convert everything to numpy
dtype = As[0].dtype
As = [A_j.cpu().numpy() for A_j in As]
y = y.cpu().numpy()
ns = np.array([int(n) for n in ns])
# Create the b variables.
b_0 = cvx.Variable()
bs = []
for _, n_j in zip(As, ns):
bs.append(cvx.Variable(n_j))
# Form g(b).
Ab = sum(A_j * b_j for A_j, b_j in zip(As, bs))
m = As[0].shape[0]
g_b = cvx.square(cvx.norm(y - b_0 - Ab)) / (2 * m)
# Form h(b).
h_b = sum(
np.sqrt(n_j) * (l_1 * cvx.norm(b_j) + l_2 * cvx.square(cvx.norm(b_j)))
for n_j, b_j in zip(ns, bs)
)
# Build the optimization problem.
# np.log(trAtA)
])
# Add row to matrix A
A = spa.vstack((A, spa.csc_matrix(A_temp)), 'csc')
# Add bounds on v
l = np.log(problem['rho_min'].iloc[0])
u = np.log(problem['rho_max'].iloc[0])
v_l = np.append(v_l, l)
v_u = np.append(v_u, u)
#
# Define CVXPY problem
alpha = cvxpy.Variable(n_params)
v = cvxpy.Variable(n_problems)
constraints = [v_l <= v, v <= v_u]
cost = cvxpy.norm(A * alpha - v)
objective = cvxpy.Minimize(cost)
problem = cvxpy.Problem(objective, constraints)
# Solve problem
print("Solving problem with CVXPY and GUROBI")
problem.solve(solver=cvxpy.MOSEK, verbose=True)
print("Solution status: %s" % problem.status)
# Get learned alpha
alpha_fit = np.asarray(alpha.value).flatten()
dual_right_fut = np.array(cons_right[1].dual_value)
for tau in range(tau_max):
for i in range(n):
end_resource[i][tau] = np.sum(Zval[:, tau*n+i])
lambda_right[i][1+tau] = dual_right_fut[tau*n+i][0]
## Generating left derivative
small = 1.0e-6
R_left = np.maximum(R - 0.0001 * np.ones((n, 1)), small*np.ones((n, 1))) # R_left should be positive
Ru_left = np.maximum(np.reshape(Ru, (tau_max*n, 1), order='F') - 0.0001 * np.ones((tau_max*n, 1)), small*np.ones((tau_max*n, 1)))
# Construct the problem.
if not M_is_empty:
X_left = cvx.Variable((num_nonzero_M, 1))
Y_left = cvx.Variable((num_nonzero_rep, 1))
Z_left = cvx.Variable((P.shape[0], tau_max*n))
obj_left = - C_coeff*Y_left + cvx.sum(cvx.multiply(P, Z_left))
if not M_is_empty:
obj_left += W_coeff*X_left
if M_is_empty:
cons_left = [R_left == row_sum_matrix_Y*Y_left,
cvx.sum(Z_left, axis=0, keepdims=True).T == col_sum_matrix_Y * Y_left + Ru_left,
0 <= Y_left, 0 <= Z_left, Z_left <= PLen]
else:
cons_left = [R_left == row_sum_matrix_X*X_left + row_sum_matrix_Y*Y_left,
cvx.sum(Z_left, axis=0, keepdims=True).T == col_sum_matrix_X * X_left + col_sum_matrix_Y * Y_left + Ru_left,
0 <= X_left, X_left <= M_coeff, 0 <= Y_left, 0 <= Z_left, Z_left <= PLen]
prob_left = cvx.Problem(cvx.Maximize(obj_left), cons_left)
def QP_optimizer(expertList, agentList):
w=cp.Variable(4)
b=cp.Variable(1)
policyMat = agentList
ExpertMat = expertList
#constraints = [ExpertMat*w + b >= 1, policyMat*w + b <= -1]
constraints = [(ExpertMat-policyMat)*w >= 2]
obj = cp.Minimize(cp.norm(w))
prob = cp.Problem(obj, constraints)
prob.solve()
print("status:", prob.status)
print("optimal value", prob.value)
#print("optimal var", w.value)
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(
g2 = gradr(pt)
g2[np.diag_indices_from(g2)] = 0
assert(np.allclose(g2,grad))
"""
# r tilde constants
txp = 1.0/(mu * pt + Pc)
c1 = np.sum(grad * txp, axis=0)
c2 = -mu * np.log(np.diag(s)/tmp2+1)*txp**2
c = c1+c2
d = -c * pt
# solve inner problem
pvar = cp.Variable(4)
obj_nl = cp.log(cp.multiply(np.diag(h)/tmp2, pvar)+1) * txp
obj_l = cp.multiply(c, pvar)
objective = cp.Maximize(cp.sum(obj_nl + obj_l + d))
constraints = [0 <= pvar, pvar <= Pmax]
prob = cp.Problem(objective, constraints)
try:
prob.solve()
except cp.SolverError:
print('ecos failed')
try:
prob.solve(solver = cp.CVXOPT)
except cp.SolverError:
print('cvxopt also failed')
break
Get optimal trade vector for given portfolio at time t.
Parameters
----------
portfolio : pd.Series
Current portfolio vector.
t : pd.timestamp
Timestamp for the optimization.
"""
if t is None:
t = dt.datetime.today()
value = sum(portfolio)
w = portfolio / value
z = cvx.Variable(w.size) # TODO pass index
wplus = w.values + z
if isinstance(self.return_forecast, BaseReturnsModel):
alpha_term = self.return_forecast.weight_expr(t, wplus)
else:
alpha_term = cvx.sum(cvx.multiply(
values_in_time(self.return_forecast, t).values,
wplus))
assert(alpha_term.is_concave())
costs, constraints = [], []
for cost in self.costs:
cost_expr, const_expr = cost.weight_expr(t, wplus, z, value)
costs.append(cost_expr)
def _generate_cvxpy_problem(self):
'''
Generate QP problem
'''
# Dimensions
nx, nu = self.nx, self.nu
T = self.T
# Initial state
x0 = cvxpy.Parameter(nx)
x0.value = self.x0
# variables
x = cvxpy.Variable((nx, T + 1))
u = cvxpy.Variable((nu, T))
# Objective
cost = cvxpy.quad_form(x[:, T], self.QN) # Terminal cost
for i in range(T):
cost += cvxpy.quad_form(x[:, i], self.Q) # State cost
cost += cvxpy.quad_form(u[:, i], self.R) # Inpout cost
objective = cvxpy.Minimize(cost)
# Dynamics
dynamics = [x[:, 0] == x0]
for i in range(T):
dynamics += [x[:, i+1] == self.A * x[:, i] + self.B * u[:, i]]
# State constraints
state_constraints = []
p_xi = 0.
P_xi = mean_active_thruster_count*mean_pulse_width*N
# General quantites
data['t_grid'] = np.linspace(0.,data['t_f'],N+1) # discretization time grid
n_x = data['state_traj_init'].shape[1]
n_u = csm.M
e = -tools.rotate(np.array([1.,0.,0.]),csm.q_dock) # dock axis in LM frame
I_e = tools.rotate(e,data['lm']['q']) # dock axis in inertial frame
data['dock_axis'] = I_e
# Optimization variables
# non-dimensionalized
x_hat = [cvx.Variable(n_x) for k in range(N+1)]
v_hat = [cvx.Variable(n_x) for k in range(N+1)]
xi_hat = cvx.Variable(N+1)
u_hat = [cvx.Variable(n_u) for k in range(N)]
eta_hat = cvx.Variable(N) # quadratic trust region size
# dimensionalized (physical units)
x = [P_x*x_hat[k]+p_x for k in range(N+1)] # unscaled state
xi = P_xi*xi_hat+p_xi
u = [P_u*u_hat[k]+p_u for k in range(N)] # unscaled control
v = [P_v*v_hat[k] for k in range(N)] # virtual control
data['lrtop_var'] = dict(x=x,u=u,xi=xi,v=v)
# Optimization parameters
A = [cvx.Parameter((n_x,n_x)) for k in range(N)]
B = [cvx.Parameter((n_x,n_u)) for k in range(N)]
r = [cvx.Parameter(n_x) for k in range(N)]
u_lb = [cvx.Parameter(n_u,value=np.zeros(n_u)) for k in range(N)]
stc_lb = [cvx.Parameter(n_u) for k in range(N)]
stc_q = cvx.Parameter(N+1)