import random as rd
from pyscipopt import Model, quicksum
def sub_LL_print(L, digit):
s = "["
for i in range(len(L)):
s = s + str(L[i])
temp = L[i]
digit_temp = 1
while temp//10>0:
digit_temp += 1
temp = temp//10
for j in range(digit-digit_temp):
s += " "
if i < len(L)-1:
s += ", "
s += "]"
return s
def LL_print(name, LL):
LL1 = [[int(LL[i][j]) for j in range(len(LL[i]))] for i in range(len(LL))]
num_max = max([max(LL1[i]) for i in range(len(LL1))])
digit = 1
while num_max//10>0:
digit += 1
num_max = num_max // 10
print("\n"+name+":")
print("["+sub_LL_print(LL[0], digit)+",")
for i in range(1,len(LL)-1):
print(" "+sub_LL_print(LL[i], digit)+",")
print(" " + sub_LL_print(LL[-1], digit) + "]")
def IP(m, n, l, r, g, time_limit):
model = Model("Machine_allocation_IP")
A = [[model.addVar(vtype="I", name="A[%s,%s]" % (i, j)) for j in range(n)] for i in range(m)]
# 以总成本最小为目标
model.setObjective(quicksum(g[j]*A[i][j] for i in range(m) for j in range(n)), "maximize")
# 机器数量约束
for i in range(m):
if i == 0:
model.addCons(quicksum(A[i][j] for j in range(n)) == l)
else:
model.addCons(quicksum(r[j] * A[i-1][j] for j in range(n)) - quicksum(A[i][j] for j in range(n)) >= 0)
model.addCons(quicksum(r[j] * A[i-1][j] for j in range(n)) - quicksum(A[i][j] for j in range(n)) <= 0.9999)
# 设置求解时间
model.setRealParam("limits/time", time_limit)
model.optimize()
print("\ngap:",model.getGap())
# 拿结果
A1 = [[round(model.getVal(A[i][j])) for j in range(n)] for i in range(m)]
return A1
if __name__ == "__main__":
#周期数、生产线数、机器数
m,n,l = 5,3,1000
#完好率、产量
r = [int(rd.random()*10)/10 for i in range(n)]
g = [int(rd.random()*10) for i in range(n)]
# r = [0.7, 0.9]
# g = [8, 5]
print("\nr:\n", r)
print("\ng:\n", g)
# 求解,得到每个工厂分配的机器数
A_IP = IP(m, n, l, r, g, 100)
LL_print("A_IP", A_IP)