-
Notifications
You must be signed in to change notification settings - Fork 1
/
simulator.py
executable file
·413 lines (305 loc) · 15.1 KB
/
simulator.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# -*- coding: utf-8 -*-
"""
Krakrobot Python Simulator
Simulator which runs the simulation and renders SVG frames.
"""
from utils import logger, logging, load_map
from Queue import Queue
import time
import datetime
from defines import *
from robot import Robot
from robot_controller import PythonTimedRobotController
from math import (
pi, sqrt, hypot, sin, cos, tan, asin, acos, atan, atan2, radians, degrees,
floor, ceil, exp
)
__author__ = u'Stanisław Jastrzębski'
__copyright__ = 'Copyright 2013-2014,\
Jagiellonian University Robotics Interest Group'
__license__ = 'MIT'
__version__ = '0.0.1a'
__maintainer__ = u'Stanisław Jastrzębski'
__email__ = 'grimghil@gmail.com'
__status__ = 'Development'
class KrakrobotSimulator(object):
COLLISION_THRESHOLD = 50
def __init__(self, map, robot_controller_class, init_position = None,
steering_noise=0.01, sonar_noise = 0.1, distance_noise=0.001,
measurement_noise=0.2,
speed = 5.0,
turning_speed = 0.4*pi,
execution_cpu_time_limit = 10.0,
simulation_time_limit = 10.0,
simulation_dt = 0.0,
frame_dt = 0.1,
gps_delay=2.0,
collision_threshold = 50,
iteration_write_frequency = 1000,
visualisation = True,
print_robot=True,
print_logger=False,
):
"""
Initialize KrakrobotSimulator object
@param steering_noise - variance of steering in move
@param distance_noise - variance of distance in move
@param measurement_noise - variance of measurement (GPS??)
@param map - map for the robot simulator representing the maze or file to map
@param init_position - starting position of the Robot (can be moved to map class) [x,y,heading]
@param speed - distance travelled by one move action (cannot be bigger than 0.5, or he could traverse the walls)
@param simulation_time_limit - limit in ms for whole robot execution (also with init)
@param collision_threshold - maximum number of collisions after which robot is destroyed
@param simulation_dt - controlls simulation calculation intensivity
@param frame_dt - save frame every dt
@param robot - RobotController class that will be simulated in run procedure
"""
if type(map) is str:
grid, metadata = load_map(map)
self.map_title = metadata["title"]
self.grid = grid
for row in grid:
logger.info(row)
else:
self.grid = map
self.map_title = ""
self.N = len(self.grid)
self.M = len(self.grid[0])
self.iteration_write_frequency = iteration_write_frequency
self.collision_threshold = collision_threshold
if init_position is not None:
self.init_position = tuple(init_position)
else:
for i in xrange(self.N):
for j in xrange(self.M):
if self.grid[i][j] == MAP_START_POSITION:
self.init_position = (i, j, 0)
self.speed = speed
self.turning_speed = turning_speed
self.simulation_dt = simulation_dt
self.frame_dt = frame_dt
self.robot_controller = robot_controller_class()
self.print_robot = print_robot
self.print_logger = print_logger
self.visualisation = visualisation
self.sonar_time = SONAR_TIME
self.gps_delay = gps_delay
self.light_sensor_time = FIELD_TIME
self.tick_move = TICK_MOVE
self.tick_rotate = TICK_ROTATE
self.simulation_time_limit = simulation_time_limit
self.execution_cpu_time_limit = execution_cpu_time_limit
self.goal_threshold = 0.5 # When to declare goal reach
self.sonar_noise = sonar_noise
self.distance_noise = distance_noise
self.measurement_noise = measurement_noise
self.steering_noise = steering_noise
self.reset()
#TODO: Disable logger printing when needed
if self.print_logger:
logger.propagate = True
else:
logger.propagate = False
for i in xrange(self.N):
for j in xrange(self.M):
if self.grid[i][j] == MAP_GOAL:
self.goal = (i,j)
def get_next_frame(self):
"""
@returns next frame of simulation data
@note the queue is thread-safe and it works like consumer-producer
those frames should be consumed by rendering thread
"""
#if len(self.sim_frames) == 0: return None
return self.sim_frames.get()
def get_next_frame_nowait(self):
"""
@returns next frame of simulation data
@note Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.sim_frames.get_nowait()
def check_goal(self, robot):
""" Checks if goal is within threshold distance"""
# dist = sqrt((float(self.goal[0]) - robot.x) ** 2 + (float(self.goal[1]) - robot.y) ** 2)
return robot.sense_field(self.grid) == MAP_GOAL#dist < self.goal_threshold
#TODO: test
def reset(self):
""" Reset state of the KrakrobotSimulator """
self.robot_path = []
self.collisions = []
self.goal_achieved = False
self.robot_timer = 0.0
self.sim_frames = Queue(100000)
self.finished = False
self.terminate_flag = False
self.logs = []
def run(self):
""" Runs simulations by quering the robot """
self.reset()
# Initialize robot object
robot = Robot(self.speed, self.turning_speed, self.gps_delay, self.sonar_time, self.tick_move, self.tick_rotate)
robot.set(self.init_position[0], self.init_position[1], self.init_position[2])
robot.set_noise(self.steering_noise,
self.distance_noise,
self.measurement_noise,
self.sonar_noise)
# Initialize robot controller object given by contestant
robot_controller = PythonTimedRobotController(self.robot_controller)
robot_controller.init(self.init_position, robot.steering_noise
,robot.distance_noise, robot.sonar_noise, robot.measurement_noise, self.speed, self.turning_speed,self.gps_delay,
self.execution_cpu_time_limit
)
maximum_timedelta = datetime.timedelta(seconds=self.execution_cpu_time_limit)
self.robot_path.append((robot.x, robot.y))
collision_counter = 0 # We have maximum collision allowed
frame_time_left = self.simulation_dt
frame_count = 0
current_command = None
iteration = 0
communicated_finished = False
try:
while not communicated_finished \
and not robot.time_elapsed >= self.simulation_time_limit \
and not self.terminate_flag:
#logger.info(robot_controller.time_consumed)
if maximum_timedelta <= robot_controller.time_consumed:
raise KrakrobotException("Robot has exceeded CPU time limit")
if iteration % self.iteration_write_frequency == 0:
logger.info("Iteration {0}, produced {1} frames".format(iteration,
frame_count))
logger.info("Elapsed {0}".format(robot.time_elapsed))
logger.info(current_command)
iteration += 1
time.sleep(self.simulation_dt)
if frame_time_left > self.frame_dt and self.visualisation:
### Save frame <=> last command took long ###
if len(self.robot_path) == 0 or\
robot.x != self.robot_path[-1][0] or robot.y != self.robot_path[-1][1]:
self.robot_path.append((robot.x, robot.y))
self.sim_frames.put(self._create_sim_data(robot))
frame_count += 1
frame_time_left -= self.frame_dt
if current_command is not None:
### Process current command ###
if current_command[0] == TURN:
robot = robot.turn(1) if current_command[1] > 0 else robot.turn(-1)
if current_command[1] > 1: current_command = [current_command[0], current_command[1] - 1]
elif current_command[1] < 1: current_command = [current_command[0], current_command[1] + 1]
else: current_command = None
frame_time_left += self.tick_rotate / self.turning_speed
elif current_command[0] == MOVE:
robot_proposed = robot.move(1)
if not robot_proposed.check_collision(self.grid):
collision_counter += 1
self.collisions.append((robot_proposed.x, robot_proposed.y))
logger.error("##Collision##")
if collision_counter >= KrakrobotSimulator.COLLISION_THRESHOLD:
raise KrakrobotException\
("The robot has been destroyed by wall. Sorry! We miss WALLE already..")
else:
robot = robot_proposed
### Register movement, just do not move the robot
if current_command[1] > 1: current_command = [current_command[0], current_command[1] - 1]
else: current_command = None
frame_time_left += self.tick_move / self.speed
else:
### Get current command ###
command = None
try:
command = list(robot_controller.act())
except Exception, e:
logger.error("Robot controller failed with exception " + str(e))
break
#logger.info("Received command "+str(command))
#logger.info("Robot timer "+str(robot.time_elapsed))
if not command or len(command) == 0:
raise KrakrobotException("No command passed, or zero length command passed")
# Dispatch command
if command[0] == SENSE_GPS:
robot_controller.on_sense_gps(*robot.sense_gps())
frame_time_left += self.gps_delay
elif command[0] == WRITE_CONSOLE:
new_line = "{'frame': " + str(frame_count) + \
", 'time': " + str(robot.time_elapsed) + \
'}:\n' + command[1]
self.logs.append(new_line)
if self.print_robot:
print new_line
elif command[0] == SENSE_SONAR:
w = robot.sense_sonar(self.grid)
robot_controller.on_sense_sonar(w)
frame_time_left += self.sonar_time
elif command[0] == SENSE_FIELD:
w = robot.sense_field(self.grid)
if w == MAP_GOAL:
print robot.x, " ", robot.y, " ", w
if type(w) is not list:
robot_controller.on_sense_field(w, 0)
else:
robot_controller.on_sense_field(w[0], w[1])
frame_time_left += self.light_sensor_time
elif command[0] == TURN:
if len(command) <= 1 or len(command) > 2:
raise KrakrobotException("Wrong command length")
current_command = command
current_command[1] = int(current_command[1])
# Turn robot
#robot = robot.turn(command[1])
elif command[0] == MOVE:
if len(command) <= 1 or len(command) > 2:
raise KrakrobotException("Wrong command length")
if command[1] < 0:
raise KrakrobotException("Not allowed negative distance")
# Move robot
current_command = command
current_command[1] = int(current_command[1])
elif command[0] == FINISH:
logger.info("Communicated finishing")
communicated_finished = True
else:
raise KrakrobotException("Not received command from act(), or command was incorrect :(")
except Exception, e:
logger.error("Simulation failed with exception " +str(e)+ " after " +str(robot.time_elapsed)+ " time")
return {"time_elapsed": robot.time_elapsed, "goal_achieved": False,
"time_consumed_robot": robot_controller.time_consumed.total_seconds()*1000,
"error":str(e)
}
logger.info("Simulation ended after "+str(robot.time_elapsed)+ " seconds with goal reached = "+str(communicated_finished and self.check_goal(robot)))
self.goal_achieved = self.check_goal(robot)
self.sim_frames.put(self._create_sim_data(robot))
while frame_time_left >= self.frame_dt and self.visualisation and not self.terminate_flag:
### Save frame <=> last command took long ###
self.sim_frames.put(self._create_sim_data(robot))
frame_time_left -= self.frame_dt
# Simulation process finished
self.finished = True
logger.info("Exiting")
try:
# Return simulation results
return {"time_elapsed": robot.time_elapsed, "goal_achieved": communicated_finished and self.check_goal(robot),
"time_consumed_robot": robot_controller.time_consumed.total_seconds()*1000,
"error": False
}
except Exception, e:
logger.error("Failed constructing result "+str(e))
return {"error":str(e)}
def get_logs(self):
return self.logs
def _create_sim_data(self, robot):
"""
@returns Descriptor that is sufficient to visualize current frame
"""
data = {}
data['GoalThreshold'] = self.goal_threshold
data['Sparks'] = []# ommiting errors list(self.collisions)
data['ActualPath'] = list(self.robot_path)
data['ActualPosition'] = [robot.x, robot.y]
data['ActualOrientation'] = robot.orientation
data['Map'] = self.grid
data['StartPos'] = self.init_position
data['GoalPos'] = self.goal
data['GoalAchieved'] = self.goal_achieved
return data
def terminate(self):
self.terminate_flag = True