-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrobot.py
2397 lines (2017 loc) · 108 KB
/
robot.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
"""Put test scripts here.
(c) Daniel Seita
With significant help from Carl Qi, Sarthak Shetty, etc.
"""
import os
from os.path import split, join, basename
import sys
import cv2
import argparse
import json
import io
import time
import datetime
import struct
import numpy as np
np.set_printoptions(suppress=True, linewidth=120, precision=4)
from scipy.spatial.transform import Rotation as R
from pyquaternion import Quaternion as quat
import cv2
from collections import defaultdict
import open3d as o3d
from dslr_capture import VideoRecorder, DoneCam
#! Packages required to run inference
import zmq
from zmq import ssh
# Other stuff from this project.
from data_collector import DataCollector
import utils_robot as U
from glob import glob
# ROS stuff.
from cv_bridge import CvBridge
import rospy
import tf2_ros
import intera_interface as ii
from intera_core_msgs.srv import (
SolvePositionIK,
SolvePositionIKRequest
)
#! Need these functions for managing the impedence while collecting BC demonstrations
from intera_motion_interface.utility_functions import int2bool, boolToggle
from intera_motion_interface import (
MotionTrajectory,
MotionWaypoint,
MotionWaypointOptions,
InteractionOptions,
InteractionPublisher
)
from intera_core_msgs.msg import InteractionControlCommand
from intera_motion_msgs.msg import TrajectoryOptions
from sensor_msgs.msg import Image, PointCloud2
from std_msgs.msg import Header
from geometry_msgs.msg import (
PoseStamped,
Pose,
Point,
Quaternion
)
# --------------------------- Various constants for MM -------------------------- #
DEG_TO_RAD = np.pi / 180.0
RAD_TO_DEG = 180.0 / np.pi
# NOTE/TODO(daniel) need to tune this and discount Fisheye effects.
PIX_TO_MM = 180.0 / 300.0 # roughly 180 mm corresponds to 300 pixels
# NOTE(daniel) these poses are w.r.t. a coordinate system that assumes it is
# centered at the gripper, where +z points down in direction of gripper. I
# measured the 33cm with a ruler and empirically it seems OK.
#TOOL_REL_POS = np.array([0.015, 0, 0.215]) # What Carl used for the dough roller.
TOOL_REL_POS = np.array([0.025, 0.0, 0.330]) # Ladle (but we might change)
# Tentative 'home' pose for MM.
MM_HOME_POSE_EE = [0.6562, 0.0113, 0.5282, -0.1823, -0.724, 0.6477, -0.1518]
# UPTIGHT_MM_HOME_POSE_EE = [0.65, -0.157, 0.5282, -0.1823, -0.724, 0.6477, -0.1518]
# Critical: tune these carefully! We have different safety constraints based on
# different stages of the robot movement.
SAFETY_LIMITS = {
# Strict constraints when the policy is in action in the water.
'policy': {
'lim_x_ee' : [ 0.40, 0.80],
'lim_y_ee' : [-0.15, 0.15],
'lim_z_ee' : [ 0.32, 0.52],
'lim_x_tool': [ 0.60, 0.70], # can be similar to EE
'lim_y_tool': [-0.30, -0.18], # lower since we tilt EE at angle
'lim_z_tool': [ 0.02, 0.22], # a lot lower (should be >0 at min)
},
# For when the policy does resets. These can be more flexible. If we go
# close to the lower limit of z, for example, ideally we should be doing
# some rotation so the ladle isn't 'digging into' the table.
'resets': {
'lim_x_ee' : [ 0.40, 0.74],
'lim_y_ee' : [-0.35, 0.20],
'lim_z_ee' : [ 0.30, 0.70],
'lim_x_tool': [ 0.40, 0.74],
'lim_y_tool': [-0.35, 0.20],
'lim_z_tool': [ 0.00, 0.50],
},
}
# ------------------------------------------------------------------------------ #
def solver(pose):
"""From one (or both) of: Carl Qi and Sarthak Shetty.
NOTE(daniel): I think, given a (position, quaternion) pose, it returns the
target joint angles.
"""
ns = 'ExternalTools/right/PositionKinematicsNode/IKService'
iksvc = rospy.ServiceProxy(ns, SolvePositionIK)
ikreq = SolvePositionIKRequest()
header = Header(stamp = rospy.Time.now(), frame_id = 'base')
poses = {
'right': PoseStamped(
header = header,
pose = Pose(
position = Point(
x=pose[0],
y=pose[1],
z=max(pose[2],0.245),
),
orientation = Quaternion(
w=pose[3],
x=pose[4],
y=pose[5],
z=pose[6]
)
)
)
}
ikreq.pose_stamp.append(poses['right'])
ikreq.tip_names.append('right_hand')
try:
rospy.wait_for_service(ns, 5.0)
resp = iksvc(ikreq)
return resp
except (rospy.ServiceException, rospy.ROSException) as e:
print('Failed due to:', e)
return False
class SawyerRobot:
"""Encapsulate things in a class to make it simpler."""
def __init__(self, policy=None):
# Is this needed?
def shutdown_func():
print("Exit the mixed media.")
# Rospy setups. The rate was borrowed from Carl, but I don't see a difference
# with my testing for 1-100 for images and EE pose querying...
rospy.init_node('thing1', anonymous=True, disable_signals=True)
rospy.Rate(100)
rospy.on_shutdown(shutdown_func)
self.buffer = tf2_ros.Buffer()
tf2_ros.TransformListener(self.buffer)
# Get limb through intera interface.
self.limb = ii.Limb('right')
#* Adding this attribute to the Sawyer so that we can control the joint speed of the robot
self.traj = MotionTrajectory(limb=self.limb)
if 'alg_t_' in policy:
"""Setting the joint_acceleration to the default value if we don't use
algorithmic demonstrator"""
rospy.loginfo('Setting special joint acceleration limits for policy: {}'.format(policy))
self.set_joint_acceleration()
else:
self.wpt_opts = MotionWaypointOptions(max_joint_speed_ratio=0.1,
max_joint_accel=0.1)
self.waypoint = MotionWaypoint(options=self.wpt_opts.to_msg(),
limb=self.limb)
self.interaction_options = InteractionOptions()
# Gripper, only if we want to use open/closing (normally we don't), which
# we might need for swapping the tool that's being gripped.
self.gripper = ii.Gripper('right_gripper')
# Data collector. This has `CvBridge()` in it.
self.DC = DataCollector(SawyerRobot=self, buffer=self.buffer)
rospy.sleep(2)
def set_joint_acceleration(self, joint_accel=0.1):
'''This function sets the joint acceleration for the 7 joints, so that we can significantly reduce the lag
between the pointcloud and the end-effector pose'''
joint_accel_list = [joint_accel for _ in range(len(self.limb.joint_names()))]
self.wpt_opts = MotionWaypointOptions(max_joint_accel=joint_accel_list, max_linear_speed=0.001, max_linear_accel=0.001, max_rotational_speed=0.001, max_rotational_accel=0.001)
self.waypoint = MotionWaypoint(options=self.wpt_opts.to_msg(),
limb=self.limb)
def set_impedence(self):
#* This function makes some select axes unconstrained. We mainly use this to collect demonstrations, and we want
#* either translation only or all 6DoFs available. Read here for more details on this funcitionality: https://sdk.rethinkrobotics.com/intera/Interaction_Control_Tutorial#Impedance.2FForce_Control_Examples
rospy.loginfo('Initializing Impedence Publishers...')
self.interaction_options.set_K_impedance([0, 0, 0, 0, 0, 0])
self.interaction_options.set_max_impedance(boolToggle(int2bool([1, 1, 1, 0, 0, 0])))
self.interaction_options.set_in_endpoint_frame(False)
self.interaction_options.set_rotations_for_constrained_zeroG(True)
ic_pub = InteractionPublisher()
ic_pub.send_command(self.interaction_options, 0)
# rospy.sleep(0.1)
def default_impedence(self):
#* We set the arm to default impedance when we want to reset to the starting position
rospy.loginfo('Reverting Impedance...')
self.interaction_options.set_K_impedance([0, 0, 0, 0, 0, 0])
self.interaction_options.set_max_impedance(boolToggle(int2bool([1, 1, 1, 1, 1, 1])))
self.interaction_options.set_in_endpoint_frame(False)
self.interaction_options.set_rotations_for_constrained_zeroG(True)
ic_pub = InteractionPublisher()
ic_pub.send_command(self.interaction_options, 0)
# rospy.sleep(0.1)
def open_gripper(self):
"""Opens the gripper."""
self.gripper.open()
def close_gripper(self):
"""Closes the gripper."""
self.gripper.close()
def reboot_gripper(self):
"""If the gripper got messed up, reboot.
Do NOT forcibly adjust the gripper width by manually pushing its fingers apart.
Then we likely have to call this (or try `gripper.calibrate()`).
"""
self.gripper.reboot()
def get_ee_pose(self):
"""Get the EE pose based on the `right_connector_plate_base`, w.r.t. the base.
The `lookup_transform` has 2 frames, the _second_ is the source, the _first_
is the target, hence we want 'base' to be listed first.
Unfortunately we have a hack of -0.004 because without it, if we query the
pose, and ask the robot to move, it seems to strangely move up by 0.004
(meters)? We might want to check this.
Also, that hack only works if the robot is pointing downwards, otherwise
we have to apply a correction transform. :-( TODO(daniel)
"""
while not rospy.is_shutdown():
try:
#! Modifying this from Daniel's original code, where he used reference/right_connector_plate_base -> right_connector_plate_base
#! It seems that if we use the impedence control then the reference/* topics stop updating
ee_transform = self.buffer.lookup_transform(
'base', 'right_connector_plate_base', rospy.Time(0))
ee_pose = np.array([
ee_transform.transform.translation.x,
ee_transform.transform.translation.y,
ee_transform.transform.translation.z,
ee_transform.transform.rotation.w,
ee_transform.transform.rotation.x,
ee_transform.transform.rotation.y,
ee_transform.transform.rotation.z
])
break
except (tf2_ros.LookupException,
tf2_ros.ConnectivityException,
tf2_ros.ExtrapolationException) as e:
continue
ee_pose[2] -= 0.004
return ee_pose
def get_tool_pose(self):
"""Get the tool pose, in the world frame.
Depends on how we define the relative pose from the tool to the robot's EE. The
robot's EE is the `right_connector_base_plate`. For mixed media, define the tool
pose to be the 'center' of the approximate sphere formed from the ladle's 'bowl'?
"""
ee_pose = self.get_ee_pose()
tool_pose = self.ee_to_tool(ee_pose)
return tool_pose
def ee_to_tool(self, ee_pose):
"""Given EE pose (world frame), determine the tool pose (world frame).
Assume the EE and tool poses (world frame) have the same quaternion.
"""
pos, Q = ee_pose[:3], ee_pose[3:]
r_mat = U.quaternion_rotation_matrix(Q)
TOOL_REL_POS_world = r_mat.dot(TOOL_REL_POS)
tool_pos_world = pos + TOOL_REL_POS_world
return np.concatenate([tool_pos_world, Q])
def tool_to_ee(self, tool_pose):
"""TODO"""
pos, Q = tool_pose[:3], tool_pose[3:]
r_mat = U.quaternion_rotation_matrix(Q)
ee_rel_pos = -TOOL_REL_POS
ee_rel_pos_world = r_mat.dot(ee_rel_pos)
ee_pos_world = pos + ee_rel_pos_world
return np.concatenate([ee_pos_world, Q])
def world_to_pixel(self, points_world):
"""Convert from world points to pixel space.
See documentation for `world_to_uv`.
"""
uu,vv = U.world_to_uv(buffer=self.buffer,
world_coordinate=points_world,
camera_ns='k4a_top')
return (uu,vv)
# TODO(daniel) need to check / test.
def pixel_to_world(self, u, v, z):
"""Convert from pixels to world space.
Input: np.array of shape (n x 1) of type integers, representing pixels.
See documentation in other method.
Might be OK to convert theseto float32?
"""
if len(np.array(u).shape) == 0:
u = np.array([u]).astype(np.float32)
if len(np.array(v).shape) == 0:
v = np.array([v]).astype(np.float32)
if len(np.array(z).shape) == 0:
z = np.array([z]).astype(np.float32) # depth
points_w = U.uv_to_world_pos(buffer=self.buffer,
u=u, v=v, z=z,
camera_ns='k4a_top')
return points_w
def is_safe(self, ee_pose=None, tool_pose=None, bounds=''):
"""Enforce safety checks.
Each time there's an action to take, we should call this to check bounds.
There are different bounds involved depending on the current action. For
example, actions when the tool is in the water have stricter bounds.
Need to test how this works if we have rotations near edgfes of containers.
Parameters
----------
ee_pose: Desired EE pose, world/base frame.
tool_pose: Desired tool pose, world/base frame.
bounds: (string) Indicates which bounds to use.
"""
assert not (ee_pose is None and tool_pose is None), 'Set one of these.'
assert bounds in SAFETY_LIMITS, 'Bounds {} is not present'.format(bounds)
is_safe = True
LIM_X_EE = SAFETY_LIMITS[bounds]['lim_x_ee']
LIM_Y_EE = SAFETY_LIMITS[bounds]['lim_y_ee']
LIM_Z_EE = SAFETY_LIMITS[bounds]['lim_z_ee']
LIM_X_TOOL = SAFETY_LIMITS[bounds]['lim_x_tool']
LIM_Y_TOOL = SAFETY_LIMITS[bounds]['lim_y_tool']
LIM_Z_TOOL = SAFETY_LIMITS[bounds]['lim_z_tool']
# Check positional bounds of the EE.
if ee_pose is not None:
cond_x = LIM_X_EE[0] <= ee_pose[0] <= LIM_X_EE[1]
cond_y = LIM_Y_EE[0] <= ee_pose[1] <= LIM_Y_EE[1]
cond_z = LIM_Z_EE[0] <= ee_pose[2] <= LIM_Z_EE[1]
inbounds = cond_x and cond_y and cond_z
if not inbounds:
print('WARNING: EE safety check failed: {} {} {} {}'.format(
ee_pose[:3], cond_x, cond_y, cond_z))
is_safe = False
# Check positional bounds of the tool.
if tool_pose is not None:
cond_x = LIM_X_TOOL[0] <= tool_pose[0] <= LIM_X_TOOL[1]
cond_y = LIM_Y_TOOL[0] <= tool_pose[1] <= LIM_Y_TOOL[1]
cond_z = LIM_Z_TOOL[0] <= tool_pose[2] <= LIM_Z_TOOL[1]
inbounds = cond_x and cond_y and cond_z
if not inbounds:
print('WARNING: tool safety check failed: {} {} {} {}'.format(
tool_pose[:3], cond_x, cond_y, cond_z))
is_safe = False
return is_safe
def move_to_ee_pose(self, ee_pose, bounds):
"""Moves the robot's EE to the given pose using solver + waypoint.
Parameters
----------
ee_pose: Desired EE pose w.r.t. world/base frame, in (position, quaternion)
format. The `solver` then converts this target pose to joint angles.
bounds: (string) Indicates which safety check to use.
Returns
-------
True if action was executed successfully, False if not.
"""
tool_pose = self.ee_to_tool(ee_pose)
# if not self.is_safe(ee_pose=ee_pose, tool_pose=tool_pose, bounds=bounds):
# print('Warning! Moving is deemed not safe.')
# return False
# else:
# print('Executing!')
resp = solver(pose=ee_pose)
self.execute_waypoint(resp)
return True
def execute_waypoint(self, resp):
"""Actually move the robot to the target joint angles.
References:
https://sdk.rethinkrobotics.com/intera/Motion_Interface_Tutorial
https://github.com/RethinkRobotics/intera_sdk/blob/development/intera_examples/scripts/go_to_joint_angles.py
Question: can we control the robot speed?
Note from the docs:
[This] moves the arm from its current position to some target set of joint
angles. Note that this script will not plan around self-collisions or obstacles.
"""
try:
self.traj.clear_waypoints()
# Get current joint angles, append to `self.traj`.
joint_angles = self.limb.joint_ordered_angles()
self.waypoint.set_joint_angles(joint_angles=joint_angles)
self.traj.append_waypoint(self.waypoint.to_msg())
# Get target joint angles, append to `self.traj`. NOTE(daniel): the GitHub
# code does not do this but assigns it using `set_joint_angles`.
joint_angles = []
for joint in range(0, 7):
joint_angles.append(resp.joints[0].position[joint])
self.waypoint.set_joint_angles(joint_angles=joint_angles)
self.traj.append_waypoint(self.waypoint.to_msg())
# Move the robot!
result = self.traj.send_trajectory()
if result is None:
rospy.logerr('Trajectory FAILED to send!')
return
if result.result:
rospy.loginfo('Motion controller successfully finished the trajectory with interaction options set!')
else:
rospy.logerr('Motion controller failed to complete the trajectory with error %s',
result.errorId)
except rospy.ROSInterruptException:
rospy.logerr('Keyboard interrupt detected from the user. %s',
'Exiting before trajectory completion.')
def rotate(self, radian, axis):
"""Rotates along some axis, keeping the position fixed.
Keep the tool position the same. But be careful, if we just specify the
axes like (1,0,0), (0,1,0), or (0,0,1), these are aligned with the world
or base frame (they're the same here) because we are getting the ee pose
and tool poses in that frame. The robot is actually gripping the ladle at
an angle. This might induce some complexities.
If we do things and keep the tool position the same, then this seems to
nicely adjust the tool. I guess that's all that matters for us?
Parameters
----------
radian: amount to rotate by in the axis (in radians).
axis: the axis that we rotate by, in the world or base frame.
"""
assert axis in ['x', 'y', 'z'], axis
if axis == 'x':
axis_arr = np.array([1, 0, 0])
elif axis == 'y':
axis_arr = np.array([0, 1, 0])
elif axis == 'z':
axis_arr = np.array([0, 0, 1])
# Getting poses and making a `new_tool_pose` with the new quaternion.
ee_pose = self.get_ee_pose()
tool_pose = self.get_tool_pose()
print('EE pose: {}'.format(ee_pose))
print('Tool pose: {}'.format(tool_pose))
new_tool_pose = np.zeros(7)
new_tool_pose[:3] = tool_pose[:3]
# Compute the new tool (NOT EE!) quat by left-multiplying it by `transform`.
transform = R.from_rotvec(radian * axis_arr)
tp_quat = [tool_pose[4], tool_pose[5], tool_pose[6], tool_pose[3]]
new_quat = (transform * R.from_quat(tp_quat)).as_quat()
new_tool_pose[3:] = [new_quat[-1], new_quat[0], new_quat[1], new_quat[2]]
# Get the EE target pose from the new tool pose, and then move to it.
target_ee_pose = self.tool_to_ee(new_tool_pose)
print('Policy action: {}'.format(new_tool_pose[:3] - tool_pose[:3]))
print('Target EE pose: {}'.format(target_ee_pose))
self.move_to_ee_pose(target_ee_pose, bounds='resets')
def reset_to_rotated_start(self, robot_z, quat, robot_y=[-0.0207], start_recording=False, img_record = True, rotations = False):
"""Reset to begin a trial for algorithmic policy.
Currently moves to the home position, then enters water and begins recording.
"""
self.move_to_ee_pose(MM_HOME_POSE_EE, bounds='resets')
inter_pose_1 = [0.6562, 0.07 , 0.5202, -0.107530688176, -0.475557657203, 0.827073107583, -0.279700090256]
inter_pose_2 = [0.6562, 0.0113, 0.5282, -0.1823, -0.724, 0.6477, -0.1518]
if rotations:
self.move_to_ee_pose(inter_pose_1, bounds='resets')
print("pcl_size before rotation: {}".format(len(self.DC.pcl_l)))
self.DC.pcl_l = []
self.DC.eep_pose_l = []
self.DC.eep_pose_p = []
self.DC.eep_pose_r = []
self.DC.clr_imgs_l = []
self.DC.d_image_l = []
self.DC.pcl_l_header = []
self.DC.eep_pose_l_header = []
self.DC.clr_imgs_header_l = []
self.DC.d_image_header_l = []
print("pcl_size after rotation: {}".format(len(self.DC.pcl_l)))
if start_recording:
rospy.loginfo('Started Recording')
self.DC.start_recording(img_record = img_record)
print("pcl_size before home: {}".format(len(self.DC.pcl_l)))
# self.move_to_ee_pose(inter_pose_2, bounds='resets')
''''Move to some slightly offset positionm from MM_HOME_POSE_EE, then start recording'''
# Initialize by inserting ladle closer to the 'top' as viewed from the image.
ee_pose_close = [0.6562, robot_y[0], robot_z[0]] + quat
# self.move_to_ee_pose(ee_pose_close, bounds='resets')
print("pcl_size after home: {}".format(len(self.DC.pcl_l)))
rospy.sleep(1)
def reset_to_start(self, robot_z, quat, robot_y=[-0.0207], start_recording=False, img_record = True):
"""Reset to begin a trial for algorithmic policy.
Currently moves to the home position, then enters water and begins recording.
"""
self.move_to_ee_pose(MM_HOME_POSE_EE, bounds='resets')
# Initialize by inserting ladle closer to the 'top' as viewed from the image.
ee_pose_close = [0.6562, robot_y[0], robot_z[0]] + quat
ee_pose_enter = [0.65, -0.0409] + robot_z + quat
if start_recording:
self.DC.start_recording(img_record = img_record)
self.move_to_ee_pose(ee_pose_close, bounds='resets')
rospy.sleep(1)
# self.move_to_ee_pose(ee_pose_enter, bounds='policy')
# rospy.sleep(1)
def reset_to_neutral_start(self, robot_z, quat, start_recording=False):
#! Copy of the above function, where the robot doesn't move to a start position but just resets in the same place
#! mainly incorporated this to avoid jerky movements when the robot resets to the start posiiton
"""Reset to begin a trial for algorithmic policy.
Currently moves to the home position, then enters water and begins recording.
"""
self.move_to_ee_pose(MM_HOME_POSE_EE, bounds='resets')
# Initialize by inserting ladle closer to the 'top' as viewed from the image.
ee_pose_close = [0.65, -0.0207, 0.550] + quat
if start_recording:
self.DC.start_recording()
self.move_to_ee_pose(ee_pose_close, bounds='resets')
rospy.sleep(1)
def reset_to_end(self, robot_z, quat, stop_recording=True):
"""Performs a reset procedure to randomize the starting configuration.
(1) Enter the center of the water, roughly.
(2) Do some stirring action.
(3) Lift + lower to release anything.
(4) Return to some home position.
Update: actually after testing, I don't know if we want the stirring. It
seems like we might get just as good data diversity by the way the robot
moves and from the dropping action.
"""
stir = False
rospy.sleep(1)
time.sleep(1)
if stop_recording:
self.DC.stop_recording()
print('Robot is now resetting!')
if stir:
# (1,2) Enter the water (possibly holding items), then stir.
ee_pose_enter = [0.65, -0.0409] + robot_z + quat
self.move_to_ee_pose(ee_pose_enter, bounds='policy')
# Move randomly to these poses to do the reset.
random_poses = [
[0.67, -0.04] + robot_z + quat,
[0.67, -0.09] + robot_z + quat,
[0.62, -0.09] + robot_z + quat,
[0.62, -0.04] + robot_z + quat,
]
n_attempts = np.random.randint(2, 5)
last_idx = -1
for _ in range(n_attempts):
pose_idx = np.random.randint(len(random_poses))
while pose_idx == last_idx:
pose_idx = np.random.randint(len(random_poses))
last_idx = pose_idx
self.move_to_ee_pose(random_poses[pose_idx], bounds='policy')
print('Finished \'stirring\' for {} attempts'.format(n_attempts))
# Back to this, then handle the lift + dumping part.
self.move_to_ee_pose(ee_pose_enter, bounds='policy')
# (3,4) Lift and rotate to release item(s) and water from ladle.
ee_poses_reset = [
[0.6443, -0.0366, 0.5143, -0.2201, -0.7134, 0.6346, -0.1998], # lift more (better for rot, updated 03/20)
[0.6077, 0.0506, 0.4815, -0.2355, -0.207 , -0.8495, 0.4243], # heavy rotation
[0.5914, 0.07 , 0.5202, 0.3514, 0.2479, 0.7746, -0.4638], # heavy rotation, more extreme
[0.6077, 0.0506, 0.4815, -0.2355, -0.207 , -0.8495, 0.4243], # heavy rotation (duplicate)
[0.6443, -0.0366, 0.5143, -0.2201, -0.7134, 0.6346, -0.1998], # return to this duplicate
MM_HOME_POSE_EE,
]
for pose in ee_poses_reset:
rospy.sleep(1)
self.move_to_ee_pose(pose, bounds='resets')
print('Robot is done with reset.')
def save_episode_results(self, args, epis, im_dict, num_demo = 0):
"""Save results from this episode for analysis later.
Saves quite a lot of information, and in particular saves both all the images
coming from ROS (to make nice videos, or get optical flow) and the images at
each particular policy time step, which comes at less frequent intervals.
"""
policy_folder = join(args.data_dir, 'policy_data')
if num_demo==0:
os.makedirs(policy_folder)
dd = join(args.data_dir, 'demo_' + str(num_demo))
'''NOTE (sarthak):Here im_dict is just a sequence of 4 images that contain: 1. The collor image, 2. The depth image with pixels
above the depth cutoff, 3. Target points that are above this depth value and 4. Distractor points that are above this depth value'''
# Store the image used for debugging. We do need the im_dict since we have
# already done the 'reset' calls beforehand, so we don't want newer images.
eval_debug_img = np.hstack([
im_dict['eval_color_proc'],
im_dict['eval_depth_cutoff'],
im_dict['targ_raised'],
im_dict['dist_raised'],
])
if self.DC.record_img == True:
# For images stored at fast rates to show a 'continuous' video.
U.make_video(dd, self.DC.c_image_proc_l, key='color_crop')
U.make_video(dd, self.DC.targ_mask_l, key='targ_mask')
U.make_video(dd, self.DC.dist_mask_l, key='dist_mask')
U.make_video(dd, self.DC.tool_mask_l, key='tool_mask')
U.make_video(dd, self.DC.area_mask_l, key='area_mask')
combo_all = []
min_l = min([
len(self.DC.c_image_proc_l),
len(self.DC.targ_mask_l),
len(self.DC.dist_mask_l),
len(self.DC.tool_mask_l),
len(self.DC.area_mask_l),
])
for t in range(min_l):
combo_t = np.hstack([
self.DC.c_image_proc_l[t],
U.triplicate(self.DC.targ_mask_l[t]),
U.triplicate(self.DC.dist_mask_l[t]),
U.triplicate(self.DC.tool_mask_l[t]),
U.triplicate(self.DC.area_mask_l[t]),
]).astype(np.uint8)
combo_all.append(combo_t)
U.make_video(dd, combo_all, key='combo_mask')
# For images (and point clouds) used in the actual policy.
pol_img_subdir = join(dd, 'policy_img')
pol_pcl_subdir = join(dd, 'policy_pcl')
pol_segm_subdir = join(dd, 'policy_segm')
os.makedirs(pol_img_subdir)
os.makedirs(pol_pcl_subdir)
os.makedirs(pol_segm_subdir)
cv2.imwrite(join(dd, 'eval_debug_img.png'), eval_debug_img)
epis_T = len(epis['cimgs'])
for t in range(epis_T):
tt = str(t).zfill(2)
# Save (roughly) aligned color images and point clouds.
pth_cimg = join(dd, 'policy_img', 't{}_cimg.png'.format(tt))
pth_draw = join(dd, 'policy_img', 't{}_cimg_draw.png'.format(tt))
pth_pcl = join(dd, 'policy_pcl', 't{}_pcl.npy'.format(tt))
cv2.imwrite(pth_cimg, epis['cimgs'][t])
cv2.imwrite(pth_draw, epis['cimgs_draw'][t])
np.save(pth_pcl, epis['pcls'][t])
# Possible way of providing input (approximately) to policy?
pth_segm = join(dd, 'policy_segm', 't{}_segm.png'.format(tt))
combo_t = np.hstack([
epis['cimgs'][t],
U.triplicate(epis['targs'][t]),
U.triplicate(epis['dists'][t]),
U.triplicate(epis['tools'][t]),
U.triplicate(epis['areas'][t]),
])
cv2.imwrite(pth_segm, combo_t)
# We can use this for evaluation.
targ_raised_pix = np.sum(im_dict['targ_raised'][:,:,0] > 0)
dist_raised_pix = np.sum(im_dict['dist_raised'][:,:,0] > 0)
print('Pixels of targ. (raised): {}'.format(targ_raised_pix))
print('Pixels of dist. (raised): {}'.format(dist_raised_pix))
# Finally, save a variety of results (in json). The 'success' criteria is a bit
# noisy so we may want to be careful. I have a heuristic now.
success = False
success = (targ_raised_pix >= 200) and (dist_raised_pix <= 200)
results = {
'targ_raised_pix': targ_raised_pix,
'dist_raised_pix': dist_raised_pix,
'success': int(success),
# Rest of these should be lists.
'dist_pix': epis['dist_pix'],
'dist_pix_mm': epis['dist_pix_mm'],
'ee_pose_b': epis['ee_pose_b'],
'tool_pose_b': epis['tool_pose_b'],
'posi_xy': epis['posi_xy'],
'attempts': epis['attempts'],
}
results_pth = join(dd, 'results.json')
with open(results_pth, 'w') as fh:
json.dump(results, fh, indent=4)
print('DONE! Success: {} (but check).'.format(success))
assert len(self.DC.eep_pose_r) == len(self.DC.pcl_l) == len(self.DC.eep_pose_p) == len(self.DC.eep_pose_l), 'Check your callback functions. Some lists are not equally shaped. EEP: {} LDR: {} LDP: {} PCL: {} IMG: {} DEPTH: {}'.format(len(self.DC.eep_pose_l), len(self.DC.eep_pose_r), len(self.DC.eep_pose_p), len(self.DC.pcl_l), len(self.DC.clr_imgs_l), len(self.DC.d_image_l))
for t in range(len(self.DC.pcl_l)):
pcl_pth = join(policy_folder, 'pcl_{}_{}_{}_{}.npy'.format(num_demo, t, self.DC.pcl_l_header[t]['secs'], self.DC.pcl_l_header[t]['nsecs']))
ldr_pth = join(policy_folder, 'ldr_{}_{}.npy'.format(num_demo, t))
ldp_pth = join(policy_folder, 'ldp_{}_{}.npy'.format(num_demo, t))
eep_pth = join(policy_folder, 'eep_{}_{}_{}_{}.npy'.format(num_demo, t, self.DC.eep_pose_l_header[t]['secs'], self.DC.eep_pose_l_header[t]['nsecs']))
img_pth = join(policy_folder, 'img_{}_{}_{}_{}.png'.format(num_demo, t, self.DC.clr_imgs_header_l[t]['secs'], self.DC.clr_imgs_header_l[t]['nsecs']))
dpt_pth = join(policy_folder, 'dpt_{}_{}_{}_{}.png'.format(num_demo, t, self.DC.d_image_header_l[t]['secs'], self.DC.d_image_header_l[t]['nsecs']))
np.save(pcl_pth, self.DC.pcl_l[t])
np.save(eep_pth, self.DC.eep_pose_l[t])
np.save(ldp_pth, self.DC.eep_pose_p[t])
np.save(ldr_pth, self.DC.eep_pose_r[t])
cv2.imwrite(img_pth, self.DC.clr_imgs_l[t])
cv2.imwrite(dpt_pth, self.DC.d_image_l[t])
# ---------------------------------------------------------------------------------- #
# Random test scripts to check the setup (e.g., for safety).
# ---------------------------------------------------------------------------------- #
def test_image_crops():
"""Quickly test image cropping, change the ranges in DataCollector.
Can also put a bounding box on the image to better understand crops. See the
documentation in DataCollector. Also, tests if color and depth images can be
aligned, and put them side-by-side, or top-down.
This should be called each time we change the physical setup. Ideally the image
crops should directly give us images for processing into a policy.
"""
robot = SawyerRobot()
c_img = robot.DC.get_color_image()
d_img = robot.DC.get_depth_image_proc()
# NOTE(daniel): careful! Slight changes in physical setup mean different values.
# The values used here should ideally be also used in the data collector class.
# Increasing the x value means moving the crop region 'rightwards'.
c_img_crop = robot.DC.crop_img(c_img, x=840, y=450, w=300, h=300)
d_img_crop = robot.DC.crop_img(d_img, x=840, y=450, w=300, h=300)
print('Image sizes: {}, {}'.format(c_img.shape, d_img.shape))
cv2.imwrite('img_color.png', c_img)
cv2.imwrite('img_depth.png', d_img)
cv2.imwrite('img_crop_color.png', c_img_crop)
cv2.imwrite('img_crop_depth.png', d_img_crop)
# Helps to visualize alignment better.
H,W,_ = c_img.shape
img_aligned_1 = c_img.copy()
img_aligned_2 = c_img.copy()
img_aligned_3 = c_img.copy()
img_aligned_4 = c_img.copy()
img_aligned_1[:, int(W/2):, :] = (d_img.copy())[:, int(W/2):, :]
cv2.imwrite('img_aligned_color_left.png', img_aligned_1)
img_aligned_2[:, :int(W/2), :] = (d_img.copy())[:, :int(W/2), :]
cv2.imwrite('img_aligned_color_right.png', img_aligned_2)
img_aligned_3[int(H/2):, :, :] = (d_img.copy())[int(H/2):, :, :]
cv2.imwrite('img_aligned_color_top.png', img_aligned_3)
img_aligned_4[:int(H/2), :, :] = (d_img.copy())[:int(H/2), :, :]
cv2.imwrite('img_aligned_color_bottom.png', img_aligned_4)
# Stack all together.
all_fname = 'img_aligned_all.png'
row1 = np.hstack([img_aligned_1, img_aligned_2])
row2 = np.hstack([img_aligned_3, img_aligned_4])
combo = np.vstack([row1, row2])
cv2.imwrite(all_fname, combo)
print('See: {}, as well as cropped images, etc.'.format(all_fname))
def test_workspace_bounds():
"""Test workspace bounds.
This should have the robot translate (maybe rotate) to test the workspace bounds.
As a sanity check, the quaternions have similar values (if we're not rotating), as
well as the heights. But we can check whatever we want.
Fortunately we can get reasonable bounds by keeping the quaternion AND height fixed,
and just do pure translation. Also, use different bounds for certain stages.
"""
robot = SawyerRobot()
rospy.sleep(2)
# Getting started.
poses_start = [
MM_HOME_POSE_EE,
[0.65 , -0.0207, 0.4753, 0.18, 0.70, -0.65, 0.16], # close to water
]
# Keep quaternions the same, and keep height fixed for the water poses.
# FYI these are for EE poses, so the y values are a bit larger than expected.
poses_water = [
[0.65 , -0.0409, 0.36, 0.18, 0.70, -0.65, 0.16], # go down
[0.69 , -0.0251, 0.36, 0.18, 0.70, -0.65, 0.16], # 1st corner
[0.69 , -0.11 , 0.36, 0.18, 0.70, -0.65, 0.16], # 2nd corner
[0.61 , -0.11 , 0.36, 0.18, 0.70, -0.65, 0.16], # 3rd corner
[0.61 , -0.0324, 0.36, 0.18, 0.70, -0.65, 0.16], # 4th corner
[0.6559, -0.0628, 0.44, 0.18, 0.70, -0.65, 0.16], # lift for evaluation
]
# The reset procedure.
poses_reset = [
[0.6443, -0.0366, 0.5143, -0.2201, -0.7134, 0.6346, -0.1998], # lift more (better for rot, updated 03/20)
[0.6077, 0.0506, 0.4815, -0.2355, -0.207 , -0.8495, 0.4243], # heavy rotation
[0.5914, 0.07 , 0.5202, 0.3514, 0.2479, 0.7746, -0.4638], # heavy rotation, more extreme
[0.6077, 0.0506, 0.4815, -0.2355, -0.207 , -0.8495, 0.4243], # heavy rotation (duplicate)
[0.6443, -0.0366, 0.5143, -0.2201, -0.7134, 0.6346, -0.1998], # return to this duplicate
MM_HOME_POSE_EE,
]
for pose in poses_start:
rospy.sleep(2)
print('\n Current TOOL posi: {}'.format(robot.get_tool_pose()[:3]))
print(' Current EE posi: {}'.format(robot.get_ee_pose()[:3]))
print(' Going to EE pose: {}'.format(pose))
robot.move_to_ee_pose(pose, bounds='resets')
for pose in poses_water:
rospy.sleep(2)
print('\n Current TOOL posi: {}'.format(robot.get_tool_pose()[:3]))
print(' Current EE posi: {}'.format(robot.get_ee_pose()[:3]))
print(' Going to EE pose: {}'.format(pose))
robot.move_to_ee_pose(pose, bounds='policy')
for pose in poses_reset:
rospy.sleep(2)
print('\n Current TOOL posi: {}'.format(robot.get_tool_pose()[:3]))
print(' Current EE posi: {}'.format(robot.get_ee_pose()[:3]))
print(' Going to EE pose: {}'.format(pose))
robot.move_to_ee_pose(pose, bounds='resets')
# ---------------------------------------------------------------------------------- #
# More test scripts
# ---------------------------------------------------------------------------------- #
def test_random_stuff(args):
"""Random tests and sanity checks.
We can manually move the robot and query the EE pose, to get a sense of the
appropriate environment boundaries. Then clip any poses (well, positions) that
exceed such bounds. Make sure that `return` is commented out, though.
"""
robot = SawyerRobot()
rospy.sleep(3) # Can let it sleep for a bit
# Might as well check images.
robot.DC.start_recording()
# Can move robot around and exit to test workspace bounds.
ee_pose = robot.get_ee_pose()
tool_pose = robot.get_tool_pose()
print('Current EE pose: {}'.format(ee_pose))
print('Current tool pose: {}'.format(tool_pose))
#pose = [0.6378, -0.0736, 0.3641, -0.161 , -0.6951, 0.6796, -0.1705] # enter the water!
#robot.move_to_ee_pose(pose)
# We only want this if replacing the tools.
#robot.open_gripper()
robot.close_gripper()
return # exit after checking poses.
if False:
# Sanity check: query current EE pose, then move to it. The robot should not move!
print('SawyerRobot.reset_pose() [start] ...')
robot.move_to_ee_pose(ee_pose)
print('SawyerRobot.reset_pose() [end] ...')
# Reset the robot to the starting 'home' position, tuned for this project.
robot.move_to_ee_pose(MM_HOME_POSE_EE)
# Test rotation.
rotations = [-np.pi/2.0, np.pi/2.0, np.pi/2.0, -np.pi/2.0]
for rot_z in rotations:
print('\nRotating: {:0.1f} (deg)'.format(rot_z*RAD_TO_DEG))
robot.rotate_z(rot_z)
rospy.sleep(1)
# Open or close the robot gripper. Careful! This will let go of the tool.
return
print('Opening and closing the robot gripper...')
robot.open_gripper()
rospy.sleep(1)
robot.close_gripper()
rospy.sleep(1)
# NOTE(daniel) uses deprecated `capture_image`.
def test_world_to_camera(args):
"""Intended use case: given world coordinates, check that we can get camera pixels.
If we get negative pixels, they won't show up when we annotate via OpenCV.
"""
robot = SawyerRobot()
rospy.sleep(0)
# Camera images. Make sure the roslaunch file 'activates' the camera nodes.
cimg1, dimg1 = robot.capture_image(args.data_dir, camera_ns='k4a', filename='k4a')
cimg2, dimg2 = robot.capture_image(args.data_dir, camera_ns='k4a_top', filename='k4a_top')
# Get the robot EE position (w.r.t. world) and get the pixels.
ee_pose = robot.get_ee_pose()
ee_posi = ee_pose[:3]
print('Current EE position: {}'.format(ee_posi))
# Use the top camera, make Nx3 matrix with world coordinates to be converted to camera.
points_world = np.array([
[0.0, 0.0, 0.0], # base of robot (i.e., this is the world center origin)
[0.1, 0.0, 0.0], # more in x direction
[0.2, 0.0, 0.0], # more in x direction
[0.3, 0.0, 0.0], # more in x direction
[0.4, 0.0, 0.0], # more in x direction
[0.5, 0.0, 0.0], # more in x direction
[0.6, 0.0, 0.0], # more in x direction
[0.7, 0.0, 0.0], # more in x direction
[0.8, 0.0, 0.0], # more in x direction
[0.9, 0.0, 0.0], # more in x direction
[1.0, 0.0, 0.0], # more in x direction
[0.5, -0.6, 0.0], # check y
[0.5, -0.5, 0.0], # check y
[0.5, -0.4, 0.0], # check y
[0.5, -0.3, 0.0], # check y
[0.5, -0.2, 0.0], # check y
[0.5, -0.1, 0.0], # check y
[0.5, 0.1, 0.0], # check y
[0.5, 0.2, 0.0], # check y
[0.5, 0.3, 0.0], # check y
[0.6, -0.1, 0.0], # check z
[0.6, -0.1, 0.1], # check z
[0.6, -0.1, 0.2], # check z
[0.6, -0.1, 0.3], # check z
[0.6, -0.2, 0.0], # check z
[0.6, -0.2, 0.1], # check z
[0.6, -0.2, 0.2], # check z
[0.6, -0.2, 0.3], # check z
[0.6, -0.3, 0.0], # check z
[0.6, -0.3, 0.1], # check z
[0.6, -0.3, 0.2], # check z
[0.6, -0.3, 0.3], # check z
[0.6, -0.4, 0.0], # check z
[0.6, -0.4, 0.1], # check z
[0.6, -0.4, 0.2], # check z
[0.6, -0.4, 0.3], # check z
[0.6, -0.5, 0.0], # check z
[0.6, -0.5, 0.1], # check z
[0.6, -0.5, 0.2], # check z
[0.6, -0.5, 0.3], # check z
[0.6, -0.6, 0.0], # check z
[0.6, -0.6, 0.1], # check z
[0.6, -0.6, 0.2], # check z
[0.6, -0.6, 0.3], # check z
[0.667, -0.374, 0.662], # center of the camera (actually not visible)
])