-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
172 lines (145 loc) · 4.95 KB
/
main.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
import sys
import math
class node(object):
def __init__(self, city,g = 0, tc = 0,f = 0,parent = None):
self.city = city
self.g = g
self.f = f
self.tc = tc
self.parent = parent
class FindRoute(object) :
def __init__( self, inputFile = None, originCity = None, destinationCity = None, heuristicFile = None) :
self.inputData = {}
self.heuristicData = {}
self.start = originCity
self.goal = destinationCity
if inputFile is not None :
self.parseInputData( inputFile )
if heuristicFile is not None :
self.parseHeuristicData( heuristicFile )
def parseInputData( self, inputFile ) :
try:
fp = open(inputFile, 'r')
lines = fp.read().replace('\r', '' ).split( '\n' )
for line in lines:
if line and line != 'END OF INPUT':
line_arr = line.strip().split(' ')
if line_arr[0].lower() in self.inputData:
self.inputData[line_arr[0].lower()].append((line_arr[1].lower(), int(line_arr[2])))
else:
self.inputData[line_arr[0].lower()] = []
self.inputData[line_arr[0].lower()].append((line_arr[1].lower(), int(line_arr[2])))
if line_arr[1].lower() in self.inputData:
self.inputData[line_arr[1].lower()].append((line_arr[0].lower(), int(line_arr[2])))
else:
self.inputData[line_arr[1].lower()] = []
self.inputData[line_arr[1].lower()].append((line_arr[0].lower(), int(line_arr[2])))
finally:
fp.close()
def parseHeuristicData( self, inputFile ) :
try:
fp = open(inputFile, 'r')
lines = fp.read().replace('\r', '' ).split( '\n' )
for line in lines:
if line and line != 'END OF INPUT':
line_arr = line.strip().split(' ')
self.heuristicData[line_arr[0].lower()] = int(line_arr[1])
finally:
fp.close()
def getLeastFvalueNode(nodes):
leastFNode = None
for node in nodes:
if leastFNode is None:
leastFNode = node
elif leastFNode.f > node.f:
leastFNode = node
return leastFNode
def getTentativeCost(cities, node):
for city in cities:
if city[0] == node:
return city[1]
return 0
def getCost(model, node, parentCost):
cost = 0
if model.start != node:
cost = parentCost.g + getTentativeCost(model.inputData[parentCost.city], node)
return cost
def getFValue(model, node, parentCost = None):
heuristic = 0
cost = 0
if node in model.heuristicData:
heuristic = model.heuristicData[node]
if model.start != node:
cost = getCost(model, node, parentCost)
return (cost, cost + heuristic)
def getNeighbor(model, node):
return model.inputData[node.city]
def generateNodes(model, neighbours, parent):
Nodes = {}
for nbour in neighbours:
cost, fvalue = getFValue(model, nbour[0], parent)
Nodes[nbour[0]] = node(nbour[0],cost,nbour[1], fvalue,parent)
return Nodes
def performSearch(model, start, goal):
opened = set()
closed = set()
fvalue = getFValue(model, start)
expanded = 1
startNode = node(start,0,0, fvalue[1], parent = None)
opened.add(startNode)
current = start
while opened:
current = getLeastFvalueNode(opened)
neighbours = getNeighbor(model, current)
neighboursNodes = generateNodes(model, neighbours, current)
if current.city == goal:
path = []
while current.parent:
path.append(current)
current = current.parent
path.append(current)
return (path[::-1],expanded)
opened.remove(current)
closed.add(current)
for nodes in neighboursNodes:
if neighboursNodes[nodes] in closed:
continue
if nodes not in [cities.city for cities in closed]:
if neighboursNodes[nodes] not in opened and nodes != model.start:
opened.add(neighboursNodes[nodes])
expanded +=1
return ([],expanded)
#---------#---------#---------#---------#---------#--------#
def _main() :
# Get the file name and the other arguments.
argLength = len(sys.argv)
if argLength >= 4:
fName = sys.argv[1]
origin_city = sys.argv[2].lower()
destination_city = sys.argv[3].lower()
if argLength > 4:
hName = sys.argv[4]
else:
hName = None
model = FindRoute( fName, origin_city, destination_city, hName )
path,expanded = performSearch(model,origin_city, destination_city)
paths = [p.city for p in path]
print(" --> ".join(paths))
distance = sum(map(lambda x: x.tc, path))
print("nodes expanded: %d"%(expanded))
if distance and len(path) > 1:
print("distance: %d km"%(distance))
print("route:")
for i in range(len(path) -1):
print("%s to %s, %d km"%(path[i].city, path[i+1].city, path[i+1].tc))
elif len(path) == 1:
print("distance: %d km"%(distance))
print("route:")
print("%s to %s, %d km"%(path[0].city, path[0].city, path[0].tc))
else:
print("distance: infinity")
print("route: none")
else:
print("Please enter all the required parameters")
if __name__ == '__main__' :
_main()