-
Notifications
You must be signed in to change notification settings - Fork 1
/
elsp.py
262 lines (213 loc) · 8.07 KB
/
elsp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from elsp import *
import sys
import os
import argparse
import math
import numpy as np
import json
import pandas
from dotmap import DotMap
import cplex
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('file', metavar='[datafile]', help='datafile name')
parser.add_argument('p',metavar='[production unit cost]',type=int, help='Cost of item in production')
parser.add_argument('q',metavar='[production setup cost]',type=int, help='Cost of setup to product the item')
parser.add_argument('hcost',metavar='[inventory holding cost]',type=int, help='Cost of hold the product in the inventory')
parser.add_argument('NT',metavar='[number of periods]',type=int, help='Number of periods of time')
parser.add_argument('sInit',metavar='[inventory initial level]',type=float, default = 0, help='size in months of the production cycle')
args = parser.parse_args()
return args
def read_data(args):
ft = args.file[-1] # last character = type of file
dat = None
if (ft == 't'):
dat = read_dat_file(args)
elif (ft == 'x'):
dat = read_excel_file(args)
elif (ft == 'n'):
dat = read_json_file(args)
else:
raise ValueError('datafile format unknown')
return dat
def read_dat_file(args):
flname = args.file
if (os.path.isfile(flname) == False):
raise Exception('file {:s} not found'.format(flname))
fl = open(flname,'r')
lines = (line.strip() for line in fl)
lines = (line for line in lines if line)
dat = DotMap()
dat.p = args.p
dat.q = args.q
dat.h = args.hcost
dat.nt = args.NT
dat.sInit = args.sInit
I = range(dat.nt)
data = []
for i in I:
dj = int(next(lines))
data.append([dj])
fl.close()
dat.data = data
return dat
def read_excel_file(args):
flname = args.file
if (os.path.isfile(flname) == False):
raise Exception('file {:s} not found'.format(flname))
dat = DotMap()
dat.p = args.p
dat.q = args.q
dat.h = args.hcost
dat.nt = args.NT
dat.sInit = args.sInit
df = pandas.read_excel(flname, sheet_name = 'dj', dtype = np.int32)
I = range(dat.nt)
data = []
for i in I:
data.append([int(df['dj'][i])])
dat.data = data
return dat
def read_json_file(args):
flname = args.file
if (os.path.isfile(flname) == False):
raise Exception('file {:s} not found'.format(flname))
with open(flname) as fl:
js = json.load(fl)
dat = DotMap(js)
dat.p = args.p
dat.q = args.q
dat.h = args.hcost
dat.nt = args.NT
dat.sInit = args.sInit
data = []
I = range(dat.nt)
for i in I:
data.append([int(js["dj"][i])])
fl.close()
dat.data = data
return dat
def create_model(dat):
p = dat.p
q = dat.q
h = dat.h
nt = dat.nt
sInit = dat.sInit
nt_1 = nt-1
I = range(nt)
NT_1 = range(nt-1)
s_begin = 2*nt;
s_begin_1 = 2*nt - 1;
dj = []
[dj.append(float(dat.data[i][0])) for i in I]
cpx = cplex.Cplex()
yt = ["yt(" + str(i) + ")" for i in I]
xt = ["xt(" + str(i) + ")" for i in I]
st = ["st(" + str(i) + ")" for i in I]
# cpx.variable.add = usar o mesmo número de vezes quanto o número de variáveis na função objetivo
cpx.variables.add(obj= [p] * nt, \
lb = [0.0] * nt,\
ub = [cplex.infinity] * nt,\
names = xt)
# adiciona a variável x(t)
# obj = qual é o coeficiente que está multiplicando a variável adicionada na função objetivo
# lb = limite inferior 0 (vetor com items posições)
# ub = limite superior infinito
# nome = vetor de caracteres xt
cpx.variables.add(obj= [q]* nt,\
lb = [0.0] * nt,\
ub = [1.0] * nt,\
types = ['B'] * nt,\
names = yt)
# adiciona a variável y(t)
# obj = qual é o coeficiente que está multiplicando a variável adicionada na função objetivo
# lb = limite inferior 0 (vetor com items posições)
# ub = limite superior 1 (bool)
# nome = vetor de caracteres yt
cpx.variables.add(obj= [h] * nt,\
lb = [0.0] * nt,\
ub = [cplex.infinity]*nt,\
names = st)
# adiciona a variável s(t)
# obj = qual é o coeficiente que está multiplicando a variável adicionada na função objetivo
# lb = limite inferior 0
# ub = limite superior infinito
# nome = vetor de caracteres st
#################################### Restrição dem_satt ###########################################################
for i in I:
if i > 0:
cpx.linear_constraints.add(lin_expr=[cplex.SparsePair([i, (i+s_begin), (i+(s_begin_1))], [1.0, -1.0, 1.0])],\
senses = "E",\
rhs = [dj[i]])
else:
cpx.linear_constraints.add(lin_expr=[cplex.SparsePair([i, (i+s_begin)], [1.0, -1.0])],\
senses = "E",\
rhs = [dj[i] - sInit])
#############################################################################################################################
# adiciona a restrição dem_satt -> st-1 + xt = dt + st
# lin_expr = SparsePair (a matriz adiciona é esparsa, há vários zeros na matriz, portanto quero adicionar só os valores não nulos)
# parâmetro 1 (SparsePair) = índice dos valores
# parâmetro 2 (SparsePair) = valores
# senses = E (a expressão é uma igualdade)
# rhs = (right hand side)
sum_dj = 0
for i in I:
sum_dj += dj[i]
[cpx.linear_constraints.add(lin_expr=[cplex.SparsePair([(i+nt), i], [sum_dj, -1.0])],\
senses = "G", \
rhs = [0.0]) for i in I]
# adiciona restrição vubt: xt =< yt*somatorio_0_a_t(dk) ----> yt*somatorio_0_a_t(dk) - xt >= 0
# lin_expr = SparsePair (a matriz adiciona é esparsa, há vários zeros na matriz, portanto quero adicionar só os valores não nulos)
# parâmetro 1 = índice dos valores
# parâmetro 2 = valores
# senses = L (a expressão é uma desigualdade menor ou igual)
# rhs = (right hand side) o lado direito é sempre igual a 0 (??)
cpx.write("elsp.lp")
return cpx
def solve_model(dat,cpx):
cpx.parameters.threads.set(1)
cpx.solve()
status = cpx.solution.get_status()
statusMsg = cpx.solution.get_status_string()
if (status != cpx.solution.status.optimal) and\
(status != cpx.solution.status.optimal_tolerance) and\
(status != cpx.solution.status.MIP_optimal) and\
(status != cpx.solution.status.MIP_time_limit_feasible) and\
(status != cpx.solution.status.MIP_dettime_limit_feasible) and\
(status != cpx.solution.status.MIP_abort_feasible) and\
(status != cpx.solution.status.MIP_feasible_relaxed_sum) and\
(status != cpx.solution.status.MIP_feasible_relaxed_inf) and\
(status != cpx.solution.status.MIP_optimal_relaxed_inf) and\
(status != cpx.solution.status.MIP_feasible_relaxed_quad) and\
(status != cpx.solution.status.MIP_optimal_relaxed_sum) and\
(status != cpx.solution.status.MIP_feasible):
statusMsg = cpx.solution.get_status_string()
print(statusMsg)
sys.exit(-1)
else:
nt = dat.nt
I = range(nt)
NT_1 = range(1,nt)
of = cpx.solution.get_objective_value()
x = cpx.solution.get_values()
sol = DotMap()
sol.msg = cpx.solution.get_status_string()
sol.of = of
sol.xt = [x[i] for i in I ]#if x[i] > 0.001]
sol.yt = [x[i+nt] for i in I ]#if x[i+nt] > 0.001]
sol.st = [x[i+((2*nt)-1)] for i in NT_1 ]#if x[i+(2*(nt-1))] > 0.001]
sol.st.insert(0, dat.sInit);
return sol
def print_sol(dat,sol):
I = range(dat.nt)
print("Solver status : {:s}".format(sol.msg))
print("Objective function : {:18,.2f}".format(sol.of))
print("\n\tTime period\t|\tProduction batch size\t|\tProduction set-up\t|\tEnd inventory level")
for i in I:
print("\t {:.2f}\t\t|{:18,.2f}\t\t|{:18,.2f}\t\t|{:18,.2f}\t".format(i, sol.xt[i], sol.yt[i], sol.st[i]))
if __name__ == "__main__":
args = parse_arguments()
dat = read_data(args)
cpx = create_model(dat)
sol = solve_model(dat,cpx)
print_sol(dat,sol)