-
Notifications
You must be signed in to change notification settings - Fork 0
/
Base.py
387 lines (328 loc) · 13.8 KB
/
Base.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
from Process import Process
import imageio
import copy
import time
import random
import networkx as nx
import matplotlib.pyplot as plt
class Base:
def __init__(self):
self._initial_stock = {}
self._stock = {}
self._process = {}
self._optimize = []
self._degrade = []
self.finite = False
self.finished = False
self.max_optimize_process = None
self.max_optimize_need_stocks = None
self._graph = nx.DiGraph()
self._verbose = None
def add_stock(self, stock_name: str, quantity: int):
if not isinstance(stock_name, str) or not isinstance(quantity, int):
raise TypeError(f"Invalid type for stock.")
self.stock[stock_name] = quantity
def add_process(self, process_name: str, process: Process):
if not isinstance(process_name, str) or not isinstance(process, Process):
raise TypeError(f"Invalid type for process.")
self.process[process_name] = process
def add_optimize(self, optimize_name: str):
if not isinstance(optimize_name, str):
raise TypeError(f"Invalid type for optimize.")
if optimize_name not in self.optimize:
self.optimize.append(optimize_name)
def set_attributes(self, initial_stock, stock, process, optimize):
self.initial_stock = dict(initial_stock)
self.stock = dict(stock)
self.process = dict(process)
self.optimize = list(optimize)
def init_stocks(self):
for stock_name in self.stock.keys():
self.stock[stock_name] = 0
@property
def initial_stock(self):
return self._initial_stock
@property
def stock(self):
return self._stock
@property
def process(self):
return self._process
@property
def optimize(self):
return self._optimize
@property
def degrade(self):
return self._degrade
@property
def graph(self):
return self._graph
@property
def verbose(self):
return self._verbose
@initial_stock.setter
def initial_stock(self, stock):
if isinstance(stock, dict):
self._initial_stock = dict(stock)
else:
raise ValueError('Stock must be a dictionary')
@stock.setter
def stock(self, stock):
if isinstance(stock, dict):
self._stock = dict(stock)
else:
raise ValueError('Stock must be a dictionary')
@process.setter
def process(self, process):
if isinstance(process, dict):
self._process = dict(process)
else:
raise ValueError('Process must be a dictionary')
@optimize.setter
def optimize(self, optimize):
if isinstance(optimize, list):
self._optimize = list(optimize)
else:
raise ValueError('Optimize must be a list')
@degrade.setter
def degrade(self, degrade):
if isinstance(degrade, list):
self._degrade = list(degrade)
else:
raise ValueError('Degrade must be a list')
@graph.setter
def graph(self, graph):
if isinstance(graph, nx.DiGraph):
self._graph = graph
else:
raise ValueError('Graph must be an instance of networkx.DiGraph')
@verbose.setter
def verbose(self, verbose):
self._verbose = verbose
def copy(self):
return copy.deepcopy(self)
def print_initial_stocks(self):
print('---initial stocks---')
for stock, quantity in self.initial_stock.items():
print(f'{stock}:{quantity}')
print('--------------------')
def print_stocks(self, stock_dict: dict):
print('--------------')
for stock, quantity in stock_dict.items():
print(f'{stock}:{quantity}')
print('--------------')
def is_stock_satisfied(self, stock_dict: dict, stock_name: str, quantity: int) -> bool:
if stock_dict[stock_name] >= quantity:
return True
return False
def is_need_satisfied(self, process: Process) -> bool:
for stock_name, quantity in process.need.items():
ret = self.is_stock_satisfied(self.stock, stock_name, quantity)
if ret == False:
return False
return True
def is_optimized(self) -> bool:
for stock in self.optimize:
if stock != 'time' and self.stock[stock] > self.initial_stock[stock] and self.finished:
return True
return False
def is_runnable_next_process(self, stock_dict: dict, process: Process) -> bool:
stock = dict(stock_dict)
for stock_name, quantity in process.need.items():
if self.is_stock_satisfied(stock, stock_name, quantity):
stock[stock_name] -= quantity
else:
return False
for stock_name, quantity in process.result.items():
stock[stock_name] += quantity
process_lst = self.get_available_process_lst()
if self.is_runnable_next_process == False:
return False
return True
def get_max_optimize_stock_quantity(self) -> int:
max_quantity = 0
for process in self.process.values():
for optimize in self.optimize:
if optimize != 'time' and optimize in process.result.keys():
if max_quantity < process.result[optimize]:
max_quantity = process.result[optimize]
return max_quantity
def get_max_optimize_process(self) -> object:
max_quantity = self.get_max_optimize_stock_quantity()
for process in self.process.values():
for optimize in self.optimize:
if optimize != 'time' and optimize in process.result.keys():
if max_quantity == process.result[optimize]:
self.max_optimize_process = process
return process
return None
def get_max_optimize_need_stocks(self) -> list:
if self.max_optimize_process != None:
process = self.process[self.max_optimize_process]
else:
process = self.get_max_optimize_process()
self.max_optimize_need_stocks = list(process.need.keys())
return self.max_optimize_need_stocks
def get_optimize_process_lst(self) -> list:
process_lst = []
for process in self.process.values():
for optimize in self.optimize:
if optimize != 'time' and optimize in process.result.keys():
process_lst.append(process.name)
return process_lst
def get_degrade_process_lst(self) -> list:
for process in self.process.values():
for optimize in self.optimize:
if optimize != 'time' and optimize in process.need.keys():
self.degrade.append(process.name)
return self.degrade
def get_available_process_lst(self) -> list:
process_lst = []
for process in self.process.values():
if self.is_need_satisfied(process):
process_lst.append(process.name)
return process_lst
def run_process_need(self, stock_dict: dict, process: Process) -> bool:
need_dict = process.need
for stock_name, quantity in need_dict.items():
if self.is_stock_satisfied(stock_dict, stock_name, quantity):
stock_dict[stock_name] -= quantity
else:
return False
def run_process_result(self, stock_dict: dict, process: Process) -> bool:
result_dict = process.result
for stock, quantity in result_dict.items():
if self.verbose:
print('result:', stock_dict[stock], 'adding:', quantity)
stock_dict[stock] += quantity
return True
def run_process(self, stock_dict: dict, process: Process) -> bool:
if self.run_process_need(stock_dict, process) == False:
return False
if self.run_process_result(stock_dict, process) == False:
return False
if self.verbose:
print(f'run: ', process.name)
self.print_stocks(self.stock)
return True
def undo_process(self, process: Process):
need_dict = process.need
for stock, quantity in need_dict.items():
self.stock[stock] += quantity
result_dict = process.result
for stock, quantity in result_dict.items():
self.stock[stock] -= quantity
def generate_walk(self, inventory: list, delay: int) -> list:
self.walk = []
stock = dict(self.stock)
max_cycle = 0
start_time = time.time()
while self.is_optimized() == False:
process_lst = self.get_available_process_lst()
if len(process_lst) == 0:
return None
process_name = random.choice(process_lst)
if len(self.walk) != 0:
last_process_name = self.walk[-1]
if max_cycle < self.process[last_process_name[0]].nb_cycle:
max_cycle = self.process[last_process_name[0]].nb_cycle
self.run_process_need(stock, self.process[process_name])
if self.is_runnable_next_process(stock, self.process[process_name]) == False:
stock = dict(self.stock)
self.cycle += int(max_cycle)
max_cycle = 0
elif len(inventory) != 0:
last_process_name = inventory[-1]
if max_cycle < self.process[last_process_name[0]].nb_cycle:
max_cycle = self.process[last_process_name[0]].nb_cycle
self.run_process_need(stock, self.process[process_name])
if self.is_runnable_next_process(stock, self.process[process_name]) == False:
stock = dict(self.stock)
self.cycle += int(max_cycle)
max_cycle = 0
if self.run_process(self.stock, self.process[process_name]):
self.walk.append([process_name, self.cycle])
current_time = time.time()
next_process_lst = self.get_available_process_lst()
if len(next_process_lst) == 0:
self.finshed = True
if self.max_optimize_process.name != process_name and process_name not in self.get_optimize_process_lst():
self.cycle = 0
return None
else:
return self.walk
if current_time - start_time >= delay:
break
return self.walk
def create_stock_image(self, process_name: str, i: int):
plt.figure(figsize=(10, 6))
colors = [
'orange' if stock in self.optimize else 'skyblue' for stock in self.stock.keys()]
bars = plt.bar(self.stock.keys(), self.stock.values(), color=colors)
# plt.title(f'Stocks after iteration {i}')
plt.title(
f'Stocks after iteration {i * 10}\nCurrent process: {process_name}')
plt.xlabel('Stock')
plt.ylabel('Quantity')
# Rotate x-axis labels
plt.setp(plt.gca().get_xticklabels(), rotation=45)
# Add quantity labels on top of each bar
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2.0, yval,
int(yval), va='bottom') # va: vertical alignment
plt.tight_layout()
plt.savefig(f'stock_images/stock_{i}.png')
# plt.show()
def save_animated_image(self, i: int):
print(f"Creating an animated image... i: {i}")
images = []
for i in range(i):
images.append(imageio.imread(f'stock_images/stock_{i}.png'))
imageio.mimsave('stocks.gif', images)
def find_connecting_process(self, process: Process) -> list:
process_lst = []
for pro in self.process.values():
if process.result.keys() == pro.need.keys() and pro != process:
process_lst.append(pro)
return process_lst
def create_graph(self):
self.graph.add_node('start')
for process in self.process.values():
self.graph.add_edge('start', process.name)
self.graph.add_edge(process.name, 'start')
for process in self.process.values():
process_name, needs, results = process.name, process.need, process.result
self.graph.add_node(process_name)
process_lst = self.find_connecting_process(process)
for pro in process_lst:
if pro != None and pro.name != process_name:
self.graph.add_edge(process_name, pro.name)
return self.graph
def visualize_graph(self, font_color='black', font_weight='bold', node_size=1500, legend=None):
node_color = ['green' if node == 'start' else 'red' if node ==
'end' else 'Orange' for node in self.graph.nodes()]
pos = nx.circular_layout(self.graph)
nx.draw(self.graph, pos, with_labels=True, node_color=node_color,
font_color=font_color, font_weight=font_weight, node_size=node_size)
if legend:
for label, color in legend.items():
plt.scatter([], [], c=color, label=label, s=node_size)
plt.legend(scatterpoints=1, frameon=False, labelspacing=1.5)
plt.show()
def __str__(self):
stock_str = ""
process_str = ""
optimize_str = "optimize:("
for key, value in self.stock.items():
if value > 0:
stock_str += key + ":" + str(value) + "\n"
for key, value in self.process.items():
process_str += value.__str__() + "\n"
optimize_len = len(self.optimize)
for index, elem in enumerate(self.optimize, start=1):
optimize_str += elem
if index < optimize_len:
optimize_str += ";"
optimize_str += ")"
return f"{stock_str}\n{process_str}\n{optimize_str}"