Пример #1
0
    def __init__(self, flp: FacilityLocationProblem, x: list):
        self.flp = flp
        self.m = Model()

        # Creates the variables
        y = self.m.addVars(flp.n_facilities, flp.n_customers, name="y")
        v1 = self.m.addVars(flp.n_facilities, name="v+")
        v2 = self.m.addVars(flp.n_customers, name="v-")

        # Creates the objective
        expr = 0
        for i in range(flp.n_facilities):
            expr += v1[i]
        for j in range(flp.n_customers):
            expr += v2[j]
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        self.dc = []
        self.cc = []
        for i in range(flp.n_facilities):
            print(x[i])
            self.cc.append(
                self.m.addConstr(
                    y.sum(i, '*') - v1[i] <= flp.capacity[i] * x[i]))
        for j in range(flp.n_customers):
            self.dc.append(
                self.m.addConstr(y.sum('*', j) + v2[j] >= flp.demands[j]))
Пример #2
0
    def __init__(self, p: CuttingStockProblem):
        self.p = p
        self.m = Model('CS1')

        # Decision variables
        n_large_rolls = self.p.get_max_number_of_large_rolls()
        n_small_roll_types = len(self.p.demand)
        print(n_large_rolls, n_small_roll_types)
        y = self.m.addVars([i for i in range(n_large_rolls)],
                           lb=0,
                           ub=1,
                           vtype=GRB.CONTINUOUS,
                           name="y")
        z = self.m.addVars([j for j in range(n_small_roll_types)],
                           [i for i in range(n_large_rolls)],
                           lb=0,
                           ub=GRB.INFINITY,
                           vtype=GRB.CONTINUOUS,
                           name="x")

        # Objective function
        self.m.setObjective(y.sum('*'))

        # Constraints
        # Note that the argument passed to quicksum is a list, and the list is built using comprehension
        self.m.addConstrs(
            quicksum([
                self.p.width_small_rolls[i] * z[i, j]
                for i in range(n_small_roll_types)
            ]) <= self.p.width_large_rolls * y[j]
            for j in range(n_large_rolls))
        self.m.addConstrs(
            z.sum(i, '*') >= self.p.demand[i]
            for i in range(n_small_roll_types))
Пример #3
0
    def __init__(self,pp:ProcurementProblem,material:int,pi:float):
        """
        Creates an instance of the DW's subproblem
        for a given material and given pi, the dual
        variable value corresponding to the complicating constraints
        in the RMP.
        :param pp:
        :param product:
        :param pi:
        """

        self.pp = pp
        self.m = Model()
        self.material = material

        # The subproblem has only one decision variable
        self.x = self.m.addVar()

        # The objective function will be
        # (c_j - pi A_j)*x, where j = material
        expr = (self.pp.costs[material] - pi*self.pp.consumption[material]) * self.x
        self.m.setObjective(expr, GRB.MINIMIZE)

        # The constraints bind the value of x to a min and max production quantity
        self.m.addConstr(self.x <=  self.pp.max_production[material])
        self.m.addConstr(self.x >= self.pp.min_production[material])
Пример #4
0
class FullModel:
    def __init__(self, flp: FacilityLocationProblem):
        self.flp = flp
        self.m = Model()

        # Creates the variables
        self.y = self.m.addVars(flp.n_facilities, flp.n_customers, name="y")
        self.x = self.m.addVars(flp.n_facilities, vtype=GRB.BINARY, name="x")

        # Creates the objective
        expr = 0
        for i in range(flp.n_facilities):
            expr += flp.fixed_costs[i] * self.x[i]
            for j in range(flp.n_customers):
                expr += flp.delivery_costs[i][j] * self.y[i, j]
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        for i in range(flp.n_facilities):
            self.m.addConstr(self.y.sum(i, '*') <= flp.capacity[i] * self.x[i])
        for j in range(flp.n_customers):
            self.m.addConstr(self.y.sum('*', j) >= flp.demands[j])

    def solve(self):
        self.m.optimize()

    def print_solution(self):
        for i in range(self.flp.n_facilities):
            print('%s %g' % (self.x[i].varName, self.x[i].x))
        print('Obj: %g' % self.m.objVal)
Пример #5
0
    def __init__(self, pp: ProcurementProblem):
        """
        Builds an instance of the DW's RMP for the
        Procurement Problem.
        :param pp:
        """

        # Builds an instance of the model
        self.m = Model()
        self.pp = pp
        # In the following list it will store all columns added to RMP during the DW algorithm
        self.columns = []

        # Initially there is no variable,
        # but we will add them here
        # as we generate them
        self.u = []

        # Creates an empty objective
        self.m.setObjective(0, GRB.MINIMIZE)

        # Creates the complicating constraints
        self.compc = self.m.addConstr(0, GRB.GREATER_EQUAL, self.pp.demand,
                                      "cc")
        # Creates the convexity constraints
        self.convc = self.m.addConstr(0, GRB.EQUAL, 1)
Пример #6
0
class KnapsackProblemModel:

    def __init__(self,p:KnapsackProblem):
        self.p = p
        self.m = Model('knapsack')
        # Creates the decision variables
        self.x = self.m.addVars(len(p.rewards),vtype = GRB.BINARY,name = "x")

        # Creates the objective
        self.m.setObjective(quicksum([self.p.rewards[i] * self.x[i] for i in range(len(self.p.rewards))]),sense=GRB.MAXIMIZE)

        # Creates the constraint
        self.m.addConstr(quicksum([self.p.weights[i] * self.x[i] for i in range(len(self.p.weights))]) <= self.p.capacity)

    def addCover(self,indices:list,rhs:int):
        self.m.addConstr(quicksum([self.x[indices[i]] for i in range(len(indices))]) <= rhs)


    def solve(self):
        self.m.optimize()

    def printSolution(self):
        print("Objective ", self.m.objVal)
        for v in self.m.getVars():
            print('%s %g' % (v.varName, v.x))
Пример #7
0
    def __init__(self, p: AlloyProductionProblem):
        self.p = p
        self.m = Model('APP')

        # Creates the decision variables
        self.materials = list(p.availability.keys())
        chemicals = list(p.max_grade.keys())
        self.x = self.m.addVars(self.materials, name='x')

        # Creates the objective function
        expr = self.x.prod(p.cost)
        self.m.setObjective(expr, sense=GRB.MINIMIZE)

        # Creates the constraints
        # Min content
        self.m.addConstrs(
            quicksum([p.content[(k, m)] * self.x[m]
                      for m in self.materials]) >= p.min_grade[k] *
            self.x.sum('*') for k in chemicals)
        # Max content
        self.m.addConstrs(
            quicksum([p.content[(k, m)] * self.x[m]
                      for m in self.materials]) <= p.max_grade[k] *
            self.x.sum('*') for k in chemicals)
        # Availability
        self.m.addConstrs(self.x[m] <= p.availability[m]
                          for m in self.materials)
        # Demand
        self.m.addConstr(self.x.sum('*') >= p.demand)
Пример #8
0
    def __init__(self):

        self.m = Model()
        self.x = self.m.addVar(name="x")
        self.phi = self.m.addVar(name="phi")

        # Objective function
        self.m.setObjective(2 * self.x + self.phi, sense=GRB.MINIMIZE)
Пример #9
0
    def __init__(self,p:KnapsackProblem):
        self.p = p
        self.m = Model('knapsack')
        # Creates the decision variables
        self.x = self.m.addVars(len(p.rewards),vtype = GRB.BINARY,name = "x")

        # Creates the objective
        self.m.setObjective(quicksum([self.p.rewards[i] * self.x[i] for i in range(len(self.p.rewards))]),sense=GRB.MAXIMIZE)

        # Creates the constraint
        self.m.addConstr(quicksum([self.p.weights[i] * self.x[i] for i in range(len(self.p.weights))]) <= self.p.capacity)
Пример #10
0
    def __init__(self,p: UraniumMineProblem):
        self.p = p
        self.m = Model('uranium')

        # Decision variables
        self.x = self.m.addVars(self.p.blocks,vtype=GRB.BINARY,name="x")
        # Objective function
        expr = quicksum([(p.values[b] - p.costs[b]) * self.x[b] for b in p.blocks])
        self.m.setObjective(expr,sense=GRB.MAXIMIZE)

        # Constraints
        self.m.addConstrs(self.x[a] - self.x[b] <= 0 for (a,b) in p.precedences)
Пример #11
0
    def __init__(self, x: float):

        self.m = Model()
        self.y1 = self.m.addVar(name = "y1")
        self.y2 = self.m.addVar(name = "y2")

        # Objective function
        self.m.setObjective(self.y1 + 3*self.y2, sense=GRB.MINIMIZE)

        # Constraints
        self.c1 = self.m.addConstr(2 * self.y1 + self.y2 == 1 - x)
        self.c2 = self.m.addConstr(-self.y1 + self.y2  == 2 - 4 * x)
Пример #12
0
    def __init__(self):

        self.m = Model()
        self.x = self.m.addVar(name="x")
        self.y1 = self.m.addVar(name="y1")
        self.y2 = self.m.addVar(name="y2")

        # Objective function
        self.m.setObjective(2 * self.x + self.y1 + 3 * self.y2,
                            sense=GRB.MINIMIZE)

        # Constraints
        self.m.addConstr(2 * self.y1 + self.y2 + self.x == 1)
        self.m.addConstr(-self.y1 + self.y2 + 4 * self.x == 2)
Пример #13
0
class CuttingStockModel2:
    def __init__(self, p: CuttingStockProblem):
        self.p = p
        self.m = Model('CS1')

        # Decision variables
        n_patterns = len(self.p.get_feasible_patterns())

        x = self.m.addVars(n_patterns,
                           lb=0,
                           ub=GRB.INFINITY,
                           vtype=GRB.INTEGER,
                           name="x")

        # Objective function
        self.m.setObjective(x.sum('*'))

        # Constraints
        # Note that the argument passed to quicksum is a list, and the list is built using comprehension
        self.m.addConstrs(
            quicksum([
                self.p.get_feasible_patterns()[q][i] * x[q]
                for q in range(n_patterns)
            ]) >= self.p.demand[i] for i in range(len(p.demand)))

    def solve(self):
        self.m.optimize()

    def print_solution(self):
        print("Objective ", self.m.objVal)
        for v in self.m.getVars():
            print("%s %g" % (v.varName, v.x))
Пример #14
0
    def __init__(self, p:CuttingStockProblem):
        self.p = p
        self.m = Model('CS1')

        # Decision variables
        n_patterns = len(self.p.get_feasible_patterns())

        x = self.m.addVars(n_patterns,lb= 0, ub= GRB.INFINITY, vtype=GRB.CONTINUOUS,name="x")

        # Objective function
        self.m.setObjective(x.sum('*'))

        # Constraints
        # Note that the argument passed to quicksum is a list, and the list is built using comprehension
        self.m.addConstrs(quicksum([self.p.get_feasible_patterns()[q][i] * x[q] for q in range(n_patterns)]) >= self.p.demand[i]  for i in range(len(p.demand)))
Пример #15
0
def defineVars(data: DataInstance):
    model = Model("GLayout")
    L = define1DIntVarArray(model, data.element_count, "L")
    R = define1DIntVarArray(model, data.element_count, "R")
    T = define1DIntVarArray(model, data.element_count, "T")
    B = define1DIntVarArray(model, data.element_count, "B")
    H = define1DIntVarArray(model, data.element_count, "H")
    W = define1DIntVarArray(model, data.element_count, "W")
    ABOVE = define2DBoolVarArrayArray(model, data.element_count, data.element_count, "ABOVE")
    LEFT = define2DBoolVarArrayArray(model, data.element_count, data.element_count, "LEFT")
    N = data.element_count
    LAG = define1DBoolVarArray(model, data.element_count, "LAG")
    RAG = define1DBoolVarArray(model, data.element_count, "RAG")
    TAG = define1DBoolVarArray(model, data.element_count, "TAG")
    BAG = define1DBoolVarArray(model, data.element_count, "BAG")
    vLAG = define1DIntVarArray(model, data.element_count, "vLAG")
    vRAG = define1DIntVarArray(model, data.element_count, "vRAG")
    vTAG = define1DIntVarArray(model, data.element_count, "vTAG")
    vBAG = define1DIntVarArray(model, data.element_count, "vBAG")
    elemAtLAG = define2DBoolVarArrayArray(model, data.element_count, data.element_count, "zLAG")
    elemAtRAG = define2DBoolVarArrayArray(model, data.element_count, data.element_count, "zRAG")
    elemAtTAG = define2DBoolVarArrayArray(model, data.element_count, data.element_count, "zTAG")
    elemAtBAG = define2DBoolVarArrayArray(model, data.element_count, data.element_count, "zBAG")

    return model, N, (L, R, T, B, H, W), (ABOVE, LEFT), (LAG, RAG, TAG, BAG), (vLAG, vRAG, vTAG, vBAG), \
        (elemAtLAG, elemAtRAG, elemAtTAG, elemAtBAG)
Пример #16
0
    def __init__(self, p: StadiumConstructionProblem):
        self.p = p
        self.m = Model('stadium')

        # Decision variables
        self.x = self.m.addVars(self.p.tasks, name="x")
        self.q = self.m.addVar(name="maxtime")

        # Objective function
        self.m.setObjective(self.q, sense=GRB.MINIMIZE)

        # Constraints
        self.m.addConstrs(self.q - self.x[t] >= 0 for t in p.tasks)
        self.m.addConstrs(self.x[t1] - self.x[t2] >= p.durations[t1]
                          for (t1, t2) in p.precedences)
        self.m.addConstrs(self.x[t] >= p.durations[t] for t in p.tasks)
Пример #17
0
def defineObjectives(data: DataInstance, model: Model, boolVars, N, posVars):
    LAG, RAG, TAG, BAG = boolVars
    L, R, T, B, H, W = posVars

    maxX = model.addVar(vtype=GRB.INTEGER, name="maxX")
    maxY = model.addVar(vtype=GRB.INTEGER, name="maxY")
    for element in range(data.element_count):
        model.addConstr(maxX >= R[element])
        model.addConstr(maxY >= B[element])

    OBJECTIVE_GRIDCOUNT = LinExpr(0.0)
    for element in range(data.element_count):
        OBJECTIVE_GRIDCOUNT.addTerms([1.0, 1.0], [LAG[element], TAG[element]])
        OBJECTIVE_GRIDCOUNT.addTerms([1.0, 1.0], [BAG[element], RAG[element]])
    OBJECTIVE_LT = LinExpr(0)
    for element in range(data.element_count):
        OBJECTIVE_LT.addTerms([1, 1, 2, 2, -1, -1],
                              [T[element], L[element], B[element], R[element], W[element], H[element]])
    Objective = LinExpr(0)
    Objective.add(OBJECTIVE_GRIDCOUNT, 1)
    Objective.add(OBJECTIVE_LT, 0.001)
    # Objective.add(maxX, 10)
    # Objective.add(maxY, 10)
    model.addConstr(OBJECTIVE_GRIDCOUNT >= (calculateLowerBound(N)))
    model.setObjective(Objective, GRB.MINIMIZE)
    return OBJECTIVE_GRIDCOUNT, OBJECTIVE_LT
Пример #18
0
class UraniumMineModel:

    """
    This class represents the model for the uranium mine problem.
    """

    def __init__(self,p: UraniumMineProblem):
        self.p = p
        self.m = Model('uranium')

        # Decision variables
        self.x = self.m.addVars(self.p.blocks,vtype=GRB.BINARY,name="x")
        # Objective function
        expr = quicksum([(p.values[b] - p.costs[b]) * self.x[b] for b in p.blocks])
        self.m.setObjective(expr,sense=GRB.MAXIMIZE)

        # Constraints
        self.m.addConstrs(self.x[a] - self.x[b] <= 0 for (a,b) in p.precedences)
        # Alternatively
        #self.m.addConstrs(self.x[a] - self.x[b] <= 0 for a, b in p.precedences)

    def solve(self):
        self.m.optimize()

    def printSolution(self):
        print("Total profit ", self.m.ObjVal)
        for b in self.p.blocks:
            print("%s %g"%(self.x[b].varName,self.x[b].x))
Пример #19
0
class OSP:

    def __init__(self, x: float):

        self.m = Model()
        self.y1 = self.m.addVar(name = "y1")
        self.y2 = self.m.addVar(name = "y2")

        # Objective function
        self.m.setObjective(self.y1 + 3*self.y2, sense=GRB.MINIMIZE)

        # Constraints
        self.c1 = self.m.addConstr(2 * self.y1 + self.y2 == 1 - x)
        self.c2 = self.m.addConstr(-self.y1 + self.y2  == 2 - 4 * x)

    def solve(self):
        self.m.optimize()

    def get_results(self):
        return self.m.objVal, self.c1.Pi, self.c2.Pi

    def print_solution(self):
        print('%s %g' % (self.y1.varName, self.y1.x))
        print('%s %g' % (self.y2.varName, self.y2.x))
        print('Obj: %g' % self.m.objVal)
Пример #20
0
    def __init__(self, x):

        self.m = Model()
        self.y1 = self.m.addVar(name="y1")
        self.y2 = self.m.addVar(name="y2")
        self.v1 = self.m.addVar(name="v1")
        self.v2 = self.m.addVar(name="v2")
        self.v3 = self.m.addVar(name="v3")
        self.v4 = self.m.addVar(name="v4")

        # Objective function
        self.m.setObjective(self.v1 + self.v2 + self.v3 + self.v4,
                            sense=GRB.MINIMIZE)

        # Constraints
        self.c1 = self.m.addConstr(2 * self.y1 + self.y2 + self.v1 -
                                   self.v2 == (1 - x))
        self.c2 = self.m.addConstr(-self.y1 + self.y2 + self.v3 -
                                   self.v4 == (2 - 4 * x))
Пример #21
0
    def __init__(self, fsp: FacilitySizingProblem, x: list):
        self.fsp = fsp
        self.m = Model()

        # Creates the variables
        y = self.m.addVars(fsp.n_facilities, fsp.n_customers, name="y")

        # Creates the objective
        expr = 0
        for i in range(fsp.n_facilities):
            for j in range(fsp.n_customers):
                expr += fsp.delivery_costs[i][j] * y[i, j]
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        self.capacity_constr = self.m.addConstrs(
            y.sum(i, '*') <= x[i] for i in range(self.fsp.n_facilities))
        self.demand_constr = self.m.addConstrs(
            y.sum('*', j) >= fsp.demands[j] for j in range(fsp.n_customers))
Пример #22
0
    def __init__(self, fsp: FacilitySizingProblem, x: list):
        self.fsp = fsp
        self.m = Model()

        # Creates the variables
        y = self.m.addVars(fsp.n_facilities, fsp.n_customers, name="y")
        v1 = self.m.addVars(fsp.n_facilities, name="v+")
        v2 = self.m.addVars(fsp.n_customers, name="v-")

        # Creates the objective
        expr = v1.sum() + v2.sum()
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        self.demand_c = self.m.addConstrs(
            y.sum('*', j) + v1[j] >= fsp.demands[j]
            for j in range(fsp.n_customers))
        self.capacity_c = self.m.addConstrs(
            y.sum(i, '*') - v2[i] <= x[i] for i in range(fsp.n_facilities))
Пример #23
0
    def __init__(self, fsp: FacilitySizingProblem):
        self.fsp = fsp
        self.m = Model()

        # Creates the variables
        self.x = self.m.addVars(fsp.n_facilities,
                                vtype=GRB.CONTINUOUS,
                                name="x")
        self.phi = self.m.addVar(name="phi")

        # Creates the objective
        expr = self.phi + quicksum([
            self.fsp.fixed_costs[i] * self.x[i]
            for i in range(self.fsp.n_facilities)
        ])
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Creates the constraints
        self.m.addConstrs(self.x[i] <= self.fsp.capacity[i]
                          for i in range(fsp.n_facilities))
Пример #24
0
    def __init__(self, flp: FacilityLocationProblem):
        self.flp = flp
        self.m = Model()

        # Creates the variables
        self.y = self.m.addVars(flp.n_facilities, flp.n_customers, name="y")
        self.x = self.m.addVars(flp.n_facilities, vtype=GRB.BINARY, name="x")

        # Creates the objective
        expr = 0
        for i in range(flp.n_facilities):
            expr += flp.fixed_costs[i] * self.x[i]
            for j in range(flp.n_customers):
                expr += flp.delivery_costs[i][j] * self.y[i, j]
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        for i in range(flp.n_facilities):
            self.m.addConstr(self.y.sum(i, '*') <= flp.capacity[i] * self.x[i])
        for j in range(flp.n_customers):
            self.m.addConstr(self.y.sum('*', j) >= flp.demands[j])
Пример #25
0
class FSP:
    def __init__(self, flp: FacilityLocationProblem, x: list):
        self.flp = flp
        self.m = Model()

        # Creates the variables
        y = self.m.addVars(flp.n_facilities, flp.n_customers, name="y")
        v1 = self.m.addVars(flp.n_facilities, name="v+")
        v2 = self.m.addVars(flp.n_customers, name="v-")

        # Creates the objective
        expr = 0
        for i in range(flp.n_facilities):
            expr += v1[i]
        for j in range(flp.n_customers):
            expr += v2[j]
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        self.dc = []
        self.cc = []
        for i in range(flp.n_facilities):
            print(x[i])
            self.cc.append(
                self.m.addConstr(
                    y.sum(i, '*') - v1[i] <= flp.capacity[i] * x[i]))
        for j in range(flp.n_customers):
            self.dc.append(
                self.m.addConstr(y.sum('*', j) + v2[j] >= flp.demands[j]))

    def solve(self):
        self.m.optimize()

    def getDuals(self):

        dualsCC = self.m.getAttr(GRB.Attr.Pi, self.cc)
        dualsDC = self.m.getAttr(GRB.Attr.Pi, self.dc)

        return self.m.objVal, dualsCC, dualsDC
Пример #26
0
    def __init__(self, pp: ProcurementProblem):
        self.m = Model()
        self.pp = pp

        # Creates the variables
        self.x = self.m.addVars(self.pp.n_materials, name="x")

        # Creates the objective
        # The expression is obtained by multiplying x to the costs dictionary.
        # See the Gurobi docs for tupledic product here
        # https://www.gurobi.com/documentation/8.1/refman/py_tupledict_prod.html
        expr = self.x.prod(self.pp.costs)
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Creates the constraints
        self.m.addConstrs((self.x[i] <= self.pp.max_production[i]
                           for i in range(self.pp.n_materials)),
                          name='max_p')
        self.m.addConstrs((self.x[i] >= self.pp.min_production[i]
                           for i in range(self.pp.n_materials)),
                          name='min_p')
        self.m.addConstr(self.x.prod(self.pp.consumption) >= self.pp.demand)
Пример #27
0
class OSP:
    def __init__(self, flp: FacilityLocationProblem, x: list):
        self.flp = flp
        self.m = Model()

        # Creates the variables
        y = self.m.addVars(flp.n_facilities, flp.n_customers, name="y")

        # Creates the objective
        expr = 0
        for i in range(flp.n_facilities):
            for j in range(flp.n_customers):
                expr += flp.delivery_costs[i][j] * y[i, j]
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        self.dc = []
        self.cc = []
        for i in range(flp.n_facilities):
            self.cc.append(
                self.m.addConstr(y.sum(i, '*') <= flp.capacity[i] * x[i]))
        for j in range(flp.n_customers):
            self.dc.append(self.m.addConstr(y.sum('*', j) >= flp.demands[j]))

    def solve(self):
        self.m.optimize()

    def getResults(self):

        dualsCC = self.m.getAttr(GRB.Attr.Pi, self.cc)
        dualsDC = self.m.getAttr(GRB.Attr.Pi, self.dc)

        return self.m.objVal, dualsCC, dualsDC

    def write(self):
        self.m.write("subproblem.lp")
Пример #28
0
class FullModel:
    def __init__(self):

        self.m = Model()
        self.x = self.m.addVar(name="x")
        self.y1 = self.m.addVar(name="y1")
        self.y2 = self.m.addVar(name="y2")

        # Objective function
        self.m.setObjective(2 * self.x + self.y1 + 3 * self.y2,
                            sense=GRB.MINIMIZE)

        # Constraints
        self.m.addConstr(2 * self.y1 + self.y2 + self.x == 1)
        self.m.addConstr(-self.y1 + self.y2 + 4 * self.x == 2)

    def solve(self):
        self.m.optimize()

    def print_solution(self):
        print('%s %g' % (self.x.varName, self.x.x))
        print('%s %g' % (self.y1.varName, self.y1.x))
        print('%s %g' % (self.y2.varName, self.y2.x))
        print('Obj: %g' % self.m.objVal)
Пример #29
0
class OSP:
    def __init__(self, fsp: FacilitySizingProblem, x: list):
        self.fsp = fsp
        self.m = Model()

        # Creates the variables
        y = self.m.addVars(fsp.n_facilities, fsp.n_customers, name="y")

        # Creates the objective
        expr = 0
        for i in range(fsp.n_facilities):
            for j in range(fsp.n_customers):
                expr += fsp.delivery_costs[i][j] * y[i, j]
        self.m.setObjective(expr, GRB.MINIMIZE)

        # Constraints
        self.capacity_constr = self.m.addConstrs(
            y.sum(i, '*') <= x[i] for i in range(self.fsp.n_facilities))
        self.demand_constr = self.m.addConstrs(
            y.sum('*', j) >= fsp.demands[j] for j in range(fsp.n_customers))

    def solve(self):
        self.m.optimize()

    def getResults(self):
        '''
        Returns, in this order,
        1) the objective value,
        2) the vector of optimal duals for the capacity constraints
        3) the vector of optimal duals for the demand constraints
        :return:
        '''
        print(self.capacity_constr)
        dualsCC = self.m.getAttr(GRB.Attr.Pi, self.capacity_constr)
        dualsDC = self.m.getAttr(GRB.Attr.Pi, self.demand_constr)

        return self.m.objVal, dualsCC, dualsDC
Пример #30
0
class FSP:
    def __init__(self, x):

        self.m = Model()
        self.y1 = self.m.addVar(name="y1")
        self.y2 = self.m.addVar(name="y2")
        self.v1 = self.m.addVar(name="v1")
        self.v2 = self.m.addVar(name="v2")
        self.v3 = self.m.addVar(name="v3")
        self.v4 = self.m.addVar(name="v4")

        # Objective function
        self.m.setObjective(self.v1 + self.v2 + self.v3 + self.v4,
                            sense=GRB.MINIMIZE)

        # Constraints
        self.c1 = self.m.addConstr(2 * self.y1 + self.y2 + self.v1 -
                                   self.v2 == (1 - x))
        self.c2 = self.m.addConstr(-self.y1 + self.y2 + self.v3 -
                                   self.v4 == (2 - 4 * x))

    def solve(self):
        self.m.optimize()

    def get_results(self):
        print(self.m.objVal, self.c1.Pi, self.c2.Pi)
        return self.m.objVal, self.c1.Pi, self.c2.Pi

    def print_solution(self):
        print('%s %g' % (self.y1.varName, self.y1.x))
        print('%s %g' % (self.y2.varName, self.y2.x))
        print('%s %g' % (self.v1.varName, self.v1.x))
        print('%s %g' % (self.v2.varName, self.v2.x))
        print('%s %g' % (self.v3.varName, self.v3.x))
        print('%s %g' % (self.v4.varName, self.v4.x))
        print('Obj: %g' % self.m.objVal)
    def __init__(self, supply, agents, approximator, log):
        """
        :param b: b of LP. If n=len(agents) then the first n values are 1./alpha and n+1 value is supply/alpha.
        :param agents: List of agents.
        """
        # Setting up master problem
        self.m = Model("master-problem")
        self.m.params.LogToConsole = 0
        # noinspection PyArgumentList,PyArgumentList,PyArgumentList
        self.z = self.m.addVar(lb=-GRB.INFINITY, ub=GRB.INFINITY, name="z")
        self.approximator = approximator
        self.agents = agents
        self.log = log

        self.allocations = {'X0': Allocation()}

        self.b = [(1. / self.approximator.gap) for i in range(0, len(self.agents))]
        self.b.append(supply / self.approximator.gap)

        # noinspection PyArgumentList,PyArgumentList,PyArgumentList
        self.price_var = self.m.addVar(lb=-GRB.INFINITY, ub=0, name="price")
        self.utility_vars = dict()
        for agent in self.agents:
            # noinspection PyArgumentList,PyArgumentList,PyArgumentList
            self.utility_vars[agent.id] = self.m.addVar(lb=-GRB.INFINITY, ub=0, name="u_%s" % agent.id)

        self.m.update()

        # Initial constraints for empty allocation
        self.add_benders_cut(Allocation(), "X0")
        self.old_price_constraint = 0.
        self.add_price_constraint(0.)
        self.m.setObjective(self.z, GRB.MAXIMIZE)

        self.price_changed = False
        self.give_second_chance = True
        self.old_z = 0.
        self.old_utilities = dict()
    def solve_restricted_primal(self, demands, demands_next, p):
        self.obj = 0.
        m = Model("multi-unit-auction")
        # self.m.params.LogToConsole = 0
        self.allocation_vars = dict()
        for agent in self.agents:
            for i in range(1, self.supply + 1):
                self.allocation_vars[agent.id, i] = m.addVar(lb=0., ub=1., vtype=GRB.CONTINUOUS,
                                                                  name='x_%s_%s' % (agent.id, i))
        m.update()
        for agent in self.agents:
            if len(demands[agent.id]) > 0 and len(demands_next[agent.id]) > 0:
                m.addConstr(quicksum(self.allocation_vars[agent.id, i] for i in range(1, self.supply + 1)),
                                 GRB.EQUAL, 1, name="u_%s_strict" % agent.id)
            else:
                m.addConstr(quicksum(self.allocation_vars[agent.id, i] for i in range(1, self.supply + 1)),
                                 GRB.LESS_EQUAL, 1, name="u_%s" % agent.id)
            for j in range(1, self.supply + 1):
                if j not in [demand.quantity for demand in demands[agent.id]]:
                    m.addConstr(self.allocation_vars[agent.id, j], GRB.EQUAL, 0, name='x_%s_%s_undemanded' % (agent.id, j))

        if p > 0:
            m.addConstr(
                quicksum(self.allocation_vars[agent.id, i] * i for i in range(1, self.supply + 1) for agent in self.agents),
                GRB.EQUAL, self.supply, name="price_strict")
        else:
            m.addConstr(
                quicksum(self.allocation_vars[agent.id, i] * i for i in range(1, self.supply + 1) for agent in self.agents),
                GRB.LESS_EQUAL, self.supply, name="price")
        obj_expr = LinExpr()
        for agent in self.agents:
            for valuation in agent.valuations:
                obj_expr.addTerms(valuation.quantity, self.allocation_vars[agent.id, valuation.quantity])
        m.setObjective(obj_expr, GRB.MAXIMIZE)
        m.update()
        m.optimize()

        m.write('optimal-lp.lp')

        if m.status == GRB.OPTIMAL:
            m.write('optimal-lp.sol')
            for v in [v for v in m.getVars() if v.x != 0.]:
                print('%s %g' % (v.varName, v.x))

            print ''
            print 'CONSTRAINTS:'

            for l in m.getConstrs():
                if l.Pi > 0:
                    print('%s %g' % (l.constrName, l.Pi))

            print m.getObjective().getValue()

        return m
from gurobipy.gurobipy import Model, GRB

__author__ = 'Usiel'

m = Model("play")

x11 = m.addVar(vtype=GRB.CONTINUOUS, name="x11", lb=0)
x12 = m.addVar(vtype=GRB.CONTINUOUS, name="x12")
x13 = m.addVar(vtype=GRB.CONTINUOUS, name="x13")
x14 = m.addVar(vtype=GRB.CONTINUOUS, name="x14")
x21 = m.addVar(vtype=GRB.CONTINUOUS, name="x21")
x22 = m.addVar(vtype=GRB.CONTINUOUS, name="x22")
x23 = m.addVar(vtype=GRB.CONTINUOUS, name="x23")
x24 = m.addVar(vtype=GRB.CONTINUOUS, name="x24")

m.update()

m.addConstr(x11 + x12 + x13 + x14 + x21 + x22 + x23 + x24, GRB.LESS_EQUAL, 2, name="all")
m.addConstr(x12, GRB.LESS_EQUAL, x11, name="c11")
m.addConstr(x13, GRB.LESS_EQUAL, x12, name="c12")
m.addConstr(x14, GRB.LESS_EQUAL, x13, name="c13")
m.addConstr(x22, GRB.LESS_EQUAL, x21, name="c21")
m.addConstr(x23, GRB.LESS_EQUAL, x22, name="c22")
m.addConstr(x24, GRB.LESS_EQUAL, x23, name="c23")
m.addConstr(x14, GRB.GREATER_EQUAL, 0, name="11")
m.addConstr(x24, GRB.GREATER_EQUAL, 0, name="12")
m.addConstr(x11, GRB.LESS_EQUAL, .5, name="u1")
m.addConstr(x21, GRB.LESS_EQUAL, .5, name="u2")
#m.addConstr(x11 + 2*x12 + 3*x13 + 4*x14 + x21 + 2*x22 + 3*x23 + 4*x24, GRB.LESS_EQUAL, 4, name="p_an")

m.setObjective(x11 * 6 + x12 * 0 + x13 * 0 + x14 * 3 + x21 * 1 + x22 * 3 + x23 * 0 + x24 * 2, GRB.MAXIMIZE)
    def __init__(self, supply, agents, gap, restriced=False):
        print ''
        print 'Optimal Solver:'

        self.m = Model("multi-unit-auction")
        self.m.params.LogToConsole = 0
        self.allocation_vars = dict()
        for agent in agents:
            for i in range(1, supply + 1):
                self.allocation_vars[agent.id, i] = self.m.addVar(lb=0., ub=1., vtype=GRB.CONTINUOUS, name='x_%s_%s' % (agent.id, i))

        self.m.update()

        for agent in agents:
            self.m.addConstr(quicksum(self.allocation_vars[agent.id, i] for i in range(1, supply + 1)), GRB.LESS_EQUAL, 1, name="u_%s" % agent.id)
            if restriced:
                for valuation in agent.valuations:
                    if valuation.valuation > 0:
                        self.m.addConstr(self.allocation_vars[agent.id, valuation.quantity] >= epsilon, name="not_zero_%s_%s" % (agent.id, valuation.quantity))


        self.m.addConstr(quicksum(self.allocation_vars[agent.id, i]*i for i in range(1, supply + 1) for agent in agents), GRB.LESS_EQUAL, supply, name="price")

        obj_expr = LinExpr()
        for agent in agents:
            for valuation in agent.valuations:
                obj_expr.addTerms(valuation.valuation, self.allocation_vars[agent.id, valuation.quantity])
        self.m.setObjective(obj_expr, GRB.MAXIMIZE)

        self.m.update()

        self.m.optimize()
        #
        # for agent in agents:
        #     for i in range(1, supply + 1):
        #         self.allocation_vars[agent.id, i] = self.m.addVar(vtype=GRB.CONTINUOUS, lb=0,
        #                                                           name='x_%s_%s' % (agent.id, i))
        #
        # self.m.update()
        #
        # self.m.addConstr(quicksum(self.allocation_vars[agent.id, i] for i in range(1, supply + 1) for agent in agents),
        #                  GRB.LESS_EQUAL, supply / gap, name="price")
        # for agent in agents:
        #     for i in range(1, supply):
        #         self.m.addConstr(self.allocation_vars[agent.id, i + 1] - self.allocation_vars[agent.id, i],
        #                          GRB.LESS_EQUAL, 0, name="chain_%s_%s" % (agent.id, i))
        #         self.m.addConstr(self.allocation_vars[agent.id, i], GRB.LESS_EQUAL, 1. / gap,
        #                          name="p_%s_%s" % (agent.id, i))
        #     self.m.addConstr(self.allocation_vars[agent.id, supply], GRB.GREATER_EQUAL, 0, name="greater_%s" % agent.id)
        #     self.m.addConstr(self.allocation_vars[agent.id, 1], GRB.LESS_EQUAL, 1. / gap, name="u_%s" % agent.id)
        #
        # # m.addConstr(x11 + 2*x12 + 3*x13 + 4*x14 + x21 + 2*x22 + 3*x23 + 4*x24, GRB.LESS_EQUAL, 4, name="p_an")
        #
        # obj_expr = LinExpr()
        # for agent in agents:
        #     prev_val = None
        #     for valuation in agent.valuations:
        #         try:
        #             prev_val = next(val for val in agent.valuations if val.quantity == valuation.quantity - 1)
        #         except StopIteration:
        #             pass
        #         marginal_value = valuation.valuation - (prev_val.valuation if prev_val else 0)
        #         obj_expr.addTerms(marginal_value, self.allocation_vars[agent.id, valuation.quantity])
        # self.m.setObjective(obj_expr, GRB.MAXIMIZE)
        #
        # self.m.optimize()

        for v in [v for v in self.m.getVars() if v.x != 0.]:
            print('%s %g' % (v.varName, v.x))

        print ''
        print 'CONSTRAINTS:'

        for l in self.m.getConstrs():
            if l.Pi > 0:
                print('%s %g' % (l.constrName, l.Pi))

        print self.m.getObjective().getValue()

        # print 'Optimal solution:'
        # for v in self.m.getVars():
        #     print('%s %g' % (v.varName, v.x))
        # for l in self.m.getConstrs():
        #     if l.Pi > 0:
        #         print('%s %g' % (l.constrName, l.Pi))
        print 'OPT social welfare %s | %s/%s=%s' % (
        self.m.getObjective().getValue(), self.m.getObjective().getValue(), gap,
        self.m.getObjective().getValue() / gap)

        self.m.write('optimal-lp.lp')
        self.m.write('optimal-lp.sol')
Пример #35
0
class SolverGurobi(Solver):
    def __init__(self):
        Solver.__init__(self, GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.OPTIMAL, GRB.INFEASIBLE, GRB.UNBOUNDED, GRB.INTERRUPTED, GRB.SUBOPTIMAL, GRB.EQUAL, GRB.LESS_EQUAL, GRB.GREATER_EQUAL, GRB.MAXIMIZE, GRB.MINIMIZE, GRB.INFINITY)
        setParam('OutputFlag', 0)
        setParam('IntFeasTol', 1e-9)
        self.problem = Model('gurobi_problem')

    def _add_variable(self, var):
        if var.var_type == self.BINARY:
            self.problem.addVar(name=var.name, vtype=var.var_type)
        else:
            self.problem.addVar(name=var.name, lb=var.lower_bound, ub=var.upper_bound, vtype=var.var_type)

    def _del_variable(self, name):
        self.problem.remove(self.problem.getVarByName(name))

    def _add_constraint(self, const):
        lhs = LinExpr()

        for elem in const.lhs:
            var = self.problem.getVarByName(elem.name)
            lhs.add(var, elem.coefficient)

        self.problem.addConstr(lhs, const.sense, const.rhs, const.name)

    def _del_constraint(self, name):
        self.problem.remove(self.problem.getConstrByName(name))

    def update(self):
        self.problem.update()

    def _set_objective(self, objective):
        expr = LinExpr()

        for elem in objective.expr:
            var = self.problem.getVarByName(elem.name)
            expr.add(var, elem.coefficient)

        self.problem.setObjective(expr, objective.sense)

    def get_variable_value(self, name):
        return self.problem.getVarByName(name).x

    def get_objective_value(self):
        return self.problem.objVal

    def get_solution_status(self):
        return self.problem.status

    def _optimize(self):
        self.problem.optimize()
Пример #36
0
 def __init__(self):
     Solver.__init__(self, GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.OPTIMAL, GRB.INFEASIBLE, GRB.UNBOUNDED, GRB.INTERRUPTED, GRB.SUBOPTIMAL, GRB.EQUAL, GRB.LESS_EQUAL, GRB.GREATER_EQUAL, GRB.MAXIMIZE, GRB.MINIMIZE, GRB.INFINITY)
     setParam('OutputFlag', 0)
     setParam('IntFeasTol', 1e-9)
     self.problem = Model('gurobi_problem')
Пример #37
0
    ('A', 'C', 'C_S1'),
    ('A', 'C', 'C_S2'),
    ('B', 'C', 'C_S2'),
    ('B', 'D', 'D_S2'),
    ('C', 'E', 'E_S2'),
    ('C', 'F', 'F_S1')
], columns=['kinase', 'substrate', 'site'])

sites, kinases, substrates = set(ks_network['site']), set(ks_network['kinase']), set(ks_network['substrate'])
in_edges, out_edges = set(ks_network['kinase'] + '_' + ks_network['site']), set(ks_network['site'] + '_' + ks_network['substrate'])

in_edges_costs = {edge: 1 / es for kinase, es in kinases_es.items() for edge in in_edges if edge.startswith(kinase)}
out_edges_costs = {edge: 1 / fc for site, fc in sites_fc.items() for edge in out_edges if edge.startswith(site)}

# Create problem
lp = Model('KS')

# Initialise nodes variables
for v in sites:
    lp.addVar(vtype=GRB.BINARY, name=v)

for v in kinases:
    lp.addVar(vtype=GRB.BINARY, name=v)

for v in substrates.difference(kinases):
    lp.addVar(vtype=GRB.BINARY, name=v)

# Initialise edges variables
for edge in in_edges:
    lp.addVar(vtype=GRB.BINARY, name=edge)
class BendersSolver:
    def __init__(self, supply, agents, approximator, log):
        """
        :param b: b of LP. If n=len(agents) then the first n values are 1./alpha and n+1 value is supply/alpha.
        :param agents: List of agents.
        """
        # Setting up master problem
        self.m = Model("master-problem")
        self.m.params.LogToConsole = 0
        # noinspection PyArgumentList,PyArgumentList,PyArgumentList
        self.z = self.m.addVar(lb=-GRB.INFINITY, ub=GRB.INFINITY, name="z")
        self.approximator = approximator
        self.agents = agents
        self.log = log

        self.allocations = {'X0': Allocation()}

        self.b = [(1. / self.approximator.gap) for i in range(0, len(self.agents))]
        self.b.append(supply / self.approximator.gap)

        # noinspection PyArgumentList,PyArgumentList,PyArgumentList
        self.price_var = self.m.addVar(lb=-GRB.INFINITY, ub=0, name="price")
        self.utility_vars = dict()
        for agent in self.agents:
            # noinspection PyArgumentList,PyArgumentList,PyArgumentList
            self.utility_vars[agent.id] = self.m.addVar(lb=-GRB.INFINITY, ub=0, name="u_%s" % agent.id)

        self.m.update()

        # Initial constraints for empty allocation
        self.add_benders_cut(Allocation(), "X0")
        self.old_price_constraint = 0.
        self.add_price_constraint(0.)
        self.m.setObjective(self.z, GRB.MAXIMIZE)

        self.price_changed = False
        self.give_second_chance = True
        self.old_z = 0.
        self.old_utilities = dict()

    @property
    def price(self):
        """
        :return: Returns current price (positive).
        """
        try:
            return math.fabs(self.price_var.x)
        except GurobiError:
            return None

    @property
    def utilities(self):
        """
        :return: Returns current utilities (positive): dict(agent_id: utility)
        """
        return dict((v[0], math.fabs(v[1].x)) for v in self.utility_vars.iteritems())

    @property
    def objective(self):
        try:
            return self.z.x
        except GurobiError:
            return 0.

    def solve(self):
        while self.iterate():
            pass
        return self.allocations

    def iterate(self):
        """
        Performs one iteration of the Bender Auction. Optimizes current master problem, requests an approximate \
        allocation based on current prices and utilities, calculates phi with current optimal values of master problem \
        and then compares this with current z value.
        :return: False if auction is done and True if a Bender's cut has been added and the auction continues.
        """
        iteration = len(self.allocations)

        self.log.log('')
        self.log.log('######## ITERATION %s ########' % iteration)

        self.optimize()
        no_change = self.old_z == self.objective and all(
            [any(old_utility == utility for old_utility in self.old_utilities) for utility in self.utilities])
        self.log.log("no change ... %s" % no_change)
        self.old_z = self.objective
        self.old_utilities = self.utilities

        # allocation := X
        allocation = self.approximator.approximate(self.price, self.utilities)

        # first_term - second_term = w*b - (c + wA) * X
        # first_term is w*b
        first_term = sum([-w * b for w, b in zip(self.utilities.values() + [self.price], self.b)])
        # second_term is (c + wA) * X
        second_term = 0
        for assignment in allocation.assignments:
            # for each x_ij which is 1 we generate c + wA which is (for MUA): v_i(j) + price * j + u_i
            second_term += self.price * assignment.quantity
            second_term += -self.utilities[assignment.agent_id]
            second_term += assignment.valuation
        phi = first_term - second_term
        self.log.log('phi = %s - %s = %s' % (first_term, second_term, phi))

        # check if phi with current result of master-problem is z (with tolerance)
        if math.fabs(phi - self.z.x) < epsilon or iteration > iteration_abort_threshold:
                self.remove_bad_cuts()
                self.set_allocation_probabilities()
                self.print_results()
                return False
        else:
            self.give_second_chance = True
            # otherwise continue and add cut based on this iteration's allocation
            allocation_name = 'X%s' % iteration
            self.allocations[allocation_name] = allocation
            self.add_benders_cut(allocation, allocation_name)
        self.set_allocation_probabilities()
        return True

    def add_price_constraint(self, new_price=None):
        if True:
            return None
        try:
            self.m.remove(self.m.getConstrByName("price_constraint"))
        except GurobiError:
            pass

        if new_price != None:
            self.old_price_constraint = new_price
        else:
            self.old_price_constraint -= .5

        self.log.log(self.old_price_constraint)
        self.m.addConstr(self.price_var, GRB.EQUAL, self.old_price_constraint, name="price_constraint")

    def print_results(self):
        """
        Prints results in console.
        """
        self.log.log('')
        self.log.log('####### SUMMARY #######')
        self.log.log('')

        self.m.write("master-program.lp")

        for item in self.allocations.iteritems():
            if item[1].probability > 0:
                # noinspection PyArgumentList
                self.log.log('%s (%s)' % (item[0], item[1].probability))
                item[1].print_me(self.log)
                self.log.log('')

        if self.price_changed:
            self.log.log('Price has decreased at some point.')
        self.log.log('%s iterations needed' % len(self.allocations))
        self.log.log('E[Social welfare] is %s' % -self.z.x)

    def optimize(self):
        """
        Optimizes current master-problem and outputs optimal values and dual variables
        """
        # for observation we save the current price
        current_price = self.price if self.price else 0.

        self.m.optimize()

        if current_price > self.price:
            self.price_changed = True

        for v in [v for v in self.m.getVars() if v.x != 0.]:
            self.log.log('%s %g' % (v.varName, v.x))

        for l in self.m.getConstrs():
            if l.Pi > 0:
                self.log.log('%s %g' % (l.constrName, l.Pi))

    def remove_bad_cuts(self):
        for l in self.m.getConstrs():
            if l.Pi == 0:
                self.m.remove(l)

    def add_benders_cut(self, allocation, name):
        """
        Adds another cut z <= wb - (c + wA) * X.
        :param allocation: Allocation as list of Assignment.
        :param name: Name for new constraint.
        """
        # wb part of cut
        expr = LinExpr(self.b, self.utility_vars.values() + [self.price_var])
        for assignment in allocation.assignments:
            # c
            expr.addConstant(-assignment.valuation)
            # if w=(u, p) then this is the uA part (for columns where X is 1)
            expr.addTerms(-1, self.utility_vars[assignment.agent_id])
            # if w=(u, p) then this is the pA part (for columns where X is 1)
            expr.addTerms(-assignment.quantity, self.price_var)
            # we get v_i(j) + u_i + j * price summed over all i,j where x_ij = 1

        self.m.addConstr(self.z, GRB.LESS_EQUAL, expr, name=name)

    def set_allocation_probabilities(self):
        for item in self.allocations.iteritems():
            # noinspection PyArgumentList
            constraint = self.m.getConstrByName(item[0])
            item[1].probability = constraint.pi if constraint else 0
Пример #39
0
 def __init__(self, network):
     self.lp = Model('PCST')
     self.network = network
Пример #40
0
class PCST:
    def __init__(self, network):
        self.lp = Model('PCST')
        self.network = network

    def initialise(self):
        # Initialise variables
        for n in self.network.nodes.values():
            n.var = self.lp.addVar(vtype=GRB.BINARY, name=n.id)

        for e in self.network.edges.values():
            e.var = self.lp.addVar(vtype=GRB.BINARY, name=e.id)

        # Update variables
        self.lp.update()

        # Root restriction
        lhs = LinExpr()
        for root_out in self.network.out_edges(self.network.root.id):
            lhs.addTerms(1, root_out.var)

        self.lp.addConstr(lhs, GRB.EQUAL, 1)

        # Income constraints
        for n in self.network.nodes.values():
            lhs = LinExpr()
            for e in self.network.in_edges(n.id):
                lhs.addTerms(1, e.var)

            self.lp.addConstr(lhs, GRB.EQUAL, LinExpr(n.var))

        # Reversibility constraint
        for e in self.network.edges.values():
            if e.inverse is not None:
                lhs = LinExpr([1, 1], [e.var, self.network.get_edge(e.inverse).var])

                self.lp.addConstr(lhs, GRB.LESS_EQUAL, self.network.get_node(e.source).var)
                self.lp.addConstr(lhs, GRB.LESS_EQUAL, self.network.get_node(e.target).var)

        for n in self.network.nodes.values():
            if n.type == Type.LEAF or n.type == Type.LEAF_TERMINAL:
                for in_edge in self.network.in_edges(n.id):
                    source = self.network.get_node(in_edge.source)
                    if source.type != Type.ROOT:
                        print n.id, in_edge.source
                        self.lp.addConstr(source.var, GRB.LESS_EQUAL, n.var)

    def objective_function(self, beta=1):
        # Set objective function
        obj = LinExpr()

        for e in self.network.edges.values():
            obj.addTerms(e.value, e.var)

        for n in self.network.nodes.values():
            if n.type == Type.NORMAL:
                obj.addTerms(-n.value * beta, n.var)

        self.lp.setObjective(obj, GRB.MINIMIZE)

    def optimise(self):
        self.lp.optimize()
        return self.get_solution()

    def edge_sensitivity_analysis(self, solution):
        scores = {}
        for e in solution.edges.values():
            edge_constraint = self.lp.addConstr(self.network.get_edge(e.id).var, GRB.EQUAL, 0)

            scores[e.id] = self.optimise()

            self.lp.remove(edge_constraint)

        print '\n[INFO] Edge sensivity analysis done! ' + str(len(solution.edges)) + ' edges analysed.'

        return scores

    def get_solution(self):
        edges = dict((e.id, Edge(e.source, e.target, self.lp.getVarByName(e.id).x)) for e in self.network.edges.values() if self.lp.getVarByName(e.id).x > 0.9999)
        obj_val = self.lp.objVal
        return Solution(edges, obj_val)

    def get_obj_value(self):
        return self.lp.objVal

    def print_solution(self):
        for v in self.lp.getVars():
            print v.varName, v.x

        print 'Obj:', self.lp.objVal
__author__ = 'emanuel'

from gurobipy.gurobipy import GRB, Model, GurobiError

try:
    # Create model
    m = Model('test')

    # Create variables
    x = m.addVar(vtype=GRB.BINARY, name='x')
    y = m.addVar(vtype=GRB.BINARY, name='y')
    z = m.addVar(vtype=GRB.BINARY, name='z')

    # Integrate new variables
    m.update()

    # Set objective function
    m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)

    # Add constraints
    m.addConstr(x + 2 * y + 3 * z <= 4, 'c0')
    m.addConstr(x + y >= 1, 'c1')

    m.optimize()

    for v in m.getVars():
        print v.varName, v.x

    print 'Obj:', m.objVal

except GurobiError: