-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepair_klampt_motion_planner.py
More file actions
1622 lines (1293 loc) · 67.2 KB
/
repair_klampt_motion_planner.py
File metadata and controls
1622 lines (1293 loc) · 67.2 KB
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 time
import numpy as np
from klampt import *
from klampt import vis
from IPython.display import clear_output
from klampt.vis.ipython import Playback
from klampt.model import ik
from klampt.plan.robotplanning import plan_to_config
import random
import klampt
from klampt.plan.cspaceutils import *
from klampt.plan.cspace import *
from klampt.plan.robotcspace import RobotCSpace
from klampt.model.collide import WorldCollider
from klampt.model.trajectory import *
from klampt.model import collide, ik, create
from klampt.math import so3, se3
import copy
# from repair_klampt_motion_planner import rotation_matrix_to_euler, euler_to_rotation_matrix
import os
import yaml
import rospy
import rospkg
from geometry_msgs.msg import Pose
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from threading import Thread
import tf2_ros
import geometry_msgs
vis.init("GLUT")
rospack = rospkg.RosPack()
pkg_path = rospack.get_path('repair_motion_controller')
home_joint_config_path = f"{pkg_path}/config/joint_config/home_joint_config.yaml"
with open(home_joint_config_path, 'r') as file:
home_joint_config = yaml.safe_load(file)['home_joint_config']
# ===================== CONFIGURATIONS START ============================================================================
# WORLD PATH
WORLD_PATH = (os.path.join(os.path.dirname(__file__), "../robot_description/klampt_world.xml"))
# INITIAL ROBOT CONFIGURATION
INITIAL_JOINT_POSITIONS = [ val for _, val in home_joint_config.items()]
# END EFFECTORS
LEFT_ARM_EE_LINK = "left_hand_v1_wide_grasp_link"
LEFT_ARM_CAMERA_LINK = "arm_1_camera_mount"
RIGHT_ARM_EE_LINK = "right_hand_v1_2_research_grasp_link"
RIGHT_ARM_CAMERA_LINK = "arm_2_camera_mount"
# VISUALIZE
VIS_UPDATE_RATE = 100 # Hz
# PLANNER
NUM_WAY_POINTS = 1000
PLANNING_TIME_LIMIT = 5.0
NUM_IK_TRIES = 100
MAX_PLANNER_ITERS = 500
MAX_PLANNER_TIME = 10.0
EDGE_CHECK_RESOLUTION = 0.01
IS_PLANNER_OPTIMIZING = True
SIMPLIFY_TYPE = "ConvexHull"
PLANNER_SETTINGS_SBL = { # SBL planner.
"type": "sbl",
"perturbationRadius": 0.25,
"bidirectional": True,
"shortcut": 1,
"restart": 1,
"restartTermCond": "{foundSolution:1,maxIters:1000}",
}
PLANNER_SETTINGS_RRT = { # RRT planner.
"type": "rrt",
"perturbationRadius": 0.25,
"bidirectional": True,
"shortcut": True,
"restart": True,
"restartTermCond": "{foundSolution:1,maxIters:1000}",
}
# CAMERA
CAMERA_DIST = 4 # Distance from the target
CAMERA_ROT = [0.0, 0.0, 1.57, 1] # Orientation as a quaternion (w, x, y, z)
CAMERA_TGT = [0.0, 0.0, 1.5] # Target position (where the camera is looking)
CAMERA_POS = [3, 2, 1] # Camera position
# ===================== CONFIGURATIONS END ============================================================================
def get_link_index_by_name(robot, link_name):
for i in range(robot.numLinks()):
if robot.link(i).getName() == link_name:
return i
raise ValueError(f"Link '{link_name}' not found")
class RepairMotionPlanner:
def __init__(self, show_vis=True):
# flags
self.show_vis = show_vis
self.moveToHome = False
self.moveToGhost = False
self.resetGhost = False
# load robot for planning
self.world = WorldModel()
self.world.loadFile(WORLD_PATH)
self.planner_robot = self.world.robot(0)
self.sand_plane = self.add_sand_to_env()
# load real_robot for visualizing real robot states
self.__world_for_real_robot = WorldModel()
self.__world_for_real_robot.loadFile(WORLD_PATH)
self.real_robot = self.__world_for_real_robot.robot(0)
# robot drivers
self._robot_drivers = [self.planner_robot.driver(i) for i in range(self.planner_robot.numDrivers())]
self._sliding_guide_driver = self._robot_drivers[0]
self._torso_driver = self._robot_drivers[1]
self._left_arm_drivers = self._robot_drivers[2:9]
self._right_arm_drivers = self._robot_drivers[9:]
# End Effectors
self.endEffector_leftArm = self.planner_robot.link(LEFT_ARM_EE_LINK)
self.endEffector_rightArm = self.planner_robot.link(RIGHT_ARM_EE_LINK)
# 'configure robot's joints to initial configuration
self.set_initial_joint_positions(self.planner_robot)
self.set_initial_joint_positions(self.real_robot)
# Retrieve link indices by name
link_1_7_index = get_link_index_by_name(self.planner_robot, "arm_1_7")
link_1_5_index = get_link_index_by_name(self.planner_robot, "arm_1_5")
link_1_flange_index = get_link_index_by_name(self.planner_robot, "arm_1_angle_flange")
# Disable self-collisions between specified link pairs
self.planner_robot.enableSelfCollision(link_1_7_index, link_1_5_index, False)
self.planner_robot.enableSelfCollision(link_1_flange_index, link_1_5_index, False)
# initialize collisions
self.ignore_sand = False
self.__collider = WorldCollider(self.world)
self.__cspace = RobotCSpace(self.planner_robot, self.__collider)
self.__cspace.eps = 1e-2
self.__init_robot_collision()
self.__set_robot_color()
if self.show_vis:
self.__visualize()
#self.print_robot_info()
self.__loginfo("RepairMotionPlanner is initialized")
def print_robot_info(self):
print("Robot info:")
print(" Name:", self.planner_robot.getName())
print(" Links:", self.planner_robot.numLinks())
print(" Link names:")
for i in range(self.planner_robot.numLinks()):
print(f" {i}: {self.planner_robot.link(i).getName()}")
print(" Joints:", self.planner_robot.numDrivers())
print(" Joint names:")
for i in range(self.planner_robot.numDrivers()):
print(" ", self.planner_robot.driver(i).getName())
def __loginfo(self, info):
print(f"[INFO] [{rospy.Time.now().secs}.{rospy.Time.now().nsecs}]: {info}")
def __logwarn(self, info):
print(f"\033[93m[WARN] [{rospy.Time.now().secs}.{rospy.Time.now().nsecs}]: {info}\033[0m")
def __logerr(self, info):
print(f"\033[91m[ERROR] [{rospy.Time.now().secs}.{rospy.Time.now().nsecs}]: {info}\033[0m")
def on_moveToHomePose(self):
print("moveToHomePose clicked!")
self.moveToHome = True
def on_moveToGhostPose(self):
print("moveToGhostPose clicked!")
self.moveToGhost = True
def on_resetGhostPose(self):
print("moveToGhostPose clicked!")
self.resetGhost = True
def update_robot_cspace_and_colliders(self):
"""
Updates the robot's configuration space and collision settings.
"""
self.__collider = WorldCollider(self.world)
self.__cspace = RobotCSpace(self.planner_robot, self.__collider)
self.__cspace.eps = 1e-2
self.__init_robot_collision()
def __visualize(self):
if self.show_vis:
# Configure Camera View
viewport = vis.getViewport() # Obtain the current viewport
# Modify the camera parameters
# viewport.camera.dist = CAMERA_DIST
# viewport.camera.rot = CAMERA_ROT
# viewport.camera.tgt = CAMERA_TGT
# viewport.camera.pos = CAMERA_POS
# vis.setViewport(viewport) # Apply the modified viewport
print("real_robot:", self.real_robot)
print("ghost config:", self.world.robot(0).getConfig())
print("World contents:")
print(" Robots:", self.world.numRobots())
print(" Rigid objects:", self.world.numRigidObjects())
print(" Terrains:", self.world.numTerrains())
vis.kill() # Force close any existing window
vis.clear() # Clear all previous items
# got some errors here with viewport etc. this config here seemed to work but might have issues
robot = self.world.robot(0)
print("Now setting cool 1")
robot.setConfig(self.real_robot.getConfig())
vis.add("world", self.world)
vis.add("real_robot", robot, color = [0.5,0.5,0.5,1]) # use to show the real robot's state
vis.add("ghost", self.world.robot(0).getConfig(), color = (0,1,0,0.5))
vis.edit("ghost")
vis.addAction(self.on_moveToHomePose, "MoveToHomePose")
vis.addAction(self.on_moveToGhostPose, "MoveToGhostPose")
vis.addAction(self.on_resetGhostPose, "ResetGhostPose")
vis.show()
#
self.update_vis_thread = Thread(target=self.__update_vis_task)
self.update_vis_thread.start()
def __update_vis_task(self):
while vis.shown():
vis.lock()
vis.setItemConfig("ghost", self.planner_robot.getConfig())
# self.planner_robot.setConfig(self.planner_robot.getConfig()) # use to show the planned target configuration
#self.real_robot.setConfig(self.planner_robot.getConfig()) #TODO ?! wth
vis.unlock()
# vis.addText("RB1", "%.2f" % (time.time(),), position=(0, 20))
time.sleep(1 / VIS_UPDATE_RATE)
def __set_robot_color(self, color=[1, 1, 0, 0.5]):
for i in range(self.planner_robot.numLinks()):
link = self.planner_robot.link(i)
appearance = link.appearance()
appearance.setColor(color[0], color[1], color[2], color[3])
def reset_ghost(self):
self.planner_robot.setConfig(self.real_robot.getConfig())
self.__loginfo("Ghost pose has been reset to the current robot pose.")
def get_ghost_config(self):
return vis.getItemConfig("ghost")
def execute_planned_path_in_vis(self, path):
"""
When vis is enabled, this will show the planned motion in vis for given the interpolate path.
"""
for milestone in path:
vis.setItemConfig("ghost", milestone)
# self.planner_robot.setConfig(milestone)
time.sleep(1 / len(path)) # Wait for visualization update
def update_real_robot_joint_states(self, joint_configs:List):
"""
Given joint joint_configs of the robot as a list,
this function update the real robot configuration in the vis.
Parameters:
joint_configs (list(float)): A list containing joint configurations of all 16 joints in the order of
[j_torso_base, j_torso_1, j_arm_1_1, j_arm_1_2, j_arm_1_3, j_arm_1_4, j_arm_1_5, j_arm_1_6, j_arm_1_7, j_arm_2_1, j_arm_2_2, j_arm_2_3, j_arm_2_4, j_arm_2_5, j_arm_2_6, j_arm_2_7]
"""
# validate number of elements in joint_states
if len(joint_configs) != 16:
raise ValueError("length of joint_states should be 16.")
for index, val in enumerate(joint_configs) :
self.real_robot.driver(index).setValue(val)
def get_robot_drivers(self):
"""
Returns a list of `RobotModelDrivers` of the robot.
Returns:
list[RobotModelDriver]: A list containing `RobotModelDriver`s of the robot.
"""
return[self.planner_robot.driver(i) for i in range(self.robot.numDrivers())]
def get_robot_drivers_link_indices(self) -> List[int]:
"""
Retrieves the indices of all links driven by the robot's drivers.
Returns:
list[int]: A list containing the indices of all links controlled by the robot's drivers.
"""
driver_indices = []
for drvId in range(self.planner_robot.numDrivers()):
linkName = self.planner_robot.driver(drvId).getName()
linkIndex = self.planner_robot.link(linkName).index
driver_indices.append(linkIndex)
return driver_indices
def get_robot_drivers_velocity_limits(self):
"""
Retrieves the velocity limits of the joints controlled by the robot's drivers.
Returns:
list[(float, float)]: A list of velocity limits of the joints.
"""
vel_limits = []
for i in range(self.planner_robot.numDrivers()):
vel_limits.append(self.planner_robot.driver(i).getVelocityLimits())
return vel_limits
def getJointValues(self, robot:RobotModel):
"""
Retrieves the current values of the joints controlled by the robot's drivers.
Returns:
list[Float]: A list of the current values of the joints controlled by the robot's drivers.
"""
drivers = self.get_robot_drivers()
return [drv.getValue() for drv in drivers]
def getJointLimits(self):
robot_drivers = self.get_robot_drivers()
return [drv.getLimits() for drv in robot_drivers]
def setJointValues(self, robot:RobotModel, vals):
for i in range(robot.numDrivers()):
robot.driver(i).setValue(vals[i])
robot.setConfig(self.planner_robot.getConfig())
def getEndEffectorPose_leftArm(self, robot:RobotModel) -> Pose:
"""
Returns the current End Effector Pose (`position`, `orientation`) of the Left Arm.
Parameters:
robot (RobotModel): The robot model from which the end effector pose is to be retrieved.
- Options: `self.planner_robot` or `self.real_robot`
Returns:
Pose: A `Pose` object containing the current position and orientation of the left arm's end effector.
"""
R, t = robot.link(LEFT_ARM_EE_LINK).getTransform()
quat = so3.quaternion(R)
# swap z and w
pose = Pose()
pose.orientation.w = quat[0]
pose.orientation.x = quat[1]
pose.orientation.y = quat[2]
pose.orientation.z = quat[3]
pose.position.x = t[0]
pose.position.y = t[1]
pose.position.z = t[2]
return pose
def getEndEffectorPose_rightArm(self, robot:RobotModel) -> Pose:
"""
Returns the current End Effector Pose (`position`, `orientation`) of the Right Arm.
Parameters:
robot (RobotModel): The robot model from which the end effector pose is to be retrieved.
- Options: `self.planner_robot` or `self.real_robot`
Returns:
Pose: A `Pose` object containing the current position and orientation of the right arm's end effector.
"""
R, t = robot.link(RIGHT_ARM_EE_LINK).getTransform()
quat = so3.quaternion(R)
# swap z and w
pose = Pose()
pose.orientation.w = quat[0]
pose.orientation.x = quat[1]
pose.orientation.y = quat[2]
pose.orientation.z = quat[3]
pose.position.x = t[0]
pose.position.y = t[1]
pose.position.z = t[2]
return pose
def get_realRobot_EEs(self):
""" Returns left and right arm End-effector poses of the real robot. """
leftEE = self.getEndEffectorPose_leftArm(self.real_robot)
rightEE = self.getEndEffectorPose_rightArm(self.real_robot)
return leftEE, rightEE
# def print_robot_info(self):
# """
# Prints the links and joint information of the robot.
# """
# self.__loginfo("Robot info:")
# self.__loginfo("\t Name:", self.planner_robot.getName())
# self.__loginfo("\t Links:", self.planner_robot.numLinks())
# self.__loginfo("\t Link names:")
# for i in range(self.planner_robot.numLinks()):
# self.__loginfo(f"\t {i}: {self.planner_robot.link(i).getName()}")
# self.__loginfo("\t Joints:", self.planner_robot.numDrivers())
# self.__loginfo("\t Joint names:")
# for i in range(self.planner_robot.numDrivers()):
# self.__loginfo("\t ", self.planner_robot.driver(i).getName(), self.planner_robot.driver(i).getLimits())
def filterJointConfigFromFullConfig(self, full_config):
"""
Filters the joint configuration values from a full configuration array.
This function extracts the values of the joints controlled by the robot's drivers
from the full configuration array. It uses the indices of the joints to retrieve
their corresponding values from the full configuration.
Parameters:
full_config (list): The full configuration array containing values for all joints of the robot.
Returns:
list: A list of the values for the joints controlled by the robot's drivers.
"""
driver_values = []
joint_ids = self.get_robot_drivers_link_indices()
for joint_id in joint_ids:
driver_values.append(full_config[joint_id])
return driver_values
def filter_path(self, path):
"""
Filters the configuration values of the robot's joints (drivers) from a given path.
Parameters:
path (list): A list of configuration arrays, where each array represents the state of all joints at a specific time step.
Returns:
list: A list of filtered configuration arrays, containing only the values for the joints controlled by the robot's drivers.
"""
filtered_path = []
joint_ids = self.get_robot_drivers_link_indices()
for i in range(len(path)):
filtered_config = [ path[i][joint_id] for joint_id in joint_ids ]
filtered_path.append(filtered_config)
return filtered_path
def set_initial_joint_positions(self, robot:RobotModel):
"""
Sets the initial configuration to a given `RobotModel`.
Parameters:
robot (RobotModel): `self.planner_robot` or `self.real_robot`.
"""
self.setJointValues(robot, INITIAL_JOINT_POSITIONS)
def __init_robot_collision(self):
"""
Initializes the robot's collision detection and handling.
This function sets up collision tests and ignores specific collisions for the robot's drivers.
It identifies collisions between different parts of the robot and adds them to a set of collisions
to be ignored. It also explicitly ignores collisions between certain predefined links of the robot.
Any detected collisions are logged as warnings.
Steps:
1. Iterate through collision tests and add colliding objects to a set to be ignored.
2. Ignore collisions for the collected set.
3. Disable self-collision for specific robot links.
4. Log warnings for any detected collisions.
5. Print an info message if self-collisions are detected.
Note:
This function assumes the existence of methods `collisionTests()`, `ignoreCollision()`,
and `enableSelfCollision()` provided by the `self.__collider` and `self.planner_robot` objects.
"""
ignore_coll_sets = set()
for i, j in self.__collider.collisionTests():
if i[1].collides(j[1]):
ignore_coll_sets.add((i[0], j[0]))
for ignore_set in ignore_coll_sets:
self.__collider.ignoreCollision(ignore_set)
if (type(ignore_set[0])) == klampt.robotsim.RobotModelLink and \
(type(ignore_set[1])) == klampt.robotsim.RobotModelLink:
self.planner_robot.enableSelfCollision(ignore_set[0].getIndex(), ignore_set[1].getIndex(), False)
# ignore collision between left_inner_finger_pad and right_inner_finger_pad
if self.ignore_sand:
terrain_index = self.world.index(self.world.terrain("Sand"))
for i in range(self.world.numTerrains() + self.world.numRigidObjects() + self.world.numRobots()):
if i != terrain_index:
self.__collider.ignoreCollision(i, terrain_index)
self.__collider.ignoreCollision(
(
self.planner_robot.link("torso_1"),
self.planner_robot.link("sliding_guide_link"),
)
)
self.planner_robot.enableSelfCollision(
self.planner_robot.link("torso_1").getIndex(),
self.planner_robot.link("sliding_guide_link").getIndex(),
False,
)
for i, j in self.__collider.collisionTests():
if i[1].collides(j[1]):
rospy.logwarn(" - Object", i[0].getName(), "collides with", j[0].getName())
if self.planner_robot.selfCollides():
self.__logwarn("Robot self collision.")
# Helper method to log planner statistics
def _log_planner_stats(self, plan, start_time, num_iters):
self.__loginfo(f"Planning time: {time.time() - start_time}s over {num_iters} iterations")
V, E = plan.getRoadmap()
self.__loginfo(f"{len(V)} feasible milestones sampled, {len(E)} edges connected")
self.__loginfo(f"Planner stats: {plan.getStats()}")
# Helper method to handle a failed plan
def _handle_failed_plan(self, verbose, plan):
self.__loginfo("[INFO] [RepairMotionPlanner]: Failed to plan a feasible path")
if verbose >= 1:
self.__loginfo(f"Planner stats: {plan.getStats()}")
if verbose >= 2:
V, _ = plan.getRoadmap()
self.__loginfo("Some sampled configurations:")
self.__loginfo(f"\t {V[:min(10, len(V))]}")
def get_ik_objective(self, link, goal_pos, goal_rot) -> IKObjective:
"""
Create an `IKObjective` for a specified link with given goal position and rotation.
Parameters:
link: The link of the robot for which the IK objective is to be created.
goal_pos: A list or tuple representing the target position (x, y, z) for the link.
goal_rot: A list or tuple representing the target rotation matrix (3x3) for the link.
Returns:
ik.Objective: The `IKObjective` with the specified goal position and rotation.
"""
return ik.objective(link, ref=None, R=goal_rot, t=goal_pos)
# def find_ik_fast(
# self,
# objectives: List[IKObjective],
# num_tries: int = 5,
# moveable_subset=[],
# oneshot=True,
# solve_nearby=True
# ) ->Tuple[List[float], Pose, Pose, str]:
# """
# Attempts to solve the inverse kinematics (IK) problem for the given objectives and start configuration.
# Returns the goal configuration, TCP poses for the left and right arms, and information about success.
# Parameters:
# objectives (List[object]): List of IK objectives for the solver.
# num_tries (int, optional): Number of tries with increasing tolerance (default is 5).
# Returns:
# Tuple ([List[float], Pose, Pose, str]):
# A tuple containing:
# - goal_config (List[float]): The resulting configuration if IK succeeds.
# - tcp_left_pose (Pose): The TCP pose of the left arm as a `geometry_msgs/Pose` object.
# - tcp_right_pose (Pose): The TCP pose of the right arm as a `geometry_msgs/Pose` object.
# - info (str): Information about the IK process, indicating success or failure.
# Raises:
# RuntimeError: If IK fails after the specified number of tries.
# """
# solver = IKSolver(self.planner_robot)
# # can be used to plot all links, care spam
# # for i in range(self.planner_robot.numLinks()):
# # link = self.planner_robot.link(i)
# # print(f"[{i}] Link name: {link.getName()}")
# if(moveable_subset != []):
# #print(f"Adding subset {moveable_subset}")
# solver.setActiveDofs(moveable_subset)
# for obj in objectives:
# solver.add(obj)
# # try to solve IK multiple times to get a good solution
# # vary the tolerance each time
# info = ""
# res = False
# for i in range(num_tries):
# solver.setTolerance(1e-4 * 10 * i)
# res = solver.solve()
# if res:
# info = f"IK succeeded after {i + 1} tries with tolerance {solver.getTolerance()}"
# break
# if not res:
# error_msg = f"IK failed after {num_tries} attempts. Target pose(s) might be invalid. \nResidual: {solver.getResidual()}"
# if(oneshot):
# raise RuntimeError(error_msg)
# else:
# return None, None, None, "False"
# goal_config = self.planner_robot.getConfig()
# # get tcp poses
# tcp_left_pose = self.getEndEffectorPose_leftArm(self.planner_robot)
# tcp_right_pose = self.getEndEffectorPose_rightArm(self.planner_robot)
# return goal_config, tcp_left_pose, tcp_right_pose, info
def find_ik_fast(
self,
objectives: List[IKObjective],
num_tries: int = 5,
moveable_subset=[],
oneshot=True,
solve_nearby=True
) -> Tuple[List[float], Pose, Pose, str]:
"""
Attempts to solve IK quickly with some robustness:
- multiple randomized seeds
- adaptive tolerance schedule
- feasibility filtering
- chooses solution closest to start configuration
"""
solver = IKSolver(self.planner_robot)
solver.setMaxIters(2000)
if moveable_subset:
solver.setActiveDofs(moveable_subset)
for obj in objectives:
solver.add(obj)
init_config = self.planner_robot.getConfig()
best_conf, best_dist = None, float("inf")
info = ""
# tolerance schedule, from strict to looser
tolerances = [1e-4, 5e-4, 1e-3, 5e-3, 1e-2]
factor = 1.2
maxDeviation=0.3
for i in range(num_tries):
# use either init config or a perturbed one
# if i == 0:
# self.planner_robot.setConfig(init_config)
# else:
# qrand = [qi + random.uniform(-0.05, 0.05) for qi in init_config]
# self.planner_robot.setConfig(qrand)
# tol = tolerances[min(i, len(tolerances)-1)]
solver.setTolerance(1e-4)
dofs = solver.getActiveDofs()
q = self.planner_robot.getConfig()
qmin,qmax = self.planner_robot.getJointLimits()
for d in dofs:
qmin[d] = max(qmin[d],q[d]-maxDeviation)
qmax[d] = min(qmax[d],q[d]+maxDeviation)
solver.setJointLimits(qmin,qmax)
solver.setBiasConfig(q)
# try solve() first, fall back to solve_nearby if requested
success = solver.solve()
# if not success and solve_nearby:
# success = ik.solve_nearby(
# objectives,
# maxDeviation=0.15,
# iters=200,
# tol=1e-3,
# feasibilityCheck=self.is_feasible,
# numRestarts=2,
# activeDofs=moveable_subset if moveable_subset else None,
# )
maxDeviation*= factor
if success and self.is_feasible():
qsol = self.planner_robot.getConfig()
dist = vectorops.distance(qsol, init_config)
if dist < best_dist:
best_conf, best_dist = qsol, dist
info = f"IK succeeded on try {i+1} with tolerance 1e-3"
if best_conf is None:
error_msg = f"IK failed after {num_tries} attempts. Residual: {solver.getResidual()}"
if oneshot:
raise RuntimeError(error_msg)
else:
return None, None, None, "False"
# set robot to the best found config
self.planner_robot.setConfig(best_conf)
# get tcp poses
tcp_left_pose = self.getEndEffectorPose_leftArm(self.planner_robot)
tcp_right_pose = self.getEndEffectorPose_rightArm(self.planner_robot)
return best_conf, tcp_left_pose, tcp_right_pose, info
def is_feasible(self):
# return True only if *no* self‐collisions are present
geoms = [g for _,g in self.__collider.geomList]
# pairs to test are given by the mask
pairs = [(i,j) for i in range(len(self.__collider.geomList))
for j in self.__collider.mask[i] if i<j]
return not any(collide.self_collision_iter(geoms, pairs))
def find_ik(
self,
objectives: List[IKObjective],
num_tries: int = 5,
moveable_subset=[],
oneshot=True,
solve_nearby=True
) ->Tuple[List[float], Pose, Pose, str]:
"""
Attempts to solve the inverse kinematics (IK) problem for the given objectives and start configuration.
Returns the goal configuration, TCP poses for the left and right arms, and information about success.
Parameters:
objectives (List[object]): List of IK objectives for the solver.
num_tries (int, optional): Number of tries with increasing tolerance (default is 5).
Returns:
Tuple ([List[float], Pose, Pose, str]):
A tuple containing:
- goal_config (List[float]): The resulting configuration if IK succeeds.
- tcp_left_pose (Pose): The TCP pose of the left arm as a `geometry_msgs/Pose` object.
- tcp_right_pose (Pose): The TCP pose of the right arm as a `geometry_msgs/Pose` object.
- info (str): Information about the IK process, indicating success or failure.
Raises:
RuntimeError: If IK fails after the specified number of tries.
"""
goal_config, tcp_left_pose, tcp_right_pose, info = self.find_ik_fast(objectives, num_tries, moveable_subset, oneshot, solve_nearby)
if goal_config is None:
return goal_config, tcp_left_pose, tcp_right_pose, info
return goal_config, tcp_left_pose, tcp_right_pose, info
active_dofs = moveable_subset if(moveable_subset != []) else None
solutions = []
success = False
deviation = 0.3
ik_max_iter = 0
init_config = self.planner_robot.getConfig()
for n in range(num_tries):
while not success and ik_max_iter <= 50:
ik_max_iter +=1
self.planner_robot.setConfig(init_config)
if solve_nearby:
success = ik.solve_nearby(
objectives,
maxDeviation=deviation,
iters=2000,
tol=1e-3,
activeDofs = active_dofs,
feasibilityCheck=self.is_feasible,
numRestarts=5, # nearby: stick to current seed and small radius
)
deviation *= 1.2
else:
success = ik.solve_global(objectives,
iters=500, # increase per‑trial iterations
tol=1e-2, # tighter convergence
numRestarts=1, # more random restarts
feasibilityCheck=self.is_feasible,
activeDofs = active_dofs,
startRandom=False # randomize even the first guess
)
if success:
solutions.append(self.planner_robot.getConfig())
print("FOUND ik solution at iteration: ", ik_max_iter)
final_solutions = []
if solutions != []:
for conf in solutions:
if not self.is_robot_config_feasible(conf):
final_solutions.append(conf)
else:
print("No Valid IK found")
return None, None, None, "False"
goal_config = min(solutions, key=lambda q: vectorops.distance(q, init_config))
self.planner_robot.setConfig(goal_config)
# get tcp poses
tcp_left_pose = self.getEndEffectorPose_leftArm(self.planner_robot)
tcp_right_pose = self.getEndEffectorPose_rightArm(self.planner_robot)
#self.planner_robot.setConfig(init_config)
return goal_config, tcp_left_pose, tcp_right_pose, "True"
def get_robot_goal_config_old(self, left_arm_target_pose=None, right_arm_target_pose=None, gazing=True):
"""
Failsafe in case gazing or avoidance does not work as assumed.
Sets the target pose for the left and/or right arm.
Parameters:
target_pose_left (geometry_msgs/Pose, optional): The target pose for the left arm. Default is None.
target_pose_right (geometry_msgs/Pose, optional): The target pose for the right arm. Default is None.
Returns:
Tuple ([List[float], Pose, Pose, str]):
A tuple containing:
- goal_config (List[float]): The resulting configuration if IK succeeds.
- tcp_left_pose (Pose): The TCP pose of the left arm as a `geometry_msgs/Pose` object.
- tcp_right_pose (Pose): The TCP pose of the right arm as a `geometry_msgs/Pose` object.
- info (str): Information about the IK process, indicating success or failure.
Raises:
ValueError: If neither `target_pose_left` nor `target_pose_right` is provided.
RuntimeError: If IK fails after the specified number of tries.
"""
if left_arm_target_pose is None and right_arm_target_pose is None:
raise ValueError("At least one of `target_pose_left` or `target_pose_right` must be provided")
ik_objs = []
# remove vis goal labels if exists
if self.show_vis:
try:
vis.remove("LeftArm IK goal")
except:
pass
try:
vis.remove("RightArm IK goal")
except:
pass
# Get Ik Objective for Left Arm
if left_arm_target_pose is not None:
# Select the end effector link.
leftEE_link = self.endEffector_leftArm
# Get current positions and orientation.
currentTransform_leftEE = leftEE_link.getTransform()
currentPose_leftEE, currentOrientation_leftEE = currentTransform_leftEE[1], so3.quaternion(currentTransform_leftEE[0])
# Determine goal orientation.
# If goal orientation is provided use that, otherwise use current orientation as goal orientation.
left_goal_rot = (
so3.from_quaternion((left_arm_target_pose.orientation.w, left_arm_target_pose.orientation.x, left_arm_target_pose.orientation.y, left_arm_target_pose.orientation.z))
if left_arm_target_pose.orientation else currentOrientation_leftEE)
# get ik objective
position = [left_arm_target_pose.position.x, left_arm_target_pose.position.y, left_arm_target_pose.position.z]
ik_objective_left = self.get_ik_objective(leftEE_link, position, left_goal_rot)
ik_objs.append(ik_objective_left)
if self.show_vis:
vis.add("LeftArm IK goal",ik_objective_left)
# Get Ik Objective for Right Arm
if right_arm_target_pose is not None:
# Select the end effector link.
rightEE_link = self.endEffector_rightArm
# Get current positions and orientation.
currentTransform_rightEE = rightEE_link.getTransform()
currentPose_rightEE, currentOrientation_rightEE = currentTransform_rightEE[1], so3.quaternion(currentTransform_rightEE[0])
# Determine goal orientation.
# If goal orientation is provided use that, otherwise use current orientation as goal orientation.
right_goal_rot = (
so3.from_quaternion((right_arm_target_pose.orientation.w, right_arm_target_pose.orientation.x, right_arm_target_pose.orientation.y, right_arm_target_pose.orientation.z))
if right_arm_target_pose.orientation else currentOrientation_rightEE)
# get ik objective
position = [right_arm_target_pose.position.x, right_arm_target_pose.position.y, right_arm_target_pose.position.z]
ik_objective_right = self.get_ik_objective(rightEE_link, position, right_goal_rot)
ik_objs.append(ik_objective_right)
if self.show_vis:
vis.add("RightArm IK goal",ik_objective_right)
# try to get the goal configuration solving IK.
try:
goal_config, left_tcp, right_tcp, info = self.find_ik(ik_objs, num_tries = NUM_IK_TRIES)
except RuntimeError as e:
raise RuntimeError(e)
torso_link = self.planner_robot.link("torso_1")
R, t = torso_link.getTransform()
print("TORSO TRANSFORM: ", t)
return goal_config, left_tcp, right_tcp, info
def get_robot_goal_config(self, left_arm_target_pose=None, right_arm_target_pose=None, gazing=True): # new test method
"""
Sets the target pose for the left and/or right arm.
Parameters:
target_pose_left (geometry_msgs/Pose, optional): The target pose for the left arm. Default is None.
target_pose_right (geometry_msgs/Pose, optional): The target pose for the right arm. Default is None.
Returns:
Tuple ([List[float], Pose, Pose, str]):
A tuple containing:
- goal_config (List[float]): The resulting configuration if IK succeeds.
- tcp_left_pose (Pose): The TCP pose of the left arm as a `geometry_msgs/Pose` object.
- tcp_right_pose (Pose): The TCP pose of the right arm as a `geometry_msgs/Pose` object.
- info (str): Information about the IK process, indicating success or failure.
Raises:
ValueError: If neither `target_pose_left` nor `target_pose_right` is provided.
RuntimeError: If IK fails after the specified number of tries.
"""
if left_arm_target_pose is None and right_arm_target_pose is None:
raise ValueError("At least one of `target_pose_left` or `target_pose_right` must be provided")
ik_objs = []
# remove vis goal labels if exists
if self.show_vis:
try:
vis.remove("LeftArm IK goal")
except:
pass
try:
vis.remove("RightArm IK goal")
except:
pass
# Get Ik Objective for Left Arm
if left_arm_target_pose is not None:
# Select the end effector link.
leftEE_link = self.endEffector_leftArm
# Get current positions and orientation.
currentTransform_leftEE = leftEE_link.getTransform()
currentPose_leftEE, currentOrientation_leftEE = currentTransform_leftEE[1], so3.quaternion(currentTransform_leftEE[0])
# Determine goal orientation.
# If goal orientation is provided use that, otherwise use current orientation as goal orientation.
left_goal_rot = (
so3.from_quaternion((left_arm_target_pose.orientation.w, left_arm_target_pose.orientation.x, left_arm_target_pose.orientation.y, left_arm_target_pose.orientation.z))
if left_arm_target_pose.orientation else currentOrientation_leftEE)
# get ik objective
position = [left_arm_target_pose.position.x, left_arm_target_pose.position.y, left_arm_target_pose.position.z]
ik_objective_left = self.get_ik_objective(leftEE_link, position, left_goal_rot)
ik_objs.append(ik_objective_left)
if self.show_vis:
vis.add("LeftArm IK goal",ik_objective_left)
# Get Ik Objective for Right Arm
if right_arm_target_pose is not None:
# Select the end effector link.
rightEE_link = self.endEffector_rightArm
# Get current positions and orientation.
currentTransform_rightEE = rightEE_link.getTransform()
currentPose_rightEE, currentOrientation_rightEE = currentTransform_rightEE[1], so3.quaternion(currentTransform_rightEE[0])
# Determine goal orientation.
# If goal orientation is provided use that, otherwise use current orientation as goal orientation.
right_goal_rot = (
so3.from_quaternion((right_arm_target_pose.orientation.w, right_arm_target_pose.orientation.x, right_arm_target_pose.orientation.y, right_arm_target_pose.orientation.z))
if right_arm_target_pose.orientation else currentOrientation_rightEE)
# get ik objective
position = [right_arm_target_pose.position.x, right_arm_target_pose.position.y, right_arm_target_pose.position.z]
ik_objective_right = self.get_ik_objective(rightEE_link, position, right_goal_rot)
ik_objs.append(ik_objective_right)
if self.show_vis:
vis.add("RightArm IK goal",ik_objective_right)
# try to get the goal configuration solving IK.
try:
goal_config, left_tcp, right_tcp, info = self.find_ik(ik_objs, num_tries = NUM_IK_TRIES)
except RuntimeError as e:
raise RuntimeError(e)
# Hirachical move other arm away
if(left_arm_target_pose is None or right_arm_target_pose is None):
print("Validating distance of goal config or replanning..")
unused_arm = "left" if left_arm_target_pose is None else "right"
if(unused_arm=="left"):
print("Unused arm is left")
EE_link = self.endEffector_leftArm
avoid_link = self.endEffector_rightArm
moveable_link_names = ["arm_1_1", "arm_1_2", "arm_1_3", "arm_1_4", "arm_1_5", "arm_1_6", "arm_1_7"]
moveable_subset = [self.planner_robot.link(name).index for name in moveable_link_names]
gaze_link = self.planner_robot.link(LEFT_ARM_CAMERA_LINK)
elif(unused_arm=="right"):
print("Unused arm is right")