-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGreedy.py
188 lines (154 loc) · 7.23 KB
/
Greedy.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
from ProbGenerate import Problem, Demand
from Route import OptimalRouting
import logging, argparse, pickle, os, time
from helpers import succFun, Dependencies, overflows
import cvxpy as cp
class Greedy(OptimalRouting):
def GreedyCache(self, R, dependencies):
X = {}
for v in self.graph.nodes():
X[v] = {}
for i in range(self.catalog_size):
X[v][i] = 0
free_capacities = self.capacities.copy()
cardinality = sum(P.capacities.values())
while cardinality > 0:
delta_max = 0
for (v, i) in dependencies:
if free_capacities[v] > 0:
delta_vi = 0
temp = X[v][i]
X[v][i] = 0
for (d, p) in dependencies[(v, i)]:
item = self.demands[d].item
rate = self.demands[d].rate
paths = self.demands[d].routing_info['paths']
path = paths[p]
prob = R[d][p]
x = self.demands[d].query_source
s = succFun(x, path)
prodsofar = (1 - prob)
# calculate cost and flow after node v
while x is not v:
prodsofar *= (1 - X[x][item])
x = s
s = succFun(x, path)
while s is not None:
delta_vi += rate * self.weights[(s, x)] * prodsofar
x = s
s = succFun(x, path)
prodsofar *= (1 - X[x][item])
X[v][i] = temp
''' Record the maximum decrease'''
if delta_vi > delta_max:
new_element = (v, i)
delta_max = delta_vi
if delta_max <= 0.:
'''there is no cost reduction by placing items'''
break
else:
'''avoid placing the same item to the node twice'''
del dependencies[new_element]
v_new, i_new = new_element
if free_capacities[v_new] > 1:
X[v_new][i_new] = 1
free_capacities[v_new] -= 1
cardinality -= 1
else:
X[v_new][i_new] = free_capacities[v_new]
free_capacities[v_new] = 0
cardinality -= free_capacities[v_new]
return X
class CacheRoute(Greedy):
def alg(self):
R = {}
for d in range(len(self.demands)):
R[d] = {}
for p in self.demands[d].routing_info['paths']:
R[d][p] = 0
dependencies = Dependencies(self.demands)
X = self.GreedyCache(R, dependencies)
R = self.OptimalRoute(X)
if R:
obj = self.obj(X, R)
flow, overflow, violation = overflows(X, R, self.demands, self.bandwidths)
print('CacheRoute', obj)
return [X, R, violation, obj]
else:
print('CacheRoute: infeasible')
return [X, R, 0]
class RouteCache(Greedy):
def alg(self):
X = {}
for v in self.graph.nodes():
X[v] = {}
for i in range(self.catalog_size):
X[v][i] = 0
dependencies = Dependencies(self.demands)
R = self.OptimalRoute(X)
if R:
X = self.GreedyCache(R, dependencies)
obj = self.obj(X, R)
flow, overflow, violation = overflows(X, R, self.demands, self.bandwidths)
print('RouteCache', obj)
return [X, R, violation, obj]
else:
print('RouteCache: infeasible')
return [X, R, 0]
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Run Greedy',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('inputfile', help='Output file')
parser.add_argument('--graph_type', default="erdos_renyi", type=str, help='Graph type',
choices=['erdos_renyi', 'balanced_tree', 'hypercube', "cicular_ladder", "cycle", "grid_2d",
'lollipop', 'expander', 'star', 'barabasi_albert', 'watts_strogatz',
'regular', 'powerlaw_tree', 'small_world', 'geant', 'abilene', 'dtelekom',
'servicenetwork', 'example1', 'example2', 'abilene1', 'abilene2', 'real1', 'real2'])
parser.add_argument('--catalog_size', default=1000, type=int, help='Catalog size')
parser.add_argument('--graph_size', default=100, type=int, help='Network size')
parser.add_argument('--query_nodes', default=10, type=int, help='Number of nodes generating queries')
parser.add_argument('--demand_size', default=5000, type=int, help='Demand size')
parser.add_argument('--max_capacity', default=20, type=int, help='Maximum capacity per cache')
parser.add_argument('--bandwidth_coefficient', default=1, type=float,
help='Coefficient of bandwidth for max flow, this coefficient should be between (1, max_paths)')
parser.add_argument('--bandwidth_type', default=1, type=int,
help='Type of generating bandwidth: 1. no cache, 2. uniform cache, 3. random integer cache')
parser.add_argument('--debug_level', default='INFO', type=str, help='Debug Level',
choices=['INFO', 'DEBUG', 'WARNING', 'ERROR'])
args = parser.parse_args()
args.debug_level = eval("logging." + args.debug_level)
logging.basicConfig(level=args.debug_level)
dir = "INPUT%d/" % (args.bandwidth_type)
input = dir + args.inputfile + "_%s_%ditems_%dnodes_%dquerynodes_%ddemands_%dcapcity_%fbandwidth" % (
args.graph_type, args.catalog_size, args.graph_size, args.query_nodes, args.demand_size,
args.max_capacity, args.bandwidth_coefficient)
P = Problem.unpickle_cls(input)
logging.info('Read data from ' + input)
CR = CacheRoute(P)
time1 = time.time()
result = CR.alg()
time2 = time.time()
duration = [time2-time1]
result = duration + result
dir = "Greedy%d/CacheRoute/" % (args.bandwidth_type)
if not os.path.exists(dir):
os.makedirs(dir)
fname = dir + "%s_%ditems_%dnodes_%dquerynodes_%ddemands_%dcapcity_%fbandwidth" % (
args.graph_type, args.catalog_size, args.graph_size, args.query_nodes, args.demand_size, args.max_capacity, args.bandwidth_coefficient)
logging.info('Save in ' + fname)
with open(fname, 'wb') as f:
pickle.dump(result, f)
RC = RouteCache(P)
time1 = time.time()
result = RC.alg()
time2 = time.time()
duration = [time2-time1]
result = duration + result
dir = "Greedy%d/RouteCache/" % (args.bandwidth_type)
if not os.path.exists(dir):
os.makedirs(dir)
fname = dir + "%s_%ditems_%dnodes_%dquerynodes_%ddemands_%dcapcity_%fbandwidth" % (
args.graph_type, args.catalog_size, args.graph_size, args.query_nodes, args.demand_size, args.max_capacity, args.bandwidth_coefficient)
logging.info('Save in ' + fname)
with open(fname, 'wb') as f:
pickle.dump(result, f)