def generate(self, T, lam, c, plower, pupper, ramp, rc, rp): import cvxpy as cp constraints = [] u = cp.Variable((T, 1)) r = cp.Variable((T, 1)) objective = cp.Minimize( cp.sum(c[0] * u**2 + cp.multiply(c[1], u) + rc[0] * r**2 + rc[1] * r - cp.multiply(lam, u) - cp.multiply(rp, r))) for i in range(0, T): constraints += [u[i] >= plower, u[i] <= pupper, r[i] >= 0] if i < T - 1: constraints += [ u[i + 1] - u[i] <= ramp, u[i] - u[i + 1] <= ramp ] prob = cp.Problem(objective, constraints) result = prob.solve(solver=cp.ECOS_BB, verbose=True) return u.value, r.value
def test_rank_one_nmf(self): X = cvxpy.Variable((3, 3), pos=True) x = cvxpy.Variable((3, ), pos=True) y = cvxpy.Variable((3, ), pos=True) xy = cvxpy.vstack([x[0] * y, x[1] * y, x[2] * y]) R = cvxpy.maximum(cvxpy.multiply(X, (xy)**(-1.0)), cvxpy.multiply(X**(-1.0), xy)) objective = cvxpy.sum(R) constraints = [ X[0, 0] == 1.0, X[0, 2] == 1.9, X[1, 1] == 0.8, X[2, 0] == 3.2, X[2, 1] == 5.9, x[0] * x[1] * x[2] == 1.0, ] # smoke test. prob = cvxpy.Problem(cvxpy.Minimize(objective), constraints) prob.solve(SOLVER, gp=True)
def test_sum_matrix(self): w = cvxpy.Variable((2, 2), pos=True) h = cvxpy.Variable((2, 2), pos=True) problem = cvxpy.Problem(cvxpy.Minimize( cvxpy.sum(h)), [cvxpy.multiply(w, h) >= 10, cvxpy.sum(w) <= 20]) problem.solve(SOLVER, gp=True) np.testing.assert_almost_equal(problem.value, 8) np.testing.assert_almost_equal(h.value, np.array([[2, 2], [2, 2]])) np.testing.assert_almost_equal(w.value, np.array([[5, 5], [5, 5]]))
def solve_glasso(cov, lambda_): p = cov.shape[0] X = cp.Variable((p, p), PSD=True) constraints = [X >> 0] objective = cp.Minimize( cp.sum(cp.multiply(cov, X)) - cp.log_det(X) + lambda_ * cp.pnorm(X, 1)) prob = cp.Problem(objective, constraints) prob.solve() theta = X.value return theta
def _constraints(self, l_cs_param, r_cs_param, beta_param, component_r0): constraints = [l_cs_param * r_cs_param >= 0, r_cs_param[0] >= 0] if self._power_signals_d.shape[1] > 365: r = r_cs_param[0, :].T if self._is_degradation_calculated: constraints.extend([ cvx.multiply(1. / component_r0[:-365], r[365:] - r[:-365]) == beta_param, beta_param >= -.25 ]) if self._max_degradation is not None: constraints.append(beta_param <= self._max_degradation) if self._min_degradation is not None: constraints.append(beta_param >= self._min_degradation) else: constraints.append( cvx.multiply(1. / component_r0[:-365], r[365:] - r[:-365]) == 0) return constraints
def set_objective(self, X, y, lmbd): self.X, self.y, self.lmbd = X, y, lmbd n_features = self.X.shape[1] self.beta = cp.Variable(n_features) loss = cp.sum(cp.logistic(-cp.multiply(self.y, self.X * self.beta))) self.problem = cp.Problem( cp.Minimize(loss + self.lmbd * cp.norm(self.beta, 1)))
def test_sum_vector(self): w = cvxpy.Variable(2, pos=True) h = cvxpy.Variable(2, pos=True) problem = cvxpy.Problem(cvxpy.Minimize( cvxpy.sum(h)), [cvxpy.multiply(w, h) >= 10, cvxpy.sum(w) <= 10]) problem.solve(SOLVER, gp=True) np.testing.assert_almost_equal(problem.value, 4) np.testing.assert_almost_equal(h.value, np.array([2, 2])) np.testing.assert_almost_equal(w.value, np.array([5, 5]))
def __init__(self, nb_measure, alpha=0.95): self.h = cp.Variable(nb_measure, nonneg=True) self.p = cp.Parameter(nb_measure, nonneg=True) self.v = cp.Parameter(nb_measure) objective = cp.Maximize(cp.matmul(self.v, cp.multiply(self.h, self.p))) constraints = [ self.h <= 1 / (1 - alpha), cp.matmul(self.h, self.p) == 1 ] self.problem = cp.Problem(objective, constraints)
def get_trades(self, portfolio, t=None): """ 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 = pd.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( time_locator(self.return_forecast, t, as_numpy=True), 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) constraints += const_expr constraints += [item for item in (con.weight_expr(t, wplus, z, value) for con in self.constraints)] for el in costs: assert (el.is_convex()) for el in constraints: assert (el.is_dcp()) self.prob = cvx.Problem( cvx.Maximize(alpha_term - sum(costs)), [cvx.sum_entries(z) == 0] + constraints) self.prob.solve(solver=self.solver, **self.solver_opts) logging.error( f'The problem is {self.prob.status}. Defaulting to no trades') return self._nulltrade(portfolio) return pd.Series(index=portfolio.index, data=(z.value.A1 * value))
def solve_svm(X, y, C, sample_weight=None, solver_kws={}): """ Solves soft-margin SVM problem. min_{beta, intercept} (1/n) * sum_{i=1}^n [1 - y_i * (x^T beta + intercept)] + C * ||beta||_1 Parameters ---------- X: (n_samples, n_features) y: (n_samples, ) C: float Strictly positive tuning parameter. sample_weight: None, (n_samples, ) Weights for samples. solver_kws: dict Keyword arguments to cp.solve Output ------ beta, intercept, problem beta: (n_features, ) SVM normal vector. intercept: float SVM intercept. problem: cp.Problem y_hat = np.sign(x.dot(beta) + intercept) """ if sample_weight is not None: raise NotImplementedError n_samples, n_features = X.shape y = y.reshape(-1, 1) beta = cp.Variable((n_features, 1)) intercept = cp.Variable() C = cp.Parameter(value=C, nonneg=True) # TODO: should we make this + intercept loss = cp.sum(cp.pos(1 - cp.multiply(y, X * beta + intercept))) reg = cp.norm(beta, 1) objective = loss / n_samples + C * reg problem = cp.Problem(cp.Minimize(objective)) problem.solve(**solver_kws) return beta.value, intercept.value, problem
def fit_OLD(self, x, y): # Detect the number of samples and classes nsamples = x.shape[0] ncols = x.shape[1] classes, cnt = np.unique(y, return_counts=True) nclasses = len(classes) # Convert classes to a categorical format yc = keras.utils.to_categorical(y, num_classes=nclasses) # Build a disciplined convex programming model w = cp.Variable(shape=(ncols, nclasses)) # Additional variables representing the actual predictions. yhat = cp.Variable(shape=(nsamples, nclasses), boolean=True) bigM = 1e3 constraints = [ cp.sum(yhat, axis=1) == 1, # only one class per sample. ] constraints += [ x @ w[:, i] - x @ w[:, i+1] <= bigM * (yhat[:, i] - yhat[:, i+1]) for i in range(nclasses - 1) ] log_reg = x @ w # out_xpr = [cp.exp(log_out_xpr[c]) for c in range(nclasses)] Z = [cp.log_sum_exp(log_reg[i]) for i in range(nsamples)] # log_likelihood = cp.sum( # cp.sum([cp.multiply(yc[:, c], log_out_xpr[c]) # for c in range(nclasses)]) - Z # ) log_likelihood = cp.sum( cp.sum([cp.multiply(yc[:, c], log_reg[:, c]) for c in range(nclasses)])) - cp.sum(Z) reg = 0 # Compute counts maxc = int(np.ceil(nsamples / nclasses)) for c in classes: reg += cp.square(maxc - cp.sum(yhat[c])) # Start the training process obj_func = - log_likelihood / nsamples + self.alpha * reg problem = cp.Problem(cp.Minimize(obj_func), constraints) problem.solve() # for c in range(nclasses): # wgt[c] = cp.Variable(ncols) # # xpr = cp.sum(cp.multiply(y, x @ wgt) - cp.logistic(x @ wgt)) # log_out_xpr[c] = x @ wgt[c] # out_xpr[c] = cp.exp(x @ wgt[c]) # if c == 0: log_likelihood = xpr # else: log_likelihood += xpr # problem = cp.Problem(cp.Maximize(log_likelihood/nsamples)) # # Start the training process # problem.solve() # Store the weights # print(wgt.value) self.weights = w.value
def grid_search_cv(samples, alphas, K=10, p=0.7): training_datasets, test_datasets = generate_partitions(samples, K=K, p=p) test_losses = np.empty((len(alphas), K)) for alpha_ix, alpha in enumerate(alphas): for data_ix, (training_data, test_data) in enumerate( tqdm(zip(training_datasets, test_datasets), total=K)): cov_train = np.cov(training_data, rowvar=False) p = cov_train.shape[1] X = cp.Variable((p, p), PSD=True) constraints = [X >> 0] cov_train_cp = cp.Parameter((p, p), PSD=True) cov_train_cp.value = cov_train objective = cp.Minimize( cp.sum(cp.multiply(cov_train, X)) - cp.log_det(X) + alpha * cp.pnorm(X, 1)) prob = cp.Problem(objective, constraints) prob.solve() theta = X.value cov_test = np.cov(test_data, rowvar=False) test_loss = np.sum(cov_test * theta) - np.log(np.linalg.det(theta)) test_losses[alpha_ix, data_ix] = test_loss avg_losses = test_losses.mean(axis=1) min_ix = np.argmin(avg_losses) best_alpha = alphas[min_ix] cov_train = np.cov(samples, rowvar=False) p = cov_train.shape[1] X = cp.Variable((p, p), PSD=True) constraints = [X >> 0] cov_train_cp = cp.Parameter((p, p), PSD=True) cov_train_cp.value = cov_train objective = cp.Minimize( cp.sum(cp.multiply(cov_train, X)) - cp.log_det(X) + best_alpha * cp.pnorm(X, 1)) prob = cp.Problem(objective, constraints) prob.solve() theta = X.value return alphas[min_ix], theta
def _construct_problem(self, bound='upper'): """ Construct the cvxpy minimization problem. It depends on the fairness regularizer chosen. """ # Variable to optimize self.alpha_var = cp.Variable((len(self.reason_pts_index), 1)) # Parameter for Kernel Matrix self.kernel_matrix = cp.Parameter(shape=(self.x_train.shape[0], len(self.reason_pts_index))) self.fair_reg_cparam = cp.Parameter(nonneg=True) # Form SVM with L2 regularization if self.fairness_lambda == 0: self.loss = cp.sum( self.loss_func( cp.multiply(self.y_train.reshape(-1, 1), self.kernel_matrix @ self.alpha_var)) ) + self.reg_beta * self.nmb_pts * cp.square( cp.norm(self.alpha_var, 2)) else: sy_hat = cp.multiply(self.s_train.reshape(-1, 1), self.kernel_matrix @ self.alpha_var) if self.fairness_regularizer == 'wu': if bound == 'upper': fairness_relaxation = cp.sum( cp.multiply(self.weight_vector, self.cvx_kappa(sy_hat))) - 1 else: fairness_relaxation = -1 * cp.sum( cp.multiply(self.weight_vector, self.cvx_delta(sy_hat))) - 1 elif self.fairness_regularizer == 'linear': if bound == 'upper': fairness_relaxation = cp.sum( cp.multiply(self.weight_vector, self.kernel_matrix @ self.alpha_var)) else: fairness_relaxation = -1 * cp.sum( cp.multiply(self.weight_vector, self.kernel_matrix @ self.alpha_var)) if self.reg_beta == 0: self.loss = (1/self.nmb_pts) * cp.sum(self.loss_func(cp.multiply(self.y_train.reshape(-1, 1), self.kernel_matrix @ self.alpha_var))) + \ self.fair_reg_cparam * fairness_relaxation else: self.loss = (1 / self.nmb_pts) * cp.sum(self.loss_func(cp.multiply(self.y_train.reshape(-1, 1), self.kernel_matrix @ self.alpha_var))) + \ self.fair_reg_cparam * fairness_relaxation + self.reg_beta * cp.square(cp.norm(self.alpha_var, 2)) self.prob = cp.Problem(cp.Minimize(self.loss))
def exprval_in_vec_eq(expr, vec): # Reference: https://docs.mosek.com/modeling-cookbook/mio.html#fixed-set-of-values assert len(expr.shape) == 1 n_entries = expr.shape[0] repeated_vec = np.broadcast_to(vec, (n_entries, len(vec))) z = Variable(repeated_vec.shape, boolean=True) main_con = cp.sum(cp.multiply(repeated_vec, z), axis=1) == expr aux_cons = [cp.sum(z, axis=1) == 1] return main_con, aux_cons
def objective_function(w, z, X, y): revenue = -1 * cp.sum(cp.multiply(X[0:nw*3], v1)) # (1') storage_cost_B = cp.multiply(data['facility_cost']['B'], cp.sum(X[0:nw])) # (2') storage_cost_C = cp.multiply(data['facility_cost']['C'][0], cp.pos(cp.sum(X[nw:nw*2]) - data['weight_threshold']['C'])) \ + cp.multiply(data['facility_cost']['C'][0], cp.sum(z[nw:nw*2])) # (3') storage_cost_D = cp.sum(cp.multiply(v4, y)) # (4) transportation_cost_D1 = cp.sum(cp.multiply(X[0:nw*3], v5)) # (5') transportation_cost_D2 = cp.sum(cp.multiply(X[0:nw*2], v6a)) + cp.sum(cp.multiply(X[nw*3:], v6b)) # (6') return revenue + storage_cost_B + storage_cost_C + storage_cost_D + transportation_cost_D1 + transportation_cost_D2
def solve(self, solver: str = "ECOS"): x, constraints = self._prepare() if self._use_factor: risk = cp.sum_squares(cp.multiply(np.sqrt(self._factor_special), x)) \ + cp.quad_form((x.T @ self._factor_load).T, self._factor_var) else: risk = cp.quad_form(x, self._variance) constraints.append(risk <= self._var_target) prob = cp.Problem(cp.Minimize(x @ self._cost), constraints=constraints) prob.solve(solver=solver) return x.value, prob.value, prob.status
def __init__(self, nb_measure, q=2, c=1): self.h = cp.Variable(nb_measure, nonneg=True) self.p = cp.Parameter(nb_measure, nonneg=True) self.v = cp.Parameter(nb_measure) self.g = cp.multiply(self.p, 1 + self.h - cp.matmul(self.h, self.p)) objective = cp.Maximize(cp.matmul(self.v, self.g)) constraints = [ self.g >= 0, cp.matmul(cp.power(self.h, q), self.p) <= c**q ] self.problem = cp.Problem(objective, constraints)
def l2_norm_LinearSVM_Primal(X, y, C): start_time = time.time() w = cp.Variable(2) b = cp.Variable() xi = cp.Variable(51) obj = cp.Minimize(1 / 2 * cp.sum_squares(w) + C / 2 * cp.sum_squares(xi)) constraints = [cp.multiply(y, (w.T * X.T + b)) >= np.ones(51) - xi] prob = cp.Problem(obj, constraints) prob.solve() sol_time = time.time() - start_time return w, b, sol_time
def primal_expr(self, y_var, voxel_weights=None): r""" Return :math:`c * \omega^T y`, for :math:`\omega\equiv```voxel_weights`` """ if voxel_weights is None: return self.weight * cvxpy.sum(y_var) else: voxel_weights = np.reshape(voxel_weights, y_var.shape) # kelsey added return self.weight * cvxpy.sum(cvxpy.multiply( voxel_weights, y_var))
def __optimize__(self, full_set, labels): # Citation: https://www.cvxpy.org/examples/machine_learning/logistic_regression.html n = 2 beta = cp.Variable(n) log_likelihood = cp.sum( cp.multiply(labels, full_set @ beta) - cp.logistic(full_set @ beta)) problem = cp.Problem(cp.Maximize(log_likelihood)) problem.solve() return beta.value
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
def test_conv_prob(self): """Test a problem with convolution. """ import numpy as np N = 5 y = np.asmatrix(np.random.randn(N, 1)) h = np.asmatrix(np.random.randn(2, 1)) x = cvx.Variable(N) v = cvx.conv(h, x) obj = cvx.Minimize(cvx.sum(cvx.multiply(y, v[0:N]))) print((cvx.Problem(obj, []).solve()))
def RicciCurvature_Edge(G, vertex_1, vertex_2, alpha, length): EPSILON = 1e-7 # to prevent division by zero assert vertex_1 != vertex_2, "Self loop is not allowed." if length[vertex_1][vertex_2] < EPSILON: assert "ricciCurvature" in G[vertex_1][vertex_2], "Divided by Zero and no ricci curvature exist in Graph!" print("Zero Weight edge detected, return previous ricci Curvature instead.") return G[vertex_1][vertex_2]["ricciCurvature"] vertex_1_nbr = list(G.neighbors(vertex_1)) vertex_2_nbr = list(G.neighbors(vertex_2)) assert len(vertex_1_nbr) > 0, "vertex_1 Nbr=0?" assert len(vertex_2_nbr) > 0, "vertex_2 Nbr=0?" + str(vertex_1) + " " + str(vertex_2) x = [(1.0 - alpha) / len(vertex_1_nbr)] * len(vertex_1_nbr) y = [(1.0 - alpha) / len(vertex_2_nbr)] * len(vertex_2_nbr) vertex_1_nbr.append(vertex_1) vertex_2_nbr.append(vertex_2) x.append(alpha) y.append(alpha) # construct the cost dictionary from x to y d = np.zeros((len(x), len(y))) for i, s in enumerate(vertex_1_nbr): for j, t in enumerate(vertex_2_nbr): assert t in length[s], "vertex_2 node not in list, should not happened, pair (%d, %d)" % (s, t) d[i][j] = length[s][t] x = np.array([x]).T # the mass that vertex_1 neighborhood initially owned y = np.array([y]).T # the mass that vertex_2 neighborhood needs to received t0 = time.time() rho = cvx.Variable(shape=(len(vertex_2_nbr), len(vertex_1_nbr))) # objective function d(x,y) * rho * x, need to do element-wise multiply here obj = cvx.Minimize(cvx.sum(cvx.multiply(np.multiply(d.T, x.T), rho))) # \sigma_i rho_{ij}=[1,1,...,1] vertex_1_sum = cvx.sum(rho, axis=0) constrains = [rho * x == y, vertex_1_sum == np.ones(len(vertex_1_nbr)), 0 <= rho, rho <= 1] prob = cvx.Problem(obj, constrains) m = prob.solve(solver='ECOS') #print(time.time() - t0, " secs for cvxpy.",) result = 1 - (m / length[vertex_1][vertex_2]) # divided by the length of d(i, j) #print("#vertex_1_nbr: %d, #vertex_2_nbr: %d, Ricci curvature = %f "%(len(vertex_1_nbr), len(vertex_2_nbr), result)) #print("%s\t%s\t%f"%(vertex_1, vertex_2, result)) EF.write("%s\t%s\t%f\n"%(vertex_1, vertex_2, result*2)) return result
def test_sum_matrix(self) -> None: w = cp.Variable((2, 2), pos=True) h = cp.Variable((2, 2), pos=True) alpha = cp.Parameter(pos=True, value=1.0) beta = cp.Parameter(pos=True, value=20) kappa = cp.Parameter(pos=True, value=10) problem = cp.Problem(cp.Minimize(alpha * cp.sum(h)), [cp.multiply(w, h) >= beta, cp.sum(w) <= kappa]) gradcheck(problem, gp=True, solve_methods=[s.SCS], atol=1e-1) perturbcheck(problem, gp=True, solve_methods=[s.SCS], atol=1e-1)
def min_R(self, calc_deg=True, max_deg=0., min_deg=-0.25): if self.R_cs.shape[1] < 365 + 2: n_tilde = 365 + 2 - self.R_cs.shape[1] R_tilde = cvx.hstack( [self.R_cs, cvx.Variable(shape=(self.k, n_tilde))]) else: R_tilde = self.R_cs W1 = np.diag(self.weights) f1 = cvx.sum( (0.5 * cvx.abs(self.D - self.L_cs.value * self.R_cs) + (self.tau - 0.5) * (self.D - self.L_cs.value * self.R_cs)) * W1) f2 = self.mu_R * cvx.norm( R_tilde[:, :-2] - 2 * R_tilde[:, 1:-1] + R_tilde[:, 2:], 'fro') constraints = [self.L_cs.value * self.R_cs >= 0, self.R_cs[0] >= 0] if self.D.shape[1] > 365: r = self.R_cs[0, :].T if calc_deg: constraints.extend([ cvx.multiply(1. / self.r0[:-365], r[365:] - r[:-365]) == self.beta, self.beta >= -.25 ]) if max_deg is not None: constraints.append(self.beta <= max_deg) if min_deg is not None: constraints.append(self.beta >= min_deg) else: constraints.append( cvx.multiply(1. / self.r0[:-365], r[365:] - r[:-365]) == 0) f3 = self.mu_R * cvx.norm(R_tilde[1:, :-365] - R_tilde[1:, 365:], 'fro') else: f3 = self.mu_R * cvx.norm(R_tilde[:, :-365] - R_tilde[:, 365:], 'fro') objective = cvx.Minimize(f1 + f2 + f3) problem = cvx.Problem(objective, constraints) problem.solve(solver='MOSEK') #problem.solve(solver=SOLVER_OBJ) if problem.status != 'optimal': raise ProblemStatusError('Minimize R status: ' + problem.status) self.r0 = self.R_cs.value[0, :]
def run(self, bl, bu, y0, yp): constraints = [self.P >> 0, self.P[0][0] == 1.0] p = 1 + self.shapes[0] for i in range(1, len(self.shapes) - 1): constraints.append(self.P[p:(p + self.shapes[i]), 0] >= 0) constraints.append( self.P[p:(p + self.shapes[i]), 0] >= cp.matmul(self.Ws[i - 1], self.P[ (p - self.shapes[i - 1]):p, 0]) + self.bs[i - 1]) constraints.append( cp.diag(self.P)[p:(p + self.shapes[i])] == cp.diag( cp.matmul( self.Ws[i - 1], self.P[(p - self.shapes[i - 1]):p, p:(p + self.shapes[i])])) + cp.multiply(self.bs[i - 1], self.P[p:(p + self.shapes[i]), 0])) p += self.shapes[i] p = 1 for i in range(0, len(self.shapes) - 1): constraints.append( cp.diag(self.P)[p:(p + self.shapes[i])] <= cp.multiply( (bl[i] + bu[i]), self.P[p:(p + self.shapes[i]), 0]) - np.multiply(bl[i], bu[i])) p += self.shapes[i] obj = (self.Ws[-1][yp] - self.Ws[-1][y0]) * self.P[ -self.shapes[-2]:, 0] + self.bs[-1][yp] - self.bs[-1][y0] self.prob = cp.Problem(cp.Maximize(obj), constraints) # self.prob.solve(solver=cp.MOSEK, verbose=True, mosek_params={ # # 'optimizerMaxTime': self.timeout, # 'MSK_DPAR_OPTIMIZER_MAX_TIME': self.timeout, # # 'numThreads': self.threads, # 'MSK_IPAR_NUM_THREADS': self.threads, # # 'lowerObjCut': 0., # 'MSK_DPAR_LOWER_OBJ_CUT': 0., # }) self.prob.solve(solver=cp.SCS, verbose=True, warm_start=True, eps=1e-2) print('status:', self.prob.status) print('optimal value:', self.prob.value)
def optim_with_cvxpy2(rtns,levs,mns,mcovs,headers,labels,worst,log_tdiscount,row_weight,ob): barrier=worst+1 merit=pd.DataFrame(index=headers,columns=labels) nrows,ncols=rtns.shape nlevs=len(levs) alloc=np.ones((nlevs,ncols),dtype='float64') prtns=np.zeros((nlevs,nrows),dtype='float64') xx=cp.Variable(ncols) for i in range(nlevs): lev=levs[i] levreturn=(rtns*lev) print("Risk Aversion: ",lev) if ob=='MV': constraints =[sum(xx)==1, 0<=xx, xx<=1] #Long-only portfolios objective=cp.Minimize(-cp.sum(cp.multiply(mns,xx)) + lev*cp.quad_form(xx,mcovs)/2.0) prob=cp.Problem(objective,constraints) result=prob.solve(eps_abs=1e-7,eps_rel=1e-7) xxvalue=xx.value prtns[i]=np.dot(rtns,xxvalue) merit['M_objective'][headers[i]]= np.sum(mns*xxvalue) - levs[i]*np.dot(np.dot(xxvalue,mcovs),xxvalue.T)/2.0 merit['W_objective'][headers[i]]= np.sum(np.multiply(row_weight,(np.log1p(np.dot(levreturn,xxvalue.T))+log_tdiscount))) elif ob=='LLS': constraints =[sum(xx)==1, 0<=xx, xx<=1, -1.0+barrier <= levreturn @ xx ] #Long-only portfolios objective=cp.Maximize(cp.sum(cp.multiply(row_weight,cp.log1p(levreturn @ xx)+log_tdiscount))) prob=cp.Problem(objective,constraints) result=prob.solve(abstol=1e-7,reltol=1e-7,verbose=False)/nrows xxvalue=xx.value if xxvalue is None: print('WARNING!!!! cvxpy problem appears not feasible.') raise prtns[i]=np.dot(rtns,xxvalue) merit['M_objective'][headers[i]]= sum(mns*xxvalue) - levs[i]*np.dot(np.dot(xxvalue,mcovs),xxvalue.T)/2.0 merit['W_objective'][headers[i]]= np.sum(np.multiply(row_weight,(np.log1p(np.dot(levreturn,xxvalue.T))+log_tdiscount))) alloc[i]=xxvalue merit['norm2'][headers[i]] = np.dot(xxvalue,xxvalue) return (prtns[::].T,alloc[::],pd.DataFrame.copy(merit,deep=True))
def square_optimize6_6(): x_2 = [1.5, 1, 0.85] x_1 = [3, -8.2, -1.95] x = cp.Variable(shape=(3)) obj = cp.Minimize(x_2 * x**2 + x_1 * x) cond_matrix = [ [1, 0, 1], [-1, 2, 0], [0, 1, 2], ] value = [2, 2, 3] cond_matrix = np.array(cond_matrix) cond = [ cp.sum(cp.multiply(cond_matrix[0], x)) <= value[0], cp.sum(cp.multiply(cond_matrix[1], x)) <= value[1], cp.sum(cp.multiply(cond_matrix[2], x)) <= value[2], cp.sum(x) == 3 ] func = cp.Problem(obj, cond) func.solve() print(func.value)
def add_type_specific(self, baseProblem): # Problem Specific variables and constraints baseProblem.b = cvx.Variable(name="offset") # shift point_distances = cvx.multiply( baseProblem.Y, baseProblem.X * baseProblem.omega + baseProblem.b) baseProblem.loss = cvx.sum(cvx.pos(1 - point_distances)) baseProblem.weight_norm = cvx.norm(baseProblem.omega, 1) baseProblem._constraints.extend([ baseProblem.weight_norm <= baseProblem.initL1, baseProblem.loss <= baseProblem.initLoss ])
def test_sum_squares_vector(self) -> None: alpha = cp.Parameter(shape=(2, ), pos=True, value=[1.0, 1.0]) beta = cp.Parameter(pos=True, value=20) kappa = cp.Parameter(pos=True, value=10) w = cp.Variable(2, pos=True) h = cp.Variable(2, pos=True) problem = cp.Problem( cp.Minimize(cp.sum_squares(alpha + h)), [cp.multiply(w, h) >= beta, cp.sum(alpha + w) <= kappa]) gradcheck(problem, gp=True, atol=1e-1) perturbcheck(problem, gp=True, atol=1e-1)