Exemplo n.º 1
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)
Exemplo n.º 2
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])
Exemplo n.º 3
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]))
Exemplo n.º 4
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)
Exemplo n.º 5
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))
Exemplo n.º 6
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)
Exemplo n.º 7
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)
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 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)
Exemplo n.º 11
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)
Exemplo n.º 12
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)))
Exemplo n.º 13
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)
    def SolveStoModel(self) -> Model:
        StoModel = Model('StoModel')
        StoModel.setParam('OutputFlag', 0)
        StoModel.modelSense = GRB.MINIMIZE

        m, n = self.m, self.n
        h, f = self.h, self.f
        d_rs = self.d_rs
        d_rs_length = len(d_rs)

        I = StoModel.addVars(m, vtype=GRB.CONTINUOUS, name='I')
        Z = StoModel.addVars(m, vtype=GRB.BINARY, name='Z')
        Transshipment_X = StoModel.addVars(self.roads,
                                           d_rs_length,
                                           vtype=GRB.CONTINUOUS,
                                           name='Transshipment_X')

        objFunc_holding = quicksum(I[i] * h[i] for i in range(m))
        objFunc_fixed = quicksum(Z[i] * f[i] for i in range(m))
        objFunc_penalty = quicksum(d_r[j] - Transshipment_X.sum('*', j, k)
                                   for k, d_r in d_rs.items()
                                   for j in range(n))
        objFunc = objFunc_holding + objFunc_fixed + (objFunc_penalty /
                                                     d_rs_length)
        StoModel.setObjective(objFunc)

        # 约束1
        for k in range(d_rs_length):
            StoModel.addConstrs(
                Transshipment_X.sum(i, '*', k) <= I[i] for i in range(m))

        # 约束2
        for k, d_r in d_rs.items():
            StoModel.addConstrs(
                Transshipment_X.sum('*', j, k) <= d_r[j] for j in range(n))

        # 约束3 I_i<=M*Z_i
        StoModel.addConstrs(I[i] <= 20000 * Z[i] for i in range(m))

        # 求解评估模型
        StoModel.optimize()
        self.model = StoModel
        return StoModel
Exemplo n.º 15
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))
Exemplo n.º 16
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))
Exemplo n.º 17
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))
Exemplo n.º 18
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))
Exemplo n.º 19
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])
Exemplo n.º 20
0
    def _balancing(self, flow_graph, sinks, frontier, demands):
        configure_gurobi()
        model = Model()

        xij = {i: {} for i in frontier}
        for node in frontier:
            congestion = sum(flow_graph[node][neighbor] for neighbor in flow_graph[node])
            for neighbor in flow_graph[node]:
                assert neighbor in sinks
                xij[node][neighbor] = model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{node}_{neighbor}")
                model.addConstr(xij[node][neighbor] >= 0)
            model.addConstr(quicksum(xij[node][neighbor] for neighbor in flow_graph[node]) == congestion)

        sink_predecessors = {i: [] for i in sinks}
        for node in frontier:
            for neighbor in flow_graph[node]:
                sink_predecessors[neighbor].append(node)

        bj = {}
        for node in sinks:
            bj[node] = model.addVar(vtype=GRB.CONTINUOUS, name=f"b_{node}")
            model.addConstr(bj[node] == quicksum(xij[pred][node] for pred in sink_predecessors[node]) + demands[node])

        model.setObjective(quicksum(bj[node] * bj[node] for node in sinks), GRB.MINIMIZE)
        model.optimize()

        any_edge_deleted = False
        for node in frontier:
            to_delete = []
            for neighbor in flow_graph[node]:
                flow = xij[node][neighbor].X
                if flow < EPS:
                    to_delete.append(neighbor)
                    any_edge_deleted = True
                else:
                    flow_graph[node][neighbor] = flow
            for neighbor in to_delete:
                del flow_graph[node][neighbor]

        return any_edge_deleted
Exemplo n.º 21
0
    def __Simulate(self, d_r):
        # define the model
        model = Model('evaluation_problem')
        model.setParam('OutputFlag', 0)
        model.modelSense = GRB.MINIMIZE

        # decision variables
        X = model.addVars(tuplelist(self.roads_Z), vtype=GRB.CONTINUOUS, lb=0.0, name='X')

        # objective function
        objFunc_penal = sum(d_r) - X.sum()
        model.setObjective(objFunc_penal)

        # constraints
        model.addConstrs(X.sum('*', j) <= d_r[j] for j in range(self.n))
        model.addConstrs(X.sum(i, '*') <= self.I[i] for i in range(self.m))

        # solve
        model.optimize()

        # record
        return {'d_r': d_r, 'X': {f'{r}': X[r].X for r in self.roads_Z}}
Exemplo n.º 22
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)
    def SolveDetModel(self) -> Model:
        DetModel = Model('StoModel')
        DetModel.setParam('OutputFlag', 0)
        DetModel.modelSense = GRB.MINIMIZE

        m, n = self.m, self.n
        h, f = self.h, self.f
        mu = self.det_param['mu']

        I = DetModel.addVars(m, vtype=GRB.CONTINUOUS, name='I')
        Z = DetModel.addVars(m, vtype=GRB.BINARY, name='Z')
        Transshipment_X = DetModel.addVars(self.roads,
                                           vtype=GRB.CONTINUOUS,
                                           name='Transshipment_X')

        objFunc_holding = quicksum(I[i] * h[i] for i in range(m))
        objFunc_fixed = quicksum(Z[i] * f[i] for i in range(m))
        objFunc_penalty = quicksum(mu[j] - Transshipment_X.sum('*', j)
                                   for j in range(n))
        objFunc = objFunc_holding + objFunc_fixed + objFunc_penalty
        DetModel.setObjective(objFunc)

        # 约束1
        DetModel.addConstrs(
            Transshipment_X.sum(i, '*') <= I[i] for i in range(m))

        # 约束2
        DetModel.addConstrs(
            Transshipment_X.sum('*', j) <= mu[j] for j in range(n))

        # 约束3 I_i<=M*Z_i
        DetModel.addConstrs(I[i] <= 20000 * Z[i] for i in range(m))

        # 求解评估模型
        DetModel.optimize()
        self.model = DetModel
        return DetModel
Exemplo n.º 24
0
from gurobipy.gurobipy import Model, GRB

# Model
m = Model('textile')

# Decision variables
xa = m.addVar(0, GRB.INFINITY, vtype=GRB.CONTINUOUS, name="xa")
xb = m.addVar(0, GRB.INFINITY, vtype=GRB.CONTINUOUS, name="xb")
yw = m.addVar(0, GRB.INFINITY, vtype=GRB.CONTINUOUS, name="yw")
yl = m.addVar(0, GRB.INFINITY, vtype=GRB.CONTINUOUS, name="yl")
yh = m.addVar(0, GRB.INFINITY, vtype=GRB.CONTINUOUS, name="yh")

# Objective function
m.setObjective(60 * xa + 65 * xb - 3 * yw - 3 * yl - 10 * yh,
               sense=GRB.MAXIMIZE)

# Constraints
m.addConstr(0.3 * xa + 0.5 * xb - yw, sense=GRB.LESS_EQUAL, rhs=0)
m.addConstr(6 * xa + 5 * xb <= yl)
m.addConstr(3 * xa + 5 * xb <= yh)
m.addConstr(yw <= 20)
m.addConstr(yl <= 300)
m.addConstr(yh <= 200)

m.optimize()

print('Objective value: %g' % m.objVal)
print('%s %g' % (xa.varName, xa.x))
print('%s %g' % (xb.varName, xb.x))
print('%s %g' % (yw.varName, yw.x))
print('%s %g' % (yl.varName, yl.x))
Exemplo n.º 25
0
from gurobipy.gurobipy import GRB, Model

# Data

months = [8, 9, 10]
cost = {8: 60, 9: 65, 10: 68}
price = {8: 90, 9: 110, 10: 105}
max_buy = 65
max_sell = 100
storage_capacity = 45
storage_cost = 7
current_stock = 25

# Model
m = Model('ref')

# Decision variables
b = m.addVars(months, lb=0, ub=max_buy, vtype=GRB.CONTINUOUS, name="b")
s = m.addVars(months, lb=0, ub=max_sell, vtype=GRB.CONTINUOUS, name="s")
k = m.addVars(months,
              lb=0,
              ub=storage_capacity,
              vtype=GRB.CONTINUOUS,
              name="k")
print(s)
# Objective function
expr = 0
for i in months:
    expr = expr + price[i] * s[i] - cost[i] * b[i] - storage_cost * k[i]
m.setObjective(expr, sense=GRB.MAXIMIZE)
Exemplo n.º 26
0
from gurobipy.gurobipy import Model, GRB

# Create the model object
m = Model('diet_problem')

# Create the variables
xa = m.addVar(0, GRB.INFINITY, vtype=GRB.CONTINUOUS, name="xa")
xb = m.addVar(0, GRB.INFINITY, vtype=GRB.CONTINUOUS, name="xb")
# a different way to create a non-negative continuous variable
xc = m.addVar(name="xc")
xd = m.addVar(0, GRB.INFINITY, name="xd")
xe = m.addVar(name="xe")

# Create the objective function
expr = 8 * xa + 10 * xb + 3 * xc + 20 * xd + 15 * xe
m.setObjective(expr, sense=GRB.MINIMIZE)

# Create the constraints. We will use different ways of adding a constraint
expr = 0.4 * xa + 1.2 * xb + 0.6 * xc + 0.6 * xd + 12.2 * xe
m.addConstr(lhs=expr, sense=GRB.GREATER_EQUAL, rhs=70)
m.addConstr(6 * xa + 10 * xb + 3 * xc + 1 * xd + 0 * xe >= 50)
m.addConstr(0.4 * xa + 0.6 * xb + 0.4 * xc + 0.2 * xd + 2.6 * xe,
            GRB.GREATER_EQUAL, 12)

m.optimize()

print('Objective value: %g' % m.objVal)
print('%s %g' % (xa.varName, xa.x))
print('%s %g' % (xb.varName, xb.x))
print('%s %g' % (xc.varName, xc.x))
print('%s %g' % (xd.varName, xd.x))
Exemplo n.º 27
0
    def Build_LDR_Model(self):
        """
        LDR for location-inventpry problem is only feasible when all affine coefficients equal to 0, which violates from
        what we want.
        For more info about how to design a reasonable prepositioning network,
        see: http://web.hec.ca/pages/erick.delage/LRC_TRO.pdf

        The above paper assume support set is a convex polyhedron characterized by linear constraints.
        """
        m, n = self.m, self.n
        f, h = self.f, self.h
        mu, sigma = self.mu, self.sigma
        roads = self.roads
        INF = float('inf')
        f_ks, K = self.ldr_params['f_k'], len(self.ldr_params['f_k'])

        # declare model
        ldr_model = Model()

        # decision variables
        I = ldr_model.addVars(m, vtype=GRB.CONTINUOUS, lb=0.0, name='I')
        Z = ldr_model.addVars(m, vtype=GRB.BINARY, lb=0.0, name='Z')
        t = ldr_model.addVars(n, vtype=GRB.CONTINUOUS, lb=-INF, name='t')
        gamma = ldr_model.addVar(lb=-INF, vtype=GRB.CONTINUOUS, name='gamma')
        s = ldr_model.addVars(K, vtype=GRB.CONTINUOUS, lb=0.0, name='s')
        phi = ldr_model.addVars(K, vtype=GRB.CONTINUOUS, lb=0.0, name='phi')
        psi = ldr_model.addVars(K, vtype=GRB.CONTINUOUS, lb=-INF, name='psi')
        xi = ldr_model.addVars(K, vtype=GRB.CONTINUOUS, lb=-INF, name='xi')
        eta = ldr_model.addVars(n, K, vtype=GRB.CONTINUOUS, lb=0.0, name='eta')
        tau = ldr_model.addVars(n, K, vtype=GRB.CONTINUOUS, lb=-INF, name='tau')
        theta = ldr_model.addVars(n, K, vtype=GRB.CONTINUOUS, lb=-INF, name='theta')
        w = ldr_model.addVars(m, K, vtype=GRB.CONTINUOUS, lb=0.0, name='w')
        lambd = ldr_model.addVars(m, K, vtype=GRB.CONTINUOUS, lb=-INF, name='lambda')
        delta = ldr_model.addVars(m, K, vtype=GRB.CONTINUOUS, lb=-INF, name='delta')
        alpha_0 = ldr_model.addVars(roads, vtype=GRB.CONTINUOUS, lb=-INF, name='alpha_0')
        alpha = ldr_model.addVars(roads, n, vtype=GRB.CONTINUOUS, lb=-INF, name='alpha')
        beta = ldr_model.addVars(roads, K, vtype=GRB.CONTINUOUS, lb=-INF, name='beta')

        # objective function
        obj1 = quicksum([f[i]*Z[i] for i in range(m)])
        obj2 = quicksum([h[i]*I[i] for i in range(m)])
        obj3 = quicksum([mu[i]*t[i] for i in range(m)])
        obj4 = quicksum(s[k]*matmul(matmul(f_k, sigma), f_k) for k, f_k in enumerate(f_ks))
        obj5 = gamma
        ldr_model.setObjective(obj1 + obj2 + obj3 + obj4 + obj5)
        ldr_model.modelSense = GRB.MINIMIZE

        # constraint
        # c1
        ldr_model.addConstr(gamma + alpha_0.sum() >= 1/2*(phi.sum() - psi.sum()),
                            name='c1')

        # c2
        ldr_model.addConstrs((1/2*(phi[k]+psi[k]) == beta.sum('*', '*', k) + s[k]*len(roads) for k in range(K)),
                             name='c2')

        # c3
        a_star_star = [alpha.sum('*', '*', l) for l in range(n)]
        ldr_model.addConstrs((xi[k]*f_ks[k][l] <= t[l]+a_star_star[l]-1 for k in range(K) for l in range(n)),
                             name='c3')

        # c4
        ldr_model.addConstrs((-alpha_0.sum('*', j) >= 1/2*(eta.sum(j, '*')-tau.sum(j, '*')) for j in range(n)),
                             name='c4')

        # c5
        ldr_model.addConstrs((-1/2*(eta[j, k]+tau[j, k]) == beta.sum('*', j, k) for k in range(K) for j in range(n)),
                             name='c5')

        # c6
        for j in range(n):
            a_star_j = [alpha.sum('*', j, l) if l != j else alpha.sum('*', j, l)-1 for l in range(n)]
            for k, f_k in enumerate(f_ks):
                ldr_model.addConstrs(-theta[j, k]*f_k[l] >= a_star_j[l] for l in range(n))

        # c7
        ldr_model.addConstrs((I[i]-alpha_0.sum(i, '*') >= 1/2*(w.sum(i, '*')-lambd.sum(i, '*')) for i in range(m)),
                             name='c7')

        # c8
        ldr_model.addConstrs((-1/2*(w[i, k]+lambd[i, k]) == beta.sum(i, '*', k) for i in range(m) for k in range(K)),
                             name='c8')

        # c9
        for i in range(m):
            a_i_star = [alpha.sum(i, '*', l) for l in range(n)]
            for k, f_k in enumerate(f_ks):
                ldr_model.addConstrs(-delta[i, k]*f_k[l] >= a_i_star[l] for l in range(n))

        # c10 I,Z
        ldr_model.addConstrs(I[i] <= 10000*Z[i] for i in range(m))

        # c11
        ldr_model.addConstrs(phi[k]*phi[k] >= psi[k]*psi[k] + xi[k]*xi[k] for k in range(K))
        ldr_model.addConstrs(eta[i, k]*eta[i, k] >= tau[i, k]*tau[i, k] + theta[i, k]*theta[i, k]
                             for k in range(K) for i in range(m))
        ldr_model.addConstrs(w[i, k]*w[i, k] >= lambd[i, k]*lambd[i, k] + delta[i, k]*delta[i, k]
                             for k in range(K) for i in range(m))

        # update
        ldr_model.update()
        ldr_model.optimize()
        # print(I)
        # print(Z)
        # print(alpha_0)
        # print(alpha)
        # print(beta)
        # print(ldr_model.ObjVal)
        self.model = ldr_model