-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpybullet_utils_cust.py
executable file
·1498 lines (1112 loc) · 58 KB
/
pybullet_utils_cust.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
from collections import namedtuple
import pybullet as p
import pybullet_data
import numpy as np
import time
import matplotlib as mpl
import matplotlib.pyplot as plt
from collections import defaultdict, deque, namedtuple
from itertools import product, combinations, count
import open3d as o3d
from math import ceil, sqrt, sin, cos
import xml.etree.ElementTree as ET
INF = np.inf
PI = np.pi
CIRCULAR_LIMITS = -PI, PI
MAX_DISTANCE = 0
def configure_pybullet(rendering=False, debug=False, yaw=50.0, pitch=-35.0, dist=1.2, target=(0.0, 0.0, 0.0)):
"""
This function is likely to be called multiples times to initiate multiple connections
Note that Only one local in-process GUI/GUI_SERVER connection allowed.
Pass in the client ID is important because otherwise they all operate on the first connection
you can use p.GUI in different python files
you can use p.DIRECT in a same python file
"""
if not rendering:
client_id = p.connect(p.DIRECT)
else:
client_id = p.connect(p.GUI) # be careful about GUI vs GUI_SERVER, GUI_SERVER should only be used with shared memory
p.setAdditionalSearchPath(pybullet_data.getDataPath(), physicsClientId=client_id)
if not debug:
p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0, physicsClientId=client_id)
reset_camera(yaw=yaw, pitch=pitch, dist=dist, target=target, client_id=client_id)
p.setPhysicsEngineParameter(enableFileCaching=0, physicsClientId=client_id)
p.resetSimulation(physicsClientId=client_id)
p.setGravity(0, 0, -9.8)
return client_id
def step(duration=1.0, client_id=0):
for i in range(int(duration * 240)):
p.stepSimulation(physicsClientId=client_id)
def step_real(duration=1.0, client_id=0):
for i in range(int(duration * 240)):
p.stepSimulation(physicsClientId=client_id)
time.sleep(1.0 / 240.0)
def split_7d(pose):
return [list(pose[:3]), list(pose[3:])]
def merge_pose_2d(pose):
return list(pose[0] + pose[1])
def get_euler_from_quaternion(quaternion):
return list(p.getEulerFromQuaternion(quaternion))
def get_quaternion_from_euler(euler):
return list(p.getQuaternionFromEuler(euler))
# Constraints
ConstraintInfo = namedtuple('ConstraintInfo', ['parentBodyUniqueId', 'parentJointIndex',
'childBodyUniqueId', 'childLinkIndex', 'constraintType',
'jointAxis', 'jointPivotInParent', 'jointPivotInChild',
'jointFrameOrientationParent', 'jointFrameOrientationChild',
'maxAppliedForce'])
def remove_all_constraints(client_id=0):
for cid in get_constraint_ids(client_id):
p.removeConstraint(cid, physicsClientId=client_id)
def get_constraint_ids(client_id=0):
"""
getConstraintUniqueId will take a serial index in range 0..getNumConstraints, and reports the constraint unique id.
Note that the constraint unique ids may not be contiguous, since you may remove constraints.
"""
return sorted([p.getConstraintUniqueId(i, physicsClientId=client_id) for i in range(p.getNumConstraints(physicsClientId=client_id))])
def get_constraint_info(constraint, client_id=0):
# there are four additional arguments
return ConstraintInfo(*p.getConstraintInfo(constraint, physicsClientId=client_id)[:11])
# Joints
JOINT_TYPES = {
p.JOINT_REVOLUTE: 'revolute', # 0
p.JOINT_PRISMATIC: 'prismatic', # 1
p.JOINT_SPHERICAL: 'spherical', # 2
p.JOINT_PLANAR: 'planar', # 3
p.JOINT_FIXED: 'fixed', # 4
p.JOINT_POINT2POINT: 'point2point', # 5
p.JOINT_GEAR: 'gear', # 6
}
def get_num_joints(body, client_id=0):
return p.getNumJoints(body, physicsClientId=client_id)
def get_joints(body, client_id=0):
return list(range(get_num_joints(body, client_id=client_id)))
def get_joint(body, joint_or_name):
if type(joint_or_name) is str:
return joint_from_name(body, joint_or_name)
return joint_or_name
JointInfo = namedtuple('JointInfo', ['jointIndex', 'jointName', 'jointType',
'qIndex', 'uIndex', 'flags',
'jointDamping', 'jointFriction', 'jointLowerLimit', 'jointUpperLimit',
'jointMaxForce', 'jointMaxVelocity', 'linkName', 'jointAxis',
'parentFramePos', 'parentFrameOrn', 'parentIndex'])
def get_joint_info(body, joint, client_id=0):
return JointInfo(*p.getJointInfo(body, joint, physicsClientId=client_id))
def get_joints_info(body, joints, client_id=0):
return [JointInfo(*p.getJointInfo(body, joint, physicsClientId=client_id)) for joint in joints]
def get_joint_name(body, joint, client_id=0):
return get_joint_info(body, joint, physicsClientId=client_id).jointName.decode('UTF-8')
def get_joint_names(body, client_id=0):
return [get_joint_name(body, joint, client_id) for joint in get_joints(body, client_id)]
def joint_from_name(body, name, client_id=0):
for joint in get_joints(body, client_id):
if get_joint_name(body, joint, client_id) == name:
return joint
raise ValueError(body, name)
def has_joint(body, name, client_id=0):
try:
joint_from_name(body, name, client_id=client_id)
except ValueError:
return False
return True
def joints_from_names(body, names, client_id=0):
return tuple(joint_from_name(body, name, client_id=client_id) for name in names)
JointState = namedtuple('JointState', ['jointPosition', 'jointVelocity',
'jointReactionForces', 'appliedJointMotorTorque'])
def get_joint_state(body, joint, client_id=0):
return JointState(*p.getJointState(body, joint, physicsClientId=client_id))
def get_joint_position(body, joint, client_id=0):
return get_joint_state(body, joint, client_id=client_id).jointPosition
def get_joint_torque(body, joint, client_id=0):
return get_joint_state(body, joint, client_id=client_id).appliedJointMotorTorque
def get_joint_positions(body, joints=None, client_id=0):
return list(get_joint_position(body, joint, client_id) for joint in joints)
def set_joint_position(body, joint, value, client_id=0):
p.resetJointState(body, joint, value, physicsClientId=client_id)
def set_joint_positions(body, joints, values, client_id=0):
assert len(joints) == len(values)
for joint, value in zip(joints, values):
set_joint_position(body, joint, value, client_id=client_id)
def get_configuration(body, client_id=0):
return get_joint_positions(body, get_movable_joints(body, client_id), client_id)
def set_configuration(body, values, client_id=0):
set_joint_positions(body, get_movable_joints(body, client_id=client_id), values, client_id=client_id)
def get_full_configuration(body, client_id=0):
# Cannot alter fixed joints
return get_joint_positions(body, get_joints(body), client_id=client_id)
def get_joint_type(body, joint, client_id=0):
return get_joint_info(body, joint, client_id=client_id).jointType
def is_movable(body, joint, client_id=0):
return get_joint_type(body, joint, client_id=client_id) != p.JOINT_FIXED
def get_movable_joints(body, client_id=0): # 45 / 87 on pr2
return [joint for joint in get_joints(body, client_id=client_id) if is_movable(body, joint,client_id=client_id)]
def joint_from_movable(body, index, client_id=0):
return get_joints(body, client_id)[index]
def is_circular(body, joint, client_id=0):
# Do not understand what this means
joint_info = get_joint_info(body, joint, client_id=client_id)
if joint_info.jointType == p.JOINT_FIXED:
return False
return joint_info.jointUpperLimit >= joint_info.jointLowerLimit # reversed?
def get_joint_limits(body, joint, client_id=0):
"""
Obtain the limits of a single joint
:param body: int
:param joint: int
:return: (int, int), lower limit and upper limit
"""
joint_info = get_joint_info(body, joint, client_id=client_id)
return joint_info.jointLowerLimit, joint_info.jointUpperLimit
def get_joints_limits(body, joints, client_id=0):
"""
Obtain the limits of a set of joints
:param body: int
:param joints: array type
:return: a tuple of 2 arrays - lower limit and higher limit
"""
lower_limit = []
upper_limit = []
for joint in joints:
lower_limit.append(get_joint_info(body, joint, client_id=client_id).jointLowerLimit)
upper_limit.append(get_joint_info(body, joint, client_id=client_id).jointUpperLimit)
return lower_limit, upper_limit
def get_min_limit(body, joint, client_id=0):
return get_joint_limits(body, joint, client_id=client_id)[0]
def get_max_limit(body, joint, client_id=0):
return get_joint_limits(body, joint, client_id=client_id)[1]
def get_max_velocity(body, joint, client_id=0):
return get_joint_info(body, joint, client_id=client_id).jointMaxVelocity
def get_max_force(body, joint, client_id=0):
return get_joint_info(body, joint, client_id=client_id).jointMaxForce
def get_joint_q_index(body, joint, client_id=0):
return get_joint_info(body, joint, client_id=client_id).qIndex
def get_joint_v_index(body, joint, client_id=0):
return get_joint_info(body, joint, client_id=client_id).uIndex
def get_joint_axis(body, joint, client_id=0):
return get_joint_info(body, joint, client_id=client_id).jointAxis
def get_joint_parent_frame(body, joint, client_id=0):
joint_info = get_joint_info(body, joint, client_id=client_id)
return joint_info.parentFramePos, joint_info.parentFrameOrn
def violates_limit(body, joint, value, client_id=0):
if not is_circular(body, joint, client_id=client_id):
lower, upper = get_joint_limits(body, joint, client_id=client_id)
if (value < lower) or (upper < value):
return True
return False
def violates_limits(body, joints, values, client_id=0):
return any(violates_limit(body, joint, value, client_id=client_id) for joint, value in zip(joints, values))
def wrap_angle(theta): # change to -np.pi ~ np.pi
return (theta + np.pi) % (2 * np.pi) - np.pi
def circular_difference(theta2, theta1):
return wrap_angle(theta2 - theta1)
def wrap_joint(body, joint, value, client_id=0):
if is_circular(body, joint, client_id=client_id):
return wrap_angle(value)
return value
def get_difference_fn(body, joints, client_id=0):
def fn(q2, q1):
difference = []
for joint, value2, value1 in zip(joints, q2, q1):
difference.append(circular_difference(value2, value1)
if is_circular(body, joint, client_id=client_id) else (value2 - value1))
return list(difference)
return fn
def get_refine_fn(body, joints, num_steps=0, client_id=0): # no use
difference_fn = get_difference_fn(body, joints, client_id=client_id)
num_steps = num_steps + 1
def fn(q1, q2):
q = q1
for i in range(num_steps):
q = tuple((1. / (num_steps - i)) * np.array(difference_fn(q2, q)) + q)
yield q
return fn
# Body and base
BodyInfo = namedtuple('BodyInfo', ['base_name', 'body_name'])
# Bodies
def get_bodies(client_id=0):
return [p.getBodyUniqueId(i, physicsClientId=client_id)
for i in range(p.getNumBodies(physicsClientId=client_id))]
def get_body_info(body, client_id=0):
return BodyInfo(*p.getBodyInfo(body, physicsClientId=client_id))
def get_base_name(body, client_id=0):
return get_body_info(body, client_id=client_id).base_name.decode(encoding='UTF-8')
def get_body_name(body, client_id=0):
return get_body_info(body, client_id).body_name.decode(encoding='UTF-8')
def get_name(body, client_id=0):
name = get_body_name(body, client_id=client_id)
if name == '':
name = 'body'
return '{}{}'.format(name, int(body))
def has_body(name, client_id=0):
try:
body_from_name(name, client_id=client_id)
except ValueError:
return False
return True
def body_from_name(name, client_id=0):
for body in get_bodies(client_id=client_id):
if get_body_name(body, client_id=client_id) == name:
return body
raise ValueError(name)
def remove_body(body, client_id=0):
return p.removeBody(body, physicsClientId=client_id)
def get_body_quat(body, client_id=0):
return get_body_pose(body, client_id=client_id)[1] # [x,y,z,w]
def set_pose(body, pose, client_id=0):
(point, quat) = pose
p.resetBasePositionAndOrientation(body, point, quat, physicsClientId=client_id)
def set_center_pose(body, center_pose, Center2Base_pose, client_id=0):
Base_pose = multiply_multi_transforms(center_pose, Center2Base_pose)
(point, quat) = Base_pose
p.resetBasePositionAndOrientation(body, point, quat, physicsClientId=client_id)
def is_rigid_body(body, client_id=0):
for joint in get_joints(body, client_id=client_id):
if is_movable(body, joint, client_id=client_id):
return False
return True
def is_fixed_base(body):
return get_mass(body) == STATIC_MASS
def dump_body(body):
print('Body id: {} | Name: {} | Rigid: {} | Fixed: {}'.format(
body, get_body_name(body), is_rigid_body(body), is_fixed_base(body)))
for joint in get_joints(body):
print('Joint id: {} | Name: {} | Type: {} | Circular: {} | Limits: {}'.format(
joint, get_joint_name(body, joint), JOINT_TYPES[get_joint_type(body, joint)],
is_circular(body, joint), get_joint_limits(body, joint)))
print('Link id: {} | Name: {} | Mass: {}'.format(-1, get_base_name(body), get_mass(body)))
for link in get_links(body):
print('Link id: {} | Name: {} | Parent: {} | Mass: {}'.format(
link, get_link_name(body, link), get_link_name(body, get_link_parent(body, link)),
get_mass(body, link)))
# print(get_joint_parent_frame(body, link))
# print(map(get_data_geometry, get_visual_data(body, link)))
# print(map(get_data_geometry, get_collision_data(body, link)))
def dump_world():
for body in get_bodies():
dump_body(body)
print()
def remove_all_bodies():
for i in get_body_ids():
p.removeBody(i)
def get_body_infos():
""" Return all body info in a list """
return [get_body_info(i) for i in get_body_ids()]
def get_body_names():
""" Return all body names in a list """
return [bi.body_name for bi in get_body_infos()]
def get_body_id(name):
return get_body_names().index(name)
def get_body_ids():
return sorted([p.getBodyUniqueId(i) for i in range(p.getNumBodies())])
def get_body_pose(body, client_id=0):
raw = p.getBasePositionAndOrientation(body, physicsClientId=client_id)
position = list(raw[0])
orn = list(raw[1])
return [position, orn]
def get_body_mesh_num(body, client_id=0):
link_num = get_num_links(body, client_id=client_id) # add baselink
num_mesh_parts = sum([len(get_link_collision_shape(body, link_index, client_id=client_id)) for link_index in range(-1, link_num-1)])
return num_mesh_parts
# Control
def control_joint(body, joint, value, client_id=0):
return p.setJointMotorControl2(bodyUniqueId=body,
jointIndex=joint,
controlMode=p.POSITION_CONTROL,
targetPosition=value,
targetVelocity=0,
maxVelocity=get_max_velocity(body, joint),
force=get_max_force(body, joint),
physicsClientId=client_id)
def control_joints(body, joints, positions, control_type='hard', client_id=0):
forces = [get_max_force(body, joint) for joint in joints] if control_type == 'limited' else [100000] * len(joints)
return p.setJointMotorControlArray(bodyUniqueId=body,
jointIndices=joints,
controlMode=p.POSITION_CONTROL,
targetPositions=positions,
targetVelocities=[0.0] * len(joints),
forces=forces, physicsClientId=client_id)
def forward_kinematics(body, joints, positions, eef_link=None, client_id=0):
eef_link = get_num_joints(body, client_id=client_id) - 1 if eef_link is None else eef_link
old_positions = get_joint_positions(body, joints, client_id=client_id)
set_joint_positions(body, joints, positions, client_id=client_id)
eef_pose = get_link_pose(body, eef_link, client_id=client_id)
set_joint_positions(body, joints, old_positions)
return eef_pose
def inverse_kinematics(body, eef_link, position, orientation=None):
if orientation is None:
jv = p.calculateInverseKinematics(bodyUniqueId=body,
endEffectorLinkIndex=eef_link,
targetPosition=position,
residualThreshold=1e-3)
else:
jv = p.calculateInverseKinematics(bodyUniqueId=body,
endEffectorLinkIndex=eef_link,
targetPosition=position,
targetOrientation=orientation,
residualThreshold=1e-3)
return jv
# Links
BASE_LINK = -1
STATIC_MASS = 0
get_num_links = get_num_joints
get_links = get_joints
def get_link_name(body, link, client_id=0):
if link == BASE_LINK:
return get_base_name(body, client_id=client_id)
return get_joint_info(body, link, client_id=client_id).linkName.decode('UTF-8')
def get_link_parent(body, link, client_id=0):
if link == BASE_LINK:
return None
return get_joint_info(body, link, client_id=client_id).parentIndex
def link_from_name(body, name, client_id=0):
if name == get_base_name(body, client_id=client_id):
return BASE_LINK
for link in get_joints(body, client_id=client_id):
if get_link_name(body, link, client_id=client_id) == name:
return link
raise ValueError(body, name)
def has_link(body, name):
try:
link_from_name(body, name)
except ValueError:
return False
return True
LinkState = namedtuple('LinkState', ['linkWorldPosition', 'linkWorldOrientation',
'localInertialFramePosition', 'localInertialFrameOrientation',
'worldLinkFramePosition', 'worldLinkFrameOrientation'])
def get_link_state(body, link, client_id=0):
return LinkState(*p.getLinkState(body, link, physicsClientId=client_id))
def get_link_collision_shape(body, link=-1, client_id=0):
return p.getCollisionShapeData(body, link, physicsClientId=client_id)
def get_com_pose(body, link, client_id=0): # COM = center of mass
if link == BASE_LINK:
return get_body_pose(body, client_id=client_id)
link_state = get_link_state(body, link, client_id=client_id)
return list(link_state.linkWorldPosition), list(link_state.linkWorldOrientation)
def get_link_inertial_pose(body, link, client_id=0):
if link == BASE_LINK:
return get_body_pose(body, client_id=client_id)
link_state = get_link_state(body, link, client_id=client_id)
return link_state.localInertialFramePosition, link_state.localInertialFrameOrientation
def get_link_pose(body, link, client_id=0):
if link == BASE_LINK:
return get_body_pose(body, client_id=client_id)
# if set to 1 (or True), the Cartesian world position/orientation will be recomputed using forward kinematics.
link_state = get_link_state(body, link, client_id=client_id)
return [list(link_state.worldLinkFramePosition), list(link_state.worldLinkFrameOrientation)]
def get_all_link_parents(body, client_id=0):
return {link: get_link_parent(body, link, client_id=client_id) for link in get_links(body, client_id=client_id)}
def get_all_link_children(body, client_id=0):
children = {}
for child, parent in get_all_link_parents(body, client_id=client_id).items():
if parent not in children:
children[parent] = []
children[parent].append(child)
return children
def get_link_children(body, link, client_id=0):
children = get_all_link_children(body, client_id=client_id)
return children.get(link, [])
def get_link_ancestors(body, link, client_id=0):
parent = get_link_parent(body, link, client_id=client_id)
if parent is None:
return []
return get_link_ancestors(body, parent, client_id=client_id) + [parent]
def get_joint_ancestors(body, link, client_id=0):
return get_link_ancestors(body, link, client_id=client_id) + [link]
def get_movable_joint_ancestors(body, link):
return list(filter(lambda j: is_movable(body, j), get_joint_ancestors(body, link)))
def get_link_descendants(body, link, client_id=0):
descendants = []
for child in get_link_children(body, link, client_id=client_id):
descendants.append(child)
descendants += get_link_descendants(body, child, client_id=client_id)
return descendants
def are_links_adjacent(body, link1, link2, client_id=0):
return (get_link_parent(body, link1, client_id=client_id) == link2) or \
(get_link_parent(body, link2, client_id=client_id) == link1)
def get_adjacent_links(body):
adjacent = set()
for link in get_links(body):
parent = get_link_parent(body, link)
adjacent.add((link, parent))
# adjacent.add((parent, link))
return adjacent
def get_adjacent_fixed_links(body):
return list(filter(lambda item: not is_movable(body, item[0]),
get_adjacent_links(body)))
def get_fixed_links(body):
edges = defaultdict(list)
for link, parent in get_adjacent_fixed_links(body):
edges[link].append(parent)
edges[parent].append(link)
visited = set()
fixed = set()
for initial_link in get_links(body):
if initial_link in visited:
continue
cluster = [initial_link]
queue = deque([initial_link])
visited.add(initial_link)
while queue:
for next_link in edges[queue.popleft()]:
if next_link not in visited:
cluster.append(next_link)
queue.append(next_link)
visited.add(next_link)
fixed.update(product(cluster, cluster))
return fixed
DynamicsInfo = namedtuple('DynamicsInfo', ['mass', 'lateral_friction',
'local_inertia_diagonal', 'local_inertial_pos', 'local_inertial_orn',
'restitution', 'rolling_friction', 'spinning_friction',
'contact_damping', 'contact_stiffness', 'body_type', 'collision_margin'])
def get_dynamics_info(body, link=BASE_LINK, client_id=0):
return DynamicsInfo(*p.getDynamicsInfo(body, link, physicsClientId=client_id))
def get_mass(body, link=BASE_LINK, client_id=0):
return get_dynamics_info(body, link, client_id=client_id).mass
def set_mass(body, mass, link=BASE_LINK, client_id=0):
p.changeDynamics(body, link, mass=mass, physicsClientId=client_id)
def fix_base(body, client_id=0):
set_mass(body, STATIC_MASS, BASE_LINK, client_id=client_id)
def get_joint_inertial_pose(body, joint):
dynamics_info = get_dynamics_info(body, joint)
return dynamics_info.local_inertial_pos, dynamics_info.local_inertial_orn
# Camera
CameraInfo = namedtuple('CameraInfo', ['width', 'height',
'viewMatrix', 'projectionMatrix', 'cameraUp',
'cameraForward', 'horizontal', 'vertical',
'yaw', 'pitch', 'dist', 'target'])
def reset_camera(yaw=50.0, pitch=-35.0, dist=5.0, target=(0.0, 0.0, 0.0), client_id=0):
p.resetDebugVisualizerCamera(cameraDistance=dist, cameraYaw=yaw, cameraPitch=pitch, cameraTargetPosition=target, physicsClientId=client_id)
def get_camera():
return CameraInfo(*p.getDebugVisualizerCamera())
# Visualization
def create_frame_marker(pose=((0, 0, 0), (0, 0, 0, 1)),
x_color=np.array([1, 0, 0]),
y_color=np.array([0, 1, 0]),
z_color=np.array([0, 0, 1]),
line_length=0.1,
line_width=2,
life_time=0,
replace_frame_id=None,
client_id=0):
"""
Create a pose marker that identifies a position and orientation in space with 3 colored lines.
"""
position = np.array(pose[0])
orientation = np.array(pose[1])
pts = np.array([[0, 0, 0], [line_length, 0, 0], [0, line_length, 0], [0, 0, line_length]])
rotIdentity = np.array([0, 0, 0, 1])
po, _ = p.multiplyTransforms(position, orientation, pts[0, :], rotIdentity)
px, _ = p.multiplyTransforms(position, orientation, pts[1, :], rotIdentity)
py, _ = p.multiplyTransforms(position, orientation, pts[2, :], rotIdentity)
pz, _ = p.multiplyTransforms(position, orientation, pts[3, :], rotIdentity)
if replace_frame_id is not None:
x_id = p.addUserDebugLine(po, px, x_color, line_width, life_time, replaceItemUniqueId=replace_frame_id[0], physicsClientId=client_id)
y_id = p.addUserDebugLine(po, py, y_color, line_width, life_time, replaceItemUniqueId=replace_frame_id[1], physicsClientId=client_id)
z_id = p.addUserDebugLine(po, pz, z_color, line_width, life_time, replaceItemUniqueId=replace_frame_id[2], physicsClientId=client_id)
else:
x_id = p.addUserDebugLine(po, px, x_color, line_width, life_time, physicsClientId=client_id)
y_id = p.addUserDebugLine(po, py, y_color, line_width, life_time, physicsClientId=client_id)
z_id = p.addUserDebugLine(po, pz, z_color, line_width, life_time, physicsClientId=client_id)
frame_id = (x_id, y_id, z_id)
return frame_id
def create_arrow_marker(pose=((0, 0, 0), (0, 0, 0, 1)),
line_length=0.1,
line_width=2,
life_time=0,
color_index=0,
raw_color=None,
replace_frame_id=None,
client_id=0):
"""
Create an arrow marker that identifies the z-axis of the end effector frame. Add a dot towards the positive direction.
"""
color = raw_color if raw_color is not None else rgb_colors_1[color_index % len(rgb_colors_1)]
po, _ = p.multiplyTransforms(pose[0], pose[1], [0, 0, 0], [0, 0, 0, 1])
pz, _ = p.multiplyTransforms(pose[0], pose[1], [0, 0, line_length], [0, 0, 0, 1])
pz_extend1, _ = p.multiplyTransforms(pz, pose[1], [0, line_length*0.2, -line_length*0.2], [0, 0, 0, 1])
pz_extend2, _ = p.multiplyTransforms(pz, pose[1], [0, -line_length*0.2, -line_length*0.2], [0, 0, 0, 1])
if replace_frame_id is not None:
z_id = p.addUserDebugLine(po, pz, color, line_width, life_time,
replaceItemUniqueId=replace_frame_id[0], physicsClientId=client_id)
z_extend_id1 = p.addUserDebugLine(pz, pz_extend1, color, line_width, life_time,
replaceItemUniqueId=replace_frame_id[1], physicsClientId=client_id)
z_extend_id2 = p.addUserDebugLine(pz, pz_extend2, color, line_width, life_time,
replaceItemUniqueId=replace_frame_id[2], physicsClientId=client_id)
else:
z_id = p.addUserDebugLine(po, pz, color, line_width, life_time, physicsClientId=client_id)
z_extend_id1 = p.addUserDebugLine(pz, pz_extend1, color, line_width, life_time, physicsClientId=client_id)
z_extend_id2 = p.addUserDebugLine(pz, pz_extend2, color, line_width, life_time, physicsClientId=client_id)
frame_id = (z_id, z_extend_id1, z_extend_id2)
return frame_id
def create_arrow_marker_points(pose=((0, 0, 0), (0, 0, 0, 1)),
line_length=0.1,
life_time=0,
color_index=0,
raw_color=None,
replace_markers_id=None,
client_id=0):
"""
Create an arrow marker that identifies the z-axis of the end effector frame. Add a dot towards the positive direction.
"""
if replace_markers_id: remove_path(replace_markers_id)
color = raw_color if raw_color is not None else rgb_colors_1[color_index % len(rgb_colors_1)]
color = color.tolist() + [1] # transfer to rgba list
po, _ = p.multiplyTransforms(pose[0], pose[1], [0, 0, 0], [0, 0, 0, 1])
pz, _ = p.multiplyTransforms(pose[0], pose[1], [0, 0, line_length], [0, 0, 0, 1])
pz_extend1, _ = p.multiplyTransforms(pz, pose[1], [0, line_length*0.2, -line_length*0.2], [0, 0, 0, 1])
pz_extend2, _ = p.multiplyTransforms(pz, pose[1], [0, -line_length*0.2, -line_length*0.2], [0, 0, 0, 1])
num_points = 20
line1 = np.linspace(po, pz, num_points).tolist()
line2 = np.linspace(pz, pz_extend1, num_points).tolist()
line3 = np.linspace(pz, pz_extend2, num_points).tolist()
all_box = line1 + line2 + line3
markers_id = []
for pos in all_box:
markers_id.append(draw_box_body(pos, rgba_color=color, client_id=client_id))
return markers_id
def change_obj_color(obj_id, linklist=None, rgba_color=[0, 0, 0, 1], client_id=0):
num_links = get_num_links(obj_id, client_id=client_id)
linklist = list(range(num_links)) + [-1] if linklist is None else linklist
for link in linklist:
if link > num_links: continue
p.changeVisualShape(obj_id, link, rgbaColor=rgba_color, physicsClientId=client_id)
class MplColorHelper:
def __init__(self, cmap_name, start_val, stop_val):
self.cmap_name = cmap_name
self.cmap = plt.get_cmap(cmap_name)
self.norm = mpl.colors.Normalize(vmin=start_val, vmax=stop_val)
def get_rgb(self, val):
return self.cmap(self.norm(val))[:3]
def rgb(value, minimum=-1, maximum=1):
""" for the color map https://stackoverflow.com/questions/20792445/calculate-rgb-value-for-a-range-of-values-to-create-heat-map """
assert minimum <= value <= maximum
minimum, maximum = float(minimum), float(maximum)
ratio = 2 * (value - minimum) / (maximum - minimum)
b = int(max(0, 255 * (1 - ratio)))
r = int(max(0, 255 * (ratio - 1)))
g = 255 - b - r
return r / 255., g / 255., b / 255.
def plot_heatmap_bar(cmap_name, vmin=-1, vmax=-1):
plt.figure(num=-1, figsize=(10, 2))
cmap = plt.get_cmap(cmap_name)
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
cb = mpl.colorbar.ColorbarBase(plt.gca(), cmap=cmap, norm=norm, orientation='horizontal')
cb.set_label('Heatmap bar')
plt.pause(0.001)
# https://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/
rgb_colors_255 = [(230, 25, 75), # red
(60, 180, 75), # green
(255, 225, 25), # yello
(0, 130, 200), # blue
(245, 130, 48), # orange
(145, 30, 180), # purple
(70, 240, 240), # cyan
(240, 50, 230), # magenta
(210, 245, 60), # lime
(250, 190, 190), # pink
(0, 128, 128), # teal
(230, 190, 255), # lavender
(170, 110, 40), # brown
(255, 250, 200), # beige
(128, 0, 0), # maroon
(170, 255, 195), # lavender
(128, 128, 0), # olive
(255, 215, 180), # apricot
(0, 0, 128), # navy
(128, 128, 128), # grey
(0, 0, 0), # white
(255, 255, 255)] # black
rgb_colors_1 = np.array(rgb_colors_255) / 255.
def draw_line(start_pos, end_pos, rgb_color=(1, 0, 0), width=15, lifetime=0, client_id=0):
lid = p.addUserDebugLine(lineFromXYZ=start_pos,
lineToXYZ=end_pos,
lineColorRGB=rgb_color,
lineWidth=width,
lifeTime=lifetime,
physicsClientId=client_id)
return lid
def draw_circle_around_z_axis(centre, radius, rgb_color=(1, 0, 0), width=3, lifetime=0, num_divs=100, client_id=0):
points = np.array(centre) + radius * np.array(
[(np.cos(ang), np.sin(ang), 0) for ang in np.linspace(0, 2 * np.pi, num_divs)])
lids = []
for i in range(len(points) - 1):
start_pos = points[i]
end_pos = points[i + 1]
lid = p.addUserDebugLine(lineFromXYZ=start_pos,
lineToXYZ=end_pos,
lineColorRGB=rgb_color,
lineWidth=width,
lifeTime=lifetime,
physicsClientId=client_id)
lids.append(lid)
return lids
def draw_sphere_body(position, radius=0.01, rgba_color=[0.5,0.5,1,0.8], client_id=0):
vs_id = p.createVisualShape(p.GEOM_SPHERE, radius=radius, rgbaColor=rgba_color, physicsClientId=client_id)
body_id = p.createMultiBody(basePosition=position, baseCollisionShapeIndex=-1, baseVisualShapeIndex=vs_id, physicsClientId=client_id)
return body_id
def draw_box_body(position, orientation=[0, 0, 0, 1], halfExtents=[0.003, 0.003, 0.003], rgba_color=[1, 0, 0, 1], client_id=0):
vs_id = p.createVisualShape(p.GEOM_BOX, halfExtents=halfExtents, rgbaColor=rgba_color, physicsClientId=client_id)
body_id = p.createMultiBody(basePosition=position, baseOrientation=orientation,
baseCollisionShapeIndex=-1, baseVisualShapeIndex=vs_id, physicsClientId=client_id)
return body_id
def create_box_body(position, orientation=[0, 0, 0, 1], halfExtents=[0.003, 0.003, 0.003], rgba_color=[1, 0, 0, 1], mass=0., client_id=0):
vs_id = p.createVisualShape(p.GEOM_BOX, halfExtents=halfExtents, rgbaColor=rgba_color, physicsClientId=client_id)
cs_id = p.createCollisionShape(p.GEOM_BOX, halfExtents=halfExtents, physicsClientId=client_id)
box_id = p.createMultiBody(baseMass=mass, basePosition=position, baseOrientation=orientation,
baseCollisionShapeIndex=cs_id, baseVisualShapeIndex=vs_id,
physicsClientId=client_id)
return box_id
def draw_path(eef_poses, client_id=0):
markers_id = []
markers_id.append(draw_sphere_body(eef_poses[0], radius=0.03, rgba_color=[1, 0, 0, 0.8], client_id=client_id)) # draw start point by red
for i in range(1, len(eef_poses)-1):
markers_id.append(draw_sphere_body(eef_poses[i], client_id=client_id))
markers_id.append(draw_sphere_body(eef_poses[-1], radius=0.03, rgba_color=[0, 1, 0, 0.8], client_id=client_id)) # draw end point by green
return markers_id
def draw_conveyor_path(discretized_trajectory, num_plot_points=None,
reachability_value=None, sphere_path=False, client_id=0):
num_plot_points = num_plot_points if num_plot_points else len(discretized_trajectory)
idx = np.linspace(0, len(discretized_trajectory) - 1, num_plot_points).astype(int)
for i in range(len(idx) - 1):
pos1 = discretized_trajectory[idx[i]][0]
pos2 = discretized_trajectory[idx[i + 1]][0]
if reachability_value is not None and reachability_value[idx[i]] and reachability_value[idx[i+1]]: piece_len_color = (reachability_value[idx[i]], 0, 0)
else: piece_len_color = (0, 0, 0)
draw_line(pos1, pos2, rgb_color=piece_len_color, client_id=client_id)
if sphere_path:
draw_sphere_body(pos1, radius=0.008, rgba_color=list(piece_len_color)+[0.8], client_id=client_id) # to record images
def get_pose_from_view_matrix(view_matrix):
view_matrix = np.array(view_matrix).reshape(4, 4).T
# Invert the view matrix to get the world transformation matrix
world_matrix = np.linalg.inv(view_matrix)
# Extract the camera position (last column of the world matrix)
position = world_matrix[:3, 3]
# Extract the rotation matrix (top-left 3x3 of the world matrix)
rotation_matrix = world_matrix[:3, :3]
return position, rotation_matrix
def draw_camera_axis(camera_pose, axis_length=0.1, old_axis_ids=None, client_id=0):
# Remove the old axes
if old_axis_ids is not None:
remove_markers(old_axis_ids, client_id=client_id)
# Compute the end points of the axes
# We manually change the sign of the Z-axis to align with PyBullet's camera orientation, which is not real orientation
origin, camera_orientation = camera_pose
origin = np.array(origin) # Make sure origin is numpy so that x, y, z are all numpy arrays
x_axis = origin + multiply_multi_transforms([[0, 0, 0], camera_orientation], [[axis_length, 0, 0], [0, 0, 0, 1.]])[0]
y_axis = origin + multiply_multi_transforms([[0, 0, 0], camera_orientation], [[0, axis_length, 0], [0, 0, 0, 1.]])[0]
z_axis = origin + multiply_multi_transforms([[0, 0, 0], camera_orientation], [[0, 0, axis_length], [0, 0, 0, 1.]])[0]
# Draw the axes using PyBullet's debug lines
xline_id = p.addUserDebugLine(origin, x_axis, [1, 0, 0], lineWidth=2, physicsClientId=client_id) # Red for the X-axis
yline_id = p.addUserDebugLine(origin, y_axis, [0, 1, 0], lineWidth=2, physicsClientId=client_id) # Green for the Y-axis
zline_id = p.addUserDebugLine(origin, z_axis, [0, 0, 1], lineWidth=2, physicsClientId=client_id) # Blue for the Z-axis
return xline_id, yline_id, zline_id
def remove_path(marker_ids, client_id=0):
for id in marker_ids:
p.removeBody(id, physicsClientId=client_id)
def remove_marker(marker_id, client_id=0):
p.removeUserDebugItem(marker_id, physicsClientId=client_id)
def remove_markers(marker_ids, client_id=0):
for i in marker_ids:
p.removeUserDebugItem(i, physicsClientId=client_id)