-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphTsp.py
197 lines (148 loc) · 6.27 KB
/
graphTsp.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
# coding: utf-8
# pylint: disable=missing-docstring, invalid-name, attribute-defined-outside-init, unsubscriptable-object
import os
import re
import pickle
import gzip
import tsplib95
import numpy as np
from log import log
from graph import GraphXY, Tour
# graph imported from TSPLIB
class GraphTSP(GraphXY):
TSPdir = 'TSPLIB'
TSPurl = 'http://comopt.ifi.uni-heidelberg.de/software/TSPLIB95/tsp/ALL_tsp.tar.gz'
def __init__(self, tspname = 'eil51'):
self.tsp, self.opt, nNodes = GraphTSP.get_tsp(tspname)
if self.tsp:
self.tspname = tspname
self.optTour = self.get_opt_tour()
super(GraphTSP, self).__init__(nNodes)
else:
self.isvalid = False
def get_names(self):
nameWoDigit = re.split(r'([\d]+)', self.tspname)[0]
self.name = r'{%s_{%d}}' %(nameWoDigit.capitalize(), self.nNodes) # for print
self.pname = f'{self.tspname}' # for matplotlib
self.fname = self.pname # for file
def get_opt_tour(self):
if self.opt:
toindex = dict((n, i) for i, n in enumerate(self.tsp.get_nodes()))
path = [toindex[n] for n in self.opt.tours[0]]
path.append(path[0]) # back to start
path = np.array(path)
length = self.tsp.trace_tours(self.opt.tours)[0]
return Tour(length = length, path = path)
return None
def get_node_labels(self):
return np.fromiter(self.tsp.get_nodes(), int)
# get all nodes Xs & Ys
def get_nodes(self):
XY = np.array([self.tsp.get_display(n) for n in self.tsp.get_nodes()], dtype='d')
return XY[:, 0], XY[:, 1] #Xs & Ys are the first & second column
def get_mat_dist(self):
nx = __import__('networkx')
return nx.to_numpy_matrix(self.tsp.get_graph())
# load a TSP file from TSPLIB
@staticmethod
def get_tsp(name):
tspdir = GraphTSP.TSPdir
tspfile = os.path.join(tspdir, f'{name}.tsp.gz')
optfile = os.path.join(tspdir, f'{name}.opt.tour.gz')
if os.path.exists(tspfile):
with gzip.open(tspfile, 'rt') as f:
tsp = tsplib95.parse(f.read())
if os.path.exists(optfile):
with gzip.open(optfile, 'rt') as f:
opt = tsplib95.parse(f.read())
else:
opt = None
needs = {'symmetric' : tsp.is_symmetric(),
'depictable' : tsp.is_depictable(),
'complete' : tsp.is_complete(),
'2D euclidian' : tsp.edge_weight_type=='EUC_2D',
'not special' : not tsp.is_special()}
if all(needs.values()):
log (f"{name} loaded {'with' if opt else 'without'} optimal tour")
return tsp, opt, tsp.dimension
errors = ' & '.join((f'{what}' for what, test in needs.items() if test is False))
log (f'{name} INVALID, should be {errors}')
else:
log (f'{name} NOT available')
return None, None, None
# get a dict of valid TSPs in TSPLIB
@staticmethod
def get_all_valid_tsp(forceupdate = False):
tspdir = GraphTSP.TSPdir
# create tspdir & download if tspdir doesn't exist
if GraphTSP.create_tsp_dir():
GraphTSP.download_tsp()
# file to store the 'state' of tspdir to track its change
tspchgfile = os.path.join(tspdir, f'{tspdir}.tspchg')
# get a list of (filename, modified time, size) in tspdir in nonrecursive way
newTspchg = []
for fname in os.listdir(tspdir):
if fname.endswith('.gz'): # only tsp files
fname = os.path.join(tspdir, fname)
stat = os.stat(fname)
newTspchg.append((fname, stat.st_mtime, stat.st_size))
newTspchg.sort()
tspchgfile = os.path.join(tspdir, f'{tspdir}.tspchg')
# get last state of tspdir if available
tspchg = []
if os.path.exists(tspchgfile):
with open(tspchgfile, 'rb') as f:
tspchg = pickle.load(f)
# check for change in tspdir
if tspchg != newTspchg:
forceupdate = True
with open(tspchgfile, 'wb') as f:
pickle.dump(newTspchg, f)
# get the valid tsp files list
tspdictfile = os.path.join(tspdir, f'{tspdir}.tsps')
if forceupdate or not os.path.exists(tspdictfile):
log ('create valid TSP list')
tsps = {}
for fname in os.listdir(tspdir):
if '.tsp.' in fname and fname.endswith('.gz'):
tspname = fname.split('.')[0]
tsp, opt, nodes = GraphTSP.get_tsp(tspname)
if tsp:
tsps[tspname] = {'nodes': nodes, 'opt': opt is not None}
# sort in nb of nodes order
tsps = sorted(tsps.items(), key=lambda item: item[1]['nodes'])
with open(tspdictfile, 'wb') as f:
pickle.dump(tsps, f)
else:
log ('load valid TSP list')
with open(tspdictfile, 'rb') as f:
tsps = pickle.load(f)
return tsps, list(name for name, value in tsps if value['opt'])
# create TSPdir if it doesn't exist
@staticmethod
def create_tsp_dir():
tspdir = GraphTSP.TSPdir
# create tspdir if it doesn't exist
if not os.path.exists(tspdir):
os.makedirs(tspdir)
return True
return False
# download all TSP
@staticmethod
def download_tsp():
log ('download all TSP')
requests = __import__('requests')
tarfile = __import__('tarfile')
BytesIO = __import__('io').BytesIO
r = requests.get(GraphTSP.TSPurl)
if r.status_code == 200:
with BytesIO(r.content) as gzdata:
with tarfile.open(fileobj=gzdata) as tar:
tar.extractall(GraphTSP.TSPdir)
tars = set(n.split('.')[0] for n in tar.getnames())
log (f'{len(tars)} tsps downloaded')
return
if __name__ == '__main__':
GraphTSP.create_tsp_dir()
GraphTSP.download_tsp()
GraphTSP.get_all_valid_tsp(True)