-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev.py
295 lines (257 loc) · 11 KB
/
dev.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
import os,sys,glob,copy
import pandas as pd
from itertools import combinations,permutations,product
import time,random
from multiprocessing import Process
import multiprocessing
from queue import Queue
def preprocess(file_s="./lic.csv",file_in="./index.csv"):
x = pd.read_csv(file_s)
x = x.fillna("")
index_map = pd.read_csv(file_in)
map_name_to_index = {
}
map_index_to_name={}
for index,i in enumerate(zip(index_map['Name'].values,index_map['Index'].values)):
map_name_to_index[i[1]] = index
map_index_to_name[index] = i[1]
return x,index_map,map_name_to_index,map_index_to_name
def nice_print(i,postfix="", max_t =50):
i =min(int(round(i)),max_t)
str_format = "\r" + "=" * i + ">" +" "*(max_t-i) + f" {i * 100 // max_t}%" + postfix
return str_format
class PrepareMinMaxFlow():
def __init__(self,name = 'min_max_cost_flow',
num_sink=None,
num_flow_to_sink = None,
Graph = None,
**kwargs):
self.__dict__.update(**kwargs)
self.name = name
assert num_sink is not None
assert num_flow_to_sink is not None
assert Graph is not None
self.num_sink = num_sink
self.num_flow_to_sink = num_flow_to_sink
self.num_source = len(Graph[0] if len(Graph) else 0)
self.anotation = {
'graph':copy.deepcopy (Graph)
}
st = time.time()
if not hasattr(self,'limit_combinations'): self.limit_combinations = -1
self.prepare_sink()
if hasattr(self,'multi_gpu'):self.prepare_combinations_mp()
else:
self.prepare_combinations_no_mp()
end = time.time()
print("\nprepare done total time = {:.2f}s\n".format(end-st))
def __str__(self):return self.name
@staticmethod
def gen(all_combination):
first_two_combination = combinations(all_combination,2)
all_xx = []
for i in list(first_two_combination):
current = set(all_combination) - set(i)
new_z =list( combinations( current, 2))
all_xx = all_xx + [i + j + tuple(current - set(j)) for j in new_z]
return all_xx
def prepare_sink(self):
if hasattr(self,'require_sink'):
require_sink = getattr(self,'require_sink')
else:
require_sink = lambda x: True
sink = [i for i in range(len(self.anotation['graph']))\
if require_sink(self.anotation['graph'][i])]
self.sink = sink
self.num_sink_valid = len(sink)
self.cans_combine_sink = [[1 for i in range(len(self.anotation['graph']))] \
for i in range(len(self.anotation['graph']))]
for i in range(len(self.anotation['graph'])):
for j in range(i, len(self.anotation['graph']) ):
x=[1 \
for i in zip(self.anotation['graph'][i],self.anotation['graph'][j])\
if (i[0]==i[1] and i[0] ==1)]
if require_sink(x):
self.cans_combine_sink[i][j] = self.cans_combine_sink[j][i] = 1
else:
self.cans_combine_sink[i][j] = self.cans_combine_sink[j][i] = 0
combination = list(combinations(sink, self.num_sink * self.num_flow_to_sink))
if hasattr(self,'shuffle_sink'):
random.shuffle(combination)
self.anotation['combinations'] = combination[:self.limit_combinations]
def prepare_combinations_mp(self):
num_process= 3
combination =self.anotation.pop("combinations",[])
# deep_combination = []
total = len(combination) // 3
map_process = []
for i in range(2):
map_process.append((i * total,i * total +total))
map_process.append((2 * total,len(combination)))
process_list = []
manager = multiprocessing.Manager()
final_list = manager.list()
def run_operation(st,end):
for com in combination[st:end]:
com_split = PrepareMinMaxFlow.gen(com)
for item in com_split:
for i in range(0, self.num_sink * self.num_flow_to_sink,2):
if self.cans_combine_sink[item[i]][item[i+1]] == 0:
break
else:
final_list.append(item)
for _ in range(num_process):
p = Process(target=run_operation, args=(map_process[_][0],map_process[_][1]))
p.start()
process_list.append(p)
for _ in range(len(process_list)):
p = process_list[_]
p.join()
self.anotation['combinations'] = list(final_list)
def prepare_combinations_no_mp(self): #10 ^ 7
combination =self.anotation.pop("combinations",[])
deep_combination = []
total = len(combination)
iter_done = 0
for com in combination:
com_split = PrepareMinMaxFlow.gen(com)
for item in com_split:
for i in range(0, self.num_sink * self.num_flow_to_sink,2):
if self.cans_combine_sink[item[i]][item[i+1]] == 0:
break
else:
deep_combination.append(item)
iter_done += 1
if iter_done % 100 ==0:
print(nice_print(iter_done * 50 / total),end="\r",sep="\r")
self.anotation['combinations'] = deep_combination
class MinMaxFlow(object):
max_off = 50
def __init__(self, Graph,sink=None):
self.Graph = copy.deepcopy(Graph)
self.offset=10
self.s=MinMaxFlow.max_off-2
self.t=MinMaxFlow.max_off-1
self.f = -1
self.p = [-1 for i in range(MinMaxFlow.max_off)]
if sink:self.setup(sink)
def setup(self,sink):
self.sink = copy.deepcopy(sink)
self.annotation = {
'reduce_path':[[0 for i in range(MinMaxFlow.max_off)] for i in range(MinMaxFlow.max_off)],
}
self.annotation['graph']= self.prepare_graph()
def prepare_graph(self):
G = [[] for i in range(MinMaxFlow.max_off)]
for i in range(0,6,2):
d1,d2 = self.sink[i],self.sink[i+1]
G[i//2].append(self.t)
G[self.t].append(i//2)
self.annotation['reduce_path'][i//2][self.t] = 9 # max
for index,ix in enumerate(zip(self.Graph[d1],self.Graph[d2])):
if ix[0] == ix[1] == 1:
G[i//2].append(self.offset + index)
G[self.offset + index].append(i//2)
self.annotation['reduce_path'][self.offset + index][i//2] = 1
self.all_cost = 0
for index in range(len(self.Graph[0])):
G[self.s].append(index + self.offset)
G[index + self.offset].append(self.s)
self.annotation['reduce_path'][self.s][index + self.offset] = 1
self.all_cost += 1
return G
def flow(self,v,cur):
if(v==self.s):
self.f = cur
return
if(self.p[v]!=-1):
# print(p,v)
h = self.annotation['reduce_path'][self.p[v]][v]
self.flow(self.p[v], min(cur,h))
self.annotation['reduce_path'][self.p[v]][v] -= self.f
self.annotation['reduce_path'][v][self.p[v]] += self.f
def run_step(self):
mf = 0
while True:
queue =Queue()
queue.put(self.s)
dfs = [0 for i in range(MinMaxFlow.max_off)]
self.p = [-1 for i in range(MinMaxFlow.max_off)]
dfs[self.s]=1
while queue.empty() == False:
top = queue.get()
if top==self.t:break
for z in self.annotation['graph'][top]:
if dfs[z] == 0 and self.annotation['reduce_path'][top][z]:
queue.put(z)
dfs[z]=1
self.p[z] = top
self.f=0
self.flow(self.t,1000000)
mf += self.f
if self.f==0:break
if mf==self.all_cost:
return True
return False
def reduce_path_graph(self,map_name = lambda x:x):
str_ans = "T {} kip {} | T {} kip {}"
reduce_day = lambda x: x // 5 + 2 if x // 5 + 2<=7 else 'CN'
reduce_kip = lambda x: x % 5 + 1
ans = {}
for index_k in range(3):
str_ans_cur = str_ans.format(reduce_day(self.sink[index_k * 2]), reduce_kip(self.sink[index_k*2]),
reduce_day(self.sink[index_k * 2 + 1]),
reduce_kip(self.sink[index_k * 2+1]))
ans[str_ans_cur] = ""
for index in range(len(self.Graph[0])):
if self.annotation['reduce_path'][index_k][index+self.offset] == 1:
# print(map_name(index),end=" ")
ans[str_ans_cur] += " " + map_name(index)
# print("")
return ans
if __name__ == "__main__":
import sys
file_pd = sys.argv[1]
file_index = sys.argv[2]
if len(sys.argv) > 3:
limit_combinations = int(sys.argv[3])
else:limit_combinations=-1
x,index_map,map_name_to_index,map_index_to_name = preprocess(file_s=file_pd,file_in=file_index)
Graph = [[1 for i in range(26)] for i in range(35)]
#Graph[i][j] = hoc sinh j co the hoc ngay i
for i in range(2,9):
index_day = f'T{i}' if i != 8 else 'CN'
for st,sc in enumerate(x[index_day].values):
sc_students = [map_name_to_index[i.strip()] for i in sc.split(",") if len(i.strip()) > 0]
for sc_student in sc_students:
Graph[(i-2) * 5 + st][sc_student] = 0
p = PrepareMinMaxFlow(num_sink=3, num_flow_to_sink=2, Graph=Graph,shuffle_sink=True,
require_sink = lambda x:True if sum(x) >= 8 else False,
limit_combinations=limit_combinations)
st=time.time()
total = len(p.anotation['combinations'])
iter_ = 0
cal_xz = MinMaxFlow(p.anotation['graph'])
total_ans = []
for item in p.anotation['combinations']:
iter_ += 1
if iter_ % 1000 ==0 or iter_ == total:
print(nice_print(iter_*50/total,postfix=" NP"),end="\r",sep="")
for i in range(3):
if max(item[i*2],item[i*2+1]) - min(item[i*2],item[i*2+1]) <= 8:
break
else:
cal_xz.setup(item)
ok =cal_xz.run_step()
if not ok :continue
ans = cal_xz.reduce_path_graph(map_name=lambda x:map_index_to_name[x])
total_ans.append(ans)
print(nice_print(iter_ * 50 /total,postfix=" PP"),end="\r",sep="")
end = time.time()
print("done {:.2f} - {}".format(end-st,len(total_ans)))
print(str(total_ans[0]))
if len(sys.argv) > 4:
save_file = sys.argv[4]
with open(save_file,"w") as f:
for ans in total_ans:
f.write(str(ans) + "\n")