-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
263 lines (202 loc) · 8.9 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import time
import threading
import numpy as np
import networkx as nx
from UDPComms import Subscriber,timeout
from utils import Transform, Robot, PointCloud
from output import Vizualizer
from pose_graph import PoseGraph
from optimization import solve_pg_rotations
class SLAM:
def __init__(self):
self.viz = Vizualizer(mm_per_pix=20)
self.odom = Subscriber(8810, timeout=0.2)
self.lidar = Subscriber(8110, timeout=0.1)
self.robot = Robot()
self.ploted_robot = Robot()
self.update_time = time.time()
self.odom_transform = Transform.fromComponents(0)
self.odom_transfrom_lock = threading.Lock()
self.graph = nx.DiGraph()
self.graph_lock = threading.Lock()
self.pg = PoseGraph(self.graph)
self.opt = False
self.running = True
self.threads = []
self.threads.append( threading.Thread( target = self.update_odom, daemon = True) )
self.threads.append( threading.Thread( target = self.update_lidar, daemon = True) )
for thread in self.threads:
thread.start()
self.viz.after(100,self.update_viz)
self.viz.protocol("WM_DELETE_WINDOW", self.quit)
self.viz.mainloop()
def quit(self):
# pg = PoseGraph(self.graph)
self.pg.save("output.json")
print("quitting")
self.viz.destroy()
def update_viz(self):
try:
# self.viz.plot_Robot(self.ploted_robot, tag="ploted")
# self.viz.plot_Robot(self.robot, c="blue", tag="main")
with self.graph_lock:
self.pg.plot(self.viz, plot_pc=True)
# for node,data in self.graph.nodes.items():
# r = Robot()
# r.transform = data['pose'].copy()
# pc = data['pc'].copy()
# if(node not in self.viz.tags.keys()):
# self.viz.plot_PointCloud(pc, tag=str(pc)+str(node))
# self.viz.plot_Robot(r, tag=node, c="green")
# for edge, data in self.graph.edges.items():
# t = str(edge[0])+"_"+str(edge[1])
# if t not in self.viz.tags:
# print("plooting edge", edge[0], edge[1])
# p1 = self.graph.nodes[edge[0]]['pose'].get_components()[1]
# p2 = self.graph.nodes[edge[1]]['pose'].get_components()[1]
# self.viz.plot_line(p1, p2, tag=t)
self.running = all([thread.is_alive() for thread in self.threads])
if not self.running:
raise RuntimeError
except:
self.running = False
raise
self.viz.after( 100 , self.update_viz)
def update_odom(self):
dt = 0.1
while self.running:
start = time.time()
try:
da, dy = self.odom.get()['single']['odom']
except timeout:
# print("odom timeout")
continue
da *= dt
dy *= dt
t = Transform.fromOdometry(da, (0,dy))
with self.odom_transfrom_lock:
self.odom_transform = t.combine(self.odom_transform)
self.ploted_robot.drive(t)
self.viz.plot_Robot(self.ploted_robot, tag="ploted")
# print("odom dt", time.time() - start)
sleep = max(0, dt - (time.time() - start) )
time.sleep(sleep)
# if self.opt:
# return
def local_keyframes(self):
MAX_DIST = 800
robot = self.robot.get_transform().get_components()[1]
out = []
for node,data in self.graph.nodes(data=True):
loc = data['pose'].get_components()[1]
distance = np.linalg.norm(robot - loc)
if distance < MAX_DIST:
out.append( (distance, node,) )
return sorted(out)
# def opt_graph(self):
# with self.graph_lock:
# print("optimizing cycle 2 ")
# solve_pg_rotations(self.pg, also_positions=True, hold_steady=self.nearest)
# self.viz.after(500, self.opt_graph)
def update_lidar(self):
dt = 0.1
while self.running:
start = time.time()
try:
scan = self.lidar.get()
except timeout:
# print("lidar timeout")
continue
if len(scan) < 50:
continue
pc = PointCloud.fromScan(scan)
# lidar in robot frame
pc = pc.move(Transform.fromComponents(0, (-100,0) ))
pc.pose = self.robot.get_transform()
# raw_pc = pc.copy()
# pc = pc.move( self.robot.get_transform() )
if self.graph.number_of_nodes() == 0:
if pc.points.shape[0] < 50:
continue
# self.scan = pc
with self.graph_lock:
self.graph.add_node(0, pc = pc.copy(), pose = pc.pose.copy() )
# self.viz.plot_PointCloud(pc)
# self.viz.plot_Robot(self.robot, c="green")
continue
self.viz.plot_PointCloud(pc, c="blue", tag="current")
keyframes = self.local_keyframes()
opt = False
first = True
added_id = None
for dist, node in keyframes:
print("mathcing node", node)
frame = self.graph.nodes[node]['pc']
cloud, transform, number_matched = frame.fitICP(pc)
new_points = pc.points.shape[0] - number_matched
new_points = 0
new_keyframe_distace = 300 # 300
print("new points", new_points)
if cloud is None:
print("match failed") #TODO
# self.viz.plot_PointCloud(frame.move(transform), c="red", tag="failed")
continue
if first:
self.nearest = node
print("robot pos updated")
self.robot.move(transform)
first = False
if dist < new_keyframe_distace and new_points < 150:
print("closest key frame happy")
break
if dist < new_keyframe_distace and new_points < 150: #400
print("closest key frame happy")
continue
print("new keyframe")
with self.graph_lock:
if added_id is None:
added_id = self.graph.number_of_nodes()
self.closest = added_id
self.graph.add_node(added_id, pc = cloud.copy(), pose=cloud.pose.copy()) #, raw_pc = raw_pc, pose = self.robot.get_transform().copy())
# edge_transfrom = self.robot.get_transform().copy().combine(self.graph.nodes[node]['pose'].inv())
edge_transform = frame.pose.combine( cloud.pose.inv() )
self.graph.add_edge(added_id, node, transform=edge_transform)
if np.abs(node - added_id) > 5:
print("optimizing cycle")
self.opt = True
if self.opt:
for k in range(5):
with self.graph_lock:
print("optimizing cycle", k)
solve_pg_rotations(self.pg, also_positions=True, hold_steady=0)
time.sleep(0.2)
# self.viz.after(500, self.opt_graph)
# try:
# cycles = nx.find_cycle(self.graph,added_id, orientation="ignore")
# except nx.NetworkXNoCycle:
# print("no cycle")
# pass
# else:
# print("cycle found")
# print(cycles)
# if max( len(c) for c in cycles) > 4:
# print("optimizing cycle")
# solve_pg_rotations(self.pg, also_positions=True, hold_steady=added_id)
with self.odom_transfrom_lock:
self.robot.drive(self.odom_transform)
self.odom_transform = Transform.fromComponents(0)
self.ploted_robot.transform = self.robot.get_transform().copy()
print("lidar dt", time.time() - start)
time.sleep(dt)
if __name__ == "__main__":
s = SLAM()
# v = Vizualizer()
# s1 = PointCloud.fromScan(scan1).move(Transform.fromComponents(0, (400,0)))
# s2 = PointCloud.fromScan(scan2).move(Transform.fromComponents(15, (400,0)))
# v.plot_PointCloud(s1)
# v.plot_PointCloud(s2, c="blue")
# s3, transform = s1.fitICP(s2)
# # v.plot_PointCloud(s3, c="green")
# s4 = s2.move(transform)
# v.plot_PointCloud(s4, c="green")
# v.mainloop()