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/params.py ADDED
@@ -0,0 +1,258 @@
1
+ """Per-world physics parameters: model values that each world (environment) sets in its step's input, for domain
2
+ randomization. Chosen at build time: PhysicsParams(fields) passed as init(..., params=) of jax_ffi / torch_ffi; a build
3
+ without them is unchanged."""
4
+ from dataclasses import dataclass
5
+
6
+ import numpy as np
7
+
8
+ WIDTHS = {"foot_solref": 2, "foot_solimp": 4, "dof_damping": "nv", "dof_armature": "nv", "dof_frictionloss": "nv",
9
+ "frictionloss_solref": 2, "frictionloss_solimp": 4, "torso_mass": 1,
10
+ "torso_inertia": 3, "foot_torsional": 1, "object_size": 3, "gravity": 3, "xfrc": "xfrc",
11
+ "body_inertial": "inertial", "sole_thickness": 1, "foot_offset": 4}
12
+ XFRC_WORDS = 9
13
+ INERTIAL_WORDS = 7
14
+ INVWEIGHT0 = ("model", "per_world", "per_world_mass")
15
+ FOOT_BODIES = ("left_ankle_roll_link", "right_ankle_roll_link")
16
+ FOOT_LINE = (-0.064, 0.142)
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class PhysicsParams:
21
+ fields: tuple = ()
22
+ size_geom: object = None
23
+ object_size_max: tuple = None
24
+ xfrc_bodies: tuple = ()
25
+ inertial_bodies: tuple = ()
26
+ sole_geoms: tuple = ()
27
+ sole_normal: tuple = None
28
+ invweight0: str = "model"
29
+ foot_bodies: tuple = ()
30
+ foot_line: tuple = None
31
+ foot_axis: tuple = None
32
+
33
+ def __post_init__(self):
34
+ f = tuple(self.fields)
35
+ bad = [x for x in f if x not in WIDTHS]
36
+ if bad or len(set(f)) != len(f):
37
+ raise ValueError(f"PhysicsParams fields {f}: each of {tuple(WIDTHS)} at most once")
38
+ object.__setattr__(self, "fields", tuple(x for x in WIDTHS if x in f))
39
+ if "object_size" in f:
40
+ if self.object_size_max is None:
41
+ raise ValueError("PhysicsParams object_size: object_size_max=(x, y, z), the largest half-extents of "
42
+ "any world, is required (the collision bounds are built for it)")
43
+ mx = tuple(float(x) for x in np.broadcast_to(np.asarray(self.object_size_max, np.float64), (3,)))
44
+ if not all(np.isfinite(x) and x > 0 for x in mx):
45
+ raise ValueError(f"PhysicsParams object_size_max={self.object_size_max}: three positive numbers")
46
+ object.__setattr__(self, "object_size_max", mx)
47
+ if isinstance(self.size_geom, (np.integer, int)) and not isinstance(self.size_geom, bool):
48
+ object.__setattr__(self, "size_geom", int(self.size_geom))
49
+ elif self.size_geom is not None and not isinstance(self.size_geom, str):
50
+ raise ValueError(f"PhysicsParams size_geom={self.size_geom!r}: a geom name or id")
51
+ elif self.size_geom is not None or self.object_size_max is not None:
52
+ raise ValueError("PhysicsParams size_geom / object_size_max belong to the object_size field")
53
+ xb = (self.xfrc_bodies,) if isinstance(self.xfrc_bodies, (str, int, np.integer)) else tuple(self.xfrc_bodies)
54
+ xb = tuple(int(x) if isinstance(x, (int, np.integer)) and not isinstance(x, bool) else x for x in xb)
55
+ if "xfrc" in f:
56
+ if not xb or not all(isinstance(x, (str, int)) and not isinstance(x, bool) for x in xb):
57
+ raise ValueError(f"PhysicsParams xfrc: xfrc_bodies={self.xfrc_bodies!r} must name one or more bodies "
58
+ "(names or model ids)")
59
+ if len(set(xb)) != len(xb):
60
+ raise ValueError(f"PhysicsParams xfrc_bodies={xb}: a body more than once")
61
+ elif xb:
62
+ raise ValueError("PhysicsParams xfrc_bodies belongs to the xfrc field")
63
+ object.__setattr__(self, "xfrc_bodies", xb)
64
+ ib = _ids(self.inertial_bodies)
65
+ if "body_inertial" in f:
66
+ if not ib or not all(isinstance(x, (str, int)) and not isinstance(x, bool) for x in ib):
67
+ raise ValueError(f"PhysicsParams body_inertial: inertial_bodies={self.inertial_bodies!r} must name one "
68
+ "or more bodies (names or model ids)")
69
+ if len(set(ib)) != len(ib):
70
+ raise ValueError(f"PhysicsParams inertial_bodies={ib}: a body more than once")
71
+ elif ib:
72
+ raise ValueError("PhysicsParams inertial_bodies belongs to the body_inertial field")
73
+ object.__setattr__(self, "inertial_bodies", ib)
74
+ sg = _ids(self.sole_geoms)
75
+ if "sole_thickness" in f:
76
+ if not all(isinstance(x, (str, int)) and not isinstance(x, bool) for x in sg) or len(set(sg)) != len(sg):
77
+ raise ValueError(f"PhysicsParams sole_geoms={self.sole_geoms!r}: distinct geom names or ids")
78
+ n = (0.0, 0.0, -1.0) if self.sole_normal is None else tuple(
79
+ float(x) for x in np.broadcast_to(np.asarray(self.sole_normal, np.float64), (3,)))
80
+ if not (np.all(np.isfinite(n)) and abs(np.linalg.norm(n) - 1.0) < 1e-6):
81
+ raise ValueError(f"PhysicsParams sole_normal={self.sole_normal}: a unit vector")
82
+ object.__setattr__(self, "sole_normal", n)
83
+ elif sg or self.sole_normal is not None:
84
+ raise ValueError("PhysicsParams sole_geoms / sole_normal belong to the sole_thickness field")
85
+ object.__setattr__(self, "sole_geoms", sg)
86
+ fb = _ids(self.foot_bodies)
87
+ if "foot_offset" in f:
88
+ fb = fb or FOOT_BODIES
89
+ if len(fb) != 2 or len(set(fb)) != 2 or not all(isinstance(x, (str, int)) and not isinstance(x, bool)
90
+ for x in fb):
91
+ raise ValueError(f"PhysicsParams foot_bodies={self.foot_bodies!r}: two distinct bodies (left, right), "
92
+ "names or ids")
93
+ ln = FOOT_LINE if self.foot_line is None else tuple(float(x) for x in np.asarray(self.foot_line).ravel())
94
+ if len(ln) != 2 or not (np.all(np.isfinite(ln)) and ln[1] > ln[0]):
95
+ raise ValueError(f"PhysicsParams foot_line={self.foot_line}: (heel, toe) with heel < toe")
96
+ ax = (1.0, 0.0, 0.0) if self.foot_axis is None else tuple(
97
+ float(x) for x in np.broadcast_to(np.asarray(self.foot_axis, np.float64), (3,)))
98
+ if not (np.all(np.isfinite(ax)) and abs(np.linalg.norm(ax) - 1.0) < 1e-6):
99
+ raise ValueError(f"PhysicsParams foot_axis={self.foot_axis}: a unit vector")
100
+ object.__setattr__(self, "foot_line", tuple(float(x) for x in ln))
101
+ object.__setattr__(self, "foot_axis", ax)
102
+ elif fb or self.foot_line is not None or self.foot_axis is not None:
103
+ raise ValueError("PhysicsParams foot_bodies / foot_line / foot_axis belong to the foot_offset field")
104
+ object.__setattr__(self, "foot_bodies", fb)
105
+ if self.invweight0 not in INVWEIGHT0:
106
+ raise ValueError(f"PhysicsParams invweight0={self.invweight0!r}: one of {INVWEIGHT0}")
107
+ if self.invweight0 != "model" and not f:
108
+ raise ValueError(f"PhysicsParams invweight0={self.invweight0!r} needs a parameter build (one or more fields)")
109
+
110
+ def __bool__(self):
111
+ return bool(self.fields)
112
+
113
+ def layout(self, nv):
114
+ """{field: (offset, width)} within the per-world parameter block."""
115
+ out, o = {}, 0
116
+ for f in self.fields:
117
+ w = (nv if WIDTHS[f] == "nv" else XFRC_WORDS * len(self.xfrc_bodies) if WIDTHS[f] == "xfrc"
118
+ else INERTIAL_WORDS * len(self.inertial_bodies) if WIDTHS[f] == "inertial" else WIDTHS[f])
119
+ out[f] = (o, w)
120
+ o += w
121
+ return out
122
+
123
+ def width(self, nv):
124
+ return sum(w for _, w in self.layout(nv).values())
125
+
126
+ def key(self):
127
+ """The build's key: the field names, and with object_size its geom and maximum, with xfrc its bodies, with
128
+ body_inertial its bodies, with sole_thickness its geoms and normal, with foot_offset its feet, line and axis,
129
+ and a per-world invweight0 (as the last entry)."""
130
+ extra = {}
131
+ if "object_size" in self.fields:
132
+ extra.update(size_geom=self.size_geom, object_size_max=list(self.object_size_max))
133
+ if "xfrc" in self.fields:
134
+ extra.update(xfrc_bodies=list(self.xfrc_bodies))
135
+ if "body_inertial" in self.fields:
136
+ extra.update(inertial_bodies=list(self.inertial_bodies))
137
+ if "sole_thickness" in self.fields:
138
+ extra.update(sole_geoms=list(self.sole_geoms), sole_normal=list(self.sole_normal))
139
+ if "foot_offset" in self.fields:
140
+ extra.update(foot_bodies=list(self.foot_bodies), foot_line=list(self.foot_line),
141
+ foot_axis=list(self.foot_axis))
142
+ if self.invweight0 != "model":
143
+ extra.update(invweight0=self.invweight0)
144
+ return list(self.fields) + ([extra] if extra else [])
145
+
146
+ def pack(self, nv, **values):
147
+ """The per-world parameter block (B, width(nv)) float32 from arrays by field name ((B, width) or a broadcastable
148
+ shape); every field of the build is required."""
149
+ lay = self.layout(nv)
150
+ missing = [f for f in lay if f not in values]
151
+ extra = [f for f in values if f not in lay]
152
+ if missing or extra:
153
+ raise ValueError(f"PhysicsParams.pack: missing {missing}, not in this build {extra}")
154
+ B = max(np.shape(np.atleast_2d(v))[0] for v in values.values())
155
+ out = np.zeros((B, self.width(nv)), np.float32)
156
+ for f, (o, w) in lay.items():
157
+ out[:, o:o + w] = np.broadcast_to(np.asarray(values[f], np.float32).reshape(-1, w), (B, w))
158
+ if "dof_frictionloss" in lay:
159
+ o, w = lay["dof_frictionloss"]
160
+ if not np.all(out[:, o:o + w] >= 0):
161
+ raise ValueError("PhysicsParams.pack: dof_frictionloss below 0")
162
+ if "frictionloss_solref" in lay:
163
+ o, w = lay["frictionloss_solref"]
164
+ if not np.all(out[:, o:o + w] > 0):
165
+ raise ValueError("PhysicsParams.pack: frictionloss_solref takes the standard form (both entries > 0)")
166
+ if "object_size" in lay:
167
+ o, w = lay["object_size"]
168
+ sz = out[:, o:o + w]
169
+ if not (np.all(sz > 0) and np.all(sz <= np.float32(self.object_size_max) * np.float32(1 + 1e-6))):
170
+ raise ValueError(f"PhysicsParams.pack: object_size outside (0, object_size_max={self.object_size_max}]")
171
+ if "foot_offset" in lay:
172
+ o, w = lay["foot_offset"]
173
+ if not np.all(out[:, o:o + w] >= 0):
174
+ raise ValueError("PhysicsParams.pack: foot_offset must be >= 0 (a support lowered under the foot; the "
175
+ "forest engine's contacts have margin 0)")
176
+ return out
177
+
178
+ def defaults(self, m, foot_pairs, com_body=None):
179
+ """The model's own values per field (one world), e.g. as pack(**defaults) for an unchanged world (com_body: the
180
+ torso fields' body, default the G1's, and object_size's default body; the foot fields take the first foot
181
+ pair's; gravity: opt.gravity; xfrc: zero wrenches, each point at its body's COM, body_ipos; body_inertial: each
182
+ body's body_mass, body_inertia and a zero COM offset, (k, 7); sole_thickness: 0; foot_offset: zeros)."""
183
+ import mujoco
184
+ from nablaengine.g1_engine import source
185
+ fp = list(foot_pairs)
186
+ if not fp and {"foot_solref", "foot_solimp", "foot_torsional"} & set(self.fields):
187
+ raise ValueError("PhysicsParams.defaults: the foot fields need foot pairs")
188
+ out = {}
189
+ if "torso_mass" in self.fields or "torso_inertia" in self.fields:
190
+ b = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, com_body or source.COM_BODY)
191
+ if b < 1:
192
+ raise ValueError(f"PhysicsParams.defaults: no body {com_body or source.COM_BODY!r}")
193
+ if "torso_mass" in self.fields:
194
+ out["torso_mass"] = np.asarray([m.body_mass[b]], np.float32)
195
+ if "torso_inertia" in self.fields:
196
+ out["torso_inertia"] = np.asarray(m.body_inertia[b], np.float32)
197
+ if "foot_solref" in self.fields:
198
+ out["foot_solref"] = np.asarray(m.pair_solref[fp[0]], np.float32)
199
+ if "foot_solimp" in self.fields:
200
+ out["foot_solimp"] = np.asarray(m.pair_solimp[fp[0], :4], np.float32)
201
+ if "foot_torsional" in self.fields:
202
+ out["foot_torsional"] = np.asarray([m.pair_friction[fp[0], 2]], np.float32)
203
+ if "dof_damping" in self.fields:
204
+ out["dof_damping"] = np.asarray(m.dof_damping, np.float32)
205
+ if "dof_armature" in self.fields:
206
+ out["dof_armature"] = np.asarray(m.dof_armature, np.float32)
207
+ if "dof_frictionloss" in self.fields:
208
+ out["dof_frictionloss"] = np.asarray(m.dof_frictionloss, np.float32)
209
+ if "frictionloss_solref" in self.fields or "frictionloss_solimp" in self.fields:
210
+ fl = np.flatnonzero(m.dof_frictionloss > 0)
211
+ d0 = int(fl[0]) if len(fl) else 0
212
+ if "frictionloss_solref" in self.fields:
213
+ out["frictionloss_solref"] = np.asarray(m.dof_solref[d0], np.float32)
214
+ if "frictionloss_solimp" in self.fields:
215
+ out["frictionloss_solimp"] = np.asarray(m.dof_solimp[d0, :4], np.float32)
216
+ if "gravity" in self.fields:
217
+ out["gravity"] = np.asarray(m.opt.gravity, np.float32)
218
+ if "xfrc" in self.fields:
219
+ x = np.zeros((len(self.xfrc_bodies), XFRC_WORDS), np.float32)
220
+ for i, b in enumerate(self.xfrc_bodies):
221
+ bid = b if isinstance(b, int) else mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, b)
222
+ if not 1 <= bid < m.nbody:
223
+ raise ValueError(f"PhysicsParams.defaults: no (moving) body {b!r}")
224
+ x[i, 6:] = m.body_ipos[bid]
225
+ out["xfrc"] = x.reshape(-1)
226
+ if "body_inertial" in self.fields:
227
+ x = np.zeros((len(self.inertial_bodies), INERTIAL_WORDS), np.float32)
228
+ for i, b in enumerate(self.inertial_bodies):
229
+ bid = b if isinstance(b, int) else mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, b)
230
+ if not 1 <= bid < m.nbody:
231
+ raise ValueError(f"PhysicsParams.defaults: no (moving) body {b!r}")
232
+ x[i, 0], x[i, 1:4] = m.body_mass[bid], m.body_inertia[bid]
233
+ out["body_inertial"] = x
234
+ if "sole_thickness" in self.fields:
235
+ out["sole_thickness"] = np.zeros(1, np.float32)
236
+ if "foot_offset" in self.fields:
237
+ out["foot_offset"] = np.zeros(4, np.float32)
238
+ if "object_size" in self.fields:
239
+ from nablaengine._optional import FOREST, load
240
+ object_size = load("nablaengine.forest_engine", FOREST, "object_size")
241
+ out["object_size"] = np.asarray(m.geom_size[object_size.size_geom(m, self, com_body)], np.float32)
242
+ return out
243
+
244
+
245
+ def _ids(x):
246
+ t = (x,) if isinstance(x, (str, int, np.integer)) else tuple(x)
247
+ return tuple(int(v) if isinstance(v, (int, np.integer)) and not isinstance(v, bool) else v for v in t)
248
+
249
+
250
+ def as_params(params):
251
+ """PhysicsParams from None, a PhysicsParams or a sequence of field names."""
252
+ if params is None:
253
+ return PhysicsParams()
254
+ if isinstance(params, PhysicsParams):
255
+ return params
256
+ if isinstance(params, str):
257
+ return PhysicsParams((params,))
258
+ return PhysicsParams(tuple(params))
@@ -0,0 +1,196 @@
1
+ """Where a result came from: the NablaEngine source revision, and for the scripts' result JSONs the GPU, driver,
2
+ toolkit, package versions and the reference physics (MuJoCo Warp's version, source tree hash and switches) it ran
3
+ with."""
4
+
5
+ import datetime
6
+ import hashlib
7
+ import importlib.metadata
8
+ import importlib.util
9
+ import os
10
+ import platform
11
+ import re
12
+ import subprocess
13
+ from pathlib import Path
14
+
15
+ REPO = Path(__file__).resolve().parents[2]
16
+ PACKAGES = ("numpy", "mujoco", "mujoco-mjx", "jax", "jaxlib", "jax-cuda12-plugin", "warp-lang", "mujoco-warp", "scipy")
17
+ MJW_SWITCH = re.compile(r"""["'](MJW_[A-Z0-9_]+)["']""")
18
+ TREE_FILES = "third_party/*/tree.sha256"
19
+ ENV_PREFIXES = ("DK_", "MJW_")
20
+ ENV_NAMES = ("JAX_PLATFORMS", "XLA_FLAGS", "XLA_PYTHON_CLIENT_PREALLOCATE", "CUDA_DEVICE_ORDER")
21
+
22
+
23
+ def _run(cmd, cwd=None, timeout=20):
24
+ try:
25
+ r = subprocess.run(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, universal_newlines=True,
26
+ timeout=timeout)
27
+ except (OSError, subprocess.SubprocessError):
28
+ return None
29
+ return r.stdout.strip() if r.returncode == 0 else None
30
+
31
+
32
+ def rel(path):
33
+ """path relative to the repository when inside it, else with the home directory as ~, else only its last part
34
+ (.../name: no absolute paths of the machine in results; str, None stays None)."""
35
+ if path is None:
36
+ return None
37
+ p = Path(path).expanduser().absolute()
38
+ try:
39
+ resolved = p.resolve()
40
+ except OSError:
41
+ resolved = p
42
+ for q in (p, resolved):
43
+ for base, prefix in ((REPO, ""), (Path.home(), "~/")):
44
+ try:
45
+ return prefix + str(q.relative_to(base))
46
+ except ValueError:
47
+ continue
48
+ return f".../{p.name}"
49
+
50
+
51
+ def _installed_commit():
52
+ import json
53
+ from importlib import metadata
54
+ try:
55
+ text = metadata.distribution("nablaengine").read_text("direct_url.json")
56
+ commit = (json.loads(text or "{}").get("vcs_info") or {}).get("commit_id")
57
+ except (metadata.PackageNotFoundError, ValueError, OSError):
58
+ return None
59
+ return commit[:7] if commit else None
60
+
61
+
62
+ def source_commit():
63
+ """(short commit, dirty) of the git checkout this package is imported from; for a pip install from a git URL, the
64
+ commit pip recorded and dirty None; (None, None) otherwise (a wheel, an rsync copy). dirty: tracked files differ
65
+ from the commit (untracked files do not count)."""
66
+ if not ((REPO / ".git").exists() and (REPO / "src" / "nablaengine").is_dir()):
67
+ return _installed_commit(), None
68
+ commit = _run(["git", "-C", str(REPO), "rev-parse", "--short=7", "HEAD"])
69
+ if commit is None:
70
+ return None, None
71
+ status = _run(["git", "-C", str(REPO), "status", "--porcelain", "--untracked-files=no"])
72
+ return commit, (None if status is None else bool(status))
73
+
74
+
75
+ def gpu():
76
+ """{name, compute_cap, driver} of the first visible GPU (nvidia-smi), None without one."""
77
+ from nablaengine import cuda
78
+ q = ["nvidia-smi", "--query-gpu=name,compute_cap,driver_version", "--format=csv,noheader"]
79
+ out = (_run([*q, "-i", cuda.visible_gpu()]) if cuda.visible_gpu() else None) or _run(q)
80
+ if not out:
81
+ return None
82
+ name, cc, driver = [x.strip() for x in out.splitlines()[0].split(",")][:3]
83
+ return dict(name=name, compute_cap=cc, driver=driver)
84
+
85
+
86
+ def nvcc_version(nvcc=None):
87
+ """The nvcc release, e.g. '12.4.131' (from 'V12.4.131' of nvcc --version), None without nvcc."""
88
+ from nablaengine import cuda
89
+ try:
90
+ nvcc = nvcc or cuda.nvcc()
91
+ except FileNotFoundError:
92
+ return None
93
+ m = re.search(r"\bV(\d+\.\d+\.\d+)", _run([nvcc, "--version"]) or "")
94
+ return m.group(1) if m else None
95
+
96
+
97
+ def packages(names=PACKAGES):
98
+ out = {}
99
+ for n in names:
100
+ try:
101
+ out[n] = importlib.metadata.version(n)
102
+ except importlib.metadata.PackageNotFoundError:
103
+ out[n] = None
104
+ return out
105
+
106
+
107
+ def tree_sha256(pkg_dir):
108
+ """sha256 over 'sha256 mujoco_warp/<path>' lines of the package's .py files in byte order: the same as
109
+ `find mujoco_warp -type f -name '*.py' | LC_ALL=C sort | xargs sha256sum | sha256sum` in the tree root."""
110
+ pkg_dir = Path(pkg_dir)
111
+ files = sorted(f"{pkg_dir.name}/{p.relative_to(pkg_dir).as_posix()}" for p in pkg_dir.rglob("*.py") if p.is_file())
112
+ lines = "".join(f"{hashlib.sha256((pkg_dir.parent / f).read_bytes()).hexdigest()} {f}\n" for f in files)
113
+ return hashlib.sha256(lines.encode()).hexdigest()
114
+
115
+
116
+ def tested_tree_sha256():
117
+ """The tree_sha256 of the MuJoCo Warp source tree the checkout pins (TREE_FILES), None when it pins none (a
118
+ released MuJoCo Warp is identified by its version)."""
119
+ for f in sorted(REPO.glob(TREE_FILES)):
120
+ try:
121
+ return next(x for x in f.read_text().split() if re.fullmatch(r"[0-9a-f]{64}", x))
122
+ except (OSError, StopIteration):
123
+ continue
124
+ return None
125
+
126
+
127
+ def mujoco_warp():
128
+ """The installed MuJoCo Warp without importing it (no Warp start-up): version, the environment switches its
129
+ sources name (MJW_SWITCH, sorted; none in a stock MuJoCo Warp), its tree_sha256 and whether that is the pinned
130
+ tree (None when the checkout pins none). None if it is not installed."""
131
+ try:
132
+ spec = importlib.util.find_spec("mujoco_warp")
133
+ except (ImportError, ValueError):
134
+ spec = None
135
+ if spec is None or not spec.submodule_search_locations:
136
+ return None
137
+ pkg = Path(list(spec.submodule_search_locations)[0])
138
+ try:
139
+ text = "".join(p.read_text(errors="replace") for p in (pkg / "_src").glob("*.py"))
140
+ tree = tree_sha256(pkg)
141
+ except OSError:
142
+ text, tree = "", None
143
+ tested = tested_tree_sha256()
144
+ return dict(version=packages(("mujoco-warp",))["mujoco-warp"], path=rel(pkg),
145
+ switches=sorted(set(MJW_SWITCH.findall(text))), tree_sha256=tree,
146
+ tested_tree=None if tested is None or tree is None else tree == tested)
147
+
148
+
149
+ def environment():
150
+ """The DK_* / MJW_* switches and a few JAX / CUDA variables that are set (paths relative, see rel)."""
151
+ out = {}
152
+ for k, v in sorted(os.environ.items()):
153
+ if k.startswith(ENV_PREFIXES) or k in ENV_NAMES:
154
+ if k == "XLA_FLAGS":
155
+ out[k] = " ".join(f"{f.split('=', 1)[0]}={rel(f.split('=', 1)[1])}" if "=" in f and "/" in f else f
156
+ for f in v.split())
157
+ else:
158
+ out[k] = rel(v) if "/" in v else v
159
+ return out
160
+
161
+
162
+ def keep_sections(res, sources):
163
+ """Record where the sections that a run keeps from earlier result JSONs (--update, --merge) came from, as
164
+ res["provenance_kept_sections"] = [{sections, provenance}] (one entry per distinct provenance; none kept: no key).
165
+ sources: [(earlier JSON, [names of the sections taken from it]), ...], later ones win. A section gets the earlier
166
+ JSON's own record of it (its provenance_kept_sections) when there is one, else that JSON's provenance (None for a
167
+ JSON without one). res["provenance"] stays the provenance of this run's sections."""
168
+ src = {}
169
+ for old, names in sources:
170
+ rec = {s: e.get("provenance") for e in old.get("provenance_kept_sections") or [] for s in e.get("sections", [])}
171
+ src.update({s: rec.get(s, old.get("provenance")) for s in names})
172
+ out = []
173
+ for s, p in src.items():
174
+ e = next((e for e in out if e["provenance"] == p), None)
175
+ if e is None:
176
+ out.append(dict(sections=[s], provenance=p))
177
+ else:
178
+ e["sections"].append(s)
179
+ res.pop("provenance_kept_sections", None)
180
+ if out:
181
+ res["provenance_kept_sections"] = out
182
+
183
+
184
+ def provenance():
185
+ """The provenance block of a result JSON (see the module docstring)."""
186
+ from nablaengine import cuda, fixtures
187
+ import nablaengine
188
+ commit, dirty = source_commit()
189
+ try:
190
+ arch = cuda.arch()
191
+ except Exception:
192
+ arch = None
193
+ return dict(date=datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
194
+ nablaengine=dict(version=nablaengine.__version__, commit=commit, dirty=dirty),
195
+ gpu=gpu(), arch=arch, nvcc=nvcc_version(), python=platform.python_version(), packages=packages(),
196
+ mujoco_warp=mujoco_warp(), environment=environment(), fixtures=rel(fixtures.fixtures_dir()))
File without changes