Ejemplo n.º 1
0
def mip_prob():
    # {LP, MIP}
    x = cp.Int(1)
    prob = cp.Problem(cp.Minimize(x),[x >= 0])
    return CVXProblem(problemID="mip_prob",
                      problem=prob,
                      opt_val=0.0)
def eqAssign(Y, C, minC=1, accurateAssign=False):

    n, nF = Y.shape
    nC = C.shape[0]
    assert C.shape[1] == nF

    YCdist = np.zeros((n, nC))
    for i in range(n):
        for j in range(nC):
            YCdist[i, j] = np.linalg.norm(Y[i] - C[j], ord=2)

    if accurateAssign:
        X = cvx.Int(n, nC)
    else:
        X = cvx.Variable(n, nC)

    obj = cvx.sum_entries(cvx.mul_elemwise(YCdist, X))

    cons = [
        cvx.sum_entries(X, axis=1) == 1,
        cvx.sum_entries(X, axis=0) >= minC, 0 <= X, X <= 1
    ]

    prob = cvx.Problem(cvx.Maximize(obj), cons)

    # Solve
    if accurateAssign:
        prob.solve(solver=cvx.ECOS_BB)  #, mi_max_iters=100
        Xopt = X.value
        assign = np.zeros(n)
        for i in range(n):
            for j in range(nC):
                if Xopt[i, j] > 0.9:
                    assign[i] = j
                    break
    else:
        prob.solve(solver=cvx.ECOS)  # , mi_max_iters=100
        Xopt = X.value
        #assign = np.argmax(Xopt, axis=1).ravel()
        assign = np.zeros(n, dtype=int)
        for i in range(n):
            maxX = 0
            maxJ = 0
            for j in range(nC):
                if Xopt[i, j] > maxX:
                    maxX = Xopt[i, j]
                    maxJ = j
            assign[i] = np.round(maxJ)

    return assign, Xopt, prob.status
def cvxpySolver(A, B):
    # declare the integer-valued optimization variable
    x = cvxpy.Int(variablesNum + 1)

    # set up the L2-norm minimization problem
    obj = cvxpy.Minimize(cvxpy.norm(list(map(list, zip(*A))) * x - B, 1))
    #obj = cvxpy.Minimize(cvxpy.norm(A * x - B, 2))
    prob = cvxpy.Problem(obj)   

    # solve the problem using an appropriate solver
    sol = prob.solve(solver = 'ECOS_BB')    

    # the optimal value of x is
    C = x.value
    C = np.matrix.tolist(C)
    C = list(map(list, zip(*C)))[0]
    print("Int: C = ", C)
    for i in range(0, len(C)):
        C[i] = round(C[i])
    print("Round Int: C = ", C)   
    return C
Ejemplo n.º 4
0
    def _minimize_q(self, n, half_n, orig_loss, cost):
        """
        Minimize over q while keeping epsilon and w constant.
        :param n: the number of instances
        :param half_n: half of n
        :param orig_loss: the original loss calculations
        :param cost: cost: the cost vector, has length of size of instances
        """

        # Setup variables and constants
        epsilon = self._old_epsilon
        w = self._old_w
        q = cvx.Int(n)

        # Calculate constants - see comment above
        cnst = self.gamma * w.dot(w)
        epsilon_diff_eta = epsilon - orig_loss

        # Setup CVX problem
        func = cnst
        for i in range(n):
            func += q[i] * epsilon_diff_eta[i]

        constraints = [0 <= q, q <= 1]
        cost_for_q = 0.0
        for i in range(half_n):
            constraints.append(q[i] + q[i + half_n] == 1)
            cost_for_q += cost[i + half_n] * q[i + half_n]
        constraints += [cost_for_q <= self.total_cost]

        prob = cvx.Problem(cvx.Minimize(func), constraints)
        prob.solve(solver=cvx.ECOS_BB, verbose=self.verbose, parallel=True)

        q_value = np.array(q.value).flatten()
        self._old_q = []
        for i in range(n):
            self._old_q.append(round(q_value[i]))
        self._old_q = np.copy(np.array(self._old_q, dtype=int))
Ejemplo n.º 5
0
def mip_prob():
    # {LP, MIP}
    x = cp.Int(1)
    return cp.Problem(cp.Minimize(x))
Ejemplo n.º 6
0
     [1631203151, 2039156791, -1073442812, 1],
     [-1736958565, 2037741599, 635288874, 1],
     [-210093103, 354655146, -718127209, 1]]
B = [-955806000, -407953638, -3774700162, -564748247]

A = [[-68308474.0, -68308472.0, -341366010.0, 1],
     [-47581579.0, -47581577.0, -1504785200.0, 1],
     [-18930757.0, -18930755.0, -2143493400.0, 1],
     [-19290484.0, -19290482.0, -2057089700.0, 1]]
B = [-68308471.0, -47581576.0, -18930754.0, -19290481.0]
print("A = ", A)
print("rank A = ", np.linalg.matrix_rank(A))
print("B = ", B)

# declare the integer-valued optimization variable
x = cvxpy.Int(n)

# set up the L2-norm minimization problem
obj = cvxpy.Minimize(cvxpy.norm(list(map(list, zip(*A))) * x - B, 1))
prob = cvxpy.Problem(obj)

# solve the problem using an appropriate solver
# sol = prob.solve(solver = 'ECOS_BB')
sol = prob.solve()

# the optimal value of x is

C = x.value
C = np.matrix.tolist(C)
C = list(map(list, zip(*C)))[0]
print("Int: C = ", C)
Ejemplo n.º 7
0
 def addIntVar(self, name):
     # name is unused for cvxpy
     return cvxpy.Int()
import cvxpy as cp
import numpy as np

# goal is to solve the problem in example_survey_responses.txt with an optimizer
# define a new fxn for every constraint, then add them all up for the obj function? (each sub function returns
# 1 if met and -1000 if not met)

#ages
a1 = cp.Int()
a2 = cp.Int()
a3 = cp.Int()
a4 = cp.Int()
a5 = cp.Int()
a6 = cp.Int()
a7 = cp.Int()
a8 = cp.Int()
a9 = cp.Int()
a10 = cp.Int()

#household indicators
hh1_1 = cp.Int()
hh1_2 = cp.Int()
hh1_3 = cp.Int()
hh1_4 = cp.Int()
hh1_5 = cp.Int()
hh1_6 = cp.Int()
hh1_7 = cp.Int()
hh1_8 = cp.Int()
hh1_9 = cp.Int()
hh1_10 = cp.Int()
hh2_1 = cp.Int()
## generate A and y
#m, n = 10, 10
#A = np.random.randn(m,n)
#B = np.random.randn(m)

## declare the integer-valued optimization variable
#x = cvxpy.Int(n)

A = [[614071408, 1569877410, -1844044328, 1],
     [1631203151, 2039156791, -1073442812, 1],
     [-1736958565, 2037741599, 635288874, 1],
     [-210093103, 354655146, -718127209, 1]]
B = [-955806000, -407953638, -3774700162, -564748247]
#x = cvxpy.Int(4)
x = cvxpy.Int(4)
x2 = cvxpy.Variable(4)

# set up the L2-norm minimization problem
obj = cvxpy.Minimize(cvxpy.norm(A * x - B, 2))
prob = cvxpy.Problem(obj)
obj2 = cvxpy.Minimize(cvxpy.norm(A * x2 - B, 2))
prob2 = cvxpy.Problem(obj2)

print("prob is DCP:", prob.is_dcp())
print("prob2 is DCP:", prob2.is_dcp())

# solve the problem using an appropriate solver
sol = prob.solve(solver='ECOS_BB')
sol2 = prob2.solve(solver='ECOS_BB')
]  # the amount of required reserve (over demand) in each of the three hours

assets = [0, 1, 2]  # There are three assets
hours = [0, 1, 2]  # There are three hours
no_of_assets = len(assets)
no_of_hours = len(hours)

# VARIABLES

# 1) p_jk: the output power of unit j during period k
# 2) y_jk: a binary variable that is equal to 1, if unit j is started up at the beginnig of period k and 0, otherwise
# 3) z_jk: a binary variable that is equal to 1, if unit j is shut down at the beginning of period k, and 0, otherwise
# 4) v_jk: a binary variable that is equal to 1, if unit j is online during period k and 0, otherwise

p_jk = cvx.Variable(no_of_assets, no_of_hours)
y_jk = cvx.Int(no_of_assets, no_of_hours)
z_jk = cvx.Int(no_of_assets, no_of_hours)
v_jk = cvx.Int(no_of_assets, no_of_hours)

# OBJECTIVE

# For each hour, for each unit, minimise: p_jk*B_j +  y_jk*C_j + z_jk*E_j + v_jk*A_j
# where,
# p_jk: the output power of unit j during period k
# B_j: the variable cost of unit j
# y_jk: a binary variable that is equal to 1, if unit j is started up at the beginnig of period k and 0, otherwise
# C_j: the startup cost of unit j
# z_jk: a binary variable that is equal to 1, if unit j is shut down at the beginning of period k, and 0, otherwise
# E_j: the shutdown cost of unit j
# v_jk: a binary variable that is equal to 1, if unit j is online during period k and 0, otherwise
# A_j: the fixed cost of unit j
Ejemplo n.º 11
0
#
# A sample code to solve a knapsack_problem with cvxpy
#
# Author: Atsushi Sakai (@Atsushi_twi)
#

import cvxpy
import numpy as np

size = np.array([21, 11, 15, 9, 34, 25, 41, 52])
weight = np.array([22, 12, 16, 10, 35, 26, 42, 53])
capacity = 100

x = cvxpy.Int(size.shape[0])
objective = cvxpy.Maximize(weight * x)
constraints = [capacity >= size * x]
constraints += [x >= 0]

prob = cvxpy.Problem(objective, constraints)
prob.solve(solver=cvxpy.ECOS_BB)
result = [round(ix[0, 0]) for ix in x.value]

print("status:", prob.status)
print("optimal value", prob.value)
print("size :", size * x.value)
print("result x:", result)