コード例 #1
0
    def test_list_input(self) -> None:
        """Test that list input is rejected.
        """
        with self.assertRaises(Exception) as cm:
            cp.max([cp.Variable(), 1])
        self.assertTrue(
            str(cm.exception) in
            ("The input must be a single CVXPY Expression, not a list. "
             "Combine Expressions using atoms such as bmat, hstack, and vstack."
             ))

        with self.assertRaises(Exception) as cm:
            cp.norm([1, cp.Variable()])
        self.assertTrue(
            str(cm.exception) in
            ("The input must be a single CVXPY Expression, not a list. "
             "Combine Expressions using atoms such as bmat, hstack, and vstack."
             ))

        x = cp.Variable()
        y = cp.Variable()
        with self.assertRaises(Exception) as cm:
            cp.norm([x, y]) <= 1
        self.assertTrue(
            str(cm.exception) in
            ("The input must be a single CVXPY Expression, not a list. "
             "Combine Expressions using atoms such as bmat, hstack, and vstack."
             ))
コード例 #2
0
def max_min_dccp(n_samples, var_importance):
    """Solve MaxMin Diversity problem on hypercube

    :nsamples : number of samples 
    :var_importance:  list of floats, specifying importance of each variable
    """
    radii = np.ones(n_samples)  # radii
    v_scale = cvx.vec(var_importance)

    c = cvx.Variable((n_samples, len(var_importance)))
    constr = []
    for i in range(n_samples - 1):
        for j in range(i + 1, n_samples):
            # distance vector is scaled by variable importance
            d = cvx.multiply(cvx.vec(c[i, :] - c[j, :]), v_scale)
            constr.append(cvx.norm(d, 2) >= radii[i] + radii[j])

    # minimize the size of the square to fit the given spheres
    # (by minimzing the largest component of any center vector)
    prob = cvx.Problem(
        cvx.Minimize(cvx.max(cvx.max(cvx.abs(c), axis=1) + radii)), constr)
    prob.solve(method='dccp', solver='ECOS', ep=1e-2, max_slack=1e-2)

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

    # shift to positive numbers
    coords = c.value - np.min(c.value)
    # scale maximum coordinate to 1
    coords /= np.max(coords)

    return coords
コード例 #3
0
def one_shot_compressed_sensing_decode(x0, y, p_matrix, delta):
    _size = y.shape[0]
    _app = p_matrix.shape[0]
    use = []
    use.append(x0)
    X = cvx.Variable((_app))
    #print(k)
    objective = cvx.Minimize(cvx.norm(X, 1))
    #if abs(k)>p_matrix[-1]:
    #    constraints = [(X.T*p_matrix-k)<=delta, (X.T*p_matrix-k)>=-delta]
    #else:
    #constraints = [(X.T*p_matrix-k)<=delta, (X.T*p_matrix-k)>=-delta,cvx.max(X)<=1,cvx.min(X)>=-1]
    constraints = [(X.T * p_matrix - k) <= delta,
                   (X.T * p_matrix - k) >= -delta,
                   cvx.max(X) <= 1,
                   cvx.min(X) >= -1]
    prob = cvx.Problem(objective, constraints)
    prob.solve(solver=cvx.ECOS_BB)
    if X.value is None:
        X = cvx.Variable((_app))
        #constraints = [(X.T*p_matrix-k)<=20, (X.T*p_matrix-k)>=-20,cvx.max(X)<=1,cvx.min(X)>=-1]
        #constraints = [(X.T*p_matrix-k)<=20, (X.T*p_matrix-k)>=-20]
        constraints = [cvx.max(X) <= 1, cvx.min(X) >= -1]
        prob = cvx.Problem(objective, constraints)
        prob.solve(solver=cvx.ECOS_BB)
        if X.value is None:
            return []
    print(X.value)
    return np.abs(x0 - X.value)
コード例 #4
0
    def e19_controlled_load(self, verbose=False):
        """Implements the charging control for the PG&E E19 rate schedule. This is not specific to EVs but has been how
        sites like Google campus traditionally are charged for their loads. It includes TOU and demand charges.
        Please refer to the first control method, `sdge_controlled_load', for comments on the
        optimization set up and constraints which are common between the two.
        """
        peak_inds, partpeak_inds, offpeak_inds, energy_prices, rate_demand_peak, rate_demand_partpeak, rate_demand_overall = e19_values(
        )

        schedule = cvx.Variable((96, self.num_sessions))
        obj = cvx.matmul(cvx.sum(schedule, axis=1),
                         energy_prices.reshape(
                             (np.shape(energy_prices)[0], 1)))  # TOU
        obj += rate_demand_overall * cvx.max(cvx.sum(
            schedule, axis=1))  # Demand charge on the whole day
        obj += rate_demand_peak * cvx.max(
            cvx.sum(schedule[peak_inds, :],
                    axis=1))  # Peak period demand charge
        obj += rate_demand_partpeak * cvx.max(
            cvx.sum(schedule[partpeak_inds, :],
                    axis=1))  # Shoulder period demand charge

        constraints = [schedule >= 0]
        for i in range(self.num_sessions):
            constraints += [
                schedule[:, i] <= np.maximum(np.max(self.power[:, i]),
                                             self.charge_rate)
            ]
            if self.departure_inds[i] >= self.arrival_inds[i]:
                if self.arrival_inds[i] > 0:
                    constraints += [
                        schedule[np.arange(0, int(self.arrival_inds[i])), i] <=
                        0
                    ]
                if self.departure_inds[i] < 96:
                    constraints += [
                        schedule[np.arange(int(self.departure_inds[i]), 96), i]
                        <= 0
                    ]
            else:
                constraints += [
                    schedule[np.arange(int(self.departure_inds[i]
                                           ), int(self.arrival_inds[i])), i] <=
                    0
                ]

        constraints += [0.25 * cvx.sum(schedule, axis=0) == self.energies]

        prob = cvx.Problem(cvx.Minimize(obj), constraints)
        result = prob.solve(solver=cvx.MOSEK)
        # Not likely necessary since there is no cap constraint, but this was implemented just in case this method
        # throws an error:
        if verbose:
            print('The objective result: ', result)
        if schedule.value is None:
            print('Optimization failed')
        else:
            self.e19_controlled_power = schedule.value
            self.controlled_total_load = np.sum(schedule.value, axis=1)
コード例 #5
0
    def controlled_load(self, num_sessions, charge_rate, arrival_inds,
                        departure_inds, power, energies, energy_prices,
                        rate_demand_peak, rate_demand_partpeak,
                        rate_demand_overall, peak_inds, partpeak_inds):
        """
            Predict controlled load
        """
        schedule = cvx.Variable((96, num_sessions))
        obj = cvx.matmul(
            cvx.sum(schedule, axis=1),
            energy_prices.reshape((np.shape(energy_prices)[0], 1)))
        obj += rate_demand_overall * cvx.max(cvx.sum(schedule, axis=1))
        obj += rate_demand_overall * cvx.max(cvx.sum(schedule, axis=1))
        obj += rate_demand_peak * cvx.max(
            cvx.sum(schedule[peak_inds, :], axis=1))
        obj += rate_demand_partpeak * cvx.max(
            cvx.sum(schedule[partpeak_inds, :], axis=1))

        constraints = [schedule >= 0]
        for i in range(num_sessions):
            constraints += [
                schedule[:, i] <= np.maximum(np.max(power[:, i]), charge_rate)
            ]
            if departure_inds[i] >= arrival_inds[i]:
                if arrival_inds[i] > 0:
                    constraints += [
                        schedule[np.arange(0, int(arrival_inds[i])), i] <= 0
                    ]
                if departure_inds[i] < 96:
                    constraints += [
                        schedule[np.arange(int(departure_inds[i]), 96), i] <= 0
                    ]
            else:
                constraints += [
                    schedule[np.arange(int(departure_inds[i]
                                           ), int(arrival_inds[i])), i] <= 0
                ]

        energies = 0.25 * np.sum(power, axis=0)
        max_energies = np.zeros((num_sessions, ))
        for i in range(num_sessions):
            if departure_inds[i] >= arrival_inds[i]:
                max_energies[i] = 0.25 * charge_rate * (departure_inds[i] -
                                                        arrival_inds[i])
            else:
                max_energies[i] = 0.25 * charge_rate * ((departure_inds[i]) +
                                                        (96 - arrival_inds[i]))
        where_violation = np.where((max_energies - energies) < 0)[0]

        energies[where_violation] = max_energies[where_violation]
        constraints += [0.25 * cvx.sum(schedule, axis=0) == energies]

        prob = cvx.Problem(cvx.Minimize(obj), constraints)
        result = prob.solve(solver=cvx.MOSEK)

        return schedule.value, power, len(where_violation)
コード例 #6
0
    def test_non_quadratic(self) -> None:
        x = Variable()
        y = Variable()
        z = Variable()

        s = cp.max(vstack([x, y, z]))**2
        self.assertFalse(s.is_quadratic())

        t = cp.max(vstack([x**2, power(y, 2), z]))
        self.assertFalse(t.is_quadratic())
コード例 #7
0
 def cost(self):
     power = -self.terminals[0].power_var
     T, S = self.terminals[0].power_var.shape
     # if self.energy is None:
     #     self.energy = cvx.Variable(self.terminals[0].power_var.shape)
     cost = cvx.sum(0.25 * power * np.reshape(self.rate_e, (1, 96)))
     cost += cvx.max(power[self.rate_d['max_demand_ind']
                           [0]]) * self.rate_d['max_demand']
     cost += cvx.max(power[self.rate_d['max_peak_demand_ind']
                           [0]]) * self.rate_d['max_peak_demand']
     cost += cvx.max(power[self.rate_d['max_part_peak_demand_ind']
                           [0]]) * self.rate_d['max_part_peak_demand']
     cost = cvx.reshape(cost, (1, S))
     return cost
コード例 #8
0
ファイル: fp_disc.py プロジェクト: psavine42/juststuff
    def as_objective(self, **kwargs):
        """ minimize the x and y domain projections
            todo I am STUCK HERE
        """
        centroids = np.asarray(self.space.faces.centroids)
        n = self._area
        mx = cvx.multiply(centroids[:, 0], self.stacked)
        my = cvx.multiply(centroids[:, 1], self.stacked)

        # my = cvx.multiply(centroids[:, 1], self.stacked)
        u = Variable(shape=n)

        ex = cvx.max(mx - cvx.sum(mx) / n)
        ey = cvx.max(my - cvx.sum(my) / n)
        return Minimize(ex + ey)
コード例 #9
0
    def __init__(self, K, J, **kwargs):
        super().__init__(K, J, **kwargs)
        self.F = cvx.Variable((self.K, self.J), nonneg=True)
        self.Fk = cvx.Parameter((self.K, self.J), nonneg=True)
        self.Pk = cvx.Parameter((self.K, self.J), nonneg=True)
        self.Pmax = cvx.Parameter(nonneg=True)
        self.N = cvx.Parameter(nonneg=True)
        self.df = cvx.Parameter(nonneg=True)
        self.rho = cvx.Parameter((self.K, self.J), nonneg=True)
        self.lam = cvx.Parameter(nonneg=True)

        self.obj = 0
        for k in range(self.K):
            num = 0
            for j in range(self.J):
                num += self.rho[k, j] * self.Pk[k, j] * self.F[k, j]
            self.obj += cvx.log(1 + num) - (cvx.max(self.rho[k, :]) -
                                            cvx.min(self.rho[k, :])) / 2

        constraints = [  #cvx.norm(self.F - self.Fk, 1) <= self.delta,
            cvx.sum(self.F, axis=0) <= self.N,
            cvx.sum(self.F, axis=0) >= 1,
            cvx.sum(self.F, axis=1) <= self.df, self.F <= 1
        ]
        for j in range(self.J):
            for k in range(self.K):
                self.obj += self.lam * ((self.Fk[k, j]**2 - self.Fk[k, j]) +
                                        (2 * self.Fk[k, j] - 1) *
                                        (self.F[k, j] - self.Fk[k, j]))
            constraints.append(self.Pk[:, j] * self.F[:, j] <= self.Pmax)
            constraints.append(self.Pk[:, j] * self.F[:, j] >= 0)

        self.prob = cvx.Problem(cvx.Maximize(self.obj), constraints)
コード例 #10
0
    def __init__(self, m, n, r, eps=1e-4):
        cvxopt.glpk.options["msg_lev"] = "GLP_MSG_OFF"
        self.m = m
        self.n = n
        self.r = r
        self.eps = eps
        self.last_move = None
        self.a = cp.Parameter(m)        # Adjustments
        self.C = cp.Parameter((m, m))   # C: Gradient inner products, G^T G
        self.Ca = cp.Parameter(m)       # d_bal^TG
        self.rhs = cp.Parameter(m)      # RHS of constraints for balancing

        self.alpha = cp.Variable(m)     # Variable to optimize

        obj_bal = cp.Maximize(self.alpha @ self.Ca)   # objective for balance
        constraints_bal = [self.alpha >= 0, cp.sum(self.alpha) == 1,  # Simplex
                           self.C @ self.alpha >= self.rhs]
        self.prob_bal = cp.Problem(obj_bal, constraints_bal)  # LP balance

        obj_dom = cp.Maximize(cp.sum(self.alpha @ self.C))  # obj for descent
        constraints_res = [self.alpha >= 0, cp.sum(self.alpha) == 1,  # Restrict
                           self.alpha @ self.Ca >= -cp.neg(cp.max(self.Ca)),
                           self.C @ self.alpha >= 0]
        constraints_rel = [self.alpha >= 0, cp.sum(self.alpha) == 1,  # Relaxed
                           self.C @ self.alpha >= 0]
        self.prob_dom = cp.Problem(obj_dom, constraints_res)  # LP dominance
        self.prob_rel = cp.Problem(obj_dom, constraints_rel)  # LP dominance

        self.gamma = 0     # Stores the latest Optimum value of the LP problem
        self.mu_rl = 0     # Stores the latest non-uniformity
コード例 #11
0
 def objective(self, **kwargs):
     # minimze max(T_k ) if k is a source
     # T_k = 0 if k is a sink
     # T_k >= max( norm(x_j - x_k) + T_j | s.t. E arc from k to j )
     # ->
     # T_k >=
     return Minimize(cvx.max())
コード例 #12
0
    def fit(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))
        constraints = []
        # Additional variables representing the actual predictions.
        log_reg = x @ w
        Z = [cp.log_sum_exp(log_reg[i]) for i in range(nsamples)]
        log_likelihood = cp.sum(
            cp.sum([cp.multiply(yc[:, c], log_reg[:, c]) for c in range(nclasses)])) - cp.sum(Z)

        reg = cp.max(cp.sum(log_reg), axis=0)

        # Start the training process
        obj_func = - log_likelihood / nsamples + self.alpha * reg
        problem = cp.Problem(cp.Minimize(obj_func), constraints)
        problem.solve()

        self.weights = w.value
コード例 #13
0
ファイル: hw3_ilu.py プロジェクト: rayjim/python_proj
def nullspace(A, atol=1e-13, rtol=0):
     A = np.atleast_2d(A)
     u, s, vh = svd(A)
     tol = max(atol, rtol * s[0])
     nnz = (s >= tol).sum()
     ns = vh[nnz:].conj().T
     return ns
コード例 #14
0
def one_shot_compressed_sensing_decode(x0,y,p_matrix,delta):
    _app = p_matrix.shape[0]
    #print(_app)
    X = cvx.Variable((_app))
    #print(k)
    objective = cvx.Minimize(cvx.norm(X,1))
    #print(y)
    #if abs(k)>p_matrix[-1]:
    #    constraints = [(X.T*p_matrix-k)<=delta, (X.T*p_matrix-k)>=-delta]
    #else:
    #constraints = [(X.T*p_matrix-k)<=delta, (X.T*p_matrix-k)>=-delta,cvx.max(X)<=1,cvx.min(X)>=-1]
    constraints = [(X.T*p_matrix-y)<=delta, (X.T*p_matrix-y)>=-delta,cvx.max(X)<=1,cvx.min(X)>=0]
    prob = cvx.Problem(objective, constraints)
    prob.solve(solver=cvx.ECOS_BB)
    if X.value is None:
        #print("error")
        #print(x0.shape[0])
        return x0.shape[0]
        '''
        X = cvx.Variable((_app))
        #constraints = [(X.T*p_matrix-k)<=20, (X.T*p_matrix-k)>=-20,cvx.max(X)<=1,cvx.min(X)>=-1]
        #constraints = [(X.T*p_matrix-k)<=20, (X.T*p_matrix-k)>=-20]
        constraints = [cvx.max(X)<=1,cvx.min(X)>=-1]
        prob = cvx.Problem(objective, constraints)
        prob.solve(solver=cvx.ECOS_BB)
        if X.value is None:
            return []
        '''
    #print(X.value)
    return np.sum(np.abs(x0-X.value))
コード例 #15
0
ファイル: test_dqcp.py プロジェクト: zxuen/cvxpy
 def test_max(self) -> None:
     x = cp.Variable(2, pos=True)
     obj = cp.max((1 - 2 * cp.sqrt(x) + x) / x)
     problem = cp.Problem(cp.Minimize(obj), [x[0] <= 0.5, x[1] <= 0.9])
     self.assertTrue(problem.is_dqcp())
     problem.solve(SOLVER, qcp=True)
     self.assertAlmostEqual(problem.objective.value, 0.1715, places=3)
コード例 #16
0
def get_diverse_teams_lineup(df, budget, pt_lim, teams):
    N = len(df)
    W = cp.Variable((N, 1), boolean=True)
    constrs = [cp.matmul(W.T, df['cost'].values.reshape(N, 1))<=budget,
               cp.matmul(W.T, df['proj'].values.reshape(N, 1))<=pt_lim,
               cp.sum(W)==9,
               cp.matmul(W.T, df['QB'].values.reshape(N, 1))==1,
               cp.matmul(W.T, df['RB'].values.reshape(N, 1))<=3,
               cp.matmul(W.T, df['WR'].values.reshape(N, 1))<=3,
               cp.matmul(W.T, df['TE'].values.reshape(N, 1))<=2,
               cp.matmul(W.T, df['TE'].values.reshape(N, 1))>=1,
               cp.matmul(W.T, df['K'].values.reshape(N, 1))==1,
               cp.matmul(W.T, df['DST'].values.reshape(N, 1))==1,
               cp.max(cp.matmul(W.T, df.iloc[:, 10:-1]))<=1]

    obj = cp.Maximize(cp.matmul(W.T, df['proj'].values.reshape(N, 1)))
    prob = cp.Problem(obj, constrs)
    prob.solve()
    W.value = W.value.round()
    idx = []
    for i, w in enumerate(W.value):
        if w == 1:
            idx.append(i)
    proj_pts = df.iloc[idx]['proj'].sum()
    lineup = df.iloc[idx]['player team pos proj cost'.split()]
    pos_map = {'QB': 1, 'RB': 2, 'WR': 3, 'TE': 4, 'K': 5, 'DST': 6}
    pos_num = [pos_map[pos] for pos in lineup['pos'].values]
    lineup['pos_num'] = pos_num
    lineup = lineup.sort_values('pos_num')
    lineup.drop('pos_num', axis=1, inplace=True)
    lineup = lineup.append(lineup.sum(numeric_only=True), ignore_index=True)
    return lineup, proj_pts
コード例 #17
0
    def test_max(self):
        x = cp.Variable(pos=True)
        y = cp.Variable(pos=True)

        alpha = cp.Parameter(value=0.5)
        beta = cp.Parameter(pos=True, value=3.0)
        kappa = cp.Parameter(pos=True, value=1.0)
        tau = cp.Parameter(pos=True, value=4.0)

        prod1 = x * y**alpha
        prod2 = beta * x * y**alpha
        obj = cp.Minimize(cp.max(cp.hstack([prod1, prod2])))
        constr = [x == kappa, y == tau]

        problem = cp.Problem(obj, constr)
        self.assertTrue(problem.is_dgp(dpp=True))
        problem.solve(SOLVER, gp=True, enforce_dpp=True)
        # max(1*2, 3*1*2) = 6
        self.assertAlmostEqual(problem.value, 6.0, places=4)
        self.assertAlmostEqual(x.value, 1.0)
        self.assertAlmostEqual(y.value, 4.0)

        alpha.value = 2
        beta.value = 0.5
        kappa.value = 2.0  # x
        tau.value = 3.0  # y
        problem.solve(SOLVER, gp=True, enforce_dpp=True)
        # max(2*9, 0.5*2*9) == 18
        self.assertAlmostEqual(problem.value, 18.0, places=4)
        self.assertAlmostEqual(x.value, 2.0)
        self.assertAlmostEqual(y.value, 3.0)
コード例 #18
0
def hinf_constraint(coefs, gamma, l1_trans=False):
    # constrain the H_inf norm of the response [coefs] <= gamma
    # using the equivalent SDP formulation from equation 4.42 of Dumitrescu
    # returns a list a cvx expression constraints
    T = len(coefs) - 1
    m, n = coefs[0].shape # m >= n, enforcing constraint on transpose system
    
    if l1_trans or T > 70:
        print('using l1 of transpose instead of h inf norm')
        ht_l1_norm = cvx.max(sum([cvx.norm(coef.T, p=1, axis=1) for coef in coefs]))
        return [ht_l1_norm <= gamma], ht_l1_norm
    
    constr = []
    hcoefs = cvx.bmat([[coef.T] for coef in coefs])
    Q = cvx.Variable((n*(T+1), n*(T+1)), PSD=True)
    # constraint 4.39, part 1
    # k == 0, diagonal of Q sums to gamma**2 I_n
    constr.append(
        sum([Q[n*t:n*(t+1), n*t:n*(t+1)] for t in range(T+1)]) == gamma**2*np.eye(n))
    # k > 0, k-th off-diagonal of Q sums to 0
    for k in range(1, T+1):
        constr.append(
            sum([Q[n*t:n*(t+1), n*(t+k):n*(t+1+k)] for t in range(T+1-k)]) == np.zeros((n, n)))
    # constraint 4.39, constrain to be PSD
    constr.append(
        cvx.bmat([[Q, hcoefs], [hcoefs.T, np.eye(m)]]) == cvx.Variable((n*(T+1)+m, n*(T+1)+m), PSD=True))
    return constr, (hcoefs, Q)
コード例 #19
0
    def execute(self):
        # Zmienna decyzyjna
        a = cvxpy.Variable((self.num_of_tasks, self.num_of_machines),
                           boolean=True)

        # Czasy wykonywania zadań
        sum = cvxpy.sum(a, axis=0, keepdims=True)
        sum_matrix = cvxpy.hstack([sum for i in range(self.num_of_tasks)])
        sum_matrix = cvxpy.reshape(sum_matrix,
                                   (self.num_of_tasks, self.num_of_machines))
        t = cvxpy.multiply(sum_matrix, self.t_peak)
        max_time = cvxpy.max(t, axis=1)

        # Koszty użycia maszyn
        e = cvxpy.multiply(a, self.t_peak * self.p)
        sum_of_expense = cvxpy.sum(e, axis=1)

        # Funkcja celu
        u = cvxpy.sum(max_time * self.w_t + sum_of_expense * self.w_e,
                      axis=0,
                      keepdims=True)

        # Ograniczenia
        subtasks_const = cvxpy.sum(a, axis=1).__eq__(self.tasks_subtasks)
        time_const = max_time.__le__(self.T)
        cost_const = sum_of_expense.__le__(self.M)

        # Rozwiązanie problemu
        problem = cvxpy.Problem(cvxpy.Minimize(u),
                                [subtasks_const, time_const, cost_const])
        problem.solve(solver=cvxpy.GLPK_MI)

        return a.value
コード例 #20
0
def compute_structure_preserving_embedding(A, C = 100.0, verbose = False):
    """
    Compute the structure-preserving embedding of a graph using CVXPY.

    This does not actually scale beyond 10 x 10 or so.

    Parameters
    ----------
    A: (n_nodes x n_nodes) adjacency matrix

    Returns
    -------
    E: (n_nodes x n_nodes) LLE embeddings
    """
    n_nodes, _ = A.shape

    K = cp.Variable((n_nodes, n_nodes), PSD = True)
    xi = cp.Variable(1)

    D = cp.bmat([[K[i, i] + K[j, j] - 2 * K[i, j] \
                  for j in range(n_nodes)] \
                  for i in range(n_nodes)])
    M = cp.max(D, axis = 1)

    objective = cp.Maximize(cp.trace(K @ A) - C * xi)
    constraints = [cp.trace(K) <= 1, xi >= 0, cp.sum(K) == 0]
    for i, j in itertools.combinations(range(n_nodes), 2):
        constraints += [D[i, j] >= (1 - A[i, j]) * M[i] - xi]

    problem = cp.Problem(objective, constraints)
    result = problem.solve(verbose = verbose, solver = "SCS")

    L, Z = np.linalg.eigh(K.value)
    return Z
コード例 #21
0
def peak(rates, infrastructure, interface, baseline_peak=0, **kwargs):
    agg_power = aggregate_power(rates, infrastructure)
    max_power = cp.max(agg_power)
    prev_peak = interface.get_prev_peak() * infrastructure.voltages[0] / 1000
    if baseline_peak > 0:
        return cp.maximum(max_power, baseline_peak, prev_peak)
    else:
        return cp.maximum(max_power, prev_peak)
コード例 #22
0
 def test_0D_conv(self) -> None:
     """Convolution with 0D input.
     """
     x = cvx.Variable((1, ))  # or cvx.Variable((1,1))
     problem = cvx.Problem(
         cvx.Minimize(cvx.max(cvx.conv([1.], cvx.multiply(1., x)))),
         [x >= 0])
     problem.solve(cvx.ECOS)
     assert problem.status == cvx.OPTIMAL
コード例 #23
0
ファイル: fp_cont.py プロジェクト: psavine42/juststuff
        def constraint_node(wi, wj, hi, hj):
            wa = Variable(pos=True)
            ha = Variable(pos=True)
            ha = Variable(pos=True)
            c = [
                wa <= wi + wj,
                ha <= cvx.max(hi + hj),
            ]

            return
コード例 #24
0
def solve_lp(payoff_matrix):
    # This is a helper function to compute the ground truth solution of the matrix
    # game. It's not used in the results presented.
    x = cp.Variable(payoff_matrix.shape[1])
    # The activity variables are created explicitly so we can access the duals.
    activity = cp.Variable(payoff_matrix.shape[0])
    prob = cp.Problem(cp.Minimize(cp.max(activity)),
                      [activity == payoff_matrix @ x,
                       cp.sum(x) == 1, x >= 0])
    prob.solve(solver=cp.CVXOPT)
    return prob.value, x.value, -prob.constraints[0].dual_value
コード例 #25
0
ファイル: test_atoms.py プロジェクト: zhouyonglong/cvxpy
    def test_max(self):
        """Test max.
        """
        # One arg, test sign.
        self.assertEqual(cp.max(1).sign, s.NONNEG)
        self.assertEqual(cp.max(-2).sign, s.NONPOS)
        self.assertEqual(cp.max(Variable()).sign, s.UNKNOWN)
        self.assertEqual(cp.max(0).sign, s.ZERO)

        # Test with axis argument.
        self.assertEqual(cp.max(Variable(2), axis=0, keepdims=True).shape, (1,))
        self.assertEqual(cp.max(Variable(2), axis=1).shape, (2,))
        self.assertEqual(cp.max(Variable((2, 3)), axis=0, keepdims=True).shape, (1, 3))
        self.assertEqual(cp.max(Variable((2, 3)), axis=1).shape, (2,))

        # Invalid axis.
        with self.assertRaises(Exception) as cm:
            cp.max(self.x, axis=4)
        self.assertEqual(str(cm.exception),
                         "Invalid argument for axis.")
コード例 #26
0
ファイル: test_grad.py プロジェクト: vishalbelsare/cvxpy
    def test_max(self) -> None:
        """Test gradient for max
        """
        expr = cp.max(self.x)
        self.x.value = [2, 1]
        self.assertItemsAlmostEqual(expr.grad[self.x].toarray(), [1, 0])

        expr = cp.max(self.A)
        self.A.value = np.array([[1, 2], [4, 3]])
        self.assertItemsAlmostEqual(expr.grad[self.A].toarray(), [0, 1, 0, 0])

        expr = cp.max(self.A, axis=0)
        self.A.value = np.array([[1, 2], [4, 3]])
        self.assertItemsAlmostEqual(expr.grad[self.A].toarray(),
                                    np.array([[0, 0], [1, 0], [0, 0], [0, 1]]))

        expr = cp.max(self.A, axis=1)
        self.A.value = np.array([[1, 2], [4, 3]])
        self.assertItemsAlmostEqual(expr.grad[self.A].toarray(),
                                    np.array([[0, 0], [0, 1], [1, 0], [0, 0]]))
コード例 #27
0
    def _xxx(self, obj):
        """ testing - todo remove"""
        if obj == 'rect':
            self._obj = Minimize(
                cvx.max(cvx.abs(X[:, 0]) + r) + cvx.max(cvx.abs(X[:, 1]) + r))
        elif obj == 'sqr':
            self._obj = Minimize(cvx.max(cvx.max(cvx.abs(X), axis=1) + r))
        else:
            # f0 =
            # f1 = Tij / Dij #  - 1 # Tij / Dij is not convex ?
            # f1 = 1 / Dij     # , -1)  # - 1
            # vbar = Variable(n, boolean=True)
            # f2 = 2 * cvx.sqrt(Cij * Tij) - 1
            # f3 = Dij / Tij  # * self._k
            # if verbose is True:
            #     print('dij', Dij.curvature)
            #     print('f0', f0.curvature)
            #     print('f1', f1.curvature)
            #     print('f3', f3.curvature)

            if obj == 'ar0':
                print('ar0', f0.shape, cvx.sum(f0).curvature)
コード例 #28
0
def cvar(v, lam, alpha):
    m = v.shape[0]
    p = cp.Variable(m, nonneg=True)
    obj = v @ p + lam * cp.sum(cp.entr(p)) - lam * np.log(m)

    constraints = [
        cp.max(p) <= 1.0 / (alpha * m),
        cp.sum(p) == 1,
    ]

    problem = cp.Problem(cp.Maximize(obj), constraints)
    problem.solve(solver=cp.MOSEK)
    return p.value
コード例 #29
0
    def minpeak_controlled_load(self, verbose=False):
        """Implements the charging control for a simple peak minimization control. Please refer to the first control
        method, `sdge_controlled_load', for comments on the optimization set up and constraints which are common
        between the two.
        """

        schedule = cvx.Variable((96, self.num_sessions))
        obj = cvx.max(
            cvx.sum(schedule, axis=1)
        )  # Minimize the peak total load reached at any time during the day

        constraints = [schedule >= 0]
        for i in range(self.num_sessions):
            constraints += [
                schedule[:, i] <= np.maximum(np.max(self.power[:, i]),
                                             self.charge_rate)
            ]
            if self.departure_inds[i] >= self.arrival_inds[i]:
                if self.arrival_inds[i] > 0:
                    constraints += [
                        schedule[np.arange(0, int(self.arrival_inds[i])), i] <=
                        0
                    ]
                if self.departure_inds[i] < 96:
                    constraints += [
                        schedule[np.arange(int(self.departure_inds[i]), 96), i]
                        <= 0
                    ]
            else:
                constraints += [
                    schedule[np.arange(int(self.departure_inds[i]
                                           ), int(self.arrival_inds[i])), i] <=
                    0
                ]

        constraints += [0.25 * cvx.sum(schedule, axis=0) == self.energies]

        prob = cvx.Problem(cvx.Minimize(obj), constraints)
        result = prob.solve(solver=cvx.MOSEK)

        self.minpeak_controlled_power = schedule.value
        # Not likely necessary since there is no cap constraint, but this was implemented just in case this method
        # throws an error:
        try:
            self.controlled_total_load = np.sum(schedule.value, axis=1)
        except:
            try:
                self.controlled_total_load = -1 * np.ones((96, ))
            except:
                donothing = 1
    def uniform_allocation():
        P = cp.Variable((n,1), name="P")
        x = np.ones((m,1))*B/m
        log_p = -np.multiply(a, x)
        source_node_logprob_constraint = [P[0] == np.log(1)]

        node_logprob_constraints = [ P[this_node] >= cp.max(cp.vstack([P[prev_node] + log_p[edge_from_prev] for (edge_from_prev, prev_node) in find_prev_node_and_edge(this_node)])) for this_node in range(1,n)]

        obj = cp.Minimize(P[-1])
        constraints = source_node_logprob_constraint + node_logprob_constraints
        prob = cp.Problem(obj, constraints)
        prob.solve()
        print("Status: " + str(prob.status))
        print("uniform P_max = " + str(np.exp(P.value[-1])))
コード例 #31
0
ファイル: test_derivative.py プロジェクト: xinyueshen/cvxpy
    def test_max(self) -> None:
        x = cp.Variable(pos=True)
        y = cp.Variable(pos=True)
        a = cp.Parameter(value=0.5)
        b = cp.Parameter(pos=True, value=1.5)
        c = cp.Parameter(pos=True, value=3.0)
        d = cp.Parameter(pos=True, value=1.0)

        prod1 = b * x * y**a
        prod2 = c * x * y**b
        obj = cp.Minimize(cp.max(cp.hstack([prod1, prod2])))
        constr = [x == d, y == b]
        problem = cp.Problem(obj, constr)
        gradcheck(problem, gp=True)
        perturbcheck(problem, gp=True)
コード例 #32
0
    def setUp(self):
        from cvxopt import matrix, normal, spdiag, misc, lapack
        from ubsdp import ubsdp

        m, n = 10, 10
        A = normal(m**2, n)

        # Z0 random positive definite with maximum e.v. less than 1.0.
        Z0 = normal(m,m)
        Z0 = Z0 * Z0.T
        w = matrix(0.0, (m,1))
        a = +Z0
        lapack.syev(a, w, jobz = 'V')
        wmax = max(w)
        if wmax > 0.9:  w = (0.9/wmax) * w
        Z0 = a * spdiag(w) * a.T

        # c = -A'(Z0)
        c = matrix(0.0, (n,1))
        misc.sgemv(A, Z0, c, dims = {'l': 0, 'q': [], 's': [m]}, trans = 'T', alpha = -1.0)

        # Z1 = I - Z0
        Z1 = -Z0
        Z1[::m+1] += 1.0

        x0 = normal(n,1)
        X0 = normal(m,m)
        X0 = X0*X0.T
        S0 = normal(m,m)
        S0 = S0*S0.T
        # B = A(x0) - X0 + S0
        B = matrix(A*x0 - X0[:] + S0[:], (m,m))

        X = ubsdp(c, A, B)

        (self.m, self.n, self.c, self.A, self.B, self.Xubsdp) = (m, n, c, A, B, X)
コード例 #33
0
ファイル: circle_packing.py プロジェクト: cvxgrp/dccp
__author__ = 'Xinyue'
import cvxpy as cvx
import numpy as np
import matplotlib.pyplot as plt
import dccp
np.random.seed(0)
n = 10
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.solve(method = 'dccp', solver='ECOS', ep = 1e-2, max_slack = 1e-2)

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
# 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])
コード例 #34
0
ファイル: hm3_ilu.py プロジェクト: rayjim/python_proj
val_ls_reg = np.max(np.abs(log(A * matrix(p_ls_reg))))
print p_ls_reg
print val_ls_reg

###########################################################################################
# solution 4
# chebshev approximation
p_chev = cp.Variable(m)
objective = cp.Minimize(cp.norm(A * p_chev - ones((n, 1)), "inf"))
constraints = [p_chev <= 1, p_chev >= 0]
p4 = cp.Problem(objective, constraints)
result = p4.solve()
f_4 = np.max(np.abs(log(A * matrix(p_chev.value))))
print p_chev.value
print f_4


###########################################################################################
# solution 5
# cvxpy
u = cp.Variable(1)
p_cp = cp.Variable(m)
objective = cp.Minimize(u)
constraints = [cp.max(matrix(A[i, :]) * p_cp, cp.inv_pos(matrix(A[i, :]) * p_cp)) <= u for i in range(n)]
constraints.extend([p_cp <= 1, p_cp >= 0])
p5 = cp.Problem(objective, constraints)
result = p5.solve()
f_5 = np.max(np.abs(log(A * matrix(p_cp.value))))
print p_cp.value
print f_5
コード例 #35
0
ファイル: hw5_3.py プロジェクト: rayjim/python_proj
from cvxpy import Minimize, Variable, Problem, max, abs, sum
import numpy as np

n = 3
N = 30
A = np.matrix([[-1, 0.4, 0.8], [1, 0, 0], [0, 1, 0]])
b = np.matrix([1, 0, 0.3]).T
x0 = zeros((n, 1))
xdes = np.matrix([7, 2, -6]).T
x = Variable(n, N + 1)
u = Variable(1, N)
objective = Minimize(sum(max(abs(u), 2 * abs(u) - 1)))
constraints1 = [x[:, 1 : N + 1] == A * x[:, 0:N] + b * u]
constraints2 = [x[:, 0] == x0]
constraints3 = [x[:, N] == xdes]
constraints = constraints1 + constraints2 + constraints3
prob1 = Problem(objective, constraints)
prob1.solve()
print u.value
step(range(30), u.value.T)
コード例 #36
0
ファイル: hm7_sep.py プロジェクト: rayjim/python_proj
#a1 = np.array([1,1]).T
#a2 = np.array([1,-5]).T
#a3 = np.array([-1,-1]).T
#b1 = 0
#b2 = 0
#b3 = 0
#######################

a1 = cp.Variable(2,1)
a2 = cp.Variable(2,1)
a3 = cp.Variable(2,1)
b1 = cp.Variable(1)
b2 = cp.Variable(1)
b3 = cp.Variable(1)
obj = cp.Minimize(0)
constraints1 = [a1.T*X-b1>=cp.max(a2.T*X-b2,a3.T*X-b3)+1]
constraints2 = [a2.T*Y-b2>=cp.max(a1.T*Y-b1,a3.T*Y-b3)+1]
constraints3 = [a3.T*Z-b3>=cp.max(a1.T*Z-b1,a2.T*Z-b2)+1]
constraints4 =[a1+a2+a3==0]
constraints5 =[b1+b2+b3==0]
constraints = constraints1+constraints2+constraints3#+constraints4+constraints5
pro = cp.Problem(obj,constraints)
pro.solve(solver=cp.CVXOPT)
a1 = np.array(a1.value.T).flatten()
a2 = np.array(a2.value.T).flatten()
a3 = np.array(a3.value.T).flatten()
b1 = b1.value
b2 = b2.value
b3 = b3.value

######################
コード例 #37
0
ファイル: hm3_data.py プロジェクト: rayjim/cvxpy
x=Variable (m,1)
objective = Minimize(normInf(matrix(A)*x-ones((n,1))))
constraints =[x>=0,x<=1]
pro = Problem(objective, constraints) 
result = pro.solve()
print x.value
val_ls_chev = np.max(np.abs(log(A*matrix(x.value))))
print val_ls_chev

#solution 5 cvxpy

from cvxpy import max
y=Variable (m,1)
Am = matrix(A)
qq = [max(Am[i,:]*y,inv_pos(Am[i,:]*y)) for i in range(n)]
objective1 = Minimize(max(*qq))
constraints1 =[y>=0,y<=1]
pro1 = Problem(objective1, constraints1) 
result1 = pro1.solve()
print y.value
val_ls_cvx = np.max(np.abs(log(A*matrix(y.value))))
print val_ls_cvx

#solution 6 cvxpy equvelent

z=Variable (m,1)
u = Variable(1)
qq = [(max(Am[i,:]*z,inv_pos(Am[i,:]*z))<=u) for i in range(n)]
objective2 = Minimize(u)
pp =[z>=0,z<=1]