-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathtest_rigid_physics.py
More file actions
5931 lines (5185 loc) · 232 KB
/
Copy pathtest_rigid_physics.py
File metadata and controls
5931 lines (5185 loc) · 232 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 math
import os
import sys
import xml.etree.ElementTree as ET
from contextlib import nullcontext
from copy import deepcopy
from typing import TYPE_CHECKING
import igl
import mujoco
import numpy as np
import pytest
import torch
import trimesh
import genesis as gs
import genesis.utils.geom as gu
import genesis.utils.terrain as tu
from genesis.ext import urdfpy
from genesis.utils import urdf as uu
from genesis.engine.states.solvers import RigidSolverState
from genesis.utils.misc import get_assets_dir, qd_to_numpy, qd_to_torch, tensor_to_array
from .utils import (
assert_allclose,
assert_equal,
check_mujoco_data_consistency,
check_mujoco_model_consistency,
get_hf_dataset,
init_simulators,
simulate_and_check_mujoco_consistency,
)
if TYPE_CHECKING:
from genesis.engine.entities.rigid_entity.rigid_entity import RigidEntity
@pytest.fixture
def xml_path(request, tmp_path, model_name):
mjcf = request.getfixturevalue(model_name)
xml_tree = ET.ElementTree(mjcf)
file_name = f"{model_name}.urdf" if mjcf.tag == "robot" else f"{model_name}.xml"
file_path = str(tmp_path / file_name)
xml_tree.write(file_path, encoding="utf-8", xml_declaration=True)
return file_path
@pytest.fixture(scope="session")
def box_plan():
"""Generate an MJCF model for a box on a plane."""
mjcf = ET.Element("mujoco", model="one_box")
ET.SubElement(mjcf, "option", timestep="0.01")
default = ET.SubElement(mjcf, "default")
ET.SubElement(default, "geom", contype="1", conaffinity="1", condim="3", friction="1. 0.5 0.5")
worldbody = ET.SubElement(mjcf, "worldbody")
ET.SubElement(worldbody, "geom", type="plane", name="floor", pos="0. 0. 0.", size="40. 40. 40.")
box_body = ET.SubElement(worldbody, "body", name="box", pos="0. 0. 0.3")
ET.SubElement(box_body, "geom", type="box", size="0.2 0.2 0.2", pos="0. 0. 0.")
ET.SubElement(box_body, "joint", name="root", type="free")
return mjcf
@pytest.fixture(scope="session")
def mimic_hinges():
mjcf = ET.Element("mujoco", model="mimic_hinges")
ET.SubElement(mjcf, "compiler", angle="degree")
ET.SubElement(mjcf, "option", timestep="0.01")
worldbody = ET.SubElement(mjcf, "worldbody")
parent = ET.SubElement(worldbody, "body", name="parent", pos="0 0 1.0")
child1 = ET.SubElement(parent, "body", name="child1", pos="0.5 0 0")
ET.SubElement(child1, "geom", type="capsule", size="0.05 0.2", rgba="0.9 0.1 0.1 1")
ET.SubElement(child1, "joint", type="hinge", name="joint1", axis="0 1 0", range="-45 45")
child2 = ET.SubElement(parent, "body", name="child2", pos="0 0.5 0")
ET.SubElement(child2, "geom", type="capsule", size="0.05 0.2", rgba="0.1 0.1 0.9 1")
ET.SubElement(child2, "joint", type="hinge", name="joint2", axis="0 1 0", range="-45 45")
equality = ET.SubElement(mjcf, "equality")
ET.SubElement(equality, "joint", name="joint_equality", joint1="joint1", joint2="joint2")
return mjcf
@pytest.fixture(scope="session")
def box_box():
"""Generate an MJCF model for two boxes."""
mjcf = ET.Element("mujoco", model="one_box")
ET.SubElement(mjcf, "option", timestep="0.01")
default = ET.SubElement(mjcf, "default")
ET.SubElement(default, "geom", contype="1", conaffinity="1", condim="3", friction="1. 0.5 0.5")
worldbody = ET.SubElement(mjcf, "worldbody")
ET.SubElement(worldbody, "geom", type="plane", name="floor", pos="0. 0. 0.", size="40. 40. 40.")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="0. 0. 0.2")
ET.SubElement(box1_body, "geom", type="box", size="0.2 0.2 0.2", pos="0. 0. 0.", rgba="0 1 0 0.4")
ET.SubElement(box1_body, "joint", name="root1", type="free")
box2_body = ET.SubElement(worldbody, "body", name="box2", pos="0. 0. 0.8")
ET.SubElement(box2_body, "geom", type="box", size="0.2 0.2 0.2", pos="0. 0. 0.", rgba="0 0 1 0.4")
ET.SubElement(box2_body, "joint", name="root2", type="free")
return mjcf
@pytest.fixture
def collision_edge_cases(asset_tmp_path, mode):
assets = {}
for i, box_size in enumerate(((0.8, 0.8, 0.04), (0.04, 0.04, 0.005))):
tmesh = trimesh.creation.box(extents=np.array(box_size) * 2)
mesh_path = str(asset_tmp_path / f"box{i}.obj")
tmesh.export(mesh_path, file_type="obj")
assets[f"box{i}"] = mesh_path
mjcf = ET.Element("mujoco", model="one_box")
ET.SubElement(mjcf, "option", timestep="0.005")
default = ET.SubElement(mjcf, "default")
ET.SubElement(default, "geom", contype="1", conaffinity="1", condim="3", friction="1. 0.5 0.5")
asset = ET.SubElement(mjcf, "asset")
for name, mesh_path in assets.items():
ET.SubElement(asset, "mesh", name=name, refpos="0 0 0", refquat="1 0 0 0", file=mesh_path)
worldbody = ET.SubElement(mjcf, "worldbody")
if mode == 0:
ET.SubElement(worldbody, "geom", type="box", size="0.8 0.8 0.04", pos="0. 0. 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="0.0 0.0 0.7")
ET.SubElement(box1_body, "geom", type="box", size="0.04 0.04 0.005", pos="-0.758 -0.758 0.", rgba="0 0 1 0.4")
elif mode == 1:
ET.SubElement(worldbody, "geom", type="box", size="0.8 0.8 0.04", pos="0. 0. 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="-0.758 -0.758 0.7")
ET.SubElement(box1_body, "geom", type="box", size="0.04 0.04 0.005", pos="0. 0. 0.", rgba="0 0 1 0.4")
elif mode == 2:
ET.SubElement(worldbody, "geom", type="box", size="0.8 0.8 0.04", pos="0. 0. 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="-0.758 -0.758 1.1")
ET.SubElement(box1_body, "geom", type="box", size="0.04 0.04 0.005", pos="0. 0. 0.", rgba="0 0 1 0.4")
elif mode == 3:
ET.SubElement(worldbody, "geom", type="box", size="0.8 0.8 0.04", pos="0. 0. 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="0.0 0.0 0.7")
ET.SubElement(box1_body, "geom", type="mesh", mesh="box1", pos="-0.758 -0.758 0.", rgba="0 0 1 0.4")
elif mode == 4:
ET.SubElement(worldbody, "geom", type="mesh", mesh="box0", pos="0. 0. 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="0.0 0.0 0.7")
ET.SubElement(box1_body, "geom", type="mesh", mesh="box1", pos="-0.758 -0.758 0.", rgba="0 0 1 0.4")
elif mode == 5:
ET.SubElement(worldbody, "geom", type="mesh", mesh="box0", pos="0. 0. 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="-0.758 -0.758 0.7")
ET.SubElement(box1_body, "geom", type="mesh", mesh="box1", pos="0. 0. 0.", rgba="0 0 1 0.4")
elif mode == 6:
ET.SubElement(worldbody, "geom", type="mesh", mesh="box0", pos="0. 0. 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="-0.758 -0.758 1.1")
ET.SubElement(box1_body, "geom", type="mesh", mesh="box1", pos="0. 0. 0.", rgba="0 0 1 0.4")
elif mode == 7:
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos=" 0.758 0.758 0.", rgba="0 1 0 0.4")
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos="-0.758 -0.758 0.", rgba="0 1 0 0.4")
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos=" 0.758 -0.758 0.", rgba="0 1 0 0.4")
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos="-0.758 0.758 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="0. 0. 0.7")
ET.SubElement(box1_body, "geom", type="mesh", mesh="box0", pos="0. 0. 0.", rgba="0 0 1 0.4")
elif mode == 8:
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos=" 0.762 0.762 0.", rgba="0 1 0 0.4")
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos="-0.762 -0.762 0.", rgba="0 1 0 0.4")
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos=" 0.762 -0.762 0.", rgba="0 1 0 0.4")
ET.SubElement(worldbody, "geom", type="mesh", mesh="box1", pos="-0.762 0.762 0.", rgba="0 1 0 0.4")
box1_body = ET.SubElement(worldbody, "body", name="box1", pos="0. 0. 0.7")
ET.SubElement(box1_body, "geom", type="mesh", mesh="box0", pos="0. 0. 0.", rgba="0 0 1 0.4")
else:
raise ValueError("Invalid mode")
ET.SubElement(box1_body, "joint", name="root", type="free")
return mjcf
@pytest.fixture(scope="session")
def two_aligned_hinges():
mjcf = ET.Element("mujoco", model="two_aligned_hinges")
ET.SubElement(mjcf, "option", timestep="0.05")
default = ET.SubElement(mjcf, "default")
ET.SubElement(default, "geom", contype="1", conaffinity="1", condim="3")
worldbody = ET.SubElement(mjcf, "worldbody")
link0 = ET.SubElement(worldbody, "body", name="body0")
ET.SubElement(link0, "geom", type="capsule", fromto="0 0 0 0.5 0 0", size="0.05")
ET.SubElement(link0, "joint", type="hinge", name="joint0", axis="0 0 1")
link1 = ET.SubElement(link0, "body", name="body1", pos="0.5 0 0")
ET.SubElement(link1, "geom", type="capsule", fromto="0 0 0 0.5 0 0", size="0.05")
ET.SubElement(link1, "joint", type="hinge", name="joint1", axis="0 0 1")
return mjcf
def _build_chain_capsule_hinge(asset_tmp_path, enable_mesh):
if enable_mesh:
mesh_path = str(asset_tmp_path / "capsule.obj")
tmesh = trimesh.creation.icosphere(radius=1.0, subdivisions=1)
tmesh.apply_transform(np.diag([0.05, 0.05, 0.25, 1]))
tmesh.export(mesh_path, file_type="obj")
mjcf = ET.Element("mujoco", model="two_stick_robot")
ET.SubElement(mjcf, "option", timestep="0.05")
default = ET.SubElement(mjcf, "default")
ET.SubElement(default, "geom", contype="1", conaffinity="1", condim="3")
if enable_mesh:
asset = ET.SubElement(mjcf, "asset")
ET.SubElement(asset, "mesh", name="capsule", refpos="0 0 -0.25", refquat="0.707 0 -0.707 0", file=mesh_path)
worldbody = ET.SubElement(mjcf, "worldbody")
link0 = ET.SubElement(worldbody, "body", name="body1", pos="0.1 0.2 0.0", quat="0.707 0 0.707 0")
if enable_mesh:
ET.SubElement(link0, "geom", type="mesh", mesh="capsule", rgba="0 0 1 0.3")
else:
ET.SubElement(link0, "geom", type="capsule", fromto="0 0 0 0.5 0 0", size="0.05", rgba="0 0 1 0.3")
link1 = ET.SubElement(link0, "body", name="body2", pos="0.5 0.2 0.0", quat="0.92388 0 0 0.38268")
if enable_mesh:
ET.SubElement(link1, "geom", type="mesh", mesh="capsule")
else:
ET.SubElement(link1, "geom", type="capsule", fromto="0 0 0 0.5 0 0", size="0.05")
ET.SubElement(link1, "joint", type="hinge", name="joint1", axis="0 0 1", pos="0.0 0.0 0.0")
link2 = ET.SubElement(link1, "body", name="body3", pos="0.5 0.2 0.0", quat="0.92388 0 0.38268 0.0")
if enable_mesh:
ET.SubElement(link2, "geom", type="mesh", mesh="capsule")
else:
ET.SubElement(link2, "geom", type="capsule", fromto="0 0 0 0.5 0 0", size="0.05")
ET.SubElement(link2, "joint", type="hinge", name="joint2", axis="0 1 0")
return mjcf
@pytest.fixture(scope="session")
def chain_capsule_hinge_mesh(asset_tmp_path):
return _build_chain_capsule_hinge(asset_tmp_path, enable_mesh=True)
@pytest.fixture(scope="session")
def chain_capsule_hinge_capsule(asset_tmp_path):
return _build_chain_capsule_hinge(asset_tmp_path, enable_mesh=False)
def _build_multi_pendulum(n, joint_damping, joint_friction):
"""Generate an URDF model of a multi-link pendulum with n segments."""
urdf = ET.Element("robot", name="multi_pendulum")
# Base link
ET.SubElement(urdf, "link", name="base")
parent_link = "base"
for i in range(n):
# Continuous joint between parent and this arm
joint = ET.SubElement(urdf, "joint", name=f"PendulumJoint_{i}", type="continuous")
ET.SubElement(joint, "origin", xyz="0.0 0.0 0.0", rpy="0.0 0.0 0.0")
ET.SubElement(joint, "axis", xyz="1 0 0")
ET.SubElement(joint, "parent", link=parent_link)
ET.SubElement(joint, "child", link=f"PendulumArm_{i}")
ET.SubElement(joint, "limit", effort=str(100.0 * (n - i)), velocity="30.0")
ET.SubElement(joint, "dynamics", damping=str(joint_damping), friction=str(joint_friction))
# Arm link
arm = ET.SubElement(urdf, "link", name=f"PendulumArm_{i}")
visual = ET.SubElement(arm, "visual")
ET.SubElement(visual, "origin", xyz="0.0 0.0 0.5", rpy="0.0 0.0 0.0")
geometry = ET.SubElement(visual, "geometry")
ET.SubElement(geometry, "box", size="0.01 0.01 1.0")
material = ET.SubElement(visual, "material", name="")
ET.SubElement(material, "color", rgba="0.0 0.0 1.0 1.0")
inertial = ET.SubElement(arm, "inertial")
ET.SubElement(inertial, "origin", xyz="0.0 0.0 0.0", rpy="0.0 0.0 0.0")
ET.SubElement(inertial, "mass", value="0.0")
ET.SubElement(inertial, "inertia", ixx="0.0", ixy="0.0", ixz="0.0", iyy="0.0", iyz="0.0", izz="0.0")
# Fixed joint to the mass
joint2 = ET.SubElement(urdf, "joint", name=f"PendulumMassJoint_{i}", type="fixed")
ET.SubElement(joint2, "origin", xyz="0.0 0.0 1.0", rpy="0.0 0.0 0.0")
ET.SubElement(joint2, "parent", link=f"PendulumArm_{i}")
ET.SubElement(joint2, "child", link=f"PendulumMass_{i}")
# Mass link
mass = ET.SubElement(urdf, "link", name=f"PendulumMass_{i}")
visual = ET.SubElement(mass, "visual")
ET.SubElement(visual, "origin", xyz="0.0 0.0 0.0", rpy="0.0 0.0 0.0")
geometry = ET.SubElement(visual, "geometry")
ET.SubElement(geometry, "sphere", radius="0.06")
material = ET.SubElement(visual, "material", name="")
ET.SubElement(material, "color", rgba="0.0 0.0 1.0 1.0")
inertial = ET.SubElement(mass, "inertial")
ET.SubElement(inertial, "origin", xyz="0.0 0.0 0.0", rpy="0.0 0.0 0.0")
ET.SubElement(inertial, "mass", value="1.0")
ET.SubElement(inertial, "inertia", ixx="1e-12", ixy="0.0", ixz="0.0", iyy="1e-12", iyz="0.0", izz="1e-12")
parent_link = f"PendulumMass_{i}"
return urdf
@pytest.fixture
def pendulum_with_joint_dynamics(joint_damping, joint_friction):
return _build_multi_pendulum(n=1, joint_damping=joint_damping, joint_friction=joint_friction)
@pytest.fixture(scope="session")
def pendulum():
return _build_multi_pendulum(n=1, joint_damping=0.0, joint_friction=0.0)
@pytest.fixture(scope="session")
def double_pendulum():
return _build_multi_pendulum(n=2, joint_damping=0.0, joint_friction=0.0)
@pytest.fixture(scope="session")
def undefined_inertia():
"""Generate a URDF with a single link that has no inertial element."""
urdf = ET.Element("robot", name="undefined_inertia")
link = ET.SubElement(urdf, "link", name="base_link")
visual = ET.SubElement(link, "visual")
geometry = ET.SubElement(visual, "geometry")
ET.SubElement(geometry, "sphere", radius="0.03")
collision = ET.SubElement(link, "collision")
geometry = ET.SubElement(collision, "geometry")
ET.SubElement(geometry, "sphere", radius="0.03")
return urdf
@pytest.fixture(scope="session")
def double_ball_pendulum():
mjcf = ET.Element("mujoco", model="double_ball_pendulum")
default = ET.SubElement(mjcf, "default")
ET.SubElement(default, "joint", armature="0.1", damping="0.5")
worldbody = ET.SubElement(mjcf, "worldbody")
base = ET.SubElement(worldbody, "body", name="base", pos="-0.02 0.0 0.0")
ET.SubElement(base, "joint", name="joint1", type="ball")
ET.SubElement(
base, "geom", name="link1_geom", type="capsule", size="0.02", fromto="0 0 0 0 0 0.5", rgba="0.8 0.2 0.2 1.0"
)
link2 = ET.SubElement(base, "body", name="link2", pos="0 0 0.5")
ET.SubElement(link2, "joint", name="joint2", type="ball")
ET.SubElement(
link2, "geom", name="link2_geom", type="capsule", size="0.02", fromto="0 0 0 0 0 0.3", rgba="0.2 0.8 0.2 1.0"
)
ee = ET.SubElement(link2, "body", name="end_effector", pos="0 0 0.3")
ET.SubElement(ee, "geom", name="ee_geom", type="sphere", size="0.02", density="200", rgba="1.0 0.8 0.2 1.0")
ET.SubElement(
ee,
"geom",
name="marker",
type="sphere",
contype="0",
conaffinity="0",
size="0.01",
density="0",
pos="0 -0.02 0",
rgba="0.0 0.0 0.0 1.0",
)
return mjcf
@pytest.fixture(scope="session")
def hinge_slide():
mjcf = ET.Element("mujoco", model="hinge_slide")
default = ET.SubElement(mjcf, "default")
ET.SubElement(default, "joint", damping="0.01")
worldbody = ET.SubElement(mjcf, "worldbody")
base = ET.SubElement(worldbody, "body", name="pendulum", pos="0.15 0.0 0.0")
ET.SubElement(base, "joint", name="hinge", type="hinge", axis="0 1 0", frictionloss="0.08")
ET.SubElement(base, "geom", name="geom1", type="capsule", size="0.02", fromto="0.0 0.0 0.0 0.1 0.0 0.0")
link1 = ET.SubElement(base, "body", name="link1", pos="0.1 0.0 0.0")
ET.SubElement(link1, "joint", name="slide", type="slide", axis="1 0 0", frictionloss="0.3", stiffness="200.0")
ET.SubElement(link1, "geom", name="geom2", type="capsule", size="0.015", fromto="-0.1 0.0 0.0 0.1 0.0 0.0")
return mjcf
@pytest.fixture(scope="session")
def ellipsoid():
mjcf = ET.Element("mujoco", model="ellipsoid")
worldbody = ET.SubElement(mjcf, "worldbody")
body = ET.SubElement(worldbody, "body", name="obj", pos="0 0 0.0")
ET.SubElement(body, "joint", name="root", type="free")
ET.SubElement(body, "geom", type="ellipsoid", size="0.05 0.05 0.02")
return mjcf
@pytest.fixture(scope="session")
def general_actuator():
"""Generate an MJCF model with mixed actuator types: PD, general, and non-actuated."""
mjcf = ET.Element("mujoco", model="general_actuator")
ET.SubElement(mjcf, "option", timestep="0.01")
worldbody = ET.SubElement(mjcf, "worldbody")
body1 = ET.SubElement(worldbody, "body", name="link1", pos="0 0 1")
ET.SubElement(body1, "joint", name="hinge_pd", type="hinge", axis="0 1 0", damping="0.5")
ET.SubElement(body1, "geom", type="capsule", size="0.05 0.3", mass="1.0")
body2 = ET.SubElement(body1, "body", name="link2", pos="0 0 -0.6")
ET.SubElement(body2, "joint", name="hinge_general", type="hinge", axis="0 1 0", damping="0.3")
ET.SubElement(body2, "geom", type="capsule", size="0.04 0.2", mass="0.5")
body3 = ET.SubElement(body2, "body", name="link3", pos="0 0 -0.4")
ET.SubElement(body3, "joint", name="hinge_motor", type="hinge", axis="0 1 0", damping="0.2")
ET.SubElement(body3, "geom", type="capsule", size="0.03 0.15", mass="0.3")
actuator = ET.SubElement(mjcf, "actuator")
ET.SubElement(actuator, "position", name="act_pd", joint="hinge_pd", kp="100")
ET.SubElement(
actuator,
"general",
name="act_general",
joint="hinge_general",
gainprm="20 0 0",
biastype="affine",
biasprm="0.5 -10 -1",
)
ET.SubElement(actuator, "motor", name="act_motor", joint="hinge_motor", gear="5")
return mjcf
@pytest.mark.required
@pytest.mark.parametrize("model_name", ["box_plan"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG, gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_box_plane_dynamics(gs_sim, mj_sim, tol):
cube_pos = np.array([0.0, 0.0, 0.6])
cube_quat = np.random.rand(4)
cube_quat /= np.linalg.norm(cube_quat)
qpos = np.concatenate((cube_pos, cube_quat))
qvel = np.random.rand(6) * 0.2
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, qpos, qvel, num_steps=150, tol=tol)
@pytest.mark.required
@pytest.mark.parametrize("model_name", ["general_actuator"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.Euler])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_general_actuator(gs_sim, mj_sim, tol):
(entity,) = gs_sim.entities
# get_dofs_kp raises for all DOFs (joint 1 is non-PD-reducible from parser)
with pytest.raises(gs.GenesisException):
entity.get_dofs_kp()
# but succeeds for the PD joint (joint 0)
entity.get_dofs_kp(dofs_idx_local=[0])
# Set different control modes per DOF via public API
entity.control_dofs_force(0.0, dofs_idx_local=[0])
entity.control_dofs_velocity(0.0, dofs_idx_local=[1])
entity.control_dofs_position(0.0, dofs_idx_local=[2])
ctrl_mode = gs_sim.rigid_solver.dofs_state.ctrl_mode.to_numpy()[:, 0]
assert ctrl_mode[entity.dof_start + 0] == gs.CTRL_MODE.FORCE
assert ctrl_mode[entity.dof_start + 1] == gs.CTRL_MODE.VELOCITY
assert ctrl_mode[entity.dof_start + 2] == gs.CTRL_MODE.POSITION
# control_dofs_position overrides all to POSITION
entity.control_dofs_position([0.0, 0.0, 0.0])
ctrl_mode = gs_sim.rigid_solver.dofs_state.ctrl_mode.to_numpy()[:, 0]
assert (ctrl_mode[entity.dof_start : entity.dof_start + 3] == gs.CTRL_MODE.POSITION).all()
# Disable constraints, keep actuation enabled
mj_sim.model.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_CONSTRAINT
gs_sim.rigid_solver._enable_collision = False
gs_sim.rigid_solver._enable_joint_limit = False
gs_sim.rigid_solver._disable_constraint = True
gs_sim.rigid_solver.collider.clear()
gs_sim.rigid_solver.constraint_solver.clear()
# Compare all dynamic quantities against MuJoCo with both PD and general actuators active.
check_mujoco_model_consistency(gs_sim, mj_sim, tol=tol)
init_simulators(gs_sim, mj_sim, qpos=np.array([0.2, 0.1, 0.0]), qvel=np.array([0.1, -0.1, 0.0]))
mj_sim.data.ctrl[:] = [0.5, 0.3, 1.0]
entity.control_dofs_position([0.5, 0.3, 0.0])
entity.control_dofs_force(5.0, dofs_idx_local=[2]) # motor: gear(5) * gainprm(1) * ctrl(1) = 5
# Pre-step so that Genesis computes qf_applied (needed for data consistency checks)
mj_sim.data.qpos[:] = gs_sim.rigid_solver.qpos.to_numpy()[:, 0]
mj_sim.data.qvel[:] = gs_sim.rigid_solver.dofs_state.vel.to_numpy()[:, 0]
mujoco.mj_step(mj_sim.model, mj_sim.data)
gs_sim.scene.step()
for _ in range(99):
check_mujoco_data_consistency(gs_sim, mj_sim, tol=tol, ignore_constraints=True)
mj_sim.data.qpos[:] = gs_sim.rigid_solver.qpos.to_numpy()[:, 0]
mj_sim.data.qvel[:] = gs_sim.rigid_solver.dofs_state.vel.to_numpy()[:, 0]
mujoco.mj_step(mj_sim.model, mj_sim.data)
gs_sim.scene.step()
# Validate setter/getter round-trips for actuator parameters
entity.set_dofs_act_gain([200.0], dofs_idx_local=[1])
assert_allclose(entity.get_dofs_act_gain()[1], 200.0, tol=1e-6)
entity.set_dofs_act_bias([0.5], [-100.0], [-5.0], dofs_idx_local=[1])
b0, b1, b2 = entity.get_dofs_act_bias()
assert_allclose(b0[1], 0.5, tol=1e-6)
assert_allclose(b1[1], -100.0, tol=1e-6)
assert_allclose(b2[1], -5.0, tol=1e-6)
# set_dofs_kp restores PD on joint 1: act_gain=kp, act_bias[0]=0, act_bias[1]=-kp
entity.set_dofs_kp([50.0], dofs_idx_local=[1])
assert_allclose(entity.get_dofs_kp(dofs_idx_local=[0, 1]), [100.0, 50.0], tol=1e-6)
b0, b1, _ = entity.get_dofs_act_bias()
assert_allclose(b0[1], 0.0, tol=1e-6)
assert_allclose(b1[1], -50.0, tol=1e-6)
@pytest.mark.required
@pytest.mark.adjacent_collision(True)
@pytest.mark.parametrize("model_name", ["chain_capsule_hinge_mesh"]) # FIXME: , "chain_capsule_hinge_capsule"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG, gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("gjk_collision", [True, False])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_simple_kinematic_chain(gs_sim, mj_sim, tol):
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, num_steps=200, tol=tol)
@pytest.mark.required
@pytest.mark.parametrize("model_name", ["hinge_slide"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG, gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_frictionloss(gs_sim, mj_sim, tol):
qvel = np.array([0.7, -0.9])
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, qvel=qvel, num_steps=2000, tol=tol)
# Check that final velocity is almost zero
gs_qvel = gs_sim.rigid_solver.dofs_state.vel.to_numpy()
assert_allclose(gs_qvel, 0.0, tol=1e-2)
@pytest.mark.required
@pytest.mark.parametrize("xml_path", ["xml/walker.xml"])
@pytest.mark.parametrize(
"gs_solver",
[
gs.constraint_solver.CG,
# gs.constraint_solver.Newton, # FIXME: This test is not passing because collision detection is too sensitive
],
)
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("gjk_collision", [True, False])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_walker(gs_sim, mj_sim, gjk_collision, tol):
# Force numpy seed because this test is very sensitive to the initial condition
np.random.seed(0)
(gs_robot,) = gs_sim.entities
qpos = np.zeros((gs_robot.n_qs,))
qpos[2] += 0.5
qvel = np.random.rand(gs_robot.n_dofs) * 0.2
# Make sure it is possible to set the configuration vector without failure
qpos = gs_robot.get_dofs_position()
gs_robot.set_dofs_position(qpos)
assert_allclose(gs_robot.get_dofs_position(), qpos, tol=gs.EPS)
qpos = torch.rand(gs_robot.n_dofs).clip(*gs_robot.get_dofs_limit())
gs_robot.set_dofs_position(qpos)
assert_allclose(gs_robot.get_dofs_position(), qpos, tol=gs.EPS)
# Cannot simulate any longer because collision detection is very sensitive
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, qpos, qvel, num_steps=90, tol=tol)
@pytest.mark.parametrize("model_name", ["mimic_hinges"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG, gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_equality_joint(gs_sim, mj_sim, gs_solver, tol):
# there is an equality constraint
assert gs_sim.rigid_solver.n_equalities == 1
qpos = np.array((0.0, -1.0))
qvel = np.array((1.0, -0.3))
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, qpos, qvel, num_steps=300, tol=tol)
# check if the two joints are equal
gs_qpos = gs_sim.rigid_solver.qpos.to_numpy()[:, 0]
assert_allclose(gs_qpos[0], gs_qpos[1], tol=tol)
@pytest.mark.required
@pytest.mark.parametrize("xml_path", ["xml/four_bar_linkage_weld.xml", "weld.xml", "connect.xml"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.Euler])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_equality_link(gs_sim, mj_sim, gs_solver, xml_path):
# Must disable self-collision caused by closing the kinematic chain (adjacent link filtering is not enough)
gs_sim.rigid_solver._enable_collision = False
mj_sim.model.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_CONTACT
# Must the time constant of the constraints to improve numerical stability
TIME_CONSTANT = 0.02
for entity in gs_sim.entities:
for equality in entity.equalities:
equality.set_sol_params((TIME_CONSTANT, *tensor_to_array(equality.sol_params)[1:]))
mj_sim.model.eq_solref[:, 0] = TIME_CONSTANT
# Randomize the initial condition for force convergence of the constraints
np.random.seed(0)
qpos = np.random.rand(gs_sim.rigid_solver.n_qs) * 0.1
# Note that the world frame in which weld constraint is computed is different between Mujoco and Genesis for sites.
# Mujoco is using site 1, whereas Genesis is using parent link frame of site 1 since it has no notion of site.
ignore_constraints = np.any(
(mj_sim.model.eq_objtype == mujoco.mjtObj.mjOBJ_SITE) & (mj_sim.model.eq_type == mujoco.mjtEq.mjEQ_WELD)
)
simulate_and_check_mujoco_consistency(
gs_sim, mj_sim, qpos, num_steps=300, tol=1e-7, ignore_constraints=ignore_constraints
)
@pytest.mark.required
def test_dynamic_weld(show_viewer, tol):
scene = gs.Scene(
show_viewer=show_viewer,
show_FPS=False,
)
plane = scene.add_entity(
gs.morphs.Plane(),
)
cube = scene.add_entity(
gs.morphs.Box(
size=(0.04, 0.04, 0.04),
pos=(0.65, 0.0, 0.02),
),
surface=gs.surfaces.Default(
color=(1, 0, 0),
),
)
robot = scene.add_entity(
gs.morphs.MJCF(
file="xml/universal_robots_ur5e/ur5e.xml",
),
)
scene.build(n_envs=4, env_spacing=(3.0, 3.0))
end_effector = robot.get_link("ee_virtual_link")
# Compute up and down robot configurations
ee_pos_up = np.array((0.65, 0.0, 0.5), dtype=gs.np_float)
ee_pos_down = np.array((0.65, 0.0, 0.15), dtype=gs.np_float)
qpos_up = robot.inverse_kinematics(
link=end_effector,
pos=np.tile(ee_pos_up, (4, 1)),
quat=np.tile(np.array((0.0, 1.0, 0.0, 0.0), dtype=gs.np_float), (4, 1)),
)
qpos_down = robot.inverse_kinematics(
link=end_effector,
pos=np.tile(ee_pos_down, (4, 1)),
quat=np.tile(np.array((0.0, 1.0, 0.0, 0.0), dtype=gs.np_float), (4, 1)),
)
# move to pre-grasp pose
robot.control_dofs_position(qpos_up)
for i in range(120):
scene.step()
# reach
robot.control_dofs_position(qpos_down)
for i in range(70):
scene.step()
# add weld constraint and move back up
scene.sim.rigid_solver.add_weld_constraint(cube.base_link.idx, end_effector.idx, envs_idx=(0, 1, 2))
robot.control_dofs_position(qpos_up)
for i in range(60):
scene.step()
cubes_pos, cubes_quat = cube.get_pos(), cube.get_quat()
assert_allclose(torch.diff(cubes_quat, dim=0), 0.0, tol=1e-3)
assert_allclose(torch.diff(cubes_pos[[0, 1, 2]], dim=0), 0.0, tol=tol)
assert_allclose(cubes_pos[-1] - cubes_pos[0], ee_pos_down - ee_pos_up, tol=1e-2)
# drop
scene.sim.rigid_solver.delete_weld_constraint(cube.base_link.idx, end_effector.idx, envs_idx=(0, 1))
for i in range(110):
scene.step()
cubes_pos, cubes_quat = cube.get_pos(), cube.get_quat()
assert_allclose(torch.diff(cubes_quat, dim=0), 0.0, tol=1e-3)
assert_allclose(torch.diff(cubes_pos[[0, 1, 3]], dim=0), 0.0, tol=1e-2)
assert_allclose(cubes_pos[2] - cubes_pos[0], ee_pos_up - ee_pos_down, tol=1e-3)
@pytest.mark.required
def test_dynamic_weld_scene_reset():
scene = gs.Scene(
rigid_options=gs.options.RigidOptions(
max_dynamic_constraints=10,
),
show_viewer=False,
)
box1 = scene.add_entity(gs.morphs.Box(size=(0.1, 0.1, 0.1), pos=(0, 0, 0.5)))
box2 = scene.add_entity(gs.morphs.Box(size=(0.1, 0.1, 0.1), pos=(0.2, 0, 0.5)))
scene.build(n_envs=2)
solver = scene.rigid_solver
n_eq_base = solver._rigid_global_info.n_equalities[None]
solver.add_weld_constraint(box1.base_link_idx, box2.base_link_idx)
assert solver.constraint_solver.constraint_state.qd_n_equalities[0] == n_eq_base + 1
assert solver.constraint_solver.constraint_state.qd_n_equalities[1] == n_eq_base + 1
scene.reset(state=scene.get_state(), envs_idx=[0])
assert solver.constraint_solver.constraint_state.qd_n_equalities[0] == n_eq_base
assert solver.constraint_solver.constraint_state.qd_n_equalities[1] == n_eq_base + 1
@pytest.mark.required
def test_reset(show_viewer):
BOOL_MASK = torch.tensor([True, False, True, False], dtype=torch.bool, device=gs.device)
scene = gs.Scene(
show_viewer=show_viewer,
)
scene.add_entity(
gs.morphs.URDF(
file="urdf/plane/plane.urdf",
fixed=True,
)
)
scene.add_entity(
gs.morphs.Box(
size=(0.1, 0.1, 0.1),
pos=(0, 0, 0.5),
)
)
scene.build(n_envs=4)
init_state = scene.get_state()
init_rigid_state = next(s for s in init_state.solvers_state if isinstance(s, RigidSolverState))
for _ in range(50):
scene.step()
fallen_state = scene.get_state()
fallen_rigid_state = next(s for s in fallen_state.solvers_state if isinstance(s, RigidSolverState))
for envs_idx in (BOOL_MASK, torch.where(BOOL_MASK)[0]):
scene.reset(state=fallen_state)
scene.reset(state=init_state, envs_idx=envs_idx)
for actual, init_ref, fallen_ref in (
(
qd_to_torch(scene.rigid_solver._rigid_global_info.qpos, transpose=True, copy=True),
init_rigid_state.qpos,
fallen_rigid_state.qpos,
),
(
qd_to_torch(scene.rigid_solver.dofs_state.vel, transpose=True, copy=True),
init_rigid_state.dofs_vel,
fallen_rigid_state.dofs_vel,
),
(
qd_to_torch(scene.rigid_solver.links_state.pos, transpose=True, copy=True),
init_rigid_state.links_pos,
fallen_rigid_state.links_pos,
),
):
assert_allclose(actual[BOOL_MASK], init_ref[BOOL_MASK], tol=gs.EPS)
assert_allclose(actual[~BOOL_MASK], fallen_ref[~BOOL_MASK], tol=gs.EPS)
# After reset, simulation from init_state should reproduce the original fallen_state trajectory
for _ in range(50):
scene.step()
for actual, fallen_ref in (
(qd_to_torch(scene.rigid_solver._rigid_global_info.qpos, transpose=True, copy=True), fallen_rigid_state.qpos),
(qd_to_torch(scene.rigid_solver.dofs_state.vel, transpose=True, copy=True), fallen_rigid_state.dofs_vel),
(qd_to_torch(scene.rigid_solver.links_state.pos, transpose=True, copy=True), fallen_rigid_state.links_pos),
):
assert_allclose(actual[BOOL_MASK], fallen_ref[BOOL_MASK], tol=gs.EPS)
@pytest.mark.required
@pytest.mark.parametrize("xml_path", ["xml/one_ball_joint.xml"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG, gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_one_ball_joint(gs_sim, mj_sim, tol):
# FIXME: Mujoco is detecting collision for some reason...
mj_sim.model.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_CONTACT
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, num_steps=600, tol=tol)
@pytest.mark.required
@pytest.mark.parametrize("xml_path", ["xml/rope_ball.xml", "xml/rope_hinge.xml"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG, gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("gjk_collision", [True, False])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_rope_ball(gs_sim, mj_sim, gs_solver, tol):
# Make sure it is possible to set the configuration vector without failure
qpos = gs_sim.rigid_solver.get_dofs_position()
gs_sim.rigid_solver.set_dofs_position(qpos)
assert_allclose(gs_sim.rigid_solver.get_dofs_position(), qpos, tol=gs.EPS)
qpos = torch.rand(gs_sim.rigid_solver.n_dofs).clip(*gs_sim.rigid_solver.get_dofs_limit())
gs_sim.rigid_solver.set_dofs_position(qpos)
assert_allclose(gs_sim.rigid_solver.get_dofs_position(), qpos, tol=gs.EPS)
check_mujoco_model_consistency(gs_sim, mj_sim, tol=tol)
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, num_steps=300, tol=1e-8)
@pytest.mark.required
@pytest.mark.parametrize("xml_path", ["linear_deformable.urdf"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast])
@pytest.mark.parametrize("gjk_collision", [True, False])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_urdf_rope(gs_sim, mj_sim, gs_solver, xml_path):
# Must increase sol params to improve numerical stability
sol_params = gu.default_solver_params()
sol_params[0] = 0.02
gs_sim.rigid_solver.set_global_sol_params(sol_params)
mj_sim.model.jnt_solref[:, 0] = sol_params[0]
mj_sim.model.geom_solref[:, 0] = sol_params[0]
mj_sim.model.eq_solref[:, 0] = sol_params[0]
# FIXME: Tolerance must be very large due to small masses and compounding of errors over long kinematic chains
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, num_steps=300, tol=5e-5)
@pytest.mark.required
@pytest.mark.mujoco_compatibility(True)
@pytest.mark.parametrize("xml_path", ["xml/tet_tet.xml", "xml/tet_ball.xml", "xml/tet_capsule.xml"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG, gs.constraint_solver.Newton])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.implicitfast, gs.integrator.Euler])
@pytest.mark.parametrize("gjk_collision", [True])
@pytest.mark.parametrize("multi_contact", [True, False])
@pytest.mark.parametrize("backend", [gs.cpu])
def test_tet_primitive_shapes(gs_sim, mj_sim, gs_integrator, gs_solver, xml_path, multi_contact, tol):
# Make sure it is possible to set the configuration vector without failure
gs_sim.rigid_solver.set_dofs_position(gs_sim.rigid_solver.get_dofs_position())
check_mujoco_model_consistency(gs_sim, mj_sim, tol=tol)
# FIXME: Because of very small numerical error, error could be this large even if there is no logical error.
# Multi-contact perturbation introduces slightly larger errors due to GJK implementation differences.
simulate_and_check_mujoco_consistency(gs_sim, mj_sim, num_steps=700, tol=2e-6)
@pytest.mark.required
@pytest.mark.parametrize("model_name", ["two_aligned_hinges"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.Euler])
def test_link_velocity(gs_sim, tol):
# Check the velocity for a few "easy" special cases
init_simulators(gs_sim, qvel=np.array([0.0, 1.0]))
assert_allclose(gs_sim.rigid_solver.links_state.cd_vel.to_numpy(), 0, tol=tol)
init_simulators(gs_sim, qvel=np.array([1.0, 0.0]))
cvel_0, cvel_1 = gs_sim.rigid_solver.links_state.cd_vel.to_numpy()[:, 0]
assert_allclose(cvel_0, np.array([0.0, 0.5, 0.0]), tol=tol)
assert_allclose(cvel_1, np.array([0.0, 0.5, 0.0]), tol=tol)
init_simulators(gs_sim, qpos=np.array([0.0, np.pi / 2.0]), qvel=np.array([0.0, 1.2]))
COM = gs_sim.rigid_solver.links_state.root_COM[0, 0]
assert_allclose(COM, np.array([0.375, 0.125, 0.0]), tol=tol)
xanchor = gs_sim.rigid_solver.joints_state.xanchor[1, 0]
assert_allclose(xanchor, np.array([0.5, 0.0, 0.0]), tol=tol)
cvel_0, cvel_1 = gs_sim.rigid_solver.links_state.cd_vel.to_numpy()[:, 0]
assert_allclose(cvel_0, 0, tol=tol)
assert_allclose(cvel_1, np.array([-1.2 * (0.125 - 0.0), 1.2 * (0.375 - 0.5), 0.0]), tol=tol)
# Check that the velocity is valid for a random configuration
init_simulators(gs_sim, qpos=np.array([-0.7, 0.2]), qvel=np.array([3.0, 13.0]))
xanchor = gs_sim.rigid_solver.joints_state.xanchor[1, 0]
theta_0, theta_1 = gs_sim.rigid_solver.qpos.to_numpy()[:, 0]
assert_allclose(xanchor[0], 0.5 * np.cos(theta_0), tol=tol)
assert_allclose(xanchor[1], 0.5 * np.sin(theta_0), tol=tol)
COM = gs_sim.rigid_solver.links_state.root_COM[0, 0]
COM_0 = np.array([0.25 * np.cos(theta_0), 0.25 * np.sin(theta_0), 0.0])
COM_1 = np.array(
[
0.5 * np.cos(theta_0) + 0.25 * np.cos(theta_0 + theta_1),
0.5 * np.sin(theta_0) + 0.25 * np.sin(theta_0 + theta_1),
0.0,
]
)
link_COM0 = gs_sim.rigid_solver.get_links_pos(ref="link_com")[0]
link_COM1 = gs_sim.rigid_solver.get_links_pos(ref="link_com")[1]
assert_allclose(link_COM0, COM_0, tol=tol)
assert_allclose(link_COM1, COM_1, tol=tol)
assert_allclose(COM, 0.5 * (COM_0 + COM_1), tol=tol)
cvel_0, cvel_1 = gs_sim.rigid_solver.links_state.cd_vel.to_numpy()[:, 0]
omega_0, omega_1 = gs_sim.rigid_solver.links_state.cd_ang.to_numpy()[:, 0, 2]
assert_allclose(omega_0, 3.0, tol=tol)
assert_allclose(omega_1 - omega_0, 13.0, tol=tol)
cvel_0_ = omega_0 * np.array([-COM[1], COM[0], 0.0])
assert_allclose(cvel_0, cvel_0_, tol=tol)
cvel_1_ = cvel_0 + (omega_1 - omega_0) * np.array([xanchor[1] - COM[1], COM[0] - xanchor[0], 0.0])
assert_allclose(cvel_1, cvel_1_, tol=tol)
xpos_0, xpos_1 = gs_sim.rigid_solver.links_state.pos.to_numpy()[:, 0]
assert_allclose(xpos_0, 0.0, tol=tol)
assert_allclose(xpos_1, xanchor, tol=tol)
xvel_0, xvel_1 = gs_sim.rigid_solver.get_links_vel()
assert_allclose(xvel_0, 0.0, tol=tol)
xvel_1_ = omega_0 * np.array([-xpos_1[1], xpos_1[0], 0.0])
assert_allclose(xvel_1, xvel_1_, tol=tol)
civel_0, civel_1 = gs_sim.rigid_solver.get_links_vel(ref="link_com")
civel_0_ = omega_0 * np.array([-COM_0[1], COM_0[0], 0.0])
assert_allclose(civel_0, civel_0_, tol=tol)
civel_1_ = omega_0 * np.array([-COM_1[1], COM_1[0], 0.0]) + (omega_1 - omega_0) * np.array(
[xanchor[1] - COM_1[1], COM_1[0] - xanchor[0], 0.0]
)
assert_allclose(civel_1, civel_1_, tol=tol)
@pytest.mark.required
@pytest.mark.merge_fixed_links(False)
@pytest.mark.parametrize("model_name", ["pendulum"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.Euler])
def test_pendulum_links_acc(gs_sim, tol):
pendulum = gs_sim.entities[0]
g = gs_sim.rigid_solver._gravity[0][2]
# Make sure that the linear and angular acceleration matches expectation
theta = np.random.rand()
theta_dot = np.random.rand()
pendulum.set_qpos([theta])
pendulum.set_dofs_velocity([theta_dot])
for _ in range(100):
# Backup state before integration
theta = gs_sim.rigid_solver.qpos[0, 0]
theta_dot = gs_sim.rigid_solver.dofs_state.vel[0, 0]
# Run one simulation step
gs_sim.scene.step()
# Angular acceleration:
# * acc_ang_x = - sin(theta) * g
acc_ang = gs_sim.rigid_solver.get_links_acc_ang()
assert_allclose(acc_ang[0], 0, tol=tol)
assert_allclose(acc_ang[2], np.array([-np.sin(theta) * g, 0.0, 0.0]), tol=tol)
# Linear spatial acceleration:
# * acc_spatial_lin_y = sin(theta) * g
acc_spatial_lin_world = gs_sim.rigid_solver.links_state.cacc_lin.to_numpy()
assert_allclose(acc_spatial_lin_world[0], 0, tol=tol)
R = np.array(
[
[1.0, 0.0, 0.0],
[0.0, np.cos(theta), np.sin(theta)],
[0.0, -np.sin(theta), np.cos(theta)],
]
)
acc_spatial_lin_local = R @ acc_spatial_lin_world[2, 0]
assert_allclose(acc_spatial_lin_local, np.array([0.0, np.sin(theta) * g, 0.0]), tol=tol)
# Linear true acceleration:
# * acc_classical_lin_y = sin(theta) * g (tangential angular acceleration effect)
# * acc_classical_lin_z = - theta_dot ** 2 (radial centripedal effect)
acc_classical_lin_world = tensor_to_array(gs_sim.rigid_solver.get_links_acc())
assert_allclose(acc_classical_lin_world[0], 0, tol=tol)
acc_classical_lin_local = R @ acc_classical_lin_world[2]
assert_allclose(acc_classical_lin_local, np.array([0.0, np.sin(theta) * g, -(theta_dot**2)]), tol=tol)
# Hold the pendulum straight using PD controller and check again
pendulum.set_dofs_kp([4000.0])
pendulum.set_dofs_kv([100.0])
pendulum.control_dofs_position([0.5 * np.pi])
for _ in range(400):
gs_sim.scene.step()
acc_classical_lin_world = gs_sim.rigid_solver.get_links_acc()
assert_allclose(acc_classical_lin_world, 0, tol=tol)
@pytest.mark.required
@pytest.mark.merge_fixed_links(False)
@pytest.mark.parametrize("model_name", ["double_pendulum"])
@pytest.mark.parametrize("gs_solver", [gs.constraint_solver.CG])
@pytest.mark.parametrize("gs_integrator", [gs.integrator.Euler])
def test_double_pendulum_links_acc(gs_sim, tol):
robot = gs_sim.entities[0]
# Make sure that the linear and angular acceleration matches expectation
qpos = np.random.rand(2)
qvel = np.random.rand(2)
robot.set_qpos(qpos)
robot.set_dofs_velocity(qvel)
for _ in range(100):
# Backup state before integration
theta = gs_sim.rigid_solver.qpos.to_numpy()[:, 0]
theta_dot = gs_sim.rigid_solver.dofs_state.vel.to_numpy()[:, 0]
# Run one simulation step
gs_sim.scene.step()
# Backup acceleration before integration
theta_ddot = gs_sim.rigid_solver.dofs_state.acc.to_numpy()[:, 0]
# Angular acceleration
acc_ang = tensor_to_array(gs_sim.rigid_solver.get_links_acc_ang())
assert_allclose(acc_ang[0], 0, tol=tol)
assert_allclose(acc_ang[1], [theta_ddot[0], 0.0, 0.0], tol=tol)
assert_allclose(acc_ang[-1], [theta_ddot[0] + theta_ddot[1], 0.0, 0.0], tol=tol)
# Linear spatial acceleration
cacc_spatial_lin_world = gs_sim.rigid_solver.links_state.cacc_lin.to_numpy()[[0, 2, 4], 0]
com = gs_sim.rigid_solver.links_state.root_COM.to_numpy()[-1, 0]
pos = gs_sim.rigid_solver.links_state.pos.to_numpy()[[0, 2, 4], 0]
assert_allclose(cacc_spatial_lin_world[1], np.cross(acc_ang[2], com), tol=tol)
acc_spatial_lin_world = cacc_spatial_lin_world + np.cross(acc_ang[[0, 2, 4]], pos - com)
assert_allclose(acc_spatial_lin_world[0], 0, tol=tol)
theta_world = theta.cumsum()
R = np.array(
[
[np.ones_like(theta), np.zeros_like(theta), np.zeros_like(theta)],
[np.zeros_like(theta), np.cos(theta_world), np.sin(theta_world)],
[np.zeros_like(theta), -np.sin(theta_world), np.cos(theta_world)],
]
)