forked from abigailhayes/rl-for-vrp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
287 lines (246 loc) · 9.82 KB
/
utils.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
import os
import json
import argparse
import vrplib
from pandas import Series
import numpy as np
import instances.utils as instances_utils
from methods.or_tools import ORtools
from methods.own import Own
def parse_experiment():
"""Parsing details for an experiment using main.py"""
# To handle dictionary input
class ParseKwargs(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, dict())
for value in values:
key, value = value.split("=")
getattr(namespace, self.dest)[key] = value
"""Parse arguments for an experiment run"""
parser = argparse.ArgumentParser(description="Experiment arguments")
parser.add_argument("--seed", help="Specify random seed")
parser.add_argument("--problem", help="Specify task. Options: 'CVRP', 'CVRPTW")
parser.add_argument("--training", default=None, help="Specify training data - not used")
parser.add_argument("--method", default="nazari", help="Specify solution method. Options: 'nazari', 'ortools', 'rl4co', 'rl4co_tsp', 'rl4co_mini' (reduced epochs)")
parser.add_argument(
"--method_settings",
default={},
help="Specify method specific parameters",
nargs="*",
action=ParseKwargs,
)
parser.add_argument(
"--testing", default=[], help="Specify test sets. Options: A, B, E, F, P, M, CMT and generate for CVRP, 25, 50 and 100 for CVRP-TW", type=str, nargs="*"
)
parser.add_argument(
"--device",
default=0,
help="Specify device that should be used. GPU: 0 (default), CPU: -1",
)
args, unknown = parser.parse_known_args()
args = vars(args)
return args
def instance_to_nazari(instance):
"""Convert an instance in the general format to that needed for Nazari"""
return np.roll(
np.column_stack((instance["node_coord"], instance["demand"])), -1, axis=0
).reshape(-1, instance["dimension"], 3)
def test_cvrp_nazari(model, folder_path):
"""Carry out testing on all examples in a specific folder for a Nazari model"""
results = {"greedy": {}, "beam": {}}
routes = {"greedy": {}, "beam": {}}
for example in next(os.walk(folder_path))[2]:
if example.endswith("sol"):
continue
print(example)
# Go through all test instances
data = vrplib.read_instance(f"{folder_path}/{example}")
if data["edge_weight_type"] != "EUC_2D":
continue
if model.args["n_nodes"] != data["dimension"]:
continue
model.testing(instance_to_nazari(data), data)
results["greedy"][example] = model.cost["greedy"]
results["beam"][example] = model.cost["beam"]
routes["greedy"][example] = model.routes["greedy"]
routes["beam"][example] = model.routes["beam"]
return results, routes
def test_cvrp_algm(method, method_settings, folder_path):
"""Carry out testing on all examples in a specific folder for an algorithm method"""
results = {}
routes = {}
print(folder_path)
for example in next(os.walk(folder_path))[2]:
if example.endswith("sol"):
continue
print(example)
# Go through all test instances
data = vrplib.read_instance(f"{folder_path}/{example}")
if data["edge_weight_type"] != "EUC_2D":
continue
# Set up model
if method == "ortools":
model = ORtools(
data,
method_settings["init_method"],
method_settings["improve_method"],
)
elif method == "own":
model = Own(data, method_settings)
# Get results
try:
model.run_all()
except (AttributeError, SystemError):
continue
results[example] = model.cost
routes[example] = model.routes
return results, routes
def test_cvrp_rl4co(model, folder_path):
"""Carry out testing on all examples in a specific folder for a RL4CO model"""
results = {}
routes = {}
for example in next(os.walk(folder_path))[2]:
if example.endswith("sol"):
continue
print(example)
# Go through all test instances
data = vrplib.read_instance(f"{folder_path}/{example}")
if data["edge_weight_type"] != "EUC_2D":
continue
try:
model.single_test(data)
results[example] = model.cost
routes[example] = model.routes
except AttributeError:
continue
return results, routes
def test_cvrp_other(model, method, method_settings, test_set):
"""Carry out testing on all examples in a specific folder for any model"""
results = {}
routes = {}
if method == "nazari":
results, routes = test_cvrp_nazari(model, f"instances/CVRP/{test_set}")
elif method in ["ortools", "own"]:
results, routes = test_cvrp_algm(
method, method_settings, f"instances/CVRP/{test_set}"
)
elif method in ["rl4co", "rl4co_tsp"]:
results, routes = test_cvrp_rl4co(model, f"instances/CVRP/{test_set}")
return results, routes
def test_cvrp_generate(model, method, method_settings):
"""Carry out testing on all examples across all generate folders for any model"""
# Running all tests for the generated test instances
results = {}
routes = {}
for subdir in next(os.walk("instances/CVRP/generate"))[1]:
results[subdir], routes[subdir] = test_cvrp_other(
model, method, method_settings, f"/generate/{subdir}"
)
return results, routes
def test_cvrp(method, method_settings, ident, testing, model=None, save=True):
"""Function for running CVRP testing
- method - the solution method being applied
- method_settings - any additional settings for the method
- ident - the experiment id
- testing - the testing instances to use
- model - provided for RL methods, after training"""
# Setting up dictionaries for saving results
results_a = {}
routes_a = {}
# Running testing
for test_set in testing:
print("Starting: ", test_set)
if test_set == "generate":
results_b, routes_b = test_cvrp_generate(model, method, method_settings)
else:
# Running all tests for the general test instances
results_a[test_set], routes_a[test_set] = test_cvrp_other(
model, method, method_settings, test_set
)
if save:
# Saving results
with open(f"results/exp_{ident}/results_a.json", "w") as f:
json.dump(results_a, f, indent=2)
with open(f"results/exp_{ident}/routes_a.json", "w") as f:
json.dump(routes_a, f, indent=2)
try:
with open(f"results/exp_{ident}/results_b.json", "w") as f:
json.dump(results_b, f, indent=2)
with open(f"results/exp_{ident}/routes_b.json", "w") as f:
json.dump(routes_b, f, indent=2)
except NameError:
pass
else:
results = {"a": results_a}
routes = {"a": routes_a}
try:
results["b"] = results_b
routes["b"] = routes_b
except NameError:
pass
return results, routes
def test_cvrptw(method, method_settings, ident, testing, model=None, save=True):
"""Function for running CVRP testing
- method - the solution method being applied
- method_settings - any additional settings for the method
- ident - the experiment id
- testing - the testing instances to use, indicated by numbers for the customer size
- model - provided for RL methods, after training"""
# Set up for saving results
results = {}
routes = {}
# Set up for different size versions of instances
for tester in testing:
results[tester] = {}
routes[tester] = {}
# Running testing
for example in next(os.walk(f"instances/CVRPTW/Solomon"))[2]:
# Go through all test instances
if example.endswith("sol"):
continue
print(example)
data = vrplib.read_instance(
f"instances/CVRPTW/Solomon/{example}", instance_format="solomon"
)
data["type"] = "CVRPTW"
data["dimension"] = len(data["demand"])
for tester in testing:
# Rescale instances as needed
data2 = instances_utils.shrink_twinstance(data, tester)
if method == "ortools":
model = ORtools(
data2,
method_settings["init_method"],
method_settings["improve_method"],
)
print("model done")
try:
model.run_all()
print("run all")
results[tester][example] = model.cost
routes[tester][example] = model.routes
except AttributeError:
continue
except SystemError:
try:
model.no_vehicles = 2 * model.no_vehicles
print("run all")
results[tester][example] = model.cost
routes[tester][example] = model.routes
except SystemError:
continue
elif method == "rl4co":
try:
model.single_test(data2)
results[tester][example] = model.cost
routes[tester][example] = model.routes
except (AttributeError, AssertionError):
continue
if save:
# Saving results
with open(f"results/exp_{ident}/results.json", "w") as f:
json.dump(results, f, indent=2)
with open(f"results/exp_{ident}/routes.json", "w") as f:
json.dump(routes, f, indent=2)
else:
return results, routes