This repository has been archived by the owner on Nov 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtspparse.py
77 lines (66 loc) · 2.52 KB
/
tspparse.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
from collections import deque
from city import GeoCoord, GeoCity, Euc_2D
def minimal_tsp():
return { "COMMENT" : ""
, "DIMENSION" : None
, "TYPE" : None
, "EDGE_WEIGHT_TYPE" : None
, "CITIES" : []}
def scan_keywords(tsp,tspfile):
for line in tspfile:
words = deque(line.split())
keyword = words.popleft().strip(": ")
if keyword == "COMMENT":
tsp["COMMENT"] += " ".join(words).strip(": ")
elif keyword == "NAME":
tsp["NAME"] = " ".join(words).strip(": ")
elif keyword == "TYPE":
tsp["TYPE"] = " ".join(words).strip(": ")
elif keyword == "DIMENSION":
tsp["DIMENSION"] = int(" ".join(words).strip(": "))
elif keyword == "EDGE_WEIGHT_TYPE":
tsp["EDGE_WEIGHT_TYPE"] = " ".join(words).strip(": ")
elif keyword == "NODE_COORD_SECTION":
break
def read_int(words):
return int(words.popleft())
def read_euc_2d_city(words):
x = float(words.popleft())
y = float(words.popleft())
return Euc_2D(x, y)
def read_geo_coord(words):
[degrees, minutes] = map(int, words.popleft().split("."))
return GeoCoord(degrees, minutes)
def read_geo_city(words):
lat = read_geo_coord(words)
lon = read_geo_coord(words)
return GeoCity(lat, lon)
def read_numbered_geo_city_line(desired_number, words):
city_number = read_int(words)
if city_number == desired_number:
return read_geo_city(words)
else:
print("Missing or mislabeld city: expected {0}".format(desired_number))
def read_numbered_euc_2d_city_line(desired_number, words):
city_number = read_int(words)
if city_number == desired_number:
return read_euc_2d_city(words)
else:
print("Missing or mislabeld city: expected {0}".format(desired_number))
def read_cities(tsp,tspfile):
for n in range(1, tsp["DIMENSION"] + 1):
line = tspfile.readline()
words = deque(line.split())
if tsp["EDGE_WEIGHT_TYPE"] == "EUC_2D":
tsp["CITIES"].append(read_numbered_euc_2d_city_line(n, words))
elif tsp["EDGE_WEIGHT_TYPE"] == "GEO":
tsp["CITIES"].append(read_numbered_geo_city_line(n, words))
else:
print("Unsupported coordinate type: " + tsp["EDGE_WEIGHT_TYPE"])
def read_tsp_file(path):
tspfile = open(path,'r')
tsp = minimal_tsp()
scan_keywords(tsp,tspfile)
read_cities(tsp,tspfile)
tspfile.close()
return tsp