-
Notifications
You must be signed in to change notification settings - Fork 1
/
optimization.py
275 lines (217 loc) · 8.91 KB
/
optimization.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
# Copyright (c) 2023 VISTEC - Vidyasirimedhi Institute of Science and Technology
# Distribute under MIT License
# Authors:
# - Sucha Supittayapornpong <sucha.s[-at-]vistec.ac.th>
# - Kanatip Chitavisutthivong <kanatip.c_s18[-at-]vistec.ac.th>
import time
import pickle
import networkx as nx
import gurobipy as gp
import os
import itertools
import state_helper as helper
from state_helper import HCONST
DEFAULT_MAX_TIMEOUT = 12 * 60 * 60 # 12 hours
class Optimization:
"""
Class Optimization
...
Attributes
----------
Name : str
a class name
NumLPThread : int
a number of thread
MaxTimeout : bool
solver maximum time out
Topo : Topology
Topology object
M : gurobipy.Model
optimization model
R : gurobipy.Variable
throughput variable
F : dict
flow variables
B : dict
source auxiliary
G : dict
destination auxiliary
"""
def __init__(self, topology, numLPThread=1, maxTimeout=DEFAULT_MAX_TIMEOUT):
self.Name = 'Optimization-' + topology.Name
self.NumLPThread = numLPThread
self.MaxTimeout = maxTimeout
self.Topo = topology
self.M = None # Optimization model
self.R = None # Throughput variable
self.F = None # Flow variables
self.B = None # Source auxiliary
self.G = None # Destination auxiliary
parameters = (self.Name, self.NumLPThread)
pickle.dump(parameters, open(HCONST['outputpath'] + '/' + 'Parameters', 'wb'))
pickle.dump(self.Topo, open(HCONST['outputpath'] + '/' + 'Topology', 'wb'))
print('-------------------------')
print('Step: Optimization')
print('-------------------------')
def optimize(self):
if os.path.exists(HCONST['outputpath'] + '/' + 'ComputedThroughput'):
print("\t Existing optimal solution is available.")
return
overallOptTime = time.time()
iterationTimes = dict()
self.initialModel()
self.createVariables()
self.setObjective()
self.setFlowConservationConstraint()
self.setAdditionalFlowConstraint()
self.setAuxThroughputConstraint()
self.setAuxFlowConstraint()
opttime = time.time()
throughput = self.computeOptimalSolution()
opttime = time.time() - opttime
if throughput != None:
print('\t Throughput = {0:.5}, Opttime = {1:.2f}'.format(throughput, opttime))
pickle.dump(throughput, open(HCONST['outputpath'] + '/' + 'ComputedThroughput', 'wb'))
pickle.dump(opttime, open(HCONST['outputpath'] + '/' + 'OptimizationTime', 'wb'))
self.saveOptimalRouting()
def initialModel(self):
M = gp.Model(name=self.Name)
M.setParam('OutputFlag', 0)
M.setParam('Threads', self.NumLPThread)
M.setParam('Method', -1)
M.setParam('TimeLimit', self.MaxTimeout)
self.M = M
def createVariables(self):
M = self.M
Topo = self.Topo
R = M.addVar(lb=0, vtype=gp.GRB.CONTINUOUS, name='r')
self.R = R
F = dict()
for repsd in Topo.RepCommodities:
F[repsd] = dict()
for repflowlink in Topo.RepCommFlowLinks[repsd]:
linkcap = Topo.UG.get_edge_data(*repflowlink)['capacity']
F[repsd][repflowlink] = M.addVar(lb=0, ub=linkcap,
vtype=gp.GRB.CONTINUOUS,
name='f_{0}_{1}_{2}_{3}'.format(repsd[0], repsd[1],
repflowlink[0], repflowlink[1]))
self.F = F
B = dict() # beta
for repaux in Topo.RepAuxiliarys:
B[repaux] = M.addVar(lb=0, vtype=gp.GRB.CONTINUOUS, name='b_{0}_{1}_{2}'.format(*repaux))
self.B = B
G = dict() # gamma
for repaux in Topo.RepAuxiliarys:
G[repaux] = M.addVar(lb=0, vtype=gp.GRB.CONTINUOUS, name='g_{0}_{1}_{2}'.format(*repaux))
self.G = G
def setObjective(self):
Topo = self.Topo
M = self.M
R = self.R
M.setObjective(R, sense=gp.GRB.MINIMIZE)
def setFlowConservationConstraint(self):
Topo = self.Topo
M = self.M
F = self.F
for repsd in Topo.RepCommodities:
s, d = repsd
flowmap = Topo.loadCommodityFlowLinkMap(repsd)
nodes = Topo.AllNodes
for n in nodes:
flowin = sum(F[repsd][flowmap[h, n]] for h in Topo.UG.neighbors(n)) + (1 if n == s else 0)
flowout = sum(F[repsd][flowmap[n, h]] for h in Topo.UG.neighbors(n)) + (1 if n == d else 0)
M.addConstr(flowin == flowout, name='fc_{0}_{1}_{2}'.format(s, d, n))
def setAdditionalFlowConstraint(self):
Topo = self.Topo
M = self.M
F = self.F
# No flows to routing non-capable nodes
for repsd in Topo.RepCommodities:
s, d = repsd
avoidlinks = itertools.product(Topo.AllNodes, Topo.NonRouteNodes.difference([d]))
for i, j in Topo.RepCommFlowLinks[repsd].intersection(avoidlinks):
M.addConstr(F[repsd][i, j] == 0, name='afa_{0}_{1}_{2}_{3}'.format(s, d, i, j))
# No flows route back to source and route away from destination
for repsd in Topo.RepCommodities:
s, d = repsd
for i, j in Topo.RepCommFlowLinks[repsd]:
if j == s or i == d:
M.addConstr(F[repsd][i, j] == 0, name='afc_{0}_{1}_{2}_{3}'.format(s, d, i, j))
def setAuxThroughputConstraint(self):
Topo = self.Topo
M = self.M
B = self.B
G = self.G
R = self.R
for i, j in Topo.RepLinkConstrs:
lhs = 0
for u in Topo.HostNodes:
linkauxtorep = Topo.loadAuxToRep(u)
auxidx = linkauxtorep[i, j]
lhs += Topo.UG.nodes[u]['numServer'] * (B[auxidx] + G[auxidx])
M.addConstr(lhs <= R, name='auxtc_{0}_{1}'.format(i, j))
def setAuxFlowConstraint(self):
Topo = self.Topo
M = self.M
F = self.F
B = self.B
G = self.G
for repsd in Topo.RepCommodities:
for repflowlink in Topo.RepCommFlowLinks[repsd]:
linkcap = Topo.UG.get_edge_data(*repflowlink)['capacity']
srclinkauxtorep = Topo.loadAuxToRep(repsd[0])
bauxidx = srclinkauxtorep[repflowlink]
dstlinkauxtorep = Topo.loadAuxToRep(repsd[1])
gauxidx = dstlinkauxtorep[repflowlink]
lhs = F[repsd][repflowlink]/linkcap - B[bauxidx] - G[gauxidx]
M.addConstr(lhs <= 0, name='auxfc_{0}_{1}_{2}_{3}'.format(*repsd, *repflowlink))
def computeOptimalSolution(self):
M = self.M
M.optimize()
if M.status == gp.GRB.OPTIMAL:
throughput = 1.0/M.ObjVal
return throughput
elif M.status == gp.GRB.TIME_LIMIT:
self.saveIntermediateRouting()
return None
else:
print('****', M.status)
assert False, 'Main optimization fails'
def saveOptimalRouting(self):
Topo = self.Topo
F = self.F
g = nx.DiGraph()
for node in Topo.UG.nodes():
g.add_node(node)
for i, j in Topo.UG.edges():
g.add_edge(i, j)
g.add_edge(j, i)
for repsd in Topo.RepCommodities:
flowmap = Topo.loadCommodityFlowLinkMap(repsd)
flowij = F[repsd][flowmap[i, j]].X
flowji = F[repsd][flowmap[j, i]].X
if flowij > 0:
g[i][j][repsd] = flowij
if flowji > 0:
g[j][i][repsd] = flowji
pickle.dump(g, open(HCONST['outputpath'] + '/' + 'OptimalRouting', 'wb'))
def saveIntermediateRouting(self):
Topo = self.Topo
F = self.F
g = nx.DiGraph()
for node in Topo.UG.nodes():
g.add_node(node)
for i, j in Topo.UG.edges():
g.add_edge(i, j)
g.add_edge(j, i)
for repsd in Topo.RepCommodities:
flowmap = Topo.loadCommodityFlowLinkMap(repsd)
flowij = F[repsd][flowmap[i, j]].X
flowji = F[repsd][flowmap[j, i]].X
if flowij > 0:
g[i][j][repsd] = flowij
if flowji > 0:
g[j][i][repsd] = flowji
pickle.dump(g, open(HCONST['outputpath'] + '/' + 'IntermediateRouting', 'wb'))
intermediatesolution = {v.varName: v.X for v in M.getVars()}
pickle.dump(intermediatesolution, open(HCONST['outputpath'] + '/' + 'IntermediateSolution', 'wb'))