-
Notifications
You must be signed in to change notification settings - Fork 6
/
TraceConverter.py
83 lines (63 loc) · 2.18 KB
/
TraceConverter.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
import math
import sys
import numpy as np
import copy
from DistanceUtils import lineAngle, distanceBetween, angleBetween
TRACE_STEP = 5
DISTANCE_THRESHOLD = 0.55
class TraceConverter():
def __init__(self, traces, distanceThreshold = None):
self.traces = copy.deepcopy(traces)
self.hasMadeLines = False
self.lines = []
if not distanceThreshold:
self.distanceThreshold = DISTANCE_THRESHOLD
else:
print ('--- Threshold: ' + str(distanceThreshold) + ' ---')
self.distanceThreshold = distanceThreshold
def getLines(self):
if not self.hasMadeLines:
self.lines = self.convertTracesToLines()
self.hasMadeLines = True
return self.lines
def convertTracesToLines(self):
lines = []
print('Converting Traces to Lines')
i = 0
for trace in self.traces:
# Print Progress dots
i += 1
if i % len(self.traces) / 50 == 0:
sys.stdout.write('.')
sys.stdout.flush()
lines.append(self.traceToLine(trace))
print ('Done')
return lines
def traceToLine(self, trace):
line = [trace[0]]
while len(trace):
lineSection = []
for i in range(TRACE_STEP):
if len(trace):
lineSection.append(trace.pop(0))
while self.getLineDistanceAverage(lineSection) < self.distanceThreshold:
if len(trace):
lineSection.append(trace.pop(0))
else:
break
line.append(lineSection[-1])
return line
def getLineDistanceAverage(self, points):
xs = [p[0] for p in points]
ys = [p[1] for p in points]
if all([xs[0] == x for x in xs]) or all([ys[0] == y for y in ys]):
return 0
a1, c1 = np.polyfit(xs, ys, 1)
b1 = -1
distanceAvg = 0
for point in points:
x = point[0]
y = point[1]
distanceAvg += float(abs(a1*x + b1*y + c1))/math.sqrt(a1**2 + b1**2)
distanceAvg = distanceAvg / len(points)
return distanceAvg