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,694 @@
1
+ """Which MuJoCo models the engine supports: input validation of a model before anything is built."""
2
+
3
+ import os
4
+ import warnings
5
+ from dataclasses import asdict, dataclass
6
+
7
+ import mujoco
8
+ import numpy as np
9
+
10
+ from nablaengine.model import fields as F
11
+
12
+ ALLOW_VAR = "DK_ALLOW_UNSUPPORTED"
13
+ COM_BODY = "torso_link"
14
+ SCOPES = {"forward": ("forward",), "engine": ("forward", "adjoint"), "kinematics": ("kinematics",),
15
+ "forest": ("forest",)}
16
+ J, G, T = mujoco.mjtJoint, mujoco.mjtGeom, mujoco.mjtTrn
17
+ GEOM_CODE = {int(G.mjGEOM_PLANE): 0, int(G.mjGEOM_SPHERE): 1, int(G.mjGEOM_CAPSULE): 2, int(G.mjGEOM_BOX): 3,
18
+ int(G.mjGEOM_CYLINDER): 5, int(G.mjGEOM_MESH): 6, int(G.mjGEOM_ELLIPSOID): 7}
19
+ FORWARD_TYPES = {0, 1, 2, 3, 5, 6}
20
+ ADJOINT_TYPES = {0, 1, 2}
21
+ DISPATCHED = {(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3),
22
+ (0, 5), (1, 5), (1, 3), (2, 5), (5, 5), (3, 5),
23
+ (0, 6), (1, 6), (2, 6), (3, 6), (5, 6), (6, 6)}
24
+ CONTACTS_PER_PAIR = {(0, 1): 1, (0, 2): 2, (0, 3): 4, (1, 1): 1, (1, 2): 1, (2, 2): 2, (2, 3): 2, (3, 3): 8,
25
+ (0, 5): 4, (1, 5): 1, (1, 3): 1, (2, 5): 4, (5, 5): 4, (3, 5): 4, (0, 6): 4, (1, 6): 1, (2, 6): 4,
26
+ (3, 6): 4, (5, 6): 4, (6, 6): 4}
27
+ D, E = mujoco.mjtDisableBit, mujoco.mjtEnableBit
28
+ DISABLE_OK = (D.mjDSBL_SENSOR, D.mjDSBL_EULERDAMP, D.mjDSBL_AUTORESET, D.mjDSBL_MIDPHASE, D.mjDSBL_ISLAND,
29
+ D.mjDSBL_FILTERPARENT, D.mjDSBL_CLAMPCTRL)
30
+ DISABLE_OK_NO_BOX = (D.mjDSBL_NATIVECCD, D.mjDSBL_MULTICCD)
31
+ DISABLE_NOOP = (D.mjDSBL_SPRING, D.mjDSBL_DAMPER, D.mjDSBL_EQUALITY)
32
+ ENABLE_OK = (E.mjENBL_ENERGY, E.mjENBL_FWDINV, E.mjENBL_INVDISCRETE)
33
+ STATUSES = ("error", "warn", "info", "ok")
34
+ CTRLSPEC_OK = (0, int(mujoco.mjtCtrlInput.mjINPUT_POS))
35
+
36
+
37
+ def _bits(flags, enum):
38
+ return [k for k, v in enum.__members__.items() if not k.startswith("mjN") and flags & int(v)]
39
+
40
+
41
+ def _mask(members):
42
+ out = 0
43
+ for v in members:
44
+ out |= int(v)
45
+ return out
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Finding:
50
+ code: str
51
+ status: str
52
+ what: str
53
+ value: object = None
54
+ scopes: tuple = ("forward",)
55
+ applies: bool = True
56
+
57
+ def line(self):
58
+ v = "" if self.value is None else f" [{_short(self.value)}]"
59
+ return f"{self.code:5s} {self.status:5s} {self.what}{v}"
60
+
61
+
62
+ def _short(v, n=160):
63
+ s = str(v)
64
+ return s if len(s) <= n else s[:n - 3] + "..."
65
+
66
+
67
+ class CapabilityReport:
68
+ """The findings of check() for one model and scope."""
69
+
70
+ def __init__(self, scope, findings):
71
+ self.scope, self.findings = scope, list(findings)
72
+
73
+ def _of(self, status):
74
+ return [f for f in self.findings if f.applies and f.status == status]
75
+
76
+ def errors(self):
77
+ return self._of("error")
78
+
79
+ def warnings(self):
80
+ return self._of("warn")
81
+
82
+ def infos(self):
83
+ return self._of("info")
84
+
85
+ def codes(self, status="error"):
86
+ return sorted({f.code for f in self._of(status)})
87
+
88
+ def ok(self):
89
+ return not self.errors()
90
+
91
+ def table(self, all_rows=False):
92
+ """One line per finding that applies and is not ok (all_rows: every finding)."""
93
+ rows = [f for f in self.findings if all_rows or (f.applies and f.status != "ok")]
94
+ return "\n".join(f.line() + ("" if f.applies else " (other scope)") for f in rows)
95
+
96
+ def summary(self):
97
+ return (f"scope {self.scope}: {len(self.errors())} errors {self.codes('error')}, {len(self.warnings())} "
98
+ f"warnings {self.codes('warn')}, {len(self.infos())} infos {self.codes('info')}")
99
+
100
+ def to_dict(self):
101
+ return dict(scope=self.scope, errors=self.codes("error"), warnings=self.codes("warn"), infos=self.codes("info"),
102
+ findings=[{k: (_jsonable(v)) for k, v in asdict(f).items()} for f in self.findings])
103
+
104
+
105
+ def _jsonable(v):
106
+ if isinstance(v, dict):
107
+ return {str(k): _jsonable(x) for k, x in v.items()}
108
+ if isinstance(v, (list, tuple)):
109
+ return [_jsonable(x) for x in v]
110
+ if isinstance(v, np.generic):
111
+ return v.item()
112
+ return v
113
+
114
+
115
+ class UnsupportedModel(ValueError, AssertionError):
116
+ """A model the engine does not support (capability errors). A ValueError (as jax_ffi.check_model's model
117
+ mismatch) and an AssertionError (as the code generators' asserts, which jax_ffi.init documents)."""
118
+
119
+ def __init__(self, report, context=""):
120
+ self.report = report
121
+ lines = "\n ".join(f.line() for f in report.errors())
122
+ eng = "the forest engine" if report.scope == "forest" else "the engine"
123
+ super().__init__(f"nablaengine: the model is not supported by {eng}{' (' + context + ')' if context else ''}"
124
+ f": {report.summary()}\n {lines}\n(nablaengine.model.capability documents the codes; "
125
+ f"${ALLOW_VAR}=<codes> overrides them, for experiments only)")
126
+
127
+
128
+ def filter_pairs(m):
129
+ """Geom pairs that MuJoCo's broadphase lets collide besides the explicit <pair>s (contype / conaffinity, not the
130
+ same weld body, the parent filter unless disabled, not excluded, not already an explicit pair; measured on mujoco
131
+ 3.17: an explicit pair replaces only its own geom pair, exclude signatures are body1 << 16 | body2): the contacts
132
+ the engine, which generates only explicit pairs, would leave out."""
133
+ ex = {int(s) for s in m.exclude_signature} if m.nexclude else set()
134
+ explicit = {frozenset((int(a), int(b))) for a, b in zip(m.pair_geom1, m.pair_geom2)}
135
+ filt_parent = not (m.opt.disableflags & int(D.mjDSBL_FILTERPARENT))
136
+ g = [i for i in range(m.ngeom) if m.geom_contype[i] or m.geom_conaffinity[i]]
137
+ out = []
138
+ for a in range(len(g)):
139
+ for b in range(a + 1, len(g)):
140
+ g1, g2 = g[a], g[b]
141
+ if not ((m.geom_contype[g1] & m.geom_conaffinity[g2]) or (m.geom_contype[g2] & m.geom_conaffinity[g1])):
142
+ continue
143
+ w1, w2 = int(m.body_weldid[m.geom_bodyid[g1]]), int(m.body_weldid[m.geom_bodyid[g2]])
144
+ if w1 == w2:
145
+ continue
146
+ p1, p2 = int(m.body_weldid[m.body_parentid[w1]]), int(m.body_weldid[m.body_parentid[w2]])
147
+ if filt_parent and w1 and w2 and (p1 == w2 or p2 == w1):
148
+ continue
149
+ b1, b2 = sorted((int(m.geom_bodyid[g1]), int(m.geom_bodyid[g2])))
150
+ if (b1 << 16) + b2 in ex or frozenset((g1, g2)) in explicit:
151
+ continue
152
+ out.append((g1, g2))
153
+ return out
154
+
155
+
156
+ def collision_geoms(m):
157
+ return sorted({int(g) for g in m.pair_geom1} | {int(g) for g in m.pair_geom2})
158
+
159
+
160
+ def _pair_codes(m, p):
161
+ a, b = int(m.geom_type[m.pair_geom1[p]]), int(m.geom_type[m.pair_geom2[p]])
162
+ return tuple(sorted((GEOM_CODE.get(a, -1), GEOM_CODE.get(b, -1))))
163
+
164
+
165
+ def _name(m, objtype, i):
166
+ return mujoco.mj_id2name(m, objtype, int(i)) or str(int(i))
167
+
168
+
169
+ def check(m, foot_pairs=None, com_body=COM_BODY, scope="engine"):
170
+ """The CapabilityReport of model m for a build scope ("forward", "engine", "kinematics": the G1 engine's;
171
+ "forest": the forest engine's, check_forest; module docstring). foot_pairs: the contact pairs that take the
172
+ per-world friction (jax_ffi's foot_pairs; None: not checked, and U4 counts the plane pairs); com_body: the body that
173
+ takes the per-world COM offset (None: not checked; the forest scope reads the G1 default torso_link as None)."""
174
+ from nablaengine.g1_engine import step
175
+ if scope not in SCOPES:
176
+ raise ValueError(f"scope {scope!r}: one of {', '.join(SCOPES)}")
177
+ if scope == "forest":
178
+ return check_forest(m, foot_pairs, None if com_body == COM_BODY else com_body)
179
+ want = set(SCOPES[scope])
180
+ out = []
181
+
182
+ def add(code, ok, status, what, value=None, scopes=("forward",)):
183
+ out.append(Finding(code, "ok" if ok else status, what, _jsonable(value), tuple(scopes),
184
+ bool(want & set(scopes))))
185
+
186
+ nb, nv, nu = int(m.nbody), int(m.nv), int(m.nu)
187
+ parent = [int(x) for x in m.body_parentid]
188
+ children = [[] for _ in range(nb)]
189
+ for b in range(1, nb):
190
+ children[parent[b]].append(b)
191
+ hinge = [j for j in range(m.njnt) if m.jnt_type[j] == J.mjJNT_HINGE]
192
+
193
+ add("H1", nb <= 63, "error", "at most 63 bodies (bodies l and l + 32 on lane l beyond 32: model_hooks.py; 64-bit "
194
+ "ancestor masks)", nb,
195
+ ("forward", "kinematics"))
196
+ add("H2", nb <= 63, "error", "at most 63 bodies in the adjoint (lane 31's second body slot carries a root rotation "
197
+ "dof)", nb,
198
+ ("adjoint",))
199
+ add("H3", nv >= 7, "error", "nv >= 7 (a free root and at least one hinge)", nv)
200
+ add("H4", nv <= 64, "error", "nv <= 64 (two rows per lane)", nv)
201
+ add("H5", 33 <= nv <= 35, "warn", "33 <= nv <= 35: the tuned CHOL_BCAST / NEWTON_REUSE / blocked triangular solve "
202
+ "(else the register Cholesky fallback: untested on a corpus, slower)", nv, ("forward", "adjoint"))
203
+ free1 = nb > 1 and m.body_jntnum[1] == 1 and m.jnt_type[m.body_jntadr[1]] == J.mjJNT_FREE
204
+ one_tree = nb > 1 and all(int(m.body_rootid[b]) == 1 for b in range(1, nb))
205
+ add("H6", free1 and children[0] == [1] and one_tree, "error",
206
+ "body 1 has the only joint of its body, a free joint, and is the world's only child (one tree)",
207
+ dict(world_children=children[0], body1_free=bool(free1)), ("forward", "kinematics"))
208
+ bad7 = [b for b in range(2, nb) if not (m.body_jntnum[b] == 1 and m.body_jntadr[b] >= 0
209
+ and m.jnt_type[m.body_jntadr[b]] == J.mjJNT_HINGE
210
+ and not np.any(m.jnt_pos[m.body_jntadr[b]]))]
211
+ add("H7", not bad7, "error", "every body after the root has one hinge at its origin (no welded, multi-joint, ball "
212
+ "or slide bodies, no hinge anchor offset)", [_name(m, mujoco.mjtObj.mjOBJ_BODY, b) for b in bad7[:8]],
213
+ ("forward", "kinematics"))
214
+ order = nb > 2 and m.body_dofadr[1] == 0 and m.body_dofnum[1] == 6 and all(
215
+ m.body_dofnum[b] == 1 and m.body_dofadr[b] == b + int(m.body_dofadr[2]) - 2 for b in range(2, nb))
216
+ add("H7b", bool(order), "error", "dofs in body order: the root's 0-5, then body b's hinge at b + const "
217
+ "(adjoint.header's ADJ_HINGE_DOF0)", None, ("adjoint",))
218
+ q0 = [j for j in hinge if m.qpos0[m.jnt_qposadr[j]] != 0]
219
+ add("H8", not q0, "error", "hinge qpos0 = 0 (the engine uses qpos as the angle, MuJoCo qpos - qpos0)",
220
+ {_name(m, mujoco.mjtObj.mjOBJ_JOINT, j): float(m.qpos0[m.jnt_qposadr[j]]) for j in q0[:8]},
221
+ ("forward", "kinematics"))
222
+ nch = max((len(c) for c in children[1:]), default=0)
223
+ add("H9", nch <= 8, "error", "at most 8 children per body (c_child; model_hooks.py beyond 3)", nch)
224
+
225
+ def nanc(b):
226
+ k, n = parent[b], 0
227
+ while k >= 2:
228
+ n, k = n + 1, parent[k]
229
+ return n
230
+ na_max = max((nanc(b) for b in range(2, nb)), default=0)
231
+ add("H10", na_max <= 12, "error", "at most 12 hinge ancestors per body (c_anc)", na_max)
232
+
233
+ bad11 = []
234
+ for a in range(int(m.nactuator)):
235
+ j = int(m.actuator_trnid[a, 0])
236
+ ok = (m.actuator_trntype[a] == T.mjTRN_JOINT and 0 <= j < m.njnt and m.jnt_type[j] == J.mjJNT_HINGE
237
+ and m.jnt_dofadr[j] == 6 + a and m.actuator_biastype[a] == mujoco.mjtBias.mjBIAS_AFFINE
238
+ and m.actuator_gear[a, 0] == 1.0 and not np.any(m.actuator_gear[a, 1:])
239
+ and m.actuator_gainprm[a, 0] == -m.actuator_biasprm[a, 1] and not m.actuator_forcelimited[a]
240
+ and m.actuator_ctrladr[a] == a and m.actuator_ctrlnum[a] == 1 and m.actuator_outadr[a] == a
241
+ and m.actuator_outnum[a] == 1)
242
+ if not ok:
243
+ bad11.append(_name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a))
244
+ add("H11a", nu == m.nactuator == m.nout == nv - 6 and not bad11, "error",
245
+ "one position servo per hinge in joint order (actuator a on dof 6 + a, one control and force each), joint "
246
+ "transmission, affine bias, gear 1, gainprm[0] = -biasprm[1], not force-limited",
247
+ dict(nu=nu, nactuator=int(m.nactuator), hinges=nv - 6, bad=bad11[:8]))
248
+ vel = [_name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a) for a in range(int(m.nactuator))
249
+ if m.actuator_gaintype[a] == mujoco.mjtGain.mjGAIN_FIXED
250
+ and m.actuator_biastype[a] == mujoco.mjtBias.mjBIAS_AFFINE and m.actuator_gainprm[a, 0] != 0
251
+ and m.actuator_biasprm[a, 1] == 0 and m.actuator_biasprm[a, 2] == -m.actuator_gainprm[a, 0]]
252
+ add("H11v", not vel, "error", "no velocity servos (MuJoCo <velocity>: gainprm[0] = kv, biasprm = (0, 0, -kv)): "
253
+ "the tree engine simulates position servos only; the forest engine simulates velocity servos, route the model "
254
+ "there with nablaengine.engines.prefer_forest(m) before init (docs/engines.md)", dict(velocity=vel[:8]))
255
+ gt = [_name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a) for a in range(int(m.nactuator))
256
+ if m.actuator_gaintype[a] != mujoco.mjtGain.mjGAIN_FIXED or m.actuator_dyntype[a] != mujoco.mjtDyn.mjDYN_NONE
257
+ or m.actuator_biasprm[a, 0] != 0 or np.any(m.actuator_biasprm[a, 3:]) or np.any(m.actuator_gainprm[a, 1:])
258
+ or int(m.actuator_ctrlspec[a]) not in CTRLSPEC_OK]
259
+ add("H11b", not gt and m.na == 0, "error", "fixed gain with one position input (ctrlspec 0 or mjINPUT_POS), no "
260
+ "activation dynamics (na 0), bias (0, -kp, -kv) only", dict(bad=gt[:8], na=int(m.na)))
261
+ clamped = int(np.asarray(m.actuator_ctrllimited).sum()) if not (m.opt.disableflags & int(D.mjDSBL_CLAMPCTRL)) else 0
262
+ add("H11c", clamped == 0, "info", "ctrl is not clamped to ctrlrange by the engine (MuJoCo and MuJoCo Warp clamp "
263
+ "it; the interface's documented semantics)", dict(ctrllimited=clamped))
264
+ asym = [_name(m, mujoco.mjtObj.mjOBJ_JOINT, j) for j in range(m.njnt)
265
+ if m.jnt_actfrclimited[j] and m.jnt_actfrcrange[j, 0] != -m.jnt_actfrcrange[j, 1]]
266
+ add("H12", not asym, "error", "symmetric actuator force ranges (jnt_actfrcrange)", asym[:8])
267
+ if com_body is not None:
268
+ tid = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, com_body)
269
+ add("H13", tid >= 1, "error", f"the COM-offset body {com_body!r} exists", tid)
270
+
271
+ cg = collision_geoms(m)
272
+ types = {GEOM_CODE.get(int(m.geom_type[g]), -1) for g in cg}
273
+ tnames = sorted({mujoco.mjtGeom(int(m.geom_type[g])).name for g in cg})
274
+ add("H14a", types <= FORWARD_TYPES, "error", "contact pair geoms are planes, spheres, capsules, boxes, cylinders or "
275
+ "meshes", tnames)
276
+ planes_off_world = [g for g in cg if m.geom_type[g] == G.mjGEOM_PLANE and m.geom_bodyid[g] != 0]
277
+ box_ok = all(_pair_codes(m, p)[0] in (0, 1, 2) or _pair_codes(m, p) in ((3, 3), (3, 5), (3, 6))
278
+ for p in range(m.npair) if 3 in _pair_codes(m, p))
279
+ cyl_ok = all(_pair_codes(m, p) in ((0, 5), (1, 5), (2, 5), (5, 5), (3, 5), (5, 6)) for p in range(m.npair)
280
+ if 5 in _pair_codes(m, p))
281
+ mesh_ok = True
282
+ add("H14b", types - {3, 5, 6} <= ADJOINT_TYPES and (3 not in types or box_ok) and (5 not in types or cyl_ok)
283
+ and (6 not in types or mesh_ok)
284
+ and not planes_off_world, "error",
285
+ "contact pair geoms are planes (on the world body), spheres or capsules in the adjoint, boxes in pairs "
286
+ "with planes, spheres, capsules or boxes (model_hooks.py), cylinders (g1_engine.cylinder, cylccd) and meshes "
287
+ "(g1_engine.mesh, cylccd)", dict(types=tnames, planes_off_world=planes_off_world[:4]), ("adjoint",))
288
+ combos = sorted({_pair_codes(m, p) for p in range(m.npair)} - DISPATCHED)
289
+ add("H14c", not combos, "error", "every pair's type combination is one the forward collides (not plane-plane)",
290
+ combos)
291
+ d_it, d_tol = F.option_default("ccd_iterations"), F.option_default("ccd_tolerance")
292
+ boxbox = sum(1 for p in range(m.npair) if _pair_codes(m, p) == (3, 3))
293
+ add("H14d", not boxbox or (m.opt.ccd_iterations >= d_it and m.opt.ccd_tolerance <= d_tol), "error",
294
+ f"box-box pairs: native CCD at least as converged as MuJoCo's default (ccd_iterations >= {d_it}, ccd_tolerance "
295
+ f"<= {d_tol:g}), whose converged contact the forward computes",
296
+ dict(boxbox_pairs=boxbox, ccd_iterations=int(m.opt.ccd_iterations), ccd_tolerance=float(m.opt.ccd_tolerance)))
297
+ fp = filter_pairs(m)
298
+ add("H15", not fp, "error", "no contype / conaffinity contacts (the engine generates only the explicit pairs)",
299
+ dict(n=len(fp), first=[(_name(m, mujoco.mjtObj.mjOBJ_GEOM, a), _name(m, mujoco.mjtObj.mjOBJ_GEOM, b))
300
+ for a, b in fp[:4]]))
301
+ mg = [p for p in range(m.npair) if m.pair_margin[p] or m.pair_gap[p]
302
+ or m.pair_friction[p, 0] != m.pair_friction[p, 1]]
303
+ add("H16", not mg, "error", "pair margin = gap = 0 and friction[0] = friction[1]",
304
+ [_name(m, mujoco.mjtObj.mjOBJ_PAIR, p) for p in mg[:8]])
305
+ cd = sorted({int(x) for x in m.pair_dim} - {1, 3, 4})
306
+ add("H17", not cd, "error", "pair condim 1, 3 or 4 (others would be simulated as frictionless)", cd)
307
+ from nablaengine.g1_engine import elliptic as _ell
308
+ ell_ok = _ell.applies(m) and _ell.supported(m)[0]
309
+ add("H18", m.opt.cone == mujoco.mjtCone.mjCONE_PYRAMIDAL or ell_ok, "error",
310
+ "pyramidal friction cone, or elliptic with condim 1 / 3 pairs, isotropic sliding friction and no "
311
+ "solreffriction (g1_engine.elliptic: forward and adjoint)",
312
+ mujoco.mjtCone(int(m.opt.cone)).name + ("" if not _ell.applies(m) or ell_ok else f" ({_ell.supported(m)[1]})"))
313
+ neg = dict(pairs=int((m.pair_solref <= 0).any(axis=1).sum()), joints=int((m.jnt_solref[1:] <= 0).any(axis=1).sum()),
314
+ dofs=int((m.dof_solref <= 0).any(axis=1).sum()))
315
+ add("H19", not any(neg.values()), "error", "solref in the standard form, both entries > 0 (time constant, damping "
316
+ "ratio; a direct, non-positive stiffness or damping entry is unsupported)", neg)
317
+ lim_free = [j for j in range(m.njnt) if m.jnt_limited[j] and m.jnt_type[j] != J.mjJNT_HINGE]
318
+ uni = (m.njnt < 2 or ((m.jnt_solref[1:] == m.jnt_solref[1]).all() and (m.jnt_solimp[1:] == m.jnt_solimp[1]).all()))
319
+ dof_uni = nv == 0 or ((m.dof_solref == m.dof_solref[0]).all() and (m.dof_solimp == m.dof_solimp[0]).all())
320
+ add("H20", bool(uni and not m.jnt_margin.any() and dof_uni and not lim_free), "error",
321
+ "one solref / solimp for every joint limit and every dof, jnt_margin 0, only hinge limits",
322
+ dict(limited_non_hinge=lim_free[:4]))
323
+ add("U10", not (m.dof_frictionloss > 0).any(), "warn", "no frictionloss rows (the tree engine's adjoint of them, "
324
+ "g1_engine/model_hooks.py, is not checked against finite differences; the forest engine's is, with per-dof "
325
+ "solreffriction / solimpfriction: scripts/forest/floss_check.py, docs/engines.md)",
326
+ int((m.dof_frictionloss > 0).sum()), ("adjoint",))
327
+
328
+ medium = dict(density=float(m.opt.density), viscosity=float(m.opt.viscosity), wind=[float(x) for x in m.opt.wind])
329
+ add("H22", m.opt.density == 0 and m.opt.viscosity == 0 and not np.any(m.opt.wind), "error",
330
+ "no fluid forces (opt density, viscosity, wind 0)", medium)
331
+ add("H23", m.opt.integrator == mujoco.mjtIntegrator.mjINT_IMPLICITFAST, "error", "implicitfast integrator",
332
+ mujoco.mjtIntegrator(int(m.opt.integrator)).name)
333
+ add("H24a", m.opt.solver == mujoco.mjtSolver.mjSOL_NEWTON, "error", "Newton solver",
334
+ mujoco.mjtSolver(int(m.opt.solver)).name)
335
+ has_box = any(m.geom_type[g] == G.mjGEOM_BOX for g in cg)
336
+ noop = DISABLE_NOOP + ((D.mjDSBL_FRICTIONLOSS,) if not (m.dof_frictionloss > 0).any() else ()) + (
337
+ (D.mjDSBL_LIMIT,) if not np.asarray(m.jnt_limited).any() else ())
338
+ dis = int(m.opt.disableflags) & ~_mask(DISABLE_OK + noop + (() if has_box else DISABLE_OK_NO_BOX))
339
+ en = int(m.opt.enableflags) & ~_mask(ENABLE_OK)
340
+ add("H24b", dis == 0 and en == 0 and m.opt.noslip_iterations == 0 and m.opt.disableactuator == 0, "error",
341
+ "no disable / enable flags that change the physics, noslip off (the forest engine has the noslip pass: "
342
+ "nablaengine.engines.prefer_forest), no disabled actuator groups",
343
+ dict(disable=_bits(dis, D), enable=_bits(en, E), noslip_iterations=int(m.opt.noslip_iterations),
344
+ disableactuator=int(m.opt.disableactuator)))
345
+ add("H25", m.ntendon == 0 and m.neq == 0 and m.nmocap == 0 and m.nflex == 0 and m.nplugin == 0, "error",
346
+ "no tendons, equality constraints, mocap bodies, flexes or plugins",
347
+ dict(ntendon=int(m.ntendon), neq=int(m.neq), nmocap=int(m.nmocap), nflex=int(m.nflex),
348
+ nplugin=int(m.nplugin)), ("forward", "kinematics"))
349
+
350
+ gen = types <= FORWARD_TYPES and not bad7 and nb > 1
351
+ kdof = step.max_support(m) if m.npair and gen else 0
352
+ maxcon = step.maxcon(m)
353
+ npset = len(step.pair_param_sets(m)[0])
354
+ add("H26a", len(cg) <= 255 and npset <= 255 and kdof <= 32 and maxcon <= 64 and m.npair < 65536, "error",
355
+ "<= 255 collision geoms and parameter sets (the pair word), KDOF <= 32, MAXCON <= 64",
356
+ dict(ngeomc=len(cg), param_sets=npset, kdof=kdof, maxcon=maxcon))
357
+ add("H26b", m.npair < 65536, "error", "fewer than 65536 contact pairs (the tape's pair index: 9 bits below 512 "
358
+ "pairs, 16 bits from there, g1_engine.step.capacity_hooks)", int(m.npair), ("adjoint",))
359
+ if foot_pairs is not None:
360
+ fps = [int(p) for p in np.asarray(foot_pairs).ravel()]
361
+ add("H30", set(fps) <= set(range(m.npair)), "error", "the friction (foot) pairs are contact pair indices",
362
+ dict(n=len(fps), outside=sorted(set(fps) - set(range(m.npair)))[:8]))
363
+
364
+ sub = np.array(m.body_mass, np.float64)
365
+ for b in range(nb - 1, 0, -1):
366
+ sub[parent[b]] += sub[b]
367
+ add("H31", not np.any(m.body_pos[0]) and np.array_equal(m.body_quat[0], [1.0, 0.0, 0.0, 0.0])
368
+ and m.body_mass[0] == 0 and (nb < 2 or sub[1:].min() >= mujoco.mjMINVAL), "error",
369
+ "kinematics outputs: the world body at the origin and massless, every subtree mass >= mjMINVAL", None,
370
+ ("kinematics",))
371
+
372
+ add("U8", nv >= 32, "warn", "nv >= 32 (the G1's; below, the solves' spare lanes repeat the last row: model_hooks.py, "
373
+ "untested on a held-out corpus)", nv)
374
+ add("U9", nch <= 3, "warn", "at most 3 children per body (the G1's; beyond, model_hooks.py widens c_child: untested "
375
+ "on a held-out corpus)", nch)
376
+ add("U1", not (33 <= nv <= 34), "warn", "CHOL_BCAST's tail of nv - 32 rows: only the G1's 3-row tail (nv 35) ran on "
377
+ "a corpus", nv, ("forward", "adjoint"))
378
+ add("U2", not gen or kdof == 16, "warn", "KDOF = 16 (the G1's): otherwise DK_JV_VEC's 128-bit con_jv loads are off and the "
379
+ "scalar path, never run on a corpus, is used", kdof)
380
+ add("U3", maxcon == 64, "warn", "MAXCON 64 in the adjoint (npair > 64; the adjoint never ran with MAXCON 32)",
381
+ maxcon, ("adjoint",))
382
+ worst = 0
383
+ dr = ([int(p) for p in np.asarray(foot_pairs).ravel()] if foot_pairs is not None
384
+ else [p for p in range(m.npair) if 0 in _pair_codes(m, p)])
385
+ for p in dr:
386
+ if 0 <= p < m.npair:
387
+ worst += CONTACTS_PER_PAIR.get(_pair_codes(m, p), 1)
388
+ add("U4", worst <= maxcon, "warn", "the friction (foot) pairs' worst-case contacts fit MAXCON (else contacts are "
389
+ "dropped and the world flagged while standing)", dict(worst_case=worst, maxcon=maxcon))
390
+ floor = step.floor_geom(m) if gen else None
391
+ add("U5", floor is None or floor >= 0 or not m.npair, "warn", "one plane among the collision geoms (FLOOR_G; else "
392
+ "the general plane path, untested on a corpus)", floor)
393
+ add("U6", bool(step.dof_body_root6(m)), "warn", "bodies and dofs in the same order (DOF_BODY_ROOT6; else the general "
394
+ "support mask, untested on a corpus)", bool(step.dof_body_root6(m)))
395
+ pw = sorted({float(np.float32(x)) for x in list(m.pair_solimp[:, 4]) + list(m.jnt_solimp[1:, 4])})
396
+ add("U7", bool(step.solimp_pow2(m)) and len(pw) <= 1, "warn", "every solimp power 2 (SOLIMP_POW2, ADJ_SOLIMP_POWER; "
397
+ "else the general power paths, untested on a corpus)", pw, ("forward", "adjoint"))
398
+ add("I1", True, "info", "the timestep (baked into the constants)", float(m.opt.timestep))
399
+
400
+ defaults = F.default_rows()
401
+ for name in F.default_fields():
402
+ f = F.FIELDS[name]
403
+ bad = F.non_default(m, name, defaults)
404
+ if bad:
405
+ kind = name.split("_", 1)[0]
406
+ obj = dict(body=mujoco.mjtObj.mjOBJ_BODY, jnt=mujoco.mjtObj.mjOBJ_JOINT, dof=None,
407
+ geom=mujoco.mjtObj.mjOBJ_GEOM, pair=mujoco.mjtObj.mjOBJ_PAIR,
408
+ actuator=mujoco.mjtObj.mjOBJ_ACTUATOR)[kind]
409
+ rows = [(_name(m, obj, i) if obj is not None else int(i)) for i in bad[:6]]
410
+ add(f.code, False, "error", f"{name} at its default ({f.note})", dict(rows=len(bad), first=rows))
411
+ unknown = F.unclassified(m)
412
+ add("F0", not unknown, "error", "every MjModel field is classified (nablaengine.model.fields; a MuJoCo version "
413
+ "with new fields needs their classification)", unknown[:8], ("forward", "adjoint", "kinematics"))
414
+ return CapabilityReport(scope, out)
415
+
416
+
417
+ FOREST_TYPES = {0, 1, 2, 3, 5, 6, 7}
418
+ FOREST_CONDIM = {1, 3, 4}
419
+
420
+
421
+ def check_forest(m, foot_pairs=None, com_body=None):
422
+ """The forest engine's CapabilityReport of model m (scope "forest"; nablaengine.forest_engine, docs/engines.md):
423
+ the codes of check() where the requirement is the same (H4, H12, H13, H15, H17, H22, H24a, H25, H30; H25 without the
424
+ equality constraints, which H25e checks, and the fixed tendons, which H25t checks: forest_engine.equality /
425
+ tendon), T1-T14 for the
426
+ forest engine's own requirements on structure, actuators, geoms, integrator, options, contact margins, contact
427
+ supports, solref forms and the elliptic cone, and T0 for an assumption of
428
+ its constant packing (forest_engine.source / step) that the explicit checks do not name. com_body: the body that
429
+ takes the per-world COM offset (None: none, the forest engine's default). Unlike check()'s scopes, physics fields
430
+ the forest engine does not model are checked only where listed here."""
431
+ out = []
432
+
433
+ def add(code, ok, what, value=None, status="error"):
434
+ out.append(Finding(code, "ok" if ok else status, what, _jsonable(value), ("forest",), True))
435
+
436
+ nb, nv = int(m.nbody), int(m.nv)
437
+ parent = [int(x) for x in m.body_parentid]
438
+ children = [[] for _ in range(nb)]
439
+ for b in range(1, nb):
440
+ children[parent[b]].append(b)
441
+
442
+ def body(b):
443
+ return _name(m, mujoco.mjtObj.mjOBJ_BODY, b)
444
+
445
+ add("T1", nb <= 128, "at most 128 bodies, the world included (bodies l, l + 32, l + 64, l + 96 on lane l; beyond 32: "
446
+ "forest_engine.nb64, beyond 64: forest_engine.nb128)", nb)
447
+ nch = max((len(c) for c in children[1:]), default=0)
448
+ add("T2", nch <= 8, "at most 8 children per body (c_child)", nch)
449
+ add("H4", nv <= 128, "nv <= 128 (dofs l, l + 32, l + 64, l + 96 on lane l; beyond 64: forest_engine.nv128)", nv)
450
+ bad = {}
451
+ for b in range(1, nb):
452
+ if m.body_jntnum[b] != 1:
453
+ bad[body(b)] = f"{int(m.body_jntnum[b])} joints"
454
+ continue
455
+ j = int(m.body_jntadr[b])
456
+ jt = int(m.jnt_type[j])
457
+ if jt not in (int(J.mjJNT_FREE), int(J.mjJNT_HINGE), int(J.mjJNT_SLIDE)):
458
+ bad[body(b)] = mujoco.mjtJoint(jt).name
459
+ elif jt == int(J.mjJNT_FREE) and parent[b] != 0:
460
+ bad[body(b)] = "a free joint below the tree root"
461
+ elif jt == int(J.mjJNT_FREE) and m.jnt_stiffness[j] != 0:
462
+ bad[body(b)] = "a free-joint spring"
463
+ elif jt != int(J.mjJNT_FREE) and np.any(m.jnt_pos[j]):
464
+ bad[body(b)] = "joint anchor off the body origin"
465
+ elif jt != int(J.mjJNT_FREE) and m.qpos0[m.jnt_qposadr[j]] != 0:
466
+ bad[body(b)] = "joint ref != 0 (the engine's angle is qpos)"
467
+ add("T3", not bad, "every body has exactly one joint: a free joint (tree roots only, no spring) or a hinge / slide "
468
+ "at the body origin with ref 0 (no welded, multi-joint or ball bodies)", dict(list(bad.items())[:8]))
469
+
470
+ def nanc(b):
471
+ k, n = parent[b], 0
472
+ while k >= 1:
473
+ if m.body_jntnum[k] == 1 and m.jnt_type[m.body_jntadr[k]] != J.mjJNT_FREE:
474
+ n += 1
475
+ k = parent[k]
476
+ return n
477
+ na_max = max((nanc(b) for b in range(1, nb)), default=0)
478
+ from nablaengine._optional import FOREST, load
479
+ _src = load("nablaengine.forest_engine", FOREST, "source")
480
+ add("T4", na_max <= _src.MAX_ANC, f"at most {_src.MAX_ANC} hinge / slide ancestors per body (c_anc)", na_max)
481
+
482
+ bad, seen = [], set()
483
+ from nablaengine._optional import FOREST, load
484
+ _ten = load("nablaengine.forest_engine", FOREST, "tendon")
485
+ tbad_act = {n for n, why in _ten.check_actuators(m)}
486
+ _mus = load("nablaengine.forest_engine", FOREST, "muscle")
487
+ general = _mus.general(m)
488
+ gbad = _mus.check(m) if general else []
489
+ for a in range(int(m.nu)):
490
+ if a in general:
491
+ continue
492
+ j = int(m.actuator_trnid[a, 0])
493
+ affine = int(m.actuator_biastype[a]) == int(mujoco.mjtBias.mjBIAS_AFFINE)
494
+ if m.actuator_trntype[a] == T.mjTRN_TENDON:
495
+ if _name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a) in tbad_act or \
496
+ (mujoco.mj_id2name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a) or str(a)) in tbad_act:
497
+ bad.append(_name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a))
498
+ continue
499
+ joint = m.actuator_trntype[a] == T.mjTRN_JOINT and 0 <= j < m.njnt
500
+ dof = int(m.jnt_dofadr[j]) if joint else -1
501
+ ok = (joint and int(m.jnt_type[j]) in (int(J.mjJNT_HINGE), int(J.mjJNT_SLIDE)) and dof not in seen
502
+ and m.actuator_dyntype[a] == mujoco.mjtDyn.mjDYN_NONE
503
+ and m.actuator_gaintype[a] == mujoco.mjtGain.mjGAIN_FIXED
504
+ and (affine or int(m.actuator_biastype[a]) == int(mujoco.mjtBias.mjBIAS_NONE))
505
+ and (not affine or m.actuator_biasprm[a, 0] == 0.0)
506
+ and m.actuator_gear[a, 0] == 1.0 and not np.any(m.actuator_gear[a, 1:])
507
+ and (not m.actuator_forcelimited[a] or m.actuator_forcerange[a, 0] == -m.actuator_forcerange[a, 1]))
508
+ seen.add(dof)
509
+ if not ok:
510
+ bad.append(_name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a))
511
+ add("T5", not bad, "actuators without activation dynamics or muscle curves: a joint transmission on a hinge or "
512
+ "slide, at most one per dof, or a tendon transmission (fixed: with a support dof free of joint actuators, unless "
513
+ "the model has spatial tendons or general actuators; spatial: forest_engine.spatial); fixed gain, affine "
514
+ "(biasprm[0] = 0) or no bias, gear 1, symmetric forcerange (force = kp ctrl - kq q - kv qdot, q the joint "
515
+ "position or the tendon length); no tendon actfrcrange", dict(bad=bad[:8]))
516
+ add("T12", not gbad, "general actuators (activation dynamics or MuJoCo's muscle: forest_engine.muscle): dyntype "
517
+ "none / integrator / filter / filterexact / muscle (one activation each), gain fixed / affine / muscle, bias "
518
+ "none / affine / muscle, on a hinge / slide joint or a tendon, gear on its first component; with implicitfast "
519
+ "no velocity-dependent gain (the muscle's FV); their tendons' and joints' actfrcrange as T5",
520
+ dict(n=len(general), bad=[f"{n}: {why}" for n, why in gbad[:4]]))
521
+ asym = [_name(m, mujoco.mjtObj.mjOBJ_JOINT, j) for j in range(m.njnt)
522
+ if m.jnt_actfrclimited[j] and m.jnt_actfrcrange[j, 0] != -m.jnt_actfrcrange[j, 1]]
523
+ add("H12", not asym, "symmetric actuator force ranges (jnt_actfrcrange)", asym[:8])
524
+ add("T6", not np.asarray(m.jnt_actgravcomp).any(), "gravity compensation as a passive force only (no "
525
+ "actuatorgravcomp)", int(np.asarray(m.jnt_actgravcomp).sum()))
526
+ if com_body is not None:
527
+ tid = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, com_body)
528
+ add("H13", tid >= 1, f"the COM-offset body {com_body!r} exists", tid)
529
+
530
+ cg = collision_geoms(m)
531
+ tnames = sorted({mujoco.mjtGeom(int(m.geom_type[g])).name for g in cg})
532
+ types = {GEOM_CODE.get(int(m.geom_type[g]), -1) for g in cg}
533
+ add("T7", types <= FOREST_TYPES, "contact pair geoms are planes, spheres, capsules, ellipsoids, cylinders, boxes "
534
+ "or meshes (convex hulls); a heightfield: nablaengine.terrain (Terrain.from_model, TerrainConfig: sphere, capsule "
535
+ "and box geoms against it), or envs.convert.to_engine(drop_types=(mjGEOM_HFIELD,)) where its pairs are "
536
+ "decoration (e.g. a flat heightfield under the floor plane)", tnames)
537
+ fp = filter_pairs(m)
538
+ add("H15", not fp, "no contype / conaffinity contacts (the engine generates only the explicit pairs; "
539
+ "nablaengine.envs.convert.to_engine turns them into pairs)",
540
+ dict(n=len(fp), first=[(_name(m, mujoco.mjtObj.mjOBJ_GEOM, a), _name(m, mujoco.mjtObj.mjOBJ_GEOM, b))
541
+ for a, b in fp[:4]]))
542
+ cdbad = [f"{_name(m, mujoco.mjtObj.mjOBJ_PAIR, p)}: {int(m.pair_dim[p])}" for p in range(m.npair)
543
+ if int(m.pair_dim[p]) not in FOREST_CONDIM]
544
+ add("H17", not cdbad, "pair condim 1, 3 or 4 (the forest engine has no rolling friction: condim 6 would run as "
545
+ "condim 3; nablaengine.envs.convert.to_engine(condim6_to=3) converts it explicitly)",
546
+ dict(n=len(cdbad), pairs=cdbad[:8]))
547
+ _mg = load("nablaengine.forest_engine", FOREST, "margin")
548
+ mgbad = _mg.problems(m)
549
+ add("T10", not mgbad, "no pair adhesion; contact margins / gaps >= 0 on pair types the forest engine collides "
550
+ "(forest_engine.margin, forest_engine.margin_convex: not two pairs of the same geoms with different margins, "
551
+ "no box-box margin on a G1-class model)", dict(n=len(mgbad), pairs=mgbad[:8]))
552
+ if m.npair and not types - FOREST_TYPES and nb <= 128 and nv <= 128:
553
+ _st = load("nablaengine.forest_engine", FOREST, "step")
554
+ ksup = int(_st.max_support(m))
555
+ _kd = load("nablaengine.forest_engine", FOREST, "kdof64")
556
+ add("T11", ksup <= _kd.MAX_KDOF, "a contact pair's Jacobian support (the dofs on exactly one of its two bodies' "
557
+ f"chains) at most {_kd.MAX_KDOF} dofs (KDOF; beyond 32: forest_engine.kdof64)", ksup)
558
+ fps = [int(p) for p in np.asarray(foot_pairs).ravel()] if foot_pairs is not None else []
559
+ if foot_pairs is not None:
560
+ add("H30", set(fps) <= set(range(m.npair)), "the friction (foot) pairs are contact pair indices",
561
+ dict(n=len(fps), outside=sorted(set(fps) - set(range(m.npair)))[:8]))
562
+
563
+ medium = dict(density=float(m.opt.density), viscosity=float(m.opt.viscosity), wind=[float(x) for x in m.opt.wind])
564
+ add("H22", m.opt.density == 0 and m.opt.viscosity == 0 and not np.any(m.opt.wind),
565
+ "no fluid forces (opt density, viscosity, wind 0)", medium)
566
+ add("T8", int(m.opt.integrator) in (int(mujoco.mjtIntegrator.mjINT_IMPLICITFAST),
567
+ int(mujoco.mjtIntegrator.mjINT_EULER)),
568
+ "implicitfast or Euler integrator", mujoco.mjtIntegrator(int(m.opt.integrator)).name)
569
+ add("H24a", m.opt.solver == mujoco.mjtSolver.mjSOL_NEWTON, "Newton solver",
570
+ mujoco.mjtSolver(int(m.opt.solver)).name)
571
+ nsbad = load("nablaengine.forest_engine", FOREST, "noslip").problems(m)
572
+ add("T9", not nsbad and m.opt.disableactuator == 0, "no disabled actuator groups; noslip (opt.noslip_iterations "
573
+ "> 0) only where forest_engine.noslip takes it (pyramidal cone, no equality constraints or tendons, at most 31 "
574
+ "bodies and 64 dofs, islands on)", dict(noslip_iterations=int(m.opt.noslip_iterations),
575
+ disableactuator=int(m.opt.disableactuator), noslip=nsbad[:4]))
576
+ tendon = load("nablaengine.forest_engine", FOREST, "tendon")
577
+ tbad = tendon.check(m)
578
+ spatial = [t for t, why in tbad if why.startswith("spatial")]
579
+ add("H25", not spatial and m.nmocap == 0 and m.nflex == 0 and m.nplugin == 0,
580
+ "no mocap bodies, flexes or plugins; spatial tendons (site paths, pulleys, sphere / cylinder wrapping with side "
581
+ "sites: forest_engine.spatial) with a Jacobian support of at most 32 dofs, path bodies with one joint each, "
582
+ "no armature (fixed tendons: H25t; equality constraints: H25e)",
583
+ dict(spatial_tendons=spatial[:8], nmocap=int(m.nmocap), nflex=int(m.nflex), nplugin=int(m.nplugin)))
584
+ add("H25t", not [b for b in tbad if not b[1].startswith("spatial")],
585
+ "tendons: fixed ones over hinge / slide joints with length0 0 (joint refs folded by the converter); limits (at most "
586
+ f"{tendon.MAX_LIMITED} limited tendons, margin >= 0), stiffness with "
587
+ "its deadband, damping, armature, tendon equalities; no tendon frictionloss (forest_engine.tendon; tendon "
588
+ "actuators: T5)", dict(ntendon=int(m.ntendon), bad=[b for b in tbad if not b[1].startswith("spatial")][:8]))
589
+ equality = load("nablaengine.forest_engine", FOREST, "equality")
590
+ eqbad = equality.check(m)
591
+ add("H25e", not eqbad, "equality constraints: joint equalities (mjEQ_JOINT) between hinge / slide joints with ref 0, "
592
+ "connect equalities (mjEQ_CONNECT, body or site objects, active at build, at most 32 dofs on their chains) and "
593
+ "tendon equalities on fixed tendons (mjEQ_TENDON, active at build) "
594
+ "(forest_engine.equality, forest_engine.tendon; no weld or flex equalities yet)",
595
+ dict(neq=int(m.neq), bad=eqbad[:8]))
596
+
597
+ _sr = load("nablaengine.forest_engine", FOREST, "solref")
598
+ srbad = _sr.problems(m)
599
+ add("T13", not srbad, "solref in MuJoCo's standard (time constant, damping ratio: both > 0) or direct (-stiffness, "
600
+ "-damping: both <= 0) form on every row the engine builds (contact pairs, joint limits, frictionloss rows, "
601
+ "equalities, tendon limits; forest_engine.solref), not mixed (MuJoCo replaces a mixed solref by the default, "
602
+ "MuJoCo Warp reads each entry on its own); refsafe on (or every time constant >= 2 h); no contact override "
603
+ "(mjENBL_OVERRIDE)", dict(n=len(srbad), bad=srbad[:8]))
604
+ if int(m.opt.cone) == int(mujoco.mjtCone.mjCONE_ELLIPTIC):
605
+ from nablaengine.g1_engine import elliptic as _ell
606
+ ell_ok, ell_why = _ell.supported(m)
607
+ add("T14", ell_ok, "elliptic cone: condim 1, 3 or 4 pairs, isotropic sliding friction, no solreffriction "
608
+ "(forest_engine.elliptic: the friction rows take the pair's solref)", ell_why)
609
+
610
+ if not any(f.status == "error" for f in out):
611
+ import traceback
612
+ adjoint = load("nablaengine.forest_engine", FOREST, "adjoint")
613
+ try:
614
+ adjoint.engine_constants(m, fps, com_body)
615
+ add("T0", True, "the forest engine's constant packing accepts the model")
616
+ except AssertionError as e:
617
+ tb = traceback.extract_tb(e.__traceback__)[-1]
618
+ add("T0", False, "the forest engine's constant packing accepts the model",
619
+ str(e) or f"{tb.name}: {tb.line}")
620
+ return CapabilityReport("forest", out)
621
+
622
+
623
+ def allowed_codes():
624
+ """The codes $DK_ALLOW_UNSUPPORTED lets through (a set; {"all"} for every code)."""
625
+ v = os.environ.get(ALLOW_VAR, "").strip()
626
+ return {c.strip() for c in v.split(",") if c.strip()}
627
+
628
+
629
+ def require(m, foot_pairs=None, com_body=COM_BODY, scope="engine", context=""):
630
+ """check(), then raise UnsupportedModel if it has errors (except the codes $DK_ALLOW_UNSUPPORTED lets through,
631
+ which become a RuntimeWarning). Returns the report."""
632
+ rep = check(m, foot_pairs, com_body, scope)
633
+ errs = rep.errors()
634
+ if errs:
635
+ allow = allowed_codes()
636
+ kept = [f for f in errs if not ("all" in allow or f.code in allow)]
637
+ if kept:
638
+ raise UnsupportedModel(CapabilityReport(scope, [f for f in rep.findings if f not in errs or f in kept]),
639
+ context)
640
+ warnings.warn(f"nablaengine: ${ALLOW_VAR}={os.environ.get(ALLOW_VAR)}: building for a model the engine does "
641
+ f"not support ({', '.join(sorted({f.code for f in errs}))}): its physics is not MuJoCo's"
642
+ + (f" ({context})" if context else ""), RuntimeWarning, stacklevel=2)
643
+ return rep
644
+
645
+
646
+ def diff(a, b):
647
+ """Codes whose status or value differ between two reports (e.g. of a model and of a modified copy of it): [{code,
648
+ what, a: (status, value), b: (status, value)}] (codes present in one report only too)."""
649
+ def by_code(r):
650
+ out = {}
651
+ for f in r.findings:
652
+ out.setdefault(f.code, []).append(f)
653
+ return out
654
+ ia, ib = by_code(a), by_code(b)
655
+ res = []
656
+ for code in sorted(set(ia) | set(ib), key=lambda c: (c[0], int("".join(ch for ch in c[1:] if ch.isdigit()) or 0), c)):
657
+ fa, fb = ia.get(code, []), ib.get(code, [])
658
+ sa = [(f.status, f.value) for f in fa]
659
+ sb = [(f.status, f.value) for f in fb]
660
+ if sa != sb:
661
+ res.append(dict(code=code, what=(fa or fb)[0].what, a=sa, b=sb))
662
+ return res
663
+
664
+
665
+ def main(argv=None):
666
+ import argparse
667
+ import json
668
+ from pathlib import Path
669
+ ap = argparse.ArgumentParser(description="The engine's capability report of a MuJoCo model (nablaengine.model."
670
+ "capability: the input validation of jax_ffi.init and the checks)")
671
+ ap.add_argument("--model", required=True, help="an .mjb or MJCF (.xml) file")
672
+ ap.add_argument("--foot-pairs", default="", help="comma-separated friction (foot) pair indices, or a g1_meta.json")
673
+ ap.add_argument("--com-body", default=COM_BODY)
674
+ ap.add_argument("--scope", default="engine", choices=sorted(SCOPES))
675
+ ap.add_argument("--all", action="store_true", help="print the passing checks too")
676
+ ap.add_argument("--json", default="", help="write the report here")
677
+ args = ap.parse_args(argv)
678
+ p = Path(args.model)
679
+ m = mujoco.MjModel.from_binary_path(str(p)) if p.suffix == ".mjb" else mujoco.MjModel.from_xml_path(str(p))
680
+ fp = None
681
+ if args.foot_pairs.endswith(".json"):
682
+ fp = json.loads(Path(args.foot_pairs).read_text())["foot_pairs"]
683
+ elif args.foot_pairs:
684
+ fp = [int(x) for x in args.foot_pairs.split(",")]
685
+ rep = check(m, fp, args.com_body, args.scope)
686
+ print(rep.table(args.all) or "(no findings)")
687
+ print(rep.summary())
688
+ if args.json:
689
+ Path(args.json).write_text(json.dumps(rep.to_dict(), indent=1) + "\n")
690
+ return 0 if rep.ok() else 1
691
+
692
+
693
+ if __name__ == "__main__":
694
+ raise SystemExit(main())