-
Notifications
You must be signed in to change notification settings - Fork 1
/
runtest.py
executable file
·82 lines (66 loc) · 2.22 KB
/
runtest.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
#!/usr/bin/python
import os, sys, subprocess, math, time
timeout = 2000
def runtest(executable, test):
p = subprocess.Popen([executable], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
f = open(test)
data = ""
positions = list()
for line in f:
data += line
w = line.split(" ")
if len(w) < 2:
continue
pos = float(w[0]), float(w[1])
positions.append(pos)
starttime = time.time()
stdout, stderr = p.communicate(input=data)
if stderr or stdout == "":
raise Exception("Stderr: " + stderr)
endtime = time.time() - starttime
path = [int(l) for l in stdout.split("\n") if l != ""]
dist = getPathDistance(positions, path)
if endtime >= 2.0:
raise Exception("Time limit exceeded " + str(endtime) + "s. \n" + "Answer was still valid: " + str(dist) + " "+ str(endtime));
return dist, endtime
def getPathDistance(positions, path):
distance = 0.0
prevPos = positions[path[0]]
visited = set()
visited.add(path[0])
for next in path[1:]:
if next in visited:
raise Exception("Validation failed. Revisited the same node! Node: " + str(next))
visited.add(next)
nextPos = positions[next]
distance += math.sqrt(abs(prevPos[0] - nextPos[0])**2 + abs(prevPos[1] - nextPos[1])**2)
#print nextPos
prevPos = nextPos
# check so all nodes were visited.
if len(visited) != len(positions):
missing = ""
for i in range(len(positions)):
if not i in visited:
missing += str(i) + " "
raise Exception("Validation failed. Did not visit all nodes! missing: " + missing )
distance += math.sqrt(abs(prevPos[0] - positions[path[0]][0])**2 + abs(prevPos[1] - positions[path[0]][1])**2)
return distance
def testTheTest():
p = 0, 0
p2 = 0, 1
p3 = 2, 2
assert(2.0 == getPathDistance([p, p2], [0, 1]))
assert(math.sqrt(8.0)*2 == getPathDistance([p, p3], [0, 1]))
assert(math.sqrt(1) + math.sqrt(5) + math.sqrt(8.0) == getPathDistance([p, p2, p3], [0, 1, 2]))
if __name__ == '__main__':
if len(sys.argv) < 3:
print """
USAGE: runtest.py <executable_file> <test_file>
Will run given TSP test using executable and print distance of
the path found and time taken.
"""
exit(1)
#print time.time()
testTheTest()
print runtest(sys.argv[1], sys.argv[2])
#print time.time()