nablaengine 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,317 @@
1
+ """Every field of MuJoCo's MjModel (mujoco 3.17), classified by what the engine does with it: the completeness proof
2
+ behind the model validation (nablaengine.model.capability)."""
3
+
4
+ from dataclasses import dataclass
5
+ from functools import lru_cache
6
+
7
+ import numpy as np
8
+
9
+ KINDS = ("consumed", "checked", "default", "derived", "irrelevant")
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Field:
14
+ kind: str
15
+ code: str = None
16
+ note: str = ""
17
+
18
+
19
+ def _f(kind, code=None, note=""):
20
+ assert kind in KINDS, kind
21
+ return Field(kind, code, note)
22
+
23
+
24
+ VISUAL = "rendering only"
25
+ USER = "user data, not read"
26
+ FILTER = ("parameter of contype / conaffinity contacts (MuJoCo's mixing rules); the engine has only explicit pairs, "
27
+ "which carry their own (H15 rejects filter contacts)")
28
+
29
+ FIELDS = {
30
+ "qpos0": _f("consumed", "H8", "the hinges' must be 0 (the engine's angle is qpos)"),
31
+ "qpos_spring": _f("irrelevant", "H22", "spring reference poses; every stiffness is default (0, H22)"),
32
+ "body_parentid": _f("consumed", "H9"), "body_rootid": _f("consumed", "H6"),
33
+ "body_weldid": _f("derived", "H7"), "body_mocapid": _f("derived", "H25"),
34
+ "body_jntnum": _f("consumed", "H7"), "body_jntadr": _f("consumed", "H7"),
35
+ "body_dofnum": _f("consumed", "H7b"), "body_dofadr": _f("consumed", "H7b"),
36
+ "body_treeid": _f("derived"), "body_geomnum": _f("derived"), "body_geomadr": _f("derived"),
37
+ "body_simple": _f("derived"), "body_sameframe": _f("derived"),
38
+ "body_pos": _f("consumed"), "body_quat": _f("consumed"), "body_ipos": _f("consumed"),
39
+ "body_iquat": _f("consumed"), "body_mass": _f("consumed"), "body_inertia": _f("consumed"),
40
+ "body_subtreemass": _f("derived"), "body_invweight0": _f("consumed"),
41
+ "body_gravcomp": _f("default", "H22", "gravity compensation"),
42
+ "body_margin": _f("derived"), "body_user": _f("irrelevant", note=USER),
43
+ "body_plugin": _f("default", "H25", "body plugins"),
44
+ "body_contype": _f("derived", "H15"), "body_conaffinity": _f("derived", "H15"),
45
+ "body_bvhadr": _f("derived"), "body_bvhnum": _f("derived"),
46
+ "jnt_type": _f("consumed", "H7"), "jnt_qposadr": _f("consumed"), "jnt_dofadr": _f("consumed", "H11a"),
47
+ "jnt_bodyid": _f("derived"), "jnt_actuatorid": _f("derived", "H11d", "the actuator whose damping / armature acts "
48
+ "on the joint (both default-checked)"),
49
+ "jnt_group": _f("irrelevant", note=VISUAL), "jnt_limited": _f("consumed", "H20"),
50
+ "jnt_actfrclimited": _f("consumed", "H12"), "jnt_actfrcrange": _f("consumed", "H12"),
51
+ "jnt_actgravcomp": _f("default", "H22", "gravity compensation through the actuators"),
52
+ "jnt_solref": _f("consumed", "H19"), "jnt_solimp": _f("consumed", "H20"), "jnt_pos": _f("consumed", "H7"),
53
+ "jnt_axis": _f("consumed"), "jnt_stiffness": _f("default", "H22", "joint springs"),
54
+ "jnt_stiffnesspoly": _f("default", "H22", "joint springs (higher order)"), "jnt_range": _f("consumed"),
55
+ "jnt_margin": _f("consumed", "H20"), "jnt_user": _f("irrelevant", note=USER),
56
+ "dof_bodyid": _f("consumed", "H7b"), "dof_jntid": _f("derived"), "dof_parentid": _f("derived"),
57
+ "dof_treeid": _f("derived"), "dof_Madr": _f("derived"), "dof_simplenum": _f("derived"),
58
+ "dof_solref": _f("consumed", "H19"), "dof_solimp": _f("consumed", "H20"),
59
+ "dof_frictionloss": _f("consumed", None, "frictionloss rows (forward and adjoint; U10)"), "dof_armature": _f("consumed"),
60
+ "dof_damping": _f("consumed", None, "joint damping (model_hooks.py: c_damp)"),
61
+ "dof_dampingpoly": _f("default", "H22", "joint damping (higher order)"),
62
+ "dof_invweight0": _f("consumed"), "dof_M0": _f("derived"), "dof_length": _f("derived"),
63
+ "tree_bodyadr": _f("derived", "H6"), "tree_bodynum": _f("derived", "H6"), "tree_dofadr": _f("derived"),
64
+ "tree_dofnum": _f("derived"),
65
+ "tree_sleep_policy": _f("irrelevant", "H24b", "island sleeping (mjENBL_SLEEP is rejected, H24b)"),
66
+ "geom_type": _f("consumed", "H14a"), "geom_contype": _f("checked", "H15"),
67
+ "geom_conaffinity": _f("checked", "H15"), "geom_condim": _f("irrelevant", "H15", FILTER),
68
+ "geom_bodyid": _f("consumed"), "geom_dataid": _f("derived", "H14a", "mesh / height field of a geom (the "
69
+ "collision geoms' types are checked)"),
70
+ "geom_matid": _f("irrelevant", note=VISUAL), "geom_group": _f("irrelevant", note=VISUAL),
71
+ "geom_priority": _f("irrelevant", "H15", FILTER), "geom_plugin": _f("default", "H25", "geom plugins (SDF)"),
72
+ "geom_sameframe": _f("derived"), "geom_solmix": _f("irrelevant", "H15", FILTER),
73
+ "geom_solref": _f("irrelevant", "H15", FILTER), "geom_solimp": _f("irrelevant", "H15", FILTER),
74
+ "geom_size": _f("consumed"), "geom_aabb": _f("derived"), "geom_rbound": _f("consumed"),
75
+ "geom_pos": _f("consumed"), "geom_quat": _f("consumed"), "geom_friction": _f("irrelevant", "H15", FILTER),
76
+ "geom_margin": _f("irrelevant", "H15", FILTER), "geom_gap": _f("irrelevant", "H15", FILTER),
77
+ "geom_surfacevel": _f("default", "H16", "contact surface velocity"),
78
+ "geom_adhesion": _f("default", "H16", "contact adhesion"),
79
+ "geom_fluid": _f("default", "H22", "the ellipsoid fluid model"), "geom_user": _f("irrelevant", note=USER),
80
+ "geom_rgba": _f("irrelevant", note=VISUAL),
81
+ "pair_dim": _f("consumed", "H17"), "pair_geom1": _f("consumed", "H14a"), "pair_geom2": _f("consumed", "H14a"),
82
+ "pair_signature": _f("derived"), "pair_solref": _f("consumed", "H19"),
83
+ "pair_solreffriction": _f("default", "H16", "a separate solref of the friction rows"),
84
+ "pair_solimp": _f("consumed"), "pair_margin": _f("consumed", "H16"), "pair_gap": _f("consumed", "H16"),
85
+ "pair_adhesion": _f("default", "H16", "contact adhesion"),
86
+ "pair_friction": _f("consumed", "H16", "tangential friction; spin and rolling unused at condim 1 / 3 (H17)"),
87
+ "exclude_signature": _f("irrelevant", "H15", "excluded body pairs of contype / conaffinity contacts (H15 "
88
+ "applies them)"),
89
+ "actuator_trntype": _f("consumed", "H11a"), "actuator_dyntype": _f("checked", "H11b"),
90
+ "actuator_gaintype": _f("checked", "H11b"), "actuator_biastype": _f("consumed", "H11a"),
91
+ "actuator_ctrladr": _f("checked", "H11a"), "actuator_ctrlnum": _f("checked", "H11a"),
92
+ "actuator_ctrlspec": _f("checked", "H11b", "the input signature: 0 (the gain type's default) or mjINPUT_POS "
93
+ "(the position shortcut's) for a fixed gain"),
94
+ "actuator_outadr": _f("checked", "H11a"), "actuator_outnum": _f("checked", "H11a"),
95
+ "actuator_actadr": _f("derived", "H11b"), "actuator_actnum": _f("derived", "H11b"),
96
+ "actuator_trnid": _f("consumed", "H11a"),
97
+ "actuator_cranklength": _f("irrelevant", "H11a", "slider-crank transmissions only (joint transmissions, H11a)"),
98
+ "actuator_dynprm": _f("irrelevant", "H11b", "activation dynamics only (dyntype none, H11b)"),
99
+ "actuator_gainprm": _f("consumed", "H11a"), "actuator_biasprm": _f("consumed", "H11a"),
100
+ "actuator_actlimited": _f("irrelevant", "H11b", "activations only (none, H11b)"),
101
+ "actuator_actrange": _f("irrelevant", "H11b", "activations only (none, H11b)"),
102
+ "actuator_actearly": _f("irrelevant", "H11b", "activations only (none, H11b)"),
103
+ "actuator_history": _f("default", "H11e", "the actuator's history buffer (delays)"),
104
+ "actuator_historyadr": _f("derived", "H11e"),
105
+ "actuator_delay": _f("default", "H11e", "actuator delay"),
106
+ "actuator_damping": _f("default", "H22", "actuator damping (added to its joint's)"),
107
+ "actuator_dampingpoly": _f("default", "H22", "actuator damping (higher order)"),
108
+ "actuator_armature": _f("default", "H11d", "actuator armature (added to its joint's)"),
109
+ "actuator_group": _f("irrelevant", "H24b", "visualization groups; disabling groups (opt.disableactuator) is "
110
+ "rejected by H24b"),
111
+ "actuator_user": _f("irrelevant", note=USER), "actuator_plugin": _f("default", "H25", "actuator plugins"),
112
+ "actuator_forcelimited": _f("consumed", "H11a"),
113
+ "actuator_forcerange": _f("irrelevant", "H11a", "unused: no actuator is force-limited (H11a)"),
114
+ "actuator_ctrllimited": _f("checked", "H11c"), "actuator_ctrlrange": _f("checked", "H11c"),
115
+ "actuator_gear": _f("consumed", "H11a"), "actuator_acc0": _f("derived"), "actuator_length0": _f("derived"),
116
+ "actuator_lengthrange": _f("derived", note="computed for muscles; no muscles (H11b)"),
117
+ "flg_gravcomp": _f("derived", "H22"), "flg_surfacevel": _f("derived", "H16"), "flg_adhesion": _f("derived", "H16"),
118
+ "names": _f("consumed", "H13", "the COM-offset body's name lookup"),
119
+ "names_map": _f("derived"), "paths": _f("irrelevant", note="asset paths"),
120
+ "signature": _f("irrelevant", note="the compiler's signature"),
121
+ "B_rownnz": _f("derived"), "B_rowadr": _f("derived"), "B_colind": _f("derived"),
122
+ "M_rownnz": _f("derived"), "M_rowadr": _f("derived"), "M_colind": _f("derived"),
123
+ "D_rownnz": _f("derived"), "D_rowadr": _f("derived"), "D_diag": _f("derived"), "D_colind": _f("derived"),
124
+ "mapM2M": _f("derived"), "mapM2D": _f("derived"), "mapD2M": _f("derived"),
125
+ "plugin": _f("checked", "H25", "plugin instances (nplugin = 0)"),
126
+ "opt.timestep": _f("consumed", "I1", "baked into the constants"),
127
+ "opt.impratio": _f("consumed"), "opt.tolerance": _f("consumed", note="the Newton tolerance (scaled by "
128
+ "stat.meaninertia, as MuJoCo)"),
129
+ "opt.ls_tolerance": _f("irrelevant", note="the engine's line search is exact (a converged Newton solve gives "
130
+ "MuJoCo's unique minimizer)"),
131
+ "opt.noslip_tolerance": _f("irrelevant", "H24b", "noslip is off (H24b)"),
132
+ "opt.ccd_tolerance": _f("checked", "H14d", "native CCD: box-box only (MuJoCo Warp's GJK / EPA, whose converged "
133
+ "result the forward computes): at most the default"),
134
+ "opt.sleep_tolerance": _f("irrelevant", "H24b", "island sleeping is off (H24b)"),
135
+ "opt.gravity": _f("consumed"), "opt.wind": _f("checked", "H22"),
136
+ "opt.magnetic": _f("irrelevant", note="magnetometer sensors only"),
137
+ "opt.density": _f("checked", "H22"), "opt.viscosity": _f("checked", "H22"),
138
+ "opt.o_margin": _f("irrelevant", "H24b", "contact override: mjENBL_OVERRIDE is rejected (H24b)"),
139
+ "opt.o_solref": _f("irrelevant", "H24b", "contact override: mjENBL_OVERRIDE is rejected (H24b)"),
140
+ "opt.o_solimp": _f("irrelevant", "H24b", "contact override: mjENBL_OVERRIDE is rejected (H24b)"),
141
+ "opt.o_friction": _f("irrelevant", "H24b", "contact override: mjENBL_OVERRIDE is rejected (H24b)"),
142
+ "opt.integrator": _f("checked", "H23"), "opt.cone": _f("checked", "H18"),
143
+ "opt.jacobian": _f("irrelevant", note="MuJoCo's dense / sparse representation"),
144
+ "opt.solver": _f("checked", "H24a"),
145
+ "opt.iterations": _f("consumed", note="the default of EnginePhysics' iterations (a call option)"),
146
+ "opt.ls_iterations": _f("irrelevant", note="the engine's line search is exact (at most 40 steps)"),
147
+ "opt.noslip_iterations": _f("checked", "H24b"),
148
+ "opt.ccd_iterations": _f("checked", "H14d", "native CCD: box-box only (MuJoCo Warp's GJK / EPA, whose converged "
149
+ "result the forward computes): at least the default"),
150
+ "opt.disableflags": _f("checked", "H24b"), "opt.enableflags": _f("checked", "H24b"),
151
+ "opt.disableactuator": _f("checked", "H24b"),
152
+ "opt.sdf_initpoints": _f("irrelevant", "H14a", "SDF collisions: none"),
153
+ "opt.sdf_iterations": _f("irrelevant", "H14a", "SDF collisions: none"),
154
+ "stat.meaninertia": _f("consumed", note="scales the Newton tolerance"),
155
+ "stat.meanmass": _f("irrelevant", note=VISUAL), "stat.meansize": _f("irrelevant", note=VISUAL),
156
+ "stat.extent": _f("irrelevant", note=VISUAL), "stat.center": _f("irrelevant", note=VISUAL),
157
+ "vis": _f("irrelevant", note=VISUAL),
158
+ }
159
+
160
+ SIZES = {
161
+ "nq": _f("consumed"), "nv": _f("consumed", "H3"), "nu": _f("consumed", "H11a"),
162
+ "nactuator": _f("checked", "H11a"), "nout": _f("checked", "H11a"), "na": _f("checked", "H11b"),
163
+ "nbody": _f("consumed", "H1"), "njnt": _f("consumed"), "ngeom": _f("consumed"), "npair": _f("consumed", "H26b"),
164
+ "nmocap": _f("checked", "H25"), "neq": _f("checked", "H25"), "ntendon": _f("checked", "H25"),
165
+ "nwrap": _f("checked", "H25"), "nJten": _f("derived", "H25"), "nflex": _f("checked", "H25"),
166
+ "nplugin": _f("checked", "H25"), "npluginattr": _f("derived", "H25"), "npluginstate": _f("derived", "H25"),
167
+ "nhistory": _f("derived", "H11e"), "ngravcomp": _f("derived", "H22"), "nexclude": _f("irrelevant", "H15", FILTER),
168
+ **{k: _f("derived", "H25") for k in (
169
+ "nflexnode", "nflexvert", "nflexedge", "nflexelem", "nflexelemdata", "nflexstiffness", "nflexbending",
170
+ "nefm0dof", "nefm0L", "nefmCvert", "nflexelemedge", "nflexshelldata", "nflextexcoord", "nJfe", "nJfv")},
171
+ **{k: _f("derived") for k in ("nbvh", "nbvhstatic", "nbvhdynamic", "ntree", "nM", "nB", "nC", "nD", "nJmom",
172
+ "nnames_map")},
173
+ **{k: _f("irrelevant", note=VISUAL) for k in (
174
+ "noct", "nsite", "ncam", "nlight", "nmesh", "nmeshvert", "nmeshnormal", "nmeshtexcoord", "nmeshface",
175
+ "nmeshgraph", "nmeshpoly", "nmeshpolyvert", "nmeshpolymap", "nskin", "nskinvert", "nskintexvert", "nskinface",
176
+ "nskinbone", "nskinbonevert", "nhfield", "nhfielddata", "ntex", "ntexdata", "nmat", "npolygonmax",
177
+ "nmeshdegmax")},
178
+ **{k: _f("irrelevant", note="sensors, custom data, keyframes, names: not read") for k in (
179
+ "nsensor", "nsensordata", "nnumeric", "nnumericdata", "ntext", "ntextdata", "ntuple", "ntupledata", "nkey",
180
+ "nuser_body", "nuser_jnt", "nuser_geom", "nuser_site", "nuser_cam", "nuser_tendon", "nuser_actuator",
181
+ "nuser_sensor", "nnames", "npaths", "nuserdata")},
182
+ **{k: _f("irrelevant", note="MuJoCo's own memory sizes (mjData)") for k in (
183
+ "narena", "nbuffer", "nemax", "njmax", "nconmax")},
184
+ }
185
+
186
+ PREFIXES = (
187
+ ("flex_", _f("checked", "H25", "flexes (nflex = 0)")),
188
+ ("flexedge_", _f("checked", "H25", "flexes (nflex = 0)")),
189
+ ("flexvert_", _f("checked", "H25", "flexes (nflex = 0)")),
190
+ ("efm0_", _f("checked", "H25", "flexes (nflex = 0)")), ("efmC_", _f("checked", "H25", "flexes (nflex = 0)")),
191
+ ("eq_", _f("checked", "H25", "equality constraints (neq = 0; the forest engine reads eq_type, obj1id, obj2id, "
192
+ "objtype, data, solref, solimp, active0 of the joint and connect equalities: H25e, "
193
+ "forest_engine.equality)")),
194
+ ("tendon_", _f("checked", "H25", "tendons (ntendon = 0; the forest engine reads the fixed tendons' adr, num, "
195
+ "limited, range, margin, solref_lim, solimp_lim, invweight0, length0, stiffness, "
196
+ "lengthspring, damping, armature, frictionloss: H25t, forest_engine.tendon)")),
197
+ ("ten_J_", _f("checked", "H25", "tendons")),
198
+ ("wrap_", _f("checked", "H25", "tendon wraps (nwrap = 0; the forest engine reads the fixed tendons' wrap_type, "
199
+ "objid, prm: H25 / H25t)")),
200
+ ("plugin_", _f("checked", "H25", "plugin instances (nplugin = 0)")),
201
+ ("bvh_", _f("derived", note="bounding volume hierarchy (MuJoCo's collision acceleration)")),
202
+ ("oct_", _f("irrelevant", note="mesh octrees (SDF collisions: none)")),
203
+ ("mesh_", _f("irrelevant", "H14a", "mesh assets (the collision geoms' types are checked)")),
204
+ ("hfield_", _f("irrelevant", "H14a", "height field assets (the collision geoms' types are checked)")),
205
+ ("skin_", _f("irrelevant", note=VISUAL)), ("tex_", _f("irrelevant", note=VISUAL)),
206
+ ("mat_", _f("irrelevant", note=VISUAL)), ("cam_", _f("irrelevant", note=VISUAL)),
207
+ ("light_", _f("irrelevant", note=VISUAL)),
208
+ ("site_", _f("irrelevant", note="sites: used only by sensors, tendons and site transmissions (none)")),
209
+ ("sensor_", _f("irrelevant", note="sensors: the engine computes none (they do not act on the dynamics)")),
210
+ ("key_", _f("irrelevant", note="keyframes: the engine takes its states as inputs")),
211
+ ("name_", _f("irrelevant", note="name addresses")),
212
+ ("numeric_", _f("irrelevant", note=USER + "; except the custom numeric nablaengine_geom_invweight, the per-geom "
213
+ "contact inverse weights (nablaengine.model.invweight)")), ("text_", _f("irrelevant", note=USER)),
214
+ ("tuple_", _f("irrelevant", note=USER)),
215
+ )
216
+
217
+
218
+ def classify(name):
219
+ """The Field of an MjModel field name (opt.<x>, stat.<x>, vis included), None if unclassified."""
220
+ if name in FIELDS:
221
+ return FIELDS[name]
222
+ if name in SIZES:
223
+ return SIZES[name]
224
+ for p, f in PREFIXES:
225
+ if name.startswith(p):
226
+ return f
227
+ return None
228
+
229
+
230
+ def model_fields(m):
231
+ """The field names of an MjModel: its public data attributes (methods and the opt / stat / vis structs left
232
+ out), then opt.<x> and stat.<x>, and vis."""
233
+ out = []
234
+ for k in dir(m):
235
+ if k.startswith("_") or k in ("opt", "stat", "vis"):
236
+ continue
237
+ try:
238
+ v = getattr(m, k)
239
+ except Exception:
240
+ continue
241
+ if not callable(v):
242
+ out.append(k)
243
+ for sub in ("opt", "stat"):
244
+ o = getattr(m, sub)
245
+ out += [f"{sub}.{k}" for k in dir(o) if not k.startswith("_") and not callable(getattr(o, k))]
246
+ return sorted(out) + ["vis"]
247
+
248
+
249
+ def unclassified(m):
250
+ """The fields of m that classify() does not know."""
251
+ return [k for k in model_fields(m) if classify(k) is None]
252
+
253
+
254
+ def default_fields():
255
+ """The names of the fields of kind default."""
256
+ return sorted(k for k, f in FIELDS.items() if f.kind == "default")
257
+
258
+
259
+ PROBE_XML = """
260
+ <mujoco>
261
+ <worldbody>
262
+ <geom name="floor" type="plane" size="1 1 0.1"/>
263
+ <body name="root">
264
+ <freejoint/>
265
+ <geom name="torso" type="sphere" size="0.1"/>
266
+ <body name="link" pos="0 0 -0.2">
267
+ <joint name="hinge" type="hinge" axis="0 1 0"/>
268
+ <geom name="leg" type="capsule" size="0.05 0.1"/>
269
+ </body>
270
+ </body>
271
+ </worldbody>
272
+ <contact>
273
+ <pair geom1="floor" geom2="leg"/>
274
+ </contact>
275
+ <actuator>
276
+ <position name="servo" joint="hinge" kp="10"/>
277
+ </actuator>
278
+ </mujoco>
279
+ """
280
+ PROBE_ROW = {"body": 2, "jnt": 1, "dof": 6, "geom": 2, "pair": 0, "actuator": 0}
281
+
282
+
283
+ @lru_cache(maxsize=1)
284
+ def _probe():
285
+ import mujoco
286
+ return mujoco.MjModel.from_xml_string(PROBE_XML)
287
+
288
+
289
+ def default_rows():
290
+ """{field: its compile default (one row)} for the fields of kind default, from the probe model compiled by the
291
+ installed MuJoCo (its row of the element kind's probe element, PROBE_ROW)."""
292
+ m = _probe()
293
+ out = {}
294
+ for k in default_fields():
295
+ kind = k.split("_", 1)[0]
296
+ out[k] = np.array(getattr(m, k)[PROBE_ROW[kind]], copy=True)
297
+ return out
298
+
299
+
300
+ def option_default(name):
301
+ """MuJoCo's default of the option opt.<name> (the probe model's, compiled by the installed MuJoCo)."""
302
+ v = getattr(_probe().opt, name)
303
+ return v.item() if isinstance(v, np.generic) else v
304
+
305
+
306
+ def non_default(m, name, defaults=None):
307
+ """Row indices of m's field `name` (kind default) that differ from the compile default (world body row 0 not
308
+ counted: it has no inertial or joint attributes)."""
309
+ d = (defaults or default_rows())[name]
310
+ a = np.asarray(getattr(m, name))
311
+ if a.size == 0:
312
+ return []
313
+ rows = a.reshape(len(a), -1) != d.reshape(1, -1)
314
+ bad = np.flatnonzero(rows.any(axis=1))
315
+ if name.startswith("body_"):
316
+ bad = bad[bad > 0]
317
+ return [int(i) for i in bad]
@@ -0,0 +1,64 @@
1
+ """Gravity compensation of fused bodies (nablaengine.envs.convert.to_engine): where a jointless body is fused into a
2
+ parent with a different body gravcomp, one body's gravcomp at its COM cannot reproduce the source's forces."""
3
+ import mujoco
4
+ import numpy as np
5
+
6
+ NUMERIC = "nablaengine_gravcomp_offset"
7
+
8
+
9
+ def offsets(m):
10
+ """(nbody, 3) float64 gravcomp application offsets from the custom numeric NUMERIC, or None without it or when
11
+ every offset is 0."""
12
+ i = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_NUMERIC, NUMERIC)
13
+ if i < 0:
14
+ return None
15
+ adr, n = int(m.numeric_adr[i]), int(m.numeric_size[i])
16
+ if n != 3 * m.nbody:
17
+ raise ValueError(f"custom numeric {NUMERIC}: size {n}, the model has {m.nbody} bodies (3 values per body)")
18
+ v = np.array(m.numeric_data[adr:adr + n], np.float64).reshape(m.nbody, 3)
19
+ if not np.isfinite(v).all():
20
+ raise ValueError(f"custom numeric {NUMERIC}: the values must be finite")
21
+ return v if v.any() else None
22
+
23
+
24
+ def groups(m0, static):
25
+ """{root body id: [member body ids]} of model m0 for the jointless bodies named in static: each fuses into its
26
+ nearest ancestor not in static (the root; the world included)."""
27
+ out = {}
28
+ ids = {mujoco.mj_name2id(m0, mujoco.mjtObj.mjOBJ_BODY, n) for n in static}
29
+ for b in sorted(ids):
30
+ r = int(m0.body_parentid[b])
31
+ while r in ids:
32
+ r = int(m0.body_parentid[r])
33
+ out.setdefault(r, [r]).append(b)
34
+ return out
35
+
36
+
37
+ def mixed(m0, static):
38
+ """{root: (members, gc_eff)} of groups(m0, static) whose members' gravcomp differ (rooted below the world), with
39
+ the group's mass-weighted gravcomp."""
40
+ out = {}
41
+ for r, mem in groups(m0, static).items():
42
+ gc = m0.body_gravcomp[mem]
43
+ if r == 0 or np.all(gc == gc[0]):
44
+ continue
45
+ mass = m0.body_mass[mem]
46
+ out[r] = (mem, float(np.dot(gc, mass) / mass.sum()) if mass.sum() > 0 else float(gc[0]))
47
+ return out
48
+
49
+
50
+ def offset_field(m0, m, mix):
51
+ """(nbody of m, 3) offsets for the groups mix (mixed's) of source m0 in the fused model m (bodies by name)."""
52
+ d0, d = mujoco.MjData(m0), mujoco.MjData(m)
53
+ d.qpos[:] = d0.qpos
54
+ mujoco.mj_kinematics(m0, d0)
55
+ mujoco.mj_kinematics(m, d)
56
+ out = np.zeros((m.nbody, 3))
57
+ for r, (mem, _) in mix.items():
58
+ w = m0.body_gravcomp[mem] * m0.body_mass[mem]
59
+ if w.sum() == 0:
60
+ continue
61
+ p = (w[:, None] * d0.xipos[mem]).sum(0) / w.sum()
62
+ b = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, m0.body(r).name)
63
+ out[b] = d.xmat[b].reshape(3, 3).T @ (p - d.xipos[b])
64
+ return out
@@ -0,0 +1,145 @@
1
+ """Per-geom contact inverse weights (both engines)."""
2
+ import mujoco
3
+ import numpy as np
4
+
5
+ NUMERIC = "nablaengine_geom_invweight"
6
+
7
+ HOOKS = (
8
+ ("c_binvw[c_gbody[PG1(pr)]]", "c_ginvw[PG1(pr)]"),
9
+ ("c_binvw[c_gbody[PG2(pr)]]", "c_ginvw[PG2(pr)]"),
10
+ ("RADD(c_binvw[b1], c_binvw[b2])", "RADD(c_ginvw[g1], c_ginvw[g2])"),
11
+ )
12
+
13
+
14
+ def geom_values(m):
15
+ """The model's per-geom inverse weights (ngeom,) float64 from the custom numeric NUMERIC (negative entries: the
16
+ geom's body's value), or None without it."""
17
+ i = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_NUMERIC, NUMERIC)
18
+ if i < 0:
19
+ return None
20
+ adr, n = int(m.numeric_adr[i]), int(m.numeric_size[i])
21
+ if n != m.ngeom:
22
+ raise ValueError(f"custom numeric {NUMERIC}: size {n}, the model has {m.ngeom} geoms (one value per geom)")
23
+ v = np.array(m.numeric_data[adr:adr + n], np.float64)
24
+ if not np.isfinite(v).all():
25
+ raise ValueError(f"custom numeric {NUMERIC}: the values must be finite")
26
+ body = m.body_invweight0[m.geom_bodyid, 0]
27
+ return np.where(v < 0, body, v)
28
+
29
+
30
+ def table(m, geoms, extra=0):
31
+ """The engine's table c_ginvw (float64, one per collision-geom table row: geoms, then `extra` world rows of value 0,
32
+ e.g. the G1 class's terrain pseudo geom), or None when the model needs none: no NUMERIC field, or every collision
33
+ geom's value equal in float32 to its body's (the text and constants then stay as without the field)."""
34
+ v = geom_values(m)
35
+ if v is None or not len(geoms):
36
+ return None
37
+ geoms = np.asarray(geoms, int)
38
+ v = v[geoms]
39
+ if (v.astype(np.float32) == m.body_invweight0[m.geom_bodyid[geoms], 0].astype(np.float32)).all():
40
+ return None
41
+ return np.concatenate([v, np.zeros(extra)])
42
+
43
+
44
+ def header(m, geoms):
45
+ """The table's declaration for step_header (\"\" without a table)."""
46
+ return "DKC float c_ginvw[NGEOMC]; // per-geom contact inverse weights (nablaengine.model.invweight)\n" \
47
+ if table(m, geoms) is not None else ""
48
+
49
+
50
+ def apply(src, m, geoms):
51
+ """src (a unit's full text, after the elliptic edits) reading c_ginvw for the contacts' inverse weight where the
52
+ model has a table, else src unchanged."""
53
+ if table(m, geoms) is None:
54
+ return src
55
+ hit = 0
56
+ for old, new in HOOKS:
57
+ hit += src.count(old)
58
+ src = src.replace(old, new)
59
+ assert hit >= 2, "nablaengine.model.invweight: the contact inverse weight's expressions were not found"
60
+ rest = [ln for ln in src.splitlines() if "c_binvw[" in ln and not ln.startswith("DKC float c_binvw[")]
61
+ assert not rest, f"nablaengine.model.invweight: c_binvw is still read: {rest}"
62
+ return src
63
+
64
+
65
+ def fill(src, m):
66
+ """The field for a model m made from the model src by fusing jointless bodies into their parents (fusestatic; m's
67
+ bodies and geoms carry src's names, the fused bodies are absent from m): (field (m.ngeom,), values (m.ngeom,)) or
68
+ None when no geom's value would differ from its body's in float32 (also when nothing was fused). field: src's
69
+ body_invweight0[:, 0] for"""
70
+ present = {m.body(b).name for b in range(m.nbody)}
71
+ touched = set()
72
+ for b0 in range(1, src.nbody):
73
+ if src.body(b0).name in present:
74
+ continue
75
+ if not src.body(b0).name:
76
+ raise ValueError(f"invweight.fill: source body {b0} is unnamed and absent from the fused model")
77
+ touched.add(b0)
78
+ par = int(src.body_parentid[b0])
79
+ while par and src.body(par).name not in present:
80
+ par = int(src.body_parentid[par])
81
+ touched.add(par)
82
+ touched.discard(0)
83
+ if not touched:
84
+ return None
85
+ body = m.body_invweight0[m.geom_bodyid, 0]
86
+ values = body.copy()
87
+ field = np.full(m.ngeom, -1.0)
88
+ for g in range(m.ngeom):
89
+ g0 = mujoco.mj_name2id(src, mujoco.mjtObj.mjOBJ_GEOM, m.geom(g).name) if m.geom(g).name else -1
90
+ if g0 < 0:
91
+ raise ValueError(f"invweight.fill: geom {g} ({m.geom(g).name!r}) has no namesake in the source model")
92
+ b0 = int(src.geom_bodyid[g0])
93
+ v0 = src.body_invweight0[b0, 0]
94
+ if b0 in touched or np.float32(v0) != np.float32(body[g]):
95
+ values[g] = field[g] = v0
96
+ if (values.astype(np.float32) == body.astype(np.float32)).all():
97
+ return None
98
+ return field, values
99
+
100
+
101
+ def add(spec, field):
102
+ """spec with the field (fill's) as the custom numeric NUMERIC."""
103
+ spec.add_numeric(name=NUMERIC, size=len(field), data=list(map(float, field)))
104
+ return spec
105
+
106
+
107
+ def fill_spec(spec):
108
+ """fill for spec (fusestatic set) against the same spec compiled without fusestatic: (fill's result or None, the
109
+ fused model, in whose geom order the field is). Call it before spec's first compile: MuJoCo's fusestatic removes
110
+ the fused bodies from the spec itself when it compiles. Works on copies (unnamed bodies and geoms named there
111
+ only, to match them); spec is unchanged. Only the masses, inertias and kinematic tree matter (body_invweight0):
112
+ later edits of actuators, pairs, damping or contact parameters do not change the field."""
113
+ named = spec.copy()
114
+ for i, b in enumerate(named.bodies[1:]):
115
+ b.name = b.name or f"_body{i}"
116
+ for k, g in enumerate(named.geoms):
117
+ g.name = g.name or f"_geom{k}"
118
+ unfused = named.copy()
119
+ unfused.compiler.fusestatic = False
120
+ m0 = unfused.compile()
121
+ mf = named.compile()
122
+ return fill(m0, mf), mf
123
+
124
+
125
+ def attach(spec, filled, pairs_only=True):
126
+ """spec (compiled since fill_spec, its geoms unchanged) with fill_spec's field as the custom numeric NUMERIC:
127
+ (spec's compiled model, the values) or (spec's compiled model, None) without a field (spec unchanged).
128
+ pairs_only: the field only where it changes a contact pair's geom (the engines' table, table()); otherwise spec
129
+ stays as it was."""
130
+ m = spec.compile()
131
+ res, mf = filled
132
+ if res is not None and pairs_only:
133
+ g = sorted({int(x) for x in m.pair_geom1} | {int(x) for x in m.pair_geom2})
134
+ body = m.body_invweight0[m.geom_bodyid[g], 0]
135
+ if (res[1][g].astype(np.float32) == body.astype(np.float32)).all():
136
+ res = None
137
+ if res is None:
138
+ return m, None
139
+ assert m.ngeom == mf.ngeom and all(m.geom(g).name in ("", mf.geom(g).name) for g in range(m.ngeom)), \
140
+ "invweight.attach: the geoms changed since fill_spec"
141
+ assert np.array_equal(m.geom_bodyid, mf.geom_bodyid) and np.array_equal(m.geom_type, mf.geom_type)
142
+ add(spec, res[0])
143
+ m = spec.compile()
144
+ assert np.array_equal(geom_values(m), res[1])
145
+ return m, res[1]