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
nablaengine/terrain.py ADDED
@@ -0,0 +1,424 @@
1
+ """Terrain for the engine: static boxes and heightfields shared by every world."""
2
+ from dataclasses import dataclass, field
3
+
4
+ import mujoco
5
+ import numpy as np
6
+
7
+ BOX_WORDS = 15
8
+ HF_WORDS = 16
9
+ HF_INTS = 4
10
+ OBJ_WORDS = 15
11
+ OBJ_VEL_WORDS = 18
12
+ OBJ_MAT_WORDS = 7
13
+ TER_MAT_WORDS = 8
14
+ TER_MAT_MODES = {"none": 0, "max": 1, "override": 2}
15
+ TER_SAND_WORDS = 4
16
+ TER_MAT_SAND_WORDS = TER_MAT_WORDS + TER_SAND_WORDS
17
+ OBJ_E0 = 0xFF00
18
+ MAX_OBJECTS = 64
19
+
20
+
21
+ def pack_com(com, objects, velocities=None, materials=None):
22
+ """com (B, 3) and objects (B, K, OBJ_WORDS) -> the com input of a build with K object slots, (B, 3 + OBJ_WORDS K)
23
+ (NumPy, JAX or torch arrays; the concatenation of the library's namespace). velocities (B, K, OBJ_VEL_WORDS), a
24
+ build with TerrainConfig.object_velocity: each slot's motion words (TerrainConfig; slot_velocity), appended after
25
+ all slots: (B, 3 + (OBJ_WORDS + OBJ_VEL_WORDS) K). materials (B, K, OBJ_MAT_WORDS), a build with
26
+ TerrainConfig.object_material: each slot's contact material (slot_material), after the velocities."""
27
+ B = com.shape[0]
28
+ parts = ([com, objects.reshape(B, -1)] + ([] if velocities is None else [velocities.reshape(B, -1)])
29
+ + ([] if materials is None else [materials.reshape(B, -1)]))
30
+ if hasattr(com, "new_zeros"):
31
+ import torch
32
+ return torch.cat(parts, 1).contiguous()
33
+ try:
34
+ import jax.numpy as jnp
35
+ if not isinstance(com, np.ndarray):
36
+ return jnp.concatenate(parts, 1)
37
+ except ImportError:
38
+ pass
39
+ return np.concatenate(parts, 1)
40
+
41
+
42
+ def slot_velocity(v=(0.0, 0.0, 0.0), w=(0.0, 0.0, 0.0), s=(0.0, 0.0, 0.0), a=(0.0, 0.0, 0.0), al=(0.0, 0.0, 0.0),
43
+ sd=(0.0, 0.0, 0.0)):
44
+ """One slot's motion words (OBJ_VEL_WORDS,) for pack_com (TerrainConfig.object_velocity; NumPy), at the start of
45
+ the control step: v, w the slot's linear velocity at its position and angular velocity (world frame); s a surface
46
+ velocity in the slot's frame (its tangential part at each contact; the pose stays); a, al the linear and angular
47
+ acceleration (world frame); sd the rate of s. Within the control step the engine moves the slot and its velocities
48
+ with them (MuJoCo's semi-implicit Euler: v_k = v + k h a, pos_k = pos + h sum_{j<=k} v_j), and the contacts take
49
+ the slot's velocity and acceleration (a moving body's J v and J qacc in MuJoCo's contact rows)."""
50
+ return np.concatenate([np.asarray(x, np.float32) for x in (v, w, s, a, al, sd)])
51
+
52
+
53
+ def slot_material(friction=1.0, solref=(0.02, 1.0), solimp=(0.9, 0.95, 0.001, 0.5)):
54
+ """One slot's contact material (OBJ_MAT_WORDS,) for pack_com (TerrainConfig.object_material; NumPy): the sliding
55
+ friction mu, solref (time constant, damping ratio; or MuJoCo's direct form, each entry <= 0: -stiffness,
56
+ -damping) and solimp (dmin, dmax, width, midpoint; the power stays the terrain pairs' own) of every contact of the
57
+ slot, in place of the robot geom's terrain-pair parameters (and of the friction input / foot_solref / foot_solimp
58
+ for foot pairs). The defaults are MuJoCo's (geom friction 1, solref (0.02, 1), solimp (0.9, 0.95, 0.001, 0.5))."""
59
+ sr, si = np.asarray(solref, np.float32).reshape(2), np.asarray(solimp, np.float32).reshape(-1)
60
+ if si.size == 5:
61
+ si = si[:4]
62
+ if si.size != 4:
63
+ raise ValueError("slot_material: solimp (dmin, dmax, width, midpoint)")
64
+ return np.concatenate([np.asarray([friction], np.float32), sr, si])
65
+
66
+
67
+ def terrain_material(friction=1.0, mode="max", solref=(0.02, 1.0), solimp=(0.9, 0.95, 0.001, 0.5), sand=None):
68
+ """One terrain element's material (TER_MAT_WORDS,) for Terrain.material (TerrainConfig.terrain_material; NumPy);
69
+ with sand (sand_fields(), or its arguments as a tuple (k, s_max, yield_force, rate)) the row of TER_MAT_SAND_WORDS
70
+ with the sand fields after the material (TerrainConfig.terrain_sand).
71
+ mode "max": the element's contacts take max(the robot side's friction, friction), as MuJoCo mixes two geoms'
72
+ frictions (the robot side: the geom's floor pair's mu, or for a foot pair the per-world friction input); solref /
73
+ solimp stay the pair's. mode "override": the contacts take friction, solref and solimp outright (the friction input
74
+ and foot_solref / foot_solimp included), as MuJoCo does for a geom of higher priority. mode "none": the pair's
75
+ parameters (the default of every element)."""
76
+ if mode not in TER_MAT_MODES:
77
+ raise ValueError(f"terrain_material: mode {mode!r}: one of {tuple(TER_MAT_MODES)}")
78
+ sr, si = np.asarray(solref, np.float32).reshape(2), np.asarray(solimp, np.float32).reshape(-1)[:4]
79
+ row = np.concatenate([np.asarray([friction], np.float32), sr, si, np.asarray([TER_MAT_MODES[mode]], np.float32)])
80
+ if sand is None:
81
+ return row
82
+ sd = np.asarray(sand, np.float32).reshape(-1)
83
+ if sd.size != TER_SAND_WORDS:
84
+ raise ValueError("terrain_material: sand (k, s_max, yield_force, rate)")
85
+ return np.concatenate([row, sand_fields(*sd)])
86
+
87
+
88
+ def sand_fields(k=1.0, s_max=0.0, yield_force=0.0, rate=0.0):
89
+ """One element's sand fields (TER_SAND_WORDS,): k in [0, 1] (0 hard ground, 1 full sand: TerrainConfig.terrain_sand),
90
+ s_max (m), the yield force F_y (body weights per foot) and the sinkage rate (m/s per body weight of normal force
91
+ above the yield). The engine applies k (the foot_offset sinkage k s(x)); it returns s_max, F_y and the rate per foot
92
+ (contact_table's foot_sand_params) without using them."""
93
+ v = np.asarray([k, s_max, yield_force, rate], np.float64)
94
+ if not 0.0 <= v[0] <= 1.0 or (v[1:] < 0).any() or not np.isfinite(v).all():
95
+ raise ValueError(f"sand_fields: k in [0, 1], s_max / yield_force / rate >= 0 (got {v.tolist()})")
96
+ return v.astype(np.float32)
97
+
98
+
99
+ def box_object(pos, rot, half):
100
+ """One object slot (OBJ_WORDS,) from a position, a rotation matrix (3, 3) and half sizes (NumPy)."""
101
+ return np.concatenate([np.asarray(pos, np.float32), np.asarray(rot, np.float32).reshape(9),
102
+ np.asarray(half, np.float32)])
103
+
104
+
105
+ @dataclass
106
+ class TerrainConfig:
107
+ """Compile-time terrain options. geoms: "feet" (the robot geoms of the foot-floor pairs), "body" (every robot
108
+ geom with a floor pair) or a list of robot geoms (names or geom ids; each needs a floor pair, whose parameters its
109
+ terrain contacts take). The terrain broad phase handles one geom per lane of a warp: up to 32 geoms take one pass,
110
+ more a second (the G1's "body" has 33: a list of at most 32 avoids the second pass); floor: keep the model's floor plane pairs too (a terrain usually has its own ground);
111
+ cap_points: heightfield samples per capsule; mode: heightfield contacts, "analytic"
112
+ (sample points against the triangle below) or "native" (MuJoCo's prisms, each measured
113
+ exactly, at most 4 contacts per geom and heightfield: step.py, TERRAIN_HF_NATIVE); maxcon: contact capacity per
114
+ world (None: the model's, step.maxcon); objects: per-world box slots (OBJ_WORDS floats each: pos, rot row major, half
115
+ sizes; half size 0 = absent) given with each step after the COM offset, com (B, 3 + OBJ_WORDS objects): kinematic
116
+ obstacles / targets whose poses the caller sets per world at any step (no recompilation), colliding with the same
117
+ robot geoms as the terrain (pack_com); object_velocity (forest engine): each slot also has motion words
118
+ (OBJ_VEL_WORDS, pack_com's velocities, slot_velocity): v, w the slot's rigid velocity (world frame, v at its
119
+ position), s a surface velocity in the slot's frame, a, al the rigid motion's accelerations, sd the rate of s.
120
+ Within a control step the engine moves the slot with them (semi-implicit Euler per substep; the caller sets the
121
+ next step's pose), and at a contact point p its surface moves with u = v + w x (p - pos) + the tangential part of
122
+ R s and accelerates with a + al x (p - pos) + the tangential part of R sd: the contact rows act on the robot's
123
+ motion relative to the slot's (a moving platform, a pusher: (v, w, a, al); a conveyor belt or an escalator: a
124
+ fixed pose and s, sd). Off: the slots are at rest (the default; the build and com layout unchanged).
125
+ terrain_material (forest engine): the static terrain's elements may carry a material (Terrain.material,
126
+ terrain_material: friction mixed as MuJoCo's max, or friction / solref / solimp overriding, as a geom of higher
127
+ priority); not differentiable (the terrain is static). Off: every element takes the pair's parameters (the default;
128
+ the build unchanged).
129
+ object_material (forest engine): each slot also has its contact material (OBJ_MAT_WORDS, pack_com's materials,
130
+ slot_material: friction mu, solref, solimp) per world, used by every contact of the slot in place of the terrain
131
+ pair's; the step's gradients include the words' cotangents. Off: the slots' contacts take the terrain pairs'
132
+ parameters (the default; the build and com layout unchanged).
133
+ terrain_sand (forest engine, with the foot_offset parameter): the elements' material rows
134
+ carry sand fields (TER_MAT_SAND_WORDS: terrain_material(sand=...), sand_fields: k, s_max, F_y, rate; 8-word rows
135
+ and elements without a row are hard ground, k = 0): a foot contact on element e takes the distance d + k_e s(x),
136
+ s(x) the per-world foot_offset; contact_table splits foot_normal into the sand and hard parts and returns the feet's
137
+ sand presence and sand parameters (docs/terrain.md). sand_other: (k, s_max, F_y, rate) of the foot contacts with
138
+ anything other than a terrain element (the floor plane, the object slots): k = 1 (the default) keeps foot_offset's
139
+ behaviour there. The material words (friction, solref, solimp, mode) act only with terrain_material as well (without
140
+ it, as there, every mode must be "none"). k is piecewise per element (no blend at element edges; a ledge in the
141
+ support of k s at a sand / hard boundary, physical). Off: the build unchanged."""
142
+ geoms: object = "feet"
143
+ floor: bool = False
144
+ cap_points: int = 3
145
+ mode: str = "analytic"
146
+ maxcon: int = None
147
+ objects: int = 0
148
+ object_velocity: bool = False
149
+ object_material: bool = False
150
+ terrain_material: bool = False
151
+ terrain_sand: bool = False
152
+ sand_other: tuple = (1.0, 0.0, 0.0, 0.0)
153
+
154
+ def __post_init__(self):
155
+ if isinstance(self.geoms, str):
156
+ if self.geoms not in ("feet", "body"):
157
+ raise ValueError(f"TerrainConfig.geoms {self.geoms!r}: 'feet', 'body' or a list of geom names / ids")
158
+ else:
159
+ try:
160
+ gs = list(self.geoms)
161
+ except TypeError:
162
+ raise ValueError(f"TerrainConfig.geoms {self.geoms!r}: 'feet', 'body' or a list of geom names / ids")
163
+ if not gs or not all(isinstance(g, str) or (isinstance(g, (int, np.integer)) and not isinstance(g, bool))
164
+ for g in gs):
165
+ raise ValueError(f"TerrainConfig.geoms {self.geoms!r}: a non-empty list of geom names (str) or ids (int)")
166
+ self.geoms = tuple(g if isinstance(g, str) else int(g) for g in gs)
167
+ if not 0 <= int(self.objects) <= MAX_OBJECTS:
168
+ raise ValueError(f"TerrainConfig.objects {self.objects}: 0 .. {MAX_OBJECTS}")
169
+ if self.object_velocity and not int(self.objects):
170
+ raise ValueError("TerrainConfig.object_velocity: needs object slots (objects > 0)")
171
+ if self.object_material and not int(self.objects):
172
+ raise ValueError("TerrainConfig.object_material: needs object slots (objects > 0)")
173
+ if self.mode not in ("analytic", "native"):
174
+ raise ValueError(f"TerrainConfig.mode {self.mode!r}: 'analytic' (sample points) or 'native' (prisms)")
175
+ self.sand_other = tuple(float(x) for x in sand_fields(*self.sand_other))
176
+
177
+ def key(self):
178
+ k = dict(geoms=self.geoms if isinstance(self.geoms, str) else list(self.geoms), floor=self.floor, cap_points=self.cap_points, mode=self.mode,
179
+ maxcon=self.maxcon)
180
+ if self.objects:
181
+ k["objects"] = int(self.objects)
182
+ if self.object_velocity:
183
+ k["object_velocity"] = True
184
+ if self.object_material:
185
+ k["object_material"] = True
186
+ if self.terrain_material:
187
+ k["terrain_material"] = True
188
+ if self.terrain_sand:
189
+ k["terrain_sand"] = True
190
+ k["sand_other"] = list(self.sand_other)
191
+ return k
192
+
193
+ def velocity_words(self):
194
+ """Floats per world of the slots' velocities (object_velocity: OBJ_VEL_WORDS per slot), else 0."""
195
+ return OBJ_VEL_WORDS * int(self.objects) if self.object_velocity else 0
196
+
197
+ def material_words(self):
198
+ """Floats per world of the slots' contact materials (object_material: OBJ_MAT_WORDS per slot), else 0."""
199
+ return OBJ_MAT_WORDS * int(self.objects) if self.object_material else 0
200
+
201
+ def com_words(self):
202
+ """Floats per world of the com input: the COM offset (3), the object slots, their velocities and materials."""
203
+ return 3 + (OBJ_WORDS + (OBJ_VEL_WORDS if self.object_velocity else 0)) * int(self.objects) + self.material_words()
204
+
205
+
206
+ @dataclass
207
+ class Terrain:
208
+ """Static terrain data in world coordinates (float64 here, float32 on the device)."""
209
+ boxes: np.ndarray = field(default_factory=lambda: np.zeros((0, BOX_WORDS)))
210
+ hf_head: np.ndarray = field(default_factory=lambda: np.zeros((0, HF_WORDS)))
211
+ hf_int: np.ndarray = field(default_factory=lambda: np.zeros((0, HF_INTS), np.int64))
212
+ hf_data: np.ndarray = field(default_factory=lambda: np.zeros(0))
213
+ material: np.ndarray = None
214
+
215
+ @staticmethod
216
+ def from_model(m, d=None):
217
+ """The static box and hfield geoms of MjModel m: those of the world body and of bodies welded to it (mjlab's
218
+ "terrain" body; poses from mj_kinematics on d, or a fresh MjData)."""
219
+ if d is None:
220
+ d = mujoco.MjData(m)
221
+ mujoco.mj_kinematics(m, d)
222
+ boxes, head, ints, data = [], [], [], []
223
+ adr = 0
224
+ for g in range(m.ngeom):
225
+ if m.body_weldid[m.geom_bodyid[g]] != 0:
226
+ continue
227
+ t = int(m.geom_type[g])
228
+ pos, rot = d.geom_xpos[g].copy(), d.geom_xmat[g].copy()
229
+ if t == mujoco.mjtGeom.mjGEOM_BOX:
230
+ boxes.append(np.concatenate([pos, rot, m.geom_size[g]]))
231
+ elif t == mujoco.mjtGeom.mjGEOM_HFIELD:
232
+ h = int(m.geom_dataid[g])
233
+ nrow, ncol = int(m.hfield_nrow[h]), int(m.hfield_ncol[h])
234
+ a = int(m.hfield_adr[h])
235
+ head.append(np.concatenate([pos, rot, m.hfield_size[h]]))
236
+ ints.append([nrow, ncol, adr, 0])
237
+ data.append(m.hfield_data[a:a + nrow * ncol])
238
+ adr += nrow * ncol
239
+ t = Terrain()
240
+ if boxes:
241
+ t.boxes = np.asarray(boxes, np.float64)
242
+ if head:
243
+ t.hf_head, t.hf_int = np.asarray(head, np.float64), np.asarray(ints, np.int64)
244
+ t.hf_data = np.concatenate(data).astype(np.float64)
245
+ return t
246
+
247
+ def save(self, path):
248
+ """Write the terrain to an .npz file (load() reads it back)."""
249
+ np.savez(path, boxes=self.boxes, hf_head=self.hf_head, hf_int=self.hf_int, hf_data=self.hf_data,
250
+ **({"material": self.material} if self.material is not None else {}))
251
+
252
+ @staticmethod
253
+ def load(path):
254
+ z = np.load(path)
255
+ return Terrain(boxes=z["boxes"], hf_head=z["hf_head"], hf_int=z["hf_int"], hf_data=z["hf_data"],
256
+ material=z["material"] if "material" in z.files else None)
257
+
258
+ def add_to_spec(self, spec, prefix="ter"):
259
+ """Add the terrain to an MjSpec's world body as box and hfield geoms (the reverse of from_model, e.g. for a
260
+ MuJoCo / MuJoCo Warp reference scene); returns the geom names."""
261
+ import mujoco
262
+ names = []
263
+ wb = spec.worldbody
264
+ for i, b in enumerate(self.boxes):
265
+ q = np.zeros(4)
266
+ mujoco.mju_mat2Quat(q, np.asarray(b[3:12], np.float64))
267
+ n = f"{prefix}_box{i}"
268
+ wb.add_geom(name=n, type=mujoco.mjtGeom.mjGEOM_BOX, size=b[12:15].tolist(), pos=b[:3].tolist(), quat=q.tolist())
269
+ names.append(n)
270
+ for j, (h, hi) in enumerate(zip(self.hf_head, self.hf_int)):
271
+ nrow, ncol, adr = int(hi[0]), int(hi[1]), int(hi[2])
272
+ n = f"{prefix}_hf{j}"
273
+ spec.add_hfield(name=n, size=h[12:16].tolist(), nrow=nrow, ncol=ncol,
274
+ userdata=self.hf_data[adr:adr + nrow * ncol].tolist())
275
+ q = np.zeros(4)
276
+ mujoco.mju_mat2Quat(q, np.asarray(h[3:12], np.float64))
277
+ wb.add_geom(name=n, type=mujoco.mjtGeom.mjGEOM_HFIELD, hfieldname=n, pos=h[:3].tolist(), quat=q.tolist())
278
+ names.append(n)
279
+ return names
280
+
281
+ def _material_rows(self):
282
+ n = len(self.boxes) + len(self.hf_head)
283
+ if self.material is None:
284
+ return None
285
+ a = np.asarray(self.material, np.float32)
286
+ if a.ndim != 2 or a.shape[1] not in (TER_MAT_WORDS, TER_MAT_SAND_WORDS):
287
+ raise ValueError(f"Terrain.material: rows of {TER_MAT_WORDS} words (terrain_material) or "
288
+ f"{TER_MAT_SAND_WORDS} (with the sand fields), got shape {a.shape}")
289
+ if len(a) != n:
290
+ raise ValueError(f"Terrain.material: {len(a)} rows for {n} elements (the boxes, then the heightfields)")
291
+ if a.shape[1] == TER_MAT_WORDS:
292
+ a = np.concatenate([a, np.zeros((n, TER_SAND_WORDS), np.float32)], 1)
293
+ return a
294
+
295
+ def material_array(self):
296
+ """(n elements, TER_MAT_WORDS) float32: Terrain.material's material words, mode 0 (none) where it is None."""
297
+ n = len(self.boxes) + len(self.hf_head)
298
+ a = self._material_rows()
299
+ if a is None:
300
+ return np.zeros((n, TER_MAT_WORDS), np.float32)
301
+ a = np.ascontiguousarray(a[:, :TER_MAT_WORDS])
302
+ if not np.isin(a[:, 7], (0, 1, 2)).all():
303
+ raise ValueError("Terrain.material: mode words 0, 1 or 2 (terrain_material)")
304
+ return a
305
+
306
+ def sand_array(self):
307
+ """(n elements, TER_SAND_WORDS) float32: the elements' sand fields (k, s_max, F_y, rate); 0 (hard ground) for
308
+ 8-word rows or material None."""
309
+ n = len(self.boxes) + len(self.hf_head)
310
+ a = self._material_rows()
311
+ if a is None:
312
+ return np.zeros((n, TER_SAND_WORDS), np.float32)
313
+ sd = np.ascontiguousarray(a[:, TER_MAT_WORDS:])
314
+ if not (np.isfinite(sd).all() and (sd[:, 0] >= 0).all() and (sd[:, 0] <= 1).all() and (sd[:, 1:] >= 0).all()):
315
+ raise ValueError("Terrain.material: sand fields k in [0, 1], s_max / yield / rate >= 0 (sand_fields)")
316
+ return sd
317
+
318
+ def material_upload(self, cfg=None):
319
+ """The device's element words for a build's TerrainConfig (or its key() dict): (n, 8) material words; with
320
+ terrain_sand (n, 12) the material and sand fields."""
321
+ get = (cfg.get if isinstance(cfg, dict) else (lambda k, d=None: getattr(cfg, k, d))) if cfg is not None else \
322
+ (lambda k, d=None: d)
323
+ mat = self.material_array()
324
+ if not get("terrain_sand", False):
325
+ return mat
326
+ return np.ascontiguousarray(np.concatenate([mat, self.sand_array()], 1).astype(np.float32))
327
+
328
+ def element_aabbs(self):
329
+ """(n, 4) xmin, ymin, xmax, ymax of the elements: the boxes, then the heightfields."""
330
+ out = []
331
+ for b in self.boxes:
332
+ R, hs = b[3:12].reshape(3, 3), b[12:15]
333
+ ext = np.abs(R) @ hs
334
+ out.append([b[0] - ext[0], b[1] - ext[1], b[0] + ext[0], b[1] + ext[1]])
335
+ for h in self.hf_head:
336
+ R, sz = h[3:12].reshape(3, 3), h[12:16]
337
+ ext = np.abs(R[:2, :2]) @ sz[:2]
338
+ out.append([h[0] - ext[0], h[1] - ext[1], h[0] + ext[0], h[1] + ext[1]])
339
+ return np.asarray(out, np.float64).reshape(-1, 4)
340
+
341
+ def pack(self, cell=1.0):
342
+ """Device arrays: boxes float32 (nbox, 15), heightfield headers float32 (nhf, 16) and ints int32 (nhf, 4), data
343
+ float32, and the broad-phase grid: grid float32 [x0, y0, 1 / cell, nx, ny, nbox], cell_start int32 (nx ny + 1),
344
+ cell_items int32 (element index: box i, or nbox + heightfield j), elem_cell int32 (n, 2): the element's first
345
+ cell (cx, cy)."""
346
+ aabb = self.element_aabbs()
347
+ nbox = len(self.boxes)
348
+ if len(aabb) >= OBJ_E0:
349
+ raise ValueError(f"{len(aabb)} terrain elements: at most {OBJ_E0 - 1} (the tape's 16-bit element index, "
350
+ "the per-world objects above)")
351
+ if len(aabb):
352
+ x0, y0 = aabb[:, 0].min() - 1e-3, aabb[:, 1].min() - 1e-3
353
+ nx = max(1, int(np.ceil((aabb[:, 2].max() - x0) / cell)) + 1)
354
+ ny = max(1, int(np.ceil((aabb[:, 3].max() - y0) / cell)) + 1)
355
+ else:
356
+ x0 = y0 = 0.0
357
+ nx = ny = 1
358
+ lists = [[] for _ in range(nx * ny)]
359
+ first = np.zeros((len(aabb), 2), np.int32)
360
+ for e, (a0, b0, a1, b1) in enumerate(aabb):
361
+ c0, c1 = int((a0 - x0) / cell), min(nx - 1, int((a1 - x0) / cell))
362
+ r0, r1 = int((b0 - y0) / cell), min(ny - 1, int((b1 - y0) / cell))
363
+ first[e] = (c0, r0)
364
+ for r in range(r0, r1 + 1):
365
+ for c in range(c0, c1 + 1):
366
+ lists[r * nx + c].append(e)
367
+ start = np.zeros(nx * ny + 1, np.int32)
368
+ start[1:] = np.cumsum([len(x) for x in lists])
369
+ items = np.asarray([e for x in lists for e in x] or [0], np.int32)
370
+ return dict(boxes=np.asarray(self.boxes, np.float32).reshape(-1, BOX_WORDS),
371
+ hf_head=np.asarray(self.hf_head, np.float32).reshape(-1, HF_WORDS),
372
+ hf_int=np.asarray(self.hf_int, np.int32).reshape(-1, HF_INTS),
373
+ hf_data=np.asarray(self.hf_data, np.float32).reshape(-1),
374
+ grid=np.asarray([x0, y0, 1.0 / cell, nx, ny, nbox], np.float32),
375
+ cell_start=start, cell_items=items, elem_cell=first.reshape(-1, 2),
376
+ material=self.material_array(), sand=self.sand_array())
377
+
378
+
379
+ def _geom_ids(m, geoms):
380
+ out = []
381
+ for g in geoms:
382
+ if isinstance(g, str):
383
+ gid = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_GEOM, g)
384
+ if gid < 0:
385
+ raise ValueError(f"TerrainConfig.geoms: no geom named {g!r} in the model")
386
+ else:
387
+ gid = int(g)
388
+ if not 0 <= gid < m.ngeom:
389
+ raise ValueError(f"TerrainConfig.geoms: geom id {gid} out of range (the model has {m.ngeom} geoms)")
390
+ out.append(gid)
391
+ return out
392
+
393
+
394
+ def robot_terrain_geoms(m, foot_pairs, which):
395
+ """[(robot geom, its floor pair index, foot flag)] of the geoms that collide with the terrain: which = "feet" (the
396
+ foot-floor pairs' robot geoms), "body" (every robot geom with a floor pair) or a list of geom names / ids (each
397
+ with a floor pair), in floor-pair order."""
398
+ foot = set(int(p) for p in foot_pairs)
399
+ sel = None
400
+ if not isinstance(which, str):
401
+ sel = set(_geom_ids(m, which))
402
+ elif which not in ("feet", "body"):
403
+ raise ValueError(f"terrain geoms {which!r}: 'feet', 'body' or a list of geom names / ids")
404
+ out = []
405
+ for p in range(m.npair):
406
+ g1, g2 = int(m.pair_geom1[p]), int(m.pair_geom2[p])
407
+ t1, t2 = int(m.geom_type[g1]), int(m.geom_type[g2])
408
+ if mujoco.mjtGeom.mjGEOM_PLANE not in (t1, t2):
409
+ continue
410
+ g = g2 if t1 == mujoco.mjtGeom.mjGEOM_PLANE else g1
411
+ if (sel is None and which == "feet" and p not in foot) or (sel is not None and g not in sel):
412
+ continue
413
+ if int(m.geom_type[g]) not in (mujoco.mjtGeom.mjGEOM_SPHERE, mujoco.mjtGeom.mjGEOM_CAPSULE,
414
+ mujoco.mjtGeom.mjGEOM_BOX):
415
+ raise ValueError(f"terrain contacts of robot geom {m.geom(g).name or g} "
416
+ f"({mujoco.mjtGeom(int(m.geom_type[g])).name}): only spheres, capsules and boxes collide "
417
+ "with the terrain (TerrainConfig.geoms='feet' when only the feet are)")
418
+ out.append((g, p, int(p in foot)))
419
+ if sel is not None:
420
+ missing = sel - {g for g, _, _ in out}
421
+ if missing:
422
+ raise ValueError("TerrainConfig.geoms: " + ", ".join(repr(m.geom(g).name or g) for g in sorted(missing))
423
+ + " without a floor pair (a terrain geom takes its floor pair's contact parameters)")
424
+ return out