workforce3.py


workforce3.py


# !/usr/bin/env python3.7 #版权所有2021,Gurobi优化狗万app足彩,LLC #分配工人轮班;每个工人可能在特定的一天上班,也可能不上班。如果问题无法解决,则放松模型#,以确定哪些约束不能满足,以及它们需要放松多少#。从gurobipy import GRB import sys #每个班次所需的工人数量,shiftreequrequirements = gp。multidict({"Mon1": 3, "Tue2": 2, "Wed3": 4, "Thu4": 4, "Fri5": 5, "Sat6": 6, "Sun7": 5, "Mon8": 2, "Tue9": 2, "Wed10": 3, "Thu11": 4, "Fri12": 6, "Sat13": 7, "Sun14": 5}) #每个工人的工资是一个轮班工人的工作,工资= gp。multidict({"Amy": 10, "Bob": 12, "Cathy": 10, "Dan": 8, "Ed": 8, "Fred": 9, "Gu": 11}) # Worker可用性= gp。tuplelist([(“艾米”、“Tue2”)(“艾米”、“Wed3”)(“艾米”、“Fri5”)(“艾米”、“Sun7”)(“艾米”、“Tue9”)(“艾米”、“Wed10”)(“艾米”、“Thu11”)(“艾米”、“Fri12”)(“艾米”、“Sat13”)(“艾米”、“Sun14”)(“鲍勃”、“Mon1”)(“鲍勃”、“Tue2”)(“鲍勃”、“Fri5”)(“鲍勃”、“Sat6”)(“鲍勃”、“Mon8”)(“鲍勃”、“Thu11”)(“鲍勃”、“Sat13”)(“凯西”,“Wed3”)(“凯西”,“Thu4”),(“凯西”、“Fri5”)(“凯西”,“Sun7”)(“凯西”,“Mon8”)(“凯西”,“Tue9”)(“凯西”,“Wed10”)(“凯西”,“Thu11”)(“凯西”,“Fri12”)(“凯西”,“Sat13”)(“凯西”,“Sun14”)(“丹”、“Tue2”)(“丹”、“Wed3”)(“丹”、“Fri5”)(“丹”、“Sat6”)(“丹”、“Mon8”)(“丹”、“Tue9”)(“丹”、“Wed10”)(“丹”、“Thu11”)(“丹”、“Fri12”)(“丹”、“Sat13”),(“丹”、“Sun14”)(“Ed”,“Mon1”)(“Ed”,“Tue2”)(“Ed”,“Wed3”)(“Ed”,“Thu4”)(“Ed”,“Fri5”)(“Ed”,“Sun7”)(“Ed”,“Mon8”)(“Ed”,“Tue9”)(“Ed”,“Thu11”)(“Ed”,“Sat13”)(“Ed”,“Sun14”)(“弗雷德”、“Mon1”)(“弗雷德”、“Tue2”)(“弗雷德”、“Wed3”)(“弗雷德”、“Sat6”)(“弗雷德”、“Mon8”)(“弗雷德”、“Tue9”)(“弗雷德”、“Fri12”)(“弗雷德”、“Sat13”),(“弗雷德”、“Sun14”)(“古”、“Mon1”)(“古”、“Tue2”)(“古”、“Wed3”)(“古”、“Fri5”)(“古”、“Sat6”)(“古”、“Sun7”)(“古”、“Mon8”)(“古”、“Tue9”)(“古”、“Wed10”)(“古”、“Thu11”)(“古”、“Fri12”)(“古”、“Sat13”)(“古”、“Sun14”)])#模型m = gp.Model(“转让”)#赋值变量: x[w,s] == 1 if worker w is assigned to shift s. # Since an assignment model always produces integer solutions, we use # continuous variables and solve as an LP. x = m.addVars(availability, ub=1, name="x") # The objective is to minimize the total pay costs m.setObjective(gp.quicksum(pay[w]*x[w, s] for w, s in availability), GRB.MINIMIZE) # Constraint: assign exactly shiftRequirements[s] workers to each shift s reqCts = m.addConstrs((x.sum('*', s) == shiftRequirements[s] for s in shifts), "_") # Optimize m.optimize() status = m.Status if status == GRB.UNBOUNDED: print('The model cannot be solved because it is unbounded') sys.exit(0) if status == GRB.OPTIMAL: print('The optimal objective is %g' % m.ObjVal) sys.exit(0) if status != GRB.INF_OR_UNBD and status != GRB.INFEASIBLE: print('Optimization was stopped with status %d' % status) sys.exit(0) # Relax the constraints to make the model feasible print('The model is infeasible; relaxing the constraints') orignumvars = m.NumVars m.feasRelaxS(0, False, False, True) m.optimize() status = m.Status if status in (GRB.INF_OR_UNBD, GRB.INFEASIBLE, GRB.UNBOUNDED): print('The relaxed model cannot be solved \ because it is infeasible or unbounded') sys.exit(1) if status != GRB.OPTIMAL: print('Optimization was stopped with status %d' % status) sys.exit(1) print('\nSlack values:') slacks = m.getVars()[orignumvars:] for sv in slacks: if sv.X > 1e-6: print('%s = %g' % (sv.VarName, sv.X))