-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathutils.py
More file actions
309 lines (206 loc) · 11.2 KB
/
Copy pathutils.py
File metadata and controls
309 lines (206 loc) · 11.2 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 28 12:36:43 2022
@author: aglabassi
"""
import os
import re
import numpy as np
from scipy.stats import gmean
from scipy.stats import gstd
import pyscipopt.scip as sp
from node_selection.recorders import CompFeaturizerSVM, CompFeaturizer, LPFeatureRecorder
from node_selection.node_selectors import (CustomNodeSelector,
OracleNodeSelectorAbdel,
OracleNodeSelectorEstimator_SVM,
OracleNodeSelectorEstimator_RankNet,
OracleNodeSelectorEstimator)
from learning.utils import normalize_graph
def distribute(n_instance, n_cpu):
if n_cpu == 1:
return [(0, n_instance)]
k = n_instance //( n_cpu -1 )
r = n_instance % (n_cpu - 1 )
res = []
for i in range(n_cpu -1):
res.append( ((k*i), (k*(i+1))) )
res.append(((n_cpu - 1) *k ,(n_cpu - 1) *k + r ))
return res
def get_nodesels2models(nodesels, instance, problem, normalize, device):
res = dict()
nodesels2nodeselectors = dict()
for nodesel in nodesels:
model = sp.Model()
model.hideOutput()
model.readProblem(instance)
model.setIntParam('randomization/permutationseed', 9)
model.setIntParam('randomization/randomseedshift',9)
model.setParam('constraints/linear/upgrade/logicor',0)
model.setParam('constraints/linear/upgrade/indicator',0)
model.setParam('constraints/linear/upgrade/knapsack', 0)
model.setParam('constraints/linear/upgrade/setppc', 0)
model.setParam('constraints/linear/upgrade/xor', 0)
model.setParam('constraints/linear/upgrade/varbound', 0)
comp = None
if not re.match('default*', nodesel):
try:
comp_policy, sel_policy, other = nodesel.split("_")
except:
comp_policy, sel_policy = nodesel.split("_")
if comp_policy == 'gnn':
comp_featurizer = CompFeaturizer()
feature_normalizor = normalize_graph if normalize else lambda x: x
n_primal = int(other.split('=')[-1])
comp = OracleNodeSelectorEstimator(problem,
comp_featurizer,
device,
feature_normalizor,
use_trained_gnn=True,
sel_policy=sel_policy,
n_primal=n_primal)
fr = LPFeatureRecorder(model, device)
comp.set_LP_feature_recorder(fr)
elif comp_policy == 'svm':
comp_featurizer = CompFeaturizerSVM(model)
n_primal = int(other.split('=')[-1])
comp = OracleNodeSelectorEstimator_SVM(problem, comp_featurizer, sel_policy=sel_policy, n_primal=n_primal)
elif comp_policy == 'ranknet':
comp_featurizer = CompFeaturizerSVM(model)
n_primal = int(other.split('=')[-1])
comp = OracleNodeSelectorEstimator_RankNet(problem, comp_featurizer, device, sel_policy=sel_policy, n_primal=n_primal)
elif comp_policy == 'expert':
comp = OracleNodeSelectorAbdel('optimal_plunger', optsol=0,inv_proba=0)
optsol = model.readSolFile(instance.replace(".lp", ".sol"))
comp.setOptsol(optsol)
else:
comp = CustomNodeSelector(comp_policy=comp_policy, sel_policy=sel_policy)
model.includeNodesel(comp, nodesel, 'testing', 536870911, 536870911)
else:
_, nsel_name, priority = nodesel.split("_")
assert(nsel_name in ['estimate', 'dfs', 'bfs']) #to do add other default methods
priority = int(priority)
model.setNodeselPriority(nsel_name, priority)
res[nodesel] = model
nodesels2nodeselectors[nodesel] = comp
return res, nodesels2nodeselectors
def get_record_file(problem, nodesel, instance):
save_dir = os.path.join(os.path.abspath(''), f'stats/{problem}/{nodesel}/')
try:
os.makedirs(save_dir)
except FileExistsError:
""
instance = str(instance).split('/')[-1]
file = os.path.join(save_dir, instance.replace('.lp', '.csv'))
return file
def record_stats_instance(problem, nodesel, model, instance, nodesel_obj):
nnode = model.getNNodes()
time = model.getSolvingTime()
if nodesel_obj != None:
comp_counter = nodesel_obj.comp_counter
sel_counter = nodesel_obj.sel_counter
else:
comp_counter = sel_counter = -1
if re.match('gnn*', nodesel):
init1_time = nodesel_obj.init_solver_cpu
init2_time = nodesel_obj.init_cpu_gpu
fe_time = nodesel_obj.fe_time
fn_time = nodesel_obj.fn_time
inference_time = nodesel_obj.inference_time
inf_counter = nodesel_obj.inf_counter
else:
init1_time, init2_time, fe_time, fn_time, inference_time, inf_counter = -1, -1, -1, -1, -1, -1
if re.match('svm*', nodesel) or re.match('expert*', nodesel) or re.match('ranknet*', nodesel):
inf_counter = nodesel_obj.inf_counter
file = get_record_file(problem, nodesel, instance)
np.savetxt(file, np.array([nnode, time, comp_counter, sel_counter, init1_time, init2_time, fe_time, fn_time, inference_time, inf_counter]), delimiter=',')
def print_infos(problem, nodesel, instance):
print("------------------------------------------")
print(f" |----Solving: {problem}")
print(f" |----Instance: {instance}")
print(f" |----Nodesel: {nodesel}")
def solve_and_record_default(problem, instance, verbose):
default_model = sp.Model()
default_model.hideOutput()
default_model.setIntParam('randomization/permutationseed',9)
default_model.setIntParam('randomization/randomseedshift',9)
default_model.readProblem(instance)
if verbose:
print_infos(problem, 'default', instance)
default_model.optimize()
record_stats_instance(problem, 'default', default_model, instance, None)
#take a list of nodeselectors to evaluate, a list of instance to test on, and the
#problem type for printing purposes
def record_stats(nodesels, instances, problem, device, normalize, verbose=False, default=True):
for instance in instances:
instance = str(instance)
if default and not os.path.isfile(get_record_file(problem,'default', instance)):
solve_and_record_default(problem, instance, verbose)
nodesels2models, nodesels2nodeselectors = get_nodesels2models(nodesels, instance, problem, normalize, device)
for nodesel in nodesels:
model = nodesels2models[nodesel]
nodeselector = nodesels2nodeselectors[nodesel]
#test nodesels
if os.path.isfile(get_record_file(problem, nodesel, instance)): #no need to resolve
continue
if verbose:
print_infos(problem, nodesel, instance)
model.optimize()
record_stats_instance(problem, nodesel, model, instance, nodeselector)
def get_mean(problem, nodesel, instances, stat_type):
res = []
n = 0
means = dict()
stat_idx = ['nnode', 'time', 'ncomp','nsel', 'init1', 'init2', 'fe', 'fn', 'inf','ninf'].index(stat_type)
for instance in instances:
try:
file = get_record_file(problem, nodesel, instance)
res.append(np.genfromtxt(file)[stat_idx])
n += 1
means[str(instance)] = np.genfromtxt(file)[stat_idx]
except:
''
if stat_type in ['nnode', 'time'] :
mu = np.exp(np.mean(np.log(np.array(res) + 1 )))
std = np.exp(np.sqrt(np.mean( ( np.log(np.array(res)+1) - np.log(mu) )**2 )))
else:
mu, std = np.mean(res), np.std(res)
return mu,n, means, std
def display_stats(problem, nodesels, instances, min_n, max_n, default=False):
print("======================================================")
print(f'Statistics on {problem} for problem size in [{min_n}, {max_n}]')
print("======================================================")
means_nodes = dict()
for nodesel in (['default'] if default else []) + nodesels:
nnode_mean, n, nnode_means, nnode_dev = get_mean(problem, nodesel, instances, 'nnode')
time_mean, _, _, time_dev = get_mean(problem, nodesel, instances, 'time')
ncomp_mean = get_mean(problem, nodesel, instances, 'ncomp')[0]
nsel_mean = get_mean(problem, nodesel, instances, 'nsel')[0]
means_nodes[nodesel] = nnode_means
print(f" {nodesel} ")
print(f" Mean over n={n} instances : ")
print(f" |- B&B Tree Size : {nnode_mean:.2f} ± {nnode_dev:.2f}")
if re.match('gnn*', nodesel):
in1_mean = get_mean(problem, nodesel, instances, 'init1')[0]
in2_mean = get_mean(problem, nodesel, instances, 'init2')[0]
print(f" |- Presolving A,b,c Feature Extraction Time : ")
print(f" |--- Init. Solver to CPU: {in1_mean:.2f}")
print(f" |--- Init. CPU to GPU : {in2_mean:.2f}")
print(f" |- Solving Time : {time_mean:.2f} ± {time_dev:.2f}")
#print(f" Median number of node created : {np.median(nnodes):.2f}")
#print(f" Median solving time : {np.median(times):.2f}""
if re.match('gnn*', nodesel):
fe_mean = get_mean(problem, nodesel, instances, 'fe')[0]
fn_mean = get_mean(problem, nodesel, instances, 'fn')[0]
inf_mean = get_mean(problem, nodesel, instances, 'inf')[0]
print(f" |--- On-GPU Feature Updates: {fe_mean:.2f}")
print(f" |--- Feature Normalization: {fn_mean:.2f}")
print(f" |--- Inference : {inf_mean:.2f}")
if not re.match('default*', nodesel):
print(f" |- nodecomp calls : {ncomp_mean:.0f}")
if re.match('gnn*', nodesel) or re.match('svm*', nodesel) or re.match('expert*', nodesel) or re.match('ranknet*', nodesel):
inf_counter_mean = get_mean(problem, nodesel, instances, 'ninf')[0]
print(f" |--- inference nodecomp calls: {inf_counter_mean:.0f}")
print(f" |- nodesel calls : {nsel_mean:.0f}")
print("-------------------------------------------------")
return means_nodes