-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvs.py
2779 lines (2318 loc) · 133 KB
/
envs.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import pkgutil
import sys
from abc import ABC, abstractmethod
from multiprocessing.connection import Client
from pathlib import Path
from pprint import pprint
# import anki_vector
import numpy as np
import pybullet
import pybullet_utils.bullet_client as bc
from scipy.ndimage import rotate as rotate_image
from scipy.ndimage.morphology import distance_transform_edt
from skimage.draw import line
from skimage.morphology import binary_dilation, dilation
from skimage.morphology.selem import disk
import vector_utils
from shortest_paths.shortest_paths import GridGraph
class VectorEnv:
WALL_HEIGHT = 0.1
CUBE_WIDTH = 0.044
RECEPTACLE_WIDTH = 0.15
IDENTITY_QUATERNION = (0, 0, 0, 1)
REMOVED_BODY_Z = -1000 # Hide removed bodies 1000 m below
CUBE_COLOR = (237.0 / 255, 201.0 / 255, 72.0 / 255, 1) # Yellow
DEBUG_LINE_COLORS = [
(78.0 / 255, 121.0 / 255, 167.0 / 255), # Blue
(89.0 / 255, 169.0 / 255, 79.0 / 255), # Green
(176.0 / 255, 122.0 / 255, 161.0 / 255), # Purple
(242.0 / 255, 142.0 / 255, 43.0 / 255), # Orange
]
def __init__(
# This comment is here to make code folding work
self, robot_config=None, room_length=1.0, room_width=0.5, num_cubes=10, env_name='small_empty',
use_robot_map=True, use_distance_to_receptacle_map=False, distance_to_receptacle_map_scale=0.25,
use_shortest_path_to_receptacle_map=True, use_shortest_path_map=True, shortest_path_map_scale=0.25,
use_intention_map=False, intention_map_encoding='ramp',
intention_map_scale=1.0, intention_map_line_thickness=2,
use_history_map=False,
use_intention_channels=False, intention_channel_encoding='spatial', intention_channel_nonspatial_scale=0.025,
use_shortest_path_partial_rewards=True, success_reward=1.0, partial_rewards_scale=2.0,
lifting_pointless_drop_penalty=0.25, obstacle_collision_penalty=0.25, robot_collision_penalty=1.0,
use_shortest_path_movement=True, use_partial_observations=True,
inactivity_cutoff_per_robot=100,
random_seed=None, use_egl_renderer=False,
show_gui=False, show_debug_annotations=False, show_occupancy_maps=False,
real=False, real_robot_indices=None, real_cube_indices=None, real_debug=False,
use_visit_frequency_map=False, visit_frequency_map_scale=0.00,
use_cube_location_map=False, cube_location_map_scale=0.00,
use_shortest_path_to_cube_map=False,
use_shortest_path_to_rescue_robot_map=False,
):
################################################################################
# Arguments
# Room configuration
self.robot_config = robot_config
self.room_length = room_length
self.room_width = room_width
self.num_cubes = num_cubes
self.env_name = env_name
# State representation
self.use_robot_map = use_robot_map
self.use_distance_to_receptacle_map = use_distance_to_receptacle_map
self.distance_to_receptacle_map_scale = distance_to_receptacle_map_scale
self.use_shortest_path_to_receptacle_map = use_shortest_path_to_receptacle_map
self.use_shortest_path_map = use_shortest_path_map
self.shortest_path_map_scale = shortest_path_map_scale
self.use_intention_map = use_intention_map
self.intention_map_encoding = intention_map_encoding
self.intention_map_scale = intention_map_scale
self.intention_map_line_thickness = intention_map_line_thickness
self.use_history_map = use_history_map
self.use_intention_channels = use_intention_channels
self.intention_channel_encoding = intention_channel_encoding
self.intention_channel_nonspatial_scale = intention_channel_nonspatial_scale
self.use_visit_frequency_map = use_visit_frequency_map
self.visit_frequency_map_scale = visit_frequency_map_scale
self.use_shortest_path_to_cube_map = use_shortest_path_to_cube_map
self.use_cube_location_map = use_cube_location_map
self.cube_location_map_scale = cube_location_map_scale
self.use_shortest_path_to_rescue_robot_map = use_shortest_path_to_rescue_robot_map
# Rewards
self.use_shortest_path_partial_rewards = use_shortest_path_partial_rewards
self.success_reward = success_reward
self.partial_rewards_scale = partial_rewards_scale
self.lifting_pointless_drop_penalty = lifting_pointless_drop_penalty
self.obstacle_collision_penalty = obstacle_collision_penalty
self.robot_collision_penalty = robot_collision_penalty
# Misc
self.use_shortest_path_movement = use_shortest_path_movement
self.use_partial_observations = use_partial_observations
self.inactivity_cutoff_per_robot = inactivity_cutoff_per_robot
self.random_seed = random_seed
self.use_egl_renderer = use_egl_renderer
# Debugging
self.show_gui = show_gui
self.show_debug_annotations = show_debug_annotations
self.show_occupancy_maps = show_occupancy_maps
# Real environment
self.real = real
self.real_robot_indices = real_robot_indices
self.real_cube_indices = real_cube_indices
self.real_debug = real_debug
pprint(self.__dict__)
################################################################################
# Set up pybullet
if self.show_gui:
self.p = bc.BulletClient(connection_mode=pybullet.GUI)
self.p.configureDebugVisualizer(pybullet.COV_ENABLE_GUI, 0)
else:
self.p = bc.BulletClient(connection_mode=pybullet.DIRECT)
# if self.use_egl_renderer:
# assert sys.platform == 'linux' # Linux only
# self.plugin_id = self.p.loadPlugin(pkgutil.get_loader('eglRenderer').get_filename(), "_eglRendererPlugin")
self.p.resetDebugVisualizerCamera(
0.47 + (5.25 - 0.47) / (10 - 0.7) * (self.room_length - 0.7), 0, -70,
(0, -(0.07 + (1.5 - 0.07) / (10 - 0.7) * (self.room_width - 0.7)), 0))
# Used to determine whether robot poses are out of date
self.step_simulation_count = 0
################################################################################
# Robots and room configuration
# Random placement of robots, cubes, and obstacles
self.room_random_state = np.random.RandomState(self.random_seed)
self.robot_spawn_bounds = None
self.cube_spawn_bounds = None
# Robots
if self.robot_config is None:
self.robot_config = [{'lifting_robot': 1}]
self.num_robots = sum(sum(g.values()) for g in self.robot_config)
self.robot_group_types = [next(iter(g.keys())) for g in self.robot_config]
self.robot_ids = None
self.robots = None
self.robot_groups = None
self.robot_random_state = np.random.RandomState(self.random_seed + 1 if self.random_seed is not None else None) # Add randomness to throwing
# Room
self.obstacle_ids = None
self.cube_ids = None
self.receptacle_id = None
if not any('rescue_robot' in g for g in self.robot_config):
self.receptacle_position = (self.room_length / 2 - VectorEnv.RECEPTACLE_WIDTH / 2, self.room_width / 2 - VectorEnv.RECEPTACLE_WIDTH / 2, 0)
# Collections for keeping track of environment state
self.obstacle_collision_body_b_ids_set = None # For collision detection
self.robot_collision_body_b_ids_set = None # For collision detection
self.available_cube_ids_set = None # Excludes removed cubes, and cubes that are being lifted, thrown, or rescued
self.found_cube_ids_set = None
self.removed_cube_ids_set = None # Cubes that have been removed
################################################################################
# Misc
# End an episode after too many steps of inactivity
self.inactivity_cutoff = self.num_robots * self.inactivity_cutoff_per_robot
# Stats
self.steps = None
self.simulation_steps = None
self.inactivity_steps = None
################################################################################
# Real environment
if self.real:
assert len(self.real_robot_indices) == self.num_robots
assert len(self.real_cube_indices) == self.num_cubes
self.real_robot_indices_map = None
self.real_cube_indices_map = None
# Connect to aruco server for pose estimates
address = 'localhost'
if self.env_name.startswith('large'):
# Left camera, right camera
self.conns = [Client((address, 6001), authkey=b'secret password'), Client((address, 6002), authkey=b'secret password')]
else:
self.conns = [Client((address, 6000), authkey=b'secret password')]
def reset(self):
# Disconnect robots
if self.real:
self._disconnect_robots()
# Reset pybullet
self.p.resetSimulation()
self.p.setRealTimeSimulation(0)
self.p.setGravity(0, 0, -9.8)
# Create env
self._create_env()
if self.real:
self.real_robot_indices_map = dict(zip(self.robot_ids, self.real_robot_indices))
self.real_cube_indices_map = dict(zip(self.cube_ids, self.real_cube_indices))
# Reset poses
if self.real:
self.update_poses()
else:
self._reset_poses()
self._step_simulation_until_still()
# Set awaiting new action for first robot
self._set_awaiting_new_action()
# State representation
for robot in self.robots:
robot.update_map()
# Stats
self.steps = 0
self.simulation_steps = 0
self.inactivity_steps = 0
return self.get_state()
def store_new_action(self, action):
for robot_group, robot_group_actions in zip(self.robot_groups, action):
for robot, a in zip(robot_group, robot_group_actions):
if a is not None:
robot.store_new_action(a)
def step(self, action):
################################################################################
# Setup before action execution
self.store_new_action(action)
# Store initial cube positions for pushing partial rewards
if any(isinstance(robot, PushingRobot) for robot in self.robots):
initial_cube_positions = {}
for cube_id in self.available_cube_ids_set:
initial_cube_positions[cube_id] = self.get_cube_position(cube_id)
################################################################################
# Execute actions
if self.real:
sim_steps = self._execute_actions_real()
else:
sim_steps = self._execute_actions()
self._set_awaiting_new_action()
################################################################################
# Process cubes after action execution
for cube_id in self.available_cube_ids_set.copy():
cube_position = self.get_cube_position(cube_id)
# Reset out-of-bounds cubes
if (cube_position[2] > VectorEnv.WALL_HEIGHT + 0.49 * VectorEnv.CUBE_WIDTH or # On top of obstacle
cube_position[2] < 0.4 * VectorEnv.CUBE_WIDTH): # Inside obstacle (0.4 since dropped cubes can temporarily go into the ground)
pos_x, pos_y, heading = self._get_random_cube_pose()
self.reset_cube_pose(cube_id, pos_x, pos_y, heading)
continue
if self.receptacle_id is not None:
closest_robot = self.robots[np.argmin([distance(robot.get_position(), cube_position) for robot in self.robots])]
# Process final cube position for pushing partial rewards
if isinstance(closest_robot, PushingRobot):
closest_robot.process_cube_position(cube_id, initial_cube_positions)
# Process cubes that are in the receptacle (cubes were pushed in)
if self.cube_position_in_receptacle(cube_position):
closest_robot.process_cube_success()
self.remove_cube(cube_id)
self.available_cube_ids_set.remove(cube_id)
# Robots that are awaiting new action need an up-to-date map
for robot in self.robots:
if robot.awaiting_new_action:
robot.update_map()
################################################################################
# Compute rewards and stats
# Increment counters
self.steps += 1
self.simulation_steps += sim_steps
if sum(robot.cubes for robot in self.robots) > 0:
self.inactivity_steps = 0
else:
self.inactivity_steps += 1
# Episode ends after too many steps of inactivity
done = len(self.removed_cube_ids_set) == self.num_cubes or self.inactivity_steps >= self.inactivity_cutoff
# Compute per-robot rewards and stats
for robot in self.robots:
if robot.awaiting_new_action or done:
robot.compute_rewards_and_stats(done=done)
################################################################################
# Compute items to return
state = [[None for _ in g] for g in self.robot_groups] if done else self.get_state()
reward = [[robot.reward if (robot.awaiting_new_action or done) else None for robot in robot_group] for robot_group in self.robot_groups]
info = {
'steps': self.steps,
'simulation_steps': self.simulation_steps,
'distance': [[robot.distance if (robot.awaiting_new_action or done) else None for robot in g] for g in self.robot_groups],
'cumulative_cubes': [[robot.cumulative_cubes if (robot.awaiting_new_action or done) else None for robot in g] for g in self.robot_groups],
'cumulative_distance': [[robot.cumulative_distance if (robot.awaiting_new_action or done) else None for robot in g] for g in self.robot_groups],
'cumulative_reward': [[robot.cumulative_reward if (robot.awaiting_new_action or done) else None for robot in g] for g in self.robot_groups],
'cumulative_obstacle_collisions': [[robot.cumulative_obstacle_collisions if (robot.awaiting_new_action or done) else None for robot in g] for g in self.robot_groups],
'cumulative_robot_collisions': [[robot.cumulative_robot_collisions if (robot.awaiting_new_action or done) else None for robot in g] for g in self.robot_groups],
'total_cubes': sum(robot.cumulative_cubes for robot in self.robots),
'total_obstacle_collisions': sum(robot.cumulative_obstacle_collisions for robot in self.robots),
'total_robot_collisions': sum(robot.cumulative_robot_collisions for robot in self.robots),
}
return state, reward, done, info
def get_state(self, all_robots=False, save_figures=False):
return [[robot.get_state(save_figures=save_figures) if robot.awaiting_new_action or all_robots else None for robot in robot_group] for robot_group in self.robot_groups]
def close(self):
if not self.show_gui and self.use_egl_renderer:
self.p.unloadPlugin(self.plugin_id)
self.p.disconnect()
if self.real:
self._disconnect_robots()
def step_simulation(self):
self.p.stepSimulation()
#import time; time.sleep(1.0 / 60)
self.step_simulation_count += 1
def get_cube_pose(self, cube_id):
return self.p.getBasePositionAndOrientation(cube_id)
def get_cube_position(self, cube_id):
position, _ = self.get_cube_pose(cube_id)
return position
def reset_cube_pose(self, cube_id, pos_x, pos_y, heading):
position = (pos_x, pos_y, VectorEnv.CUBE_WIDTH / 2)
self.p.resetBasePositionAndOrientation(cube_id, position, heading_to_orientation(heading))
def remove_cube(self, cube_id):
self.p.resetBasePositionAndOrientation(cube_id, (0, 0, VectorEnv.REMOVED_BODY_Z), VectorEnv.IDENTITY_QUATERNION)
self.removed_cube_ids_set.add(cube_id)
def cube_position_in_receptacle(self, cube_position):
assert self.receptacle_id is not None
half_width = (VectorEnv.RECEPTACLE_WIDTH - VectorEnv.CUBE_WIDTH) / 2
#if (self.receptacle_position[0] - half_width < cube_position[0] < self.receptacle_position[0] + half_width and
# self.receptacle_position[1] - half_width < cube_position[1] < self.receptacle_position[1] + half_width):
if cube_position[0] > self.receptacle_position[0] - half_width and cube_position[1] > self.receptacle_position[1] - half_width:
# Note: Assumes receptacle is in top right corner
return True
return False
def get_robot_group_types(self):
return self.robot_group_types
@staticmethod
def get_state_width():
return Mapper.LOCAL_MAP_PIXEL_WIDTH
@staticmethod
def get_num_output_channels(robot_type):
return Robot.get_robot_cls(robot_type).NUM_OUTPUT_CHANNELS
@staticmethod
def get_action_space(robot_type):
return VectorEnv.get_num_output_channels(robot_type) * Mapper.LOCAL_MAP_PIXEL_WIDTH * Mapper.LOCAL_MAP_PIXEL_WIDTH
def get_camera_image(self, image_width=1024, image_height=768):
renderer = pybullet.ER_BULLET_HARDWARE_OPENGL if self.show_gui else pybullet.ER_TINY_RENDERER
return self.p.getCameraImage(image_width, image_height, flags=pybullet.ER_NO_SEGMENTATION_MASK, renderer=renderer)[2]
def start_video_logging(self, video_path):
assert self.show_gui
return self.p.startStateLogging(pybullet.STATE_LOGGING_VIDEO_MP4, video_path)
def stop_video_logging(self, log_id):
self.p.stopStateLogging(log_id)
def update_poses(self):
assert self.real
# Get new pose estimates
for conn in self.conns:
if self.real_debug:
debug_data = [(robot.waypoint_positions, robot.target_end_effector_position, robot.controller.debug_data) for robot in self.robots]
#debug_data = [(robot.controller.get_intention_path(), robot.target_end_effector_position, robot.controller.debug_data) for robot in self.robots]
#debug_data = [(robot.controller.get_history_path(), robot.target_end_effector_position, robot.controller.debug_data) for robot in self.robots]
conn.send(debug_data)
else:
conn.send(None)
for conn in self.conns:
robot_poses, cube_poses = conn.recv()
# Update cube poses
if cube_poses is not None:
for cube_id in self.available_cube_ids_set:
cube_pose = cube_poses.get(self.real_cube_indices_map[cube_id], None)
if cube_pose is not None:
self.reset_cube_pose(cube_id, cube_pose['position'][0], cube_pose['position'][1], cube_pose['heading'])
for robot in self.robots:
# Update robot poses
if robot_poses is not None:
robot_pose = robot_poses.get(self.real_robot_indices_map[robot.id], None)
if robot_pose is not None:
robot.reset_pose(robot_pose['position'][0], robot_pose['position'][1], robot_pose['heading'])
if cube_poses is not None:
if isinstance(robot, (LiftingRobot, ThrowingRobot, RescueRobot)) and robot.cube_id is not None:
cube_pose = cube_poses.get(self.real_cube_indices_map[robot.cube_id])
if cube_pose is not None:
if isinstance(robot, LiftingRobot):
robot.controller.monitor_lifted_cube(cube_pose)
elif isinstance(robot, ThrowingRobot):
self.reset_cube_pose(robot.cube_id, cube_pose['position'][0], cube_pose['position'][1], cube_pose['heading'])
if isinstance(robot, RescueRobot):
robot.controller.monitor_rescued_cube(cube_pose)
self.step_simulation()
def _create_env(self):
# Assertions
assert self.room_length >= self.room_width
assert self.num_cubes > 0
assert all(len(g) == 1 for g in self.robot_config) # Each robot group should be homogeneous
assert not len(self.robot_group_types) > 4 # More than 4 groups not supported
if any('rescue_robot' in g for g in self.robot_config):
assert all(robot_type == 'rescue_robot' or robot_type == 'exploring_robot' or robot_type == 'uav_robot' for g in self.robot_config for robot_type in g)
# Create floor
floor_thickness = 10
wall_thickness = 1.4
room_length_with_walls = self.room_length + 2 * wall_thickness
room_width_with_walls = self.room_width + 2 * wall_thickness
floor_half_extents = (room_length_with_walls / 2, room_width_with_walls / 2, floor_thickness / 2)
floor_collision_shape_id = self.p.createCollisionShape(pybullet.GEOM_BOX, halfExtents=floor_half_extents)
floor_visual_shape_id = self.p.createVisualShape(pybullet.GEOM_BOX, halfExtents=floor_half_extents)
self.p.createMultiBody(0, floor_collision_shape_id, floor_visual_shape_id, (0, 0, -floor_thickness / 2))
# Create obstacles (including walls)
obstacle_color = (0.9, 0.9, 0.9, 1)
rounded_corner_path = str(Path(__file__).parent / 'assets' / 'rounded_corner.obj')
self.obstacle_ids = []
self.uav_obstacle_ids = []
for obstacle in self._get_obstacles(wall_thickness):
if obstacle['type'] == 'corner':
obstacle_collision_shape_id = self.p.createCollisionShape(pybullet.GEOM_MESH, fileName=rounded_corner_path)
obstacle_visual_shape_id = self.p.createVisualShape(pybullet.GEOM_MESH, fileName=rounded_corner_path, rgbaColor=obstacle_color)
else:
half_height = VectorEnv.CUBE_WIDTH / 2 if 'low' in obstacle else VectorEnv.WALL_HEIGHT / 2
obstacle_half_extents = (obstacle['x_len'] / 2, obstacle['y_len'] / 2, half_height)
obstacle_collision_shape_id = self.p.createCollisionShape(pybullet.GEOM_BOX, halfExtents=obstacle_half_extents)
obstacle_visual_shape_id = self.p.createVisualShape(pybullet.GEOM_BOX, halfExtents=obstacle_half_extents, rgbaColor=obstacle_color)
obstacle_id = self.p.createMultiBody(
0, obstacle_collision_shape_id, obstacle_visual_shape_id,
(obstacle['position'][0], obstacle['position'][1], VectorEnv.WALL_HEIGHT / 2), heading_to_orientation(obstacle['heading']))
self.obstacle_ids.append(obstacle_id)
if obstacle['type'] != 'wall':
self.uav_obstacle_ids.append(obstacle_id)
# Create target receptacle
if not any('rescue_robot' in g for g in self.robot_config):
receptacle_color = (1, 87.0 / 255, 89.0 / 255, 1) # Red
receptacle_collision_shape_id = self.p.createCollisionShape(pybullet.GEOM_BOX, halfExtents=(0, 0, 0))
receptacle_visual_shape_id = self.p.createVisualShape(
#pybullet.GEOM_BOX, halfExtents=(VectorEnv.RECEPTACLE_WIDTH / 2, VectorEnv.RECEPTACLE_WIDTH / 2, 0), # Gets rendered incorrectly in EGL renderer if height is 0
pybullet.GEOM_BOX, halfExtents=(VectorEnv.RECEPTACLE_WIDTH / 2, VectorEnv.RECEPTACLE_WIDTH / 2, 0.0001),
rgbaColor=receptacle_color, visualFramePosition=(0, 0, 0.0001))
self.receptacle_id = self.p.createMultiBody(0, receptacle_collision_shape_id, receptacle_visual_shape_id, self.receptacle_position)
# Create robots
self.robot_collision_body_b_ids_set = set()
self.robot_ids = []
self.robots = [] # Flat list
self.robot_groups = [[] for _ in range(len(self.robot_config))] # Grouped list
for robot_group_index, g in enumerate(self.robot_config):
robot_type, count = next(iter(g.items()))
for _ in range(count):
if self.real:
real_robot_index = self.real_robot_indices[len(self.robots)]
robot = Robot.get_robot(robot_type, self, robot_group_index, real=True, real_robot_index=real_robot_index)
else:
robot = Robot.get_robot(robot_type, self, robot_group_index)
self.robots.append(robot)
self.robot_groups[robot_group_index].append(robot)
self.robot_ids.append(robot.id)
# Create cubes
cube_half_extents = (VectorEnv.CUBE_WIDTH / 2, VectorEnv.CUBE_WIDTH / 2, VectorEnv.CUBE_WIDTH / 2)
cube_collision_shape_id = self.p.createCollisionShape(pybullet.GEOM_BOX, halfExtents=cube_half_extents)
cube_visual_shape_id = self.p.createVisualShape(pybullet.GEOM_BOX, halfExtents=cube_half_extents, rgbaColor=VectorEnv.CUBE_COLOR)
cube_mass = 0.024 # 24 g
self.cube_ids = []
for _ in range(self.num_cubes):
cube_id = self.p.createMultiBody(cube_mass, cube_collision_shape_id, cube_visual_shape_id)
self.cube_ids.append(cube_id)
# Initialize collections
self.obstacle_collision_body_b_ids_set = set(self.obstacle_ids)
self.robot_collision_body_b_ids_set.update(self.robot_ids)
self.available_cube_ids_set = set(self.cube_ids)
self.found_cube_ids_set = set()
self.removed_cube_ids_set = set()
# Remove collisions for uav_robots
for robot in self.robots:
if hasattr(robot, 'uav'):
for cube_id in self.cube_ids:
self.p.setCollisionFilterPair(robot.id, cube_id, -1, -1, 0)
for obstacle_id in self.uav_obstacle_ids:
self.p.setCollisionFilterPair(robot.id, obstacle_id, -1, -1, 0)
for robot_b in self.robots:
if not hasattr(robot_b, 'uav'):
self.p.setCollisionFilterPair(robot.id, robot_b.id, -1, -1, 0)
def _get_obstacles(self, wall_thickness):
# if self.env_name.startswith('small'):
# assert math.isclose(self.room_length, 1)
# assert math.isclose(self.room_width, 0.5)
# elif self.env_name.startswith('large'):
# assert math.isclose(self.room_length, 1)
# assert math.isclose(self.room_width, 1)
def add_divider(x_offset=0):
divider_width = 0.05
opening_width = 0.16
obstacles.append({'type': 'divider', 'position': (x_offset, 0), 'heading': 0, 'x_len': divider_width, 'y_len': self.room_width - 2 * opening_width})
self.robot_spawn_bounds = (x_offset + divider_width / 2, None, None, None)
self.cube_spawn_bounds = (None, x_offset - divider_width / 2, None, None)
def add_tunnels(tunnel_length, x_offset=0, y_offset=0):
tunnel_width = 0.18
tunnel_x = (self.room_length + tunnel_width) / 6 + x_offset
outer_divider_len = self.room_length / 2 - tunnel_x - tunnel_width / 2
divider_x = self.room_length / 2 - outer_divider_len / 2
middle_divider_len = 2 * (tunnel_x - tunnel_width / 2)
obstacles.append({'type': 'divider', 'position': (-divider_x, y_offset), 'heading': 0, 'x_len': outer_divider_len, 'y_len': tunnel_length})
obstacles.append({'type': 'divider', 'position': (0, y_offset), 'heading': 0, 'x_len': middle_divider_len, 'y_len': tunnel_length})
obstacles.append({'type': 'divider', 'position': (divider_x, y_offset), 'heading': 0, 'x_len': outer_divider_len, 'y_len': tunnel_length})
self.robot_spawn_bounds = (None, None, y_offset + tunnel_length / 2, None)
self.cube_spawn_bounds = (None, None, None, y_offset - tunnel_length / 2)
def add_rooms(x_offset=0, y_offset=0):
divider_width = 0.05
opening_width = 0.18
divider_len = self.room_width / 2 - opening_width - divider_width / 2
top_divider_len = divider_len - y_offset
bot_divider_len = divider_len + y_offset
top_divider_y = self.room_width / 2 - opening_width - top_divider_len / 2
bot_divider_y = -self.room_width / 2 + opening_width + bot_divider_len / 2
obstacles.append({'type': 'divider', 'position': (0, y_offset), 'heading': 0, 'x_len': self.room_length - 2 * opening_width, 'y_len': divider_width})
obstacles.append({'type': 'divider', 'position': (x_offset, top_divider_y), 'heading': 0, 'x_len': divider_width, 'y_len': top_divider_len, 'snap_y': y_offset + divider_width / 2})
obstacles.append({'type': 'divider', 'position': (x_offset, bot_divider_y), 'heading': 0, 'x_len': divider_width, 'y_len': bot_divider_len, 'snap_y': y_offset - divider_width / 2})
def add_random_columns(num_columns, random_state):
column_length = 0.1
column_width = 0.1
buffer_width = 0.08
for _ in range(num_columns):
x = random_state.uniform(
-self.room_length / 2 + 2 * buffer_width + column_length / 2,
self.room_length / 2 - 2 * buffer_width - column_length / 2
)
y = random_state.uniform(
-self.room_width / 2 + 2 * buffer_width + column_width / 2,
self.room_width / 2 - 2 * buffer_width - column_width / 2
)
obstacles.append({'type': 'column', 'position': (x, y), 'heading': 0, 'x_len': column_length, 'y_len': column_width})
# Walls
obstacles = []
for x, y, length, width in [
(-self.room_length / 2 - wall_thickness / 2, 0, wall_thickness, self.room_width),
(self.room_length / 2 + wall_thickness / 2, 0, wall_thickness, self.room_width),
(0, -self.room_width / 2 - wall_thickness / 2, self.room_length + 2 * wall_thickness, wall_thickness),
(0, self.room_width / 2 + wall_thickness / 2, self.room_length + 2 * wall_thickness, wall_thickness),
]:
obstacles.append({'type': 'wall', 'position': (x, y), 'heading': 0, 'x_len': length, 'y_len': width})
# Other obstacles
if self.env_name == 'small_empty':
pass
elif self.env_name == 'small_divider_norand':
add_divider()
elif self.env_name == 'small_divider':
add_divider(x_offset=self.room_random_state.uniform(-0.1, 0.1))
elif self.env_name == 'large_empty':
pass
elif self.env_name == 'large_doors_norand':
add_tunnels(0.05)
elif self.env_name == 'large_doors':
add_tunnels(0.05, x_offset=self.room_random_state.uniform(-0.05, 0.05), y_offset=self.room_random_state.uniform(-0.1, 0.1))
elif self.env_name == 'large_tunnels_norand':
add_tunnels(0.25)
elif self.env_name == 'large_tunnels':
add_tunnels(0.25, x_offset=self.room_random_state.uniform(-0.05, 0.05), y_offset=self.room_random_state.uniform(-0.05, 0.05))
elif self.env_name == 'large_rooms_norand':
add_rooms()
elif self.env_name == 'large_rooms':
add_rooms(x_offset=self.room_random_state.uniform(-0.05, 0.05), y_offset=self.room_random_state.uniform(-0.05, 0.05))
elif self.env_name == 'large_columns':
add_random_columns(num_columns=self.room_random_state.randint(1, 10), random_state=self.room_random_state)
else:
raise Exception(self.env_name)
################################################################################
# Rounded corners
rounded_corner_width = 0.1006834873
# Room corners
for i, (x, y) in enumerate([
(-self.room_length / 2, self.room_width / 2),
(self.room_length / 2, self.room_width / 2),
(self.room_length / 2, -self.room_width / 2),
(-self.room_length / 2, -self.room_width / 2),
]):
if any('rescue_robot' in g for g in self.robot_config) or distance((x, y), self.receptacle_position) > (1 + 1e-6) * (VectorEnv.RECEPTACLE_WIDTH / 2) * math.sqrt(2):
heading = -math.radians(i * 90)
offset = rounded_corner_width / math.sqrt(2)
adjusted_position = (x + offset * math.cos(heading - math.radians(45)), y + offset * math.sin(heading - math.radians(45)))
obstacles.append({'type': 'corner', 'position': adjusted_position, 'heading': heading})
# Corners between walls and dividers
new_obstacles = []
for obstacle in obstacles:
if obstacle['type'] == 'divider':
position, length, width = obstacle['position'], obstacle['x_len'], obstacle['y_len']
x, y = position
corner_positions = None
if math.isclose(x - length / 2, -self.room_length / 2):
corner_positions = [(-self.room_length / 2, y - width / 2), (-self.room_length / 2, y + width / 2)]
corner_headings = [0, 90]
elif math.isclose(x + length / 2, self.room_length / 2):
corner_positions = [(self.room_length / 2, y - width / 2), (self.room_length / 2, y + width / 2)]
corner_headings = [-90, 180]
elif math.isclose(y - width / 2, -self.room_width / 2):
corner_positions = [(x - length / 2, -self.room_width / 2), (x + length / 2, -self.room_width / 2)]
corner_headings = [180, 90]
elif math.isclose(y + width / 2, self.room_width / 2):
corner_positions = [(x - length / 2, self.room_width / 2), (x + length / 2, self.room_width / 2)]
corner_headings = [-90, 0]
elif 'snap_y' in obstacle:
snap_y = obstacle['snap_y']
corner_positions = [(x - length / 2, snap_y), (x + length / 2, snap_y)]
corner_headings = [-90, 0] if snap_y > y else [180, 90]
if corner_positions is not None:
for position, heading in zip(corner_positions, corner_headings):
heading = math.radians(heading)
offset = rounded_corner_width / math.sqrt(2)
adjusted_position = (
position[0] + offset * math.cos(heading - math.radians(45)),
position[1] + offset * math.sin(heading - math.radians(45))
)
obstacles.append({'type': 'corner', 'position': adjusted_position, 'heading': heading})
obstacles.extend(new_obstacles)
return obstacles
def _reset_poses(self):
# Reset robot poses
for robot in self.robots:
pos_x, pos_y, heading = self._get_random_robot_pose(padding=robot.RADIUS, bounds=self.robot_spawn_bounds)
robot.reset_pose(pos_x, pos_y, heading)
# Reset cube poses
for cube_id in self.cube_ids:
pos_x, pos_y, heading = self._get_random_cube_pose()
self.reset_cube_pose(cube_id, pos_x, pos_y, heading)
# Check if any robots need another pose reset
done = False
while not done:
done = True
self.step_simulation()
for robot in self.robots:
reset_robot_pose = False
# Check if robot is stacked on top of a cube
if robot.get_position(set_z_to_zero=False)[2] > 0.001: # 1 mm
reset_robot_pose = True
# Check if robot is inside an obstacle or another robot
for contact_point in self.p.getContactPoints(robot.id):
if contact_point[2] in self.obstacle_collision_body_b_ids_set or contact_point[2] in self.robot_collision_body_b_ids_set:
reset_robot_pose = True
break
if reset_robot_pose:
done = False
pos_x, pos_y, heading = self._get_random_robot_pose(padding=robot.RADIUS, bounds=self.robot_spawn_bounds)
robot.reset_pose(pos_x, pos_y, heading)
def _get_random_cube_pose(self):
done = False
while not done:
pos_x, pos_y = self._get_random_position(padding=VectorEnv.CUBE_WIDTH / 2, bounds=self.cube_spawn_bounds)
# Only spawn cubes outside of the receptacle
if self.receptacle_id is None or not self.cube_position_in_receptacle((pos_x, pos_y)):
done = True
heading = self.room_random_state.uniform(-math.pi, math.pi)
return pos_x, pos_y, heading
def _get_random_robot_pose(self, padding=0, bounds=None):
position_x, position_y = self._get_random_position(padding=padding, bounds=bounds)
heading = self.room_random_state.uniform(-math.pi, math.pi)
return position_x, position_y, heading
def _get_random_position(self, padding=0, bounds=None):
low_x = -self.room_length / 2 + padding
high_x = self.room_length / 2 - padding
low_y = -self.room_width / 2 + padding
high_y = self.room_width / 2 - padding
if bounds is not None:
x_min, x_max, y_min, y_max = bounds
if x_min is not None:
low_x = x_min + padding
if x_max is not None:
high_x = x_max - padding
if y_min is not None:
low_y = y_min + padding
if y_max is not None:
high_y = y_max - padding
position_x, position_y = self.room_random_state.uniform((low_x, low_y), (high_x, high_y))
return position_x, position_y
def _step_simulation_until_still(self):
# Kick-start gravity
for _ in range(2):
self.step_simulation()
movable_body_ids = self.robot_ids + self.cube_ids
prev_positions = []
sim_steps = 0
done = False
while not done:
# Check whether any bodies moved since last step
positions = [self.p.getBasePositionAndOrientation(body_id)[0] for body_id in movable_body_ids]
if len(prev_positions) > 0:
done = True
for prev_position, position in zip(prev_positions, positions):
change = distance(prev_position, position)
# Ignore removed cubes (negative z)
if position[2] > -0.0001 and change > 0.0005: # 0.5 mm
done = False
break
prev_positions = positions
self.step_simulation()
sim_steps += 1
if sim_steps > 800:
break
def _set_awaiting_new_action(self):
if sum(robot.awaiting_new_action for robot in self.robots) == 0:
for robot in self.robots:
if robot.is_idle():
robot.awaiting_new_action = True
break
def _execute_actions(self):
sim_steps = 0
while True:
if any(robot.is_idle() for robot in self.robots):
break
self.step_simulation()
sim_steps += 1
for robot in self.robots:
robot.step()
return sim_steps
def _execute_actions_real(self):
assert self.real
# If debug mode is enabled, all robots will pause and resume actions during any robot's action selection
if self.real_debug:
for robot in self.robots:
robot.controller.resume()
sim_steps = 0
any_idle = False
while True:
if not any_idle and any(robot.is_idle() for robot in self.robots):
any_idle = True
if self.real_debug:
for robot in self.robots:
robot.controller.pause()
if any_idle:
# If debug mode is enabled, do not exit loop until all robots have actually stopped moving
if not self.real_debug or all((robot.is_idle() or robot.controller.state == 'paused') for robot in self.robots):
break
self.update_poses()
sim_steps += 1
for robot in self.robots:
robot.step()
return sim_steps
def _disconnect_robots(self):
assert self.real
if self.robots is not None:
for robot in self.robots:
robot.controller.disconnect()
class Robot(ABC):
HALF_WIDTH = 0.03
BACKPACK_OFFSET = -0.0135
BASE_LENGTH = 0.065 # Does not include the hooks
TOP_LENGTH = 0.057 # Leaves 1 mm gap for lifted cube
END_EFFECTOR_LOCATION = BACKPACK_OFFSET + BASE_LENGTH
RADIUS = math.sqrt(HALF_WIDTH**2 + END_EFFECTOR_LOCATION**2)
HEIGHT = 0.07
NUM_OUTPUT_CHANNELS = 1
COLOR = (0.3529, 0.3529, 0.3529, 1) # Gray
CONSTRAINT_MAX_FORCE = 10
@abstractmethod # Should not be instantiated directly
def __init__(self, env, group_index, real=False, real_robot_index=None):
self.env = env
self.group_index = group_index
self.real = real
self.id = self._create_multi_body()
self.cid = self.env.p.createConstraint(self.id, -1, -1, -1, pybullet.JOINT_FIXED, None, (0, 0, 0), (0, 0, 0))
self._last_step_simulation_count = -1 # Used to determine whether pose is out of date
self._position_raw = None # Most current position, not to be directly accessed (use self.get_position())
self._position = None # Most current position (with z set to 0), not to be directly accessed (use self.get_position())
self._heading = None # Most current heading, not to be directly accessed (use self.get_heading())
# Movement
self.action = None
self.target_end_effector_position = None
self.waypoint_positions = None
self.waypoint_headings = None
self.controller = RealRobotController(self, real_robot_index, debug=self.env.real_debug) if real else RobotController(self)
# Collision detection
self.collision_body_a_ids_set = set([self.id])
# State representation
self.mapper = Mapper(self.env, self)
# Step variables and stats
self.awaiting_new_action = False # Only one robot at a time can be awaiting new action
self.cubes = 0
self.reward = None
self.cubes_with_reward = 0
self.distance = 0
self.prev_waypoint_position = None # For tracking distance traveled over the step
self.collided_with_obstacle = False
self.collided_with_robot = False
# Episode stats (robots are recreated every episode)
self.cumulative_cubes = 0
self.cumulative_distance = 0
self.cumulative_reward = 0
self.cumulative_obstacle_collisions = 0
self.cumulative_robot_collisions = 0
def store_new_action(self, action):
# Action is specified as an index specifying an end effector action, along with (row, col) of the selected pixel location
self.action = tuple(np.unravel_index(action, (self.NUM_OUTPUT_CHANNELS, Mapper.LOCAL_MAP_PIXEL_WIDTH, Mapper.LOCAL_MAP_PIXEL_WIDTH))) # Immutable tuple
# Get current robot pose
current_position, current_heading = self.get_position(), self.get_heading()
# Compute distance from front of robot (not center of robot), which is used to find the
# robot position and heading that would place the end effector over the specified location
dx, dy = Mapper.pixel_indices_to_position(self.action[1], self.action[2], (Mapper.LOCAL_MAP_PIXEL_WIDTH, Mapper.LOCAL_MAP_PIXEL_WIDTH))
dist = math.sqrt(dx**2 + dy**2)
theta = current_heading + math.atan2(-dx, dy)
self.target_end_effector_position = (current_position[0] + dist * math.cos(theta), current_position[1] + dist * math.sin(theta), 0)
################################################################################
# Waypoints
# Compute waypoint positions
if self.env.use_shortest_path_movement and not hasattr(self, 'uav'):
self.waypoint_positions = self.mapper.shortest_path(current_position, self.target_end_effector_position)
else:
self.waypoint_positions = [current_position, self.target_end_effector_position]
# Compute waypoint headings
self.waypoint_headings = [current_heading]
for i in range(1, len(self.waypoint_positions)):
dx = self.waypoint_positions[i][0] - self.waypoint_positions[i - 1][0]
dy = self.waypoint_positions[i][1] - self.waypoint_positions[i - 1][1]
self.waypoint_headings.append(restrict_heading_range(math.atan2(dy, dx)))
# Compute target position and heading for the robot. This involves applying an
# offset to shift the final waypoint from end effector position to robot position.
signed_dist = distance(self.waypoint_positions[-2], self.waypoint_positions[-1]) - (self.END_EFFECTOR_LOCATION + VectorEnv.CUBE_WIDTH / 2)
target_heading = self.waypoint_headings[-1]
target_position = (
self.waypoint_positions[-2][0] + signed_dist * math.cos(target_heading),
self.waypoint_positions[-2][1] + signed_dist * math.sin(target_heading),
0
)
self.waypoint_positions[-1] = target_position
# Avoid awkward backing up to reach the last waypoint
if len(self.waypoint_positions) > 2 and signed_dist < 0:
self.waypoint_positions[-2] = self.waypoint_positions[-1]
dx = self.waypoint_positions[-2][0] - self.waypoint_positions[-3][0]
dy = self.waypoint_positions[-2][1] - self.waypoint_positions[-3][1]
self.waypoint_headings[-2] = restrict_heading_range(math.atan2(dy, dx))
################################################################################
# Step variables and stats
# Reset controller
self.controller.reset()
self.controller.new_action()
# Reset step variables and stats
self.awaiting_new_action = False
self.cubes = 0
self.reward = None
self.cubes_with_reward = 0
self.distance = 0
self.prev_waypoint_position = current_position
self.collided_with_obstacle = False
self.collided_with_robot = False
def step(self):
self.controller.step()
def update_map(self):
self.mapper.update()
def get_state(self, save_figures=False):
return self.mapper.get_state(save_figures=save_figures)
def process_cube_success(self):
self.cubes += 1
def compute_rewards_and_stats(self, done=False):
# Ways a step can end
# - Successfully completed action
# - Collision
# - Step limit exceeded
# - Episode ended (no cubes left or too many steps of inactivity)
if done:
self.update_distance()
self.controller.reset()
# Calculate final reward
success_reward = self.env.success_reward * self.cubes_with_reward
obstacle_collision_penalty = -self.env.obstacle_collision_penalty * self.collided_with_obstacle
robot_collision_penalty = -self.env.robot_collision_penalty * self.collided_with_robot
self.reward = success_reward + obstacle_collision_penalty + robot_collision_penalty
# Update cumulative stats
self.cumulative_cubes += self.cubes
self.cumulative_reward += self.reward
self.cumulative_distance += self.distance
self.cumulative_obstacle_collisions += self.collided_with_obstacle