-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
183 lines (168 loc) · 7.44 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
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/python3
#-*- coding: utf-8 -*-
from pprint import pprint, pformat
from problem import problem
from frontier import frontier
from treeNode import treeNode
from subprocess import call
from state import state
from lxml import etree
import time, sys, gc, os
def main():
filename, strategy, depthl, pruning, stat, heu = askInfo()
if(strategy == 3): depthi = int(input('depth increment: '))
p = problem('%s.json' % filename)
print(p._state_space._path.lower())
itime = time.time()
#run algorithms
if(strategy == 3): sol, num_f = search(p, strategy, depthl, depthi, pruning, heu)
else: sol, num_f = limSearch(p, strategy, depthl, pruning, heu)
etime = time.time()
createSolution(sol, itime, etime, num_f)
createGpx(p, sol, itime, etime, num_f, stat)
call(['solu/gpx2svg', '-i', 'solu/out.gpx', '-o', 'solu/out.svg'])
def askInfo():
"""
:return: all user inputs needed to run the program
:raises ValueError: not entering a valid input
"""
try:
filename = input('json file: ')
if filename.isdigit():
raise ValueError
print(filename + ".json") #print json file name
switch = {
0: 'breath-first search', 1: 'depth-first search', 2: 'depth-limited search',\
3: 'iterative deepening search', 4: 'uniform cost search', 5: 'greedy search', 6: 'a* search'}
print("\n".join("{}: {}".format(k, v) for k, v in switch.items()))
strategy = int(input('strategy: ')); heu = 'h0'
if isinstance(strategy, str) or strategy > 6 or strategy < 0: raise ValueError
if(strategy == 5 or strategy == 6): heu = input('heuristic(h0/h1): ').lower()
if not (heu == 'h1' or heu == 'h0'): raise ValueError
yes = {'y','yes','yay'}; no = {'n','no','nay'}
pruning = input('pruning(y/n): ').lower()
if pruning in yes: pruning = True; stat = switch[strategy] + ' w/ pruning'; print(stat)
elif pruning in no: pruning = False; stat = switch[strategy] + ' w/o pruning'; print(stat)
else: raise ValueError
depthl = int(input('depth: '))-1
if isinstance(depthl, str): raise ValueError
return filename, strategy, depthl, pruning, stat, heu
except ValueError:
print("error. not a valid input")
sys.exit(1)
def limSearch(problem, strategy, depthl, pruning, heu):
"""
:param problem: problem class object
:param strategy: strategy int
:param depthl: depth limit int
:param pruning: pruning option boolean
:param heu: heuristic string
:return: goal node and number of elements in the frontier
"""
f = frontier(); problem._visitedList = {}
num_f = 0
initial = treeNode(problem._init_state, strategy)
f.insert(initial); num_f += 1
problem._visitedList[initial._state._md5] = initial._f
sol = False
while(not sol and not f.isEmpty()):
act = f.remove()
if(problem.isGoal(act._state)): sol = True
else:
ls = problem._state_space.successors(act._state)
ln = problem.createTreeNodes(ls, act, depthl, strategy, heu)
if pruning:
for node in ln:
if node._state._md5 not in problem._visitedList:
f.insert(node); num_f += 1
problem._visitedList[node._state._md5] = node._f
elif abs(node._f) < abs(problem._visitedList[node._state._md5]):
f.insert(node); num_f += 1
problem._visitedList[node._state._md5] = node._f
else:
for node in ln: f.insert(node); num_f += 1
if(sol): return act, num_f
else: return None
def search(problem, strategy, depthl, depthi, pruning, heu):
"""
:param problem: problem class object
:param strategy: strategy int
:param depthl: depth limit int
:param depthi: depth limit increment
:param pruning: pruning option boolean
:param heu: heuristic string
:return: path to the problem's solution
"""
depthact = depthi
sol = None
while(not sol and depthact <= depthl+1):
sol = limSearch(problem, strategy, depthact, pruning, heu)
depthact += depthi
return sol
def createSolution(sol, itime, etime, num_f):
"""
creates txt file with the solution + statistics
:param sol: problem solution
:param itime: initial time
:param etime: end time
:param num_f: number of elements in the frontier
"""
txt = open('solu/out.txt','w')
if(sol is not None):
list = []
act = sol
list.append(act._action)
while(act._parent is not None and act._parent._action is not None):
list.append(act._parent._action)
act = act._parent
list.reverse()
print('cost: %.3f, depth: %d, spatialcxty: %d, temporalcxty: %fs\ncheck out.txt for more info' % (sol._cost, sol._d, num_f, etime-itime))
line1 = 'cost: %.3f, depth: %d, spatialcxty: %d, temporalcxty: %fs\n' % (sol._cost, sol._d, num_f, etime-itime)
line2 = 'goal node: %s - %s\n' % (sol, sol._state._current)
line3 = time.strftime('time and date: %H:%M:%S-%d/%m/%Y\n\n')
line4 = pformat(list)
txt.writelines([line1, line2, line3, line4])
else:
print('no solution found for the given depth limit')
txt.write('no solution found for the given depth limit')
txt.close()
def createGpx(problem, sol, itime, etime, num_f, stat):
"""
creates gpx(xml) file representing the solution
:param problem: problem class object
:param sol: problem solution
:param itime: initial time
:param etime: end time
:param num_f: number of elements in the frontier
:param stat: strategy string
"""
if(sol is not None):
list, points = [], []
act = sol
list.append(problem._state_space.positionNode(act._state._current))
while(act._parent is not None):
list.append(problem._state_space.positionNode(act._parent._state._current))
act = act._parent
list.reverse()
points.append(problem._init_state._current)
for i in problem._init_state._nodes: points.append(i)
gpx = open('solu/out.gpx','wb')
root = etree.Element('gpx', version='1.0'); root.text = '\n'
for n in points:
wpt = etree.SubElement(root, 'wpt', lat=problem._state_space.positionNode(n)[0], lon=problem._state_space.positionNode(n)[1]); wpt.tail = '\n'
w_name = etree.SubElement(wpt, 'name'); w_name.text = n
w_desc = etree.SubElement(wpt, 'desc'); w_desc.text = problem._state_space.positionNode(n)[0] + ', ' + problem._state_space.positionNode(n)[1]
trk = etree.SubElement(root, 'trk')
t_name = etree.SubElement(trk, 'name'); t_name.text = 'out.gpx'; t_name.tail = '\n'
desc = etree.SubElement(trk, 'desc'); desc.text = '%s, cost: %.3f, depth: %d, scxty: %d, tcxty: %fs' % (stat, sol._cost, sol._d, num_f, etime-itime); desc.tail = '\n'
link = etree.SubElement(trk, 'link', href='http://www.uclm.es')
text = link = etree.SubElement(link, 'text'); text.text = 'uclm project'
trkseg = etree.SubElement(trk, 'trkseg'); trkseg.text = '\n'
for n in list:
trkpt = etree.SubElement(trkseg, 'trkpt', lat=n[0].zfill(10), lon=n[1].zfill(10)); trkpt.tail = '\n'
date = etree.SubElement(trkpt, 'time'); date.text = time.strftime('%Y-%m-%dT%H:%M:%S')
doc = etree.ElementTree(root)
doc.write(gpx, xml_declaration=True, encoding='utf-8')
gpx.close()
if __name__ == '__main__':
main()