-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathilp.py
428 lines (337 loc) · 18 KB
/
ilp.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
from gurobipy import GRB
import gurobipy as gp
import logging
import graph
import utils
logger = logging.getLogger(__name__)
TOLERANCE = 0.1 #tolerance allowed for Gurobi numerical values
def tail(grb_edge): return int(grb_edge.split("[")[1].split(",")[0])
def head(grb_edge): return int(grb_edge.split("[")[1].split(",")[1])
class Encode_LeastSquares:
def __init__(self,n,E,source,sink,F,edge_width,R,P2F,epsilon,timeout,threads):
self.n = n
self.m = len(E)
self.source = source
self.target = sink
self.E = E
self.F = F
self.R = R
self.vars2fix = P2F
self.epsilon = epsilon
self.k = edge_width #the largest edge antichain is a lower bound for the size of any flow decomposition
self.w_max = max(map(lambda edge : F[edge], self.E))
self.edge_vars = {}
self.pi_vars = {}
self.weights = {}
self.spc_vars = {}
self.timeout = timeout
self.threads = threads
self.model = self.create_solver()
self.final_k = None
def create_solver(self):
env = gp.Env(empty=True)
env.setParam('OutputFlag' , 0)
env.setParam('LogToConsole' , 0)
env.setParam('TimeLimit' , self.timeout)
env.setParam('Threads' , self.threads)
env.start()
model = gp.Model("MFD_LeastSquares", env=env)
if not model:
logger.error("FATAL, could not create Gurobi model")
exit(0)
return model
def clear(self):
self.model = self.create_solver()
self.edge_vars = {}
self.pi_vars = {}
self.weights = {}
self.spc_vars = {}
def solve(self):
self.model.optimize()
def encode(self):
# Create variables
edge_indexes = [ (u,v,i) for i in range(self.k) for (u, v) in self.E ]
path_indexes = [ ( i) for i in range(self.k) ]
subpath_indexes = [ (i,j ) for i in range(self.k) for j in range(len(self.R)) ]
self.edge_vars = self.model.addVars( edge_indexes, vtype=GRB.BINARY , name='e' )
self.pi_vars = self.model.addVars( edge_indexes, vtype=GRB.INTEGER, name='p', lb=0, ub=self.w_max)
self.weights = self.model.addVars( path_indexes, vtype=GRB.INTEGER, name='w', lb=1, ub=self.w_max)
self.spc_vars = self.model.addVars(subpath_indexes, vtype=GRB.BINARY , name='r' )
#The identifiers of the constraints come from https://arxiv.org/pdf/2201.10923 page 14-15
for i in range(self.k):
self.model.addConstr( self.edge_vars.sum(self.source,'*',i) == 1, "10a_i={}".format(i) )
self.model.addConstr( self.edge_vars.sum('*',self.target,i) == 1, "10b_i={}".format(i) )
for i in range(self.k):
for v in range(1,self.n-1): #find all wedges u->v->w for v in V\{s,t}
self.model.addConstr( self.edge_vars.sum('*',v,i) - self.edge_vars.sum(v,'*',i) == 0, "10c_v={}_i={}".format(v,i) )
for (u,v) in self.E:
for i in range(self.k):
self.model.addConstr( self.pi_vars[u,v,i] <= self.edge_vars[u,v,i] * self.w_max , "10e_u={}_v={}_i={}".format(u,v,i) )
self.model.addConstr( self.pi_vars[u,v,i] <= self.weights[i] , "10f_u={}_v={}_i={}".format(u,v,i) )
self.model.addConstr( self.pi_vars[u,v,i] >= self.weights[i] - (1 - self.edge_vars[u,v,i]) * self.w_max , "10g_u={}_v={}_i={}".format(u,v,i) )
#Example of a subpath constraint: R=[ [(1,3),(3,5)], [(0,1)] ], means that we have 2 paths to cover, the first one is 1-3-5. the second path is just a single edge 0-1
def EncodeSubpathConstraints():
for i in range(self.k):
for j in range(len(self.R)):
edgevars_on_subpath = list(map(lambda e: self.edge_vars[e[0],e[1],i], self.R[j]))
self.model.addConstr( sum(edgevars_on_subpath) >= len(self.R[j]) * self.spc_vars[i,j] )
for j in range(len(self.R)):
self.model.addConstr( self.spc_vars.sum('*',j) >= 1 )
def Fix_Variables():
for i in range(len(self.vars2fix)):
for (u,v) in self.vars2fix[i]:
self.model.addConstr( self.edge_vars[u,v,i] == 1 )
if self.R!=[]:
EncodeSubpathConstraints()
if self.vars2fix!=[]:
Fix_Variables()
self.model.setObjective( sum( (self.F[(u,v)] - self.pi_vars.sum(u,v,'*') )**2 for (u,v) in self.E), GRB.MINIMIZE )
def print_solution(self,solution):
opt, dif, paths = solution
print("\n#####SOLUTION#####\n","> FD size :", opt,"\n> LeastSquares difference :", dif,"\n> Weight-Path decomposition:")
for p in paths:
print(*p)
def build_solution(self):
paths = []
for i in range(self.k):
path = []
u = self.source
while u != self.target:
edges = list(filter(lambda grb_var : grb_var.X>1-TOLERANCE , self.edge_vars.select(u,'*',i) ))
assert(len(edges)==1)
v = head(edges[0].VarName)
path.append(v)
u = v
paths.append( (self.weights[i].X, path[:-1]) )
return (self.k, self.model.ObjVal, paths)
def solve_once(self):
logger.info(">>> Solving once")
self.encode()
self.solve()
logger.info("Gurobi solver status " + str(self.model.status))
if self.model.status == GRB.TIME_LIMIT:
raise utils.GRB_TimeOut("ilp.LeastSquares.solve_once while finding feasible solution")
elif self.model.status == GRB.OPTIMAL:
_,_,p = self.build_solution()
weights,paths = list(map(lambda x : x[0], p)), list(map(lambda x : x[1], p))
return (paths,weights)
else:
logger.error("FATAL: solver finished with status " + str(self.model.status) + ", which is not OPT nor TIME_LIMIT.")
def optimize_linear(self):
#Assumption: the initial value of self.k is sufficiently high so that the ILP solver starts with a feasible solution
self.encode()
self.solve()
if self.model.status == GRB.TIME_LIMIT:
self.final_k = self.k
raise utils.GRB_TimeOut("ilp.LeastSquares.optimize_linear while optimizing")
prev_obj = self.model.ObjVal
if prev_obj == 0:
logger.info(">>> No optimization step required, found perfect solution in init solving with " + str(self.k))
self.final_k = self.k
return self.final_k
self.clear()
self.k += 1
logger.info(">>> Optimality, starting with " + str(self.k))
while True: #optimality criteria: find the k for which the ratio of slacks between two consecutive iterations becomes sufficiently small
self.encode()
self.solve()
logger.info("Gurobi solver status " + str(self.model.status))
if self.model.status == GRB.TIME_LIMIT:
self.final_k = self.k - 1
raise utils.GRB_TimeOut("ilp.LeastSquares.optimize_linear while optimizing")
if self.model.ObjVal >= prev_obj: #if we do not improve by allowing more paths we stop
self.final_k = self.k-1
break
if self.model.ObjVal==0: #if we found a perfect solution we stop
self.final_k = self.k
break
assert(prev_obj != 0)
if 1-self.model.ObjVal/prev_obj < self.epsilon: # if the relative improvement is small we also stop
self.final_k = self.k - 1
break
prev_obj = self.model.ObjVal
self.clear()
self.k += 1
return self.final_k
class Encode_Robust:
def __init__(self,n,E,source,sink,F,edge_width,R,P2F,epsilon,timeout,threads):
self.n = n
self.m = len(E)
self.source = source
self.target = sink
self.E = E
self.F = F
self.R = R
self.vars2fix = P2F
self.epsilon = epsilon
self.k = edge_width #the largest edge antichain is a lower bound for the size of any flow decomposition
self.w_max = max(map(lambda edge : F[edge], self.E))
self.edge_vars = {}
self.phi_vars = {}
self.gam_vars = {}
self.weights = {}
self.slacks = {}
self.spc_vars = {}
self.timeout = timeout
self.threads = threads
self.model = self.create_solver()
self.final_k = None
def create_solver(self):
env = gp.Env(empty=True)
env.setParam('OutputFlag' , 0)
env.setParam('LogToConsole' , 0)
env.setParam('TimeLimit' , self.timeout)
env.setParam('Threads' , self.threads)
env.start()
model = gp.Model("MFD_Robust", env=env)
if not model:
logger.error("FATAL, could not create Gurobi model")
exit(0)
return model
def clear(self):
self.model = self.create_solver()
self.edge_vars = {}
self.phi_vars = {}
self.gam_vars = {}
self.weights = {}
self.slacks = {}
self.spc_vars = {}
def solve(self):
self.model.optimize()
def encode(self):
# Create variables
edge_indexes = [ (u,v,i) for i in range(self.k) for (u, v) in self.E ]
path_indexes = [ ( i) for i in range(self.k) ]
subpath_indexes = [ (i,j ) for i in range(self.k) for j in range(len(self.R)) ]
self.edge_vars = self.model.addVars( edge_indexes, vtype=GRB.BINARY , name='e' )
self.spc_vars = self.model.addVars(subpath_indexes, vtype=GRB.BINARY , name='r' )
self.phi_vars = self.model.addVars( edge_indexes, vtype=GRB.INTEGER, name='p', lb=0, ub=self.w_max)
self.gam_vars = self.model.addVars( edge_indexes, vtype=GRB.INTEGER, name='g', lb=0, ub=self.w_max)
self.weights = self.model.addVars( path_indexes, vtype=GRB.INTEGER, name='w', lb=1, ub=self.w_max)
self.slacks = self.model.addVars( path_indexes, vtype=GRB.INTEGER, name='s', lb=0, ub=self.w_max)
#The identifiers of the constraints come from https://www.biorxiv.org/content/10.1101/2023.03.20.533019v1.full.pdf page 13
for i in range(self.k):
self.model.addConstr( self.edge_vars.sum(self.source,'*',i) == 1, "14a_i={}".format(i) )
self.model.addConstr( self.edge_vars.sum('*',self.target,i) == 1, "14b_i={}".format(i) )
for i in range(self.k):
for v in range(1,self.n-1): #find all wedges u->v->w for v in V\{s,t}
self.model.addConstr( self.edge_vars.sum('*',v,i) - self.edge_vars.sum(v,'*',i) == 0, "14c_v={}_i={}".format(v,i) )
for (u,v) in self.E:
f_uv = self.F[(u,v)]
phi_sum = self.phi_vars.sum(u,v,'*')
gam_sum = self.gam_vars.sum(u,v,'*')
self.model.addConstr( f_uv - phi_sum <= gam_sum, "14d_u={}_v={}".format(u,v) )
self.model.addConstr( f_uv - phi_sum >= -gam_sum, "14e_u={}_v={}".format(u,v) )
for i in range(self.k):
self.model.addConstr( self.phi_vars[u,v,i] <= self.w_max * self.edge_vars[u,v,i] , "14f_u={}_v={}_i={}".format(u,v,i) )
self.model.addConstr( self.gam_vars[u,v,i] <= self.w_max * self.edge_vars[u,v,i] , "14i_u={}_v={}_i={}".format(u,v,i) )
self.model.addConstr( self.phi_vars[u,v,i] <= self.weights[i] , "14g_u={}_v={}_i={}".format(u,v,i) )
self.model.addConstr( self.gam_vars[u,v,i] <= self.slacks [i] , "14j_u={}_v={}_i={}".format(u,v,i) )
self.model.addConstr( self.phi_vars[u,v,i] >= self.weights[i] - (1 - self.edge_vars[u,v,i]) * self.w_max, "14h_u={}_v={}_i={}".format(u,v,i) )
self.model.addConstr( self.gam_vars[u,v,i] >= self.slacks [i] - (1 - self.edge_vars[u,v,i]) * self.w_max, "14k_u={}_v={}_i={}".format(u,v,i) )
#Example of a subpath constraint: R=[ [(1,3),(3,5)], [(0,1)] ], means that we have 2 paths to cover, the first one is 1-3-5. the second path is just a single edge 0-1
def EncodeSubpathConstraints():
for i in range(self.k):
for j in range(len(self.R)):
edgevars_on_subpath = list(map(lambda e: self.edge_vars[e[0],e[1],i], self.R[j]))
self.model.addConstr( sum(edgevars_on_subpath) >= len(self.R[j]) * self.spc_vars[i,j] )
for j in range(len(self.R)):
self.model.addConstr( self.spc_vars.sum('*',j) >= 1 )
def Fix_Variables():
for i in range(len(self.vars2fix)):
for (u,v) in self.vars2fix[i]:
self.model.addConstr( self.edge_vars[u,v,i] == 1 )
if self.R!=[]:
EncodeSubpathConstraints()
if self.vars2fix!=[]:
Fix_Variables()
self.model.setObjective( self.slacks.sum(), GRB.MINIMIZE )
def print_solution(self,solution):
opt, slack, paths = solution
print("\n#####SOLUTION#####\n","> FD size :", opt,"\n> Slack sum :", slack,"\n> Weight-Slack-Path decomposition:")
for p in paths:
print(*p)
def build_solution(self):
paths = []
for i in range(self.k):
path = []
u = self.source
while u != self.target:
edges = list(filter(lambda grb_var : grb_var.X>1-TOLERANCE , self.edge_vars.select(u,'*',i) ))
assert(len(edges)==1)
v = head(edges[0].VarName)
path.append(v)
u = v
paths.append( (self.weights[i].X, self.slacks[i].X, path[:-1]) )
return (self.k, self.model.ObjVal, paths)
def solve_once(self):
logger.info(">>> Solving once")
self.encode()
self.solve()
logger.info("Gurobi solver status " + str(self.model.status))
if self.model.status == GRB.TIME_LIMIT:
raise utils.GRB_TimeOut("ilp.Robust.solve_once while finding feasible solution")
elif self.model.status == GRB.OPTIMAL:
_,_,p = self.build_solution()
weights,paths = list(map(lambda x : x[0], p)), list(map(lambda x : x[2], p))
return (paths,weights)
else:
logger.error("FATAL: solver finished with status " + str(self.model.status) + ", which is not OPT nor TIME_LIMIT.")
def optimize_linear(self):
#Assumption: the initial value of self.k is sufficiently high so that the ILP solver starts with a feasible solution
self.encode()
self.solve()
if self.model.status == GRB.TIME_LIMIT:
self.final_k = self.k
raise utils.GRB_TimeOut("ilp.Robust.optimize_linear while optimizing")
previous_slack = self.model.ObjVal
if previous_slack == 0:
logger.info(">>> No optimization step required, found perfect solution in init solving with " + str(self.k))
self.final_k = self.k
return self.final_k
self.clear()
self.k += 1
logger.info(">>> Optimality, starting with " + str(self.k))
while True: #optimality criteria: find the k for which the ratio of slacks between two consecutive iterations becomes sufficiently small
self.encode()
self.solve()
logger.info("Gurobi solver status " + str(self.model.status))
if self.model.status == GRB.TIME_LIMIT:
self.final_k = self.k-1
raise utils.GRB_TimeOut("ilp.Robust.optimize_linear while optimizing")
if self.model.ObjVal >= previous_slack: #if we do not improve by allowing more paths we stop
self.final_k = self.k-1
break
if self.model.ObjVal==0: #if we found a perfect solution we stop
self.final_k = self.k
break
assert(previous_slack != 0)
if 1-self.model.ObjVal/previous_slack < self.epsilon: # if the relative improvement is small we also stop
self.final_k = self.k-1
break
previous_slack = self.model.ObjVal
self.clear()
self.k += 1
return self.final_k
def robust(G : graph.st_DAG, epsilon=0.25, timeout=300, threads=4, path_constraints=[], vars_to_fix=[], optimize=False):
logger.info("Robust BEGIN on graph %s", G.id)
if len(G.edge_list)==0:
logger.warning("Empty edge list in graph %s. Returning empty list of paths.", G.id)
return []
encoder = Encode_Robust(G.n, G.edge_list, G.source, G.sink, G.flow, G.w, path_constraints, vars_to_fix, epsilon, timeout, threads)
if optimize:
return encoder.optimize_linear()
else:
status,paths = encoder.solve_once()
return (status,paths)
def leastsquares(G : graph.st_DAG, epsilon=0.25, timeout=300, threads=4, path_constraints=[], vars_to_fix=[], optimize=False):
logger.info("LeastSquares BEGIN on graph %s", G.id)
if len(G.edge_list)==0:
logger.warning("Empty edge list in graph %s. Returning empty list of paths.", G.id)
return []
encoder = Encode_LeastSquares(G.n, G.edge_list, G.source, G.sink, G.flow, G.w, path_constraints, vars_to_fix, epsilon, timeout, threads)
if optimize:
return encoder.optimize_linear()
else:
status,paths = encoder.solve_once()
return (status,paths)