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,166 @@
1
+ """Per-world gravity and external wrenches (nablaengine.params fields gravity and xfrc) in the forest engine's text. A
2
+ build without these fields is unchanged."""
3
+ import numpy as np
4
+
5
+ FIELDS = ("gravity", "xfrc")
6
+
7
+
8
+ def active(params):
9
+ return bool(params) and any(f in params.fields for f in FIELDS)
10
+
11
+
12
+ def body_ids(m, params):
13
+ """The model ids of PhysicsParams.xfrc_bodies (ValueError where one is not a moving body)."""
14
+ import mujoco
15
+ out = []
16
+ for b in params.xfrc_bodies:
17
+ bid = b if isinstance(b, int) else mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, b)
18
+ if not 1 <= bid < m.nbody:
19
+ raise ValueError(f"PhysicsParams xfrc_bodies: {b!r} is not a moving body of the model")
20
+ out.append(int(bid))
21
+ if len(set(out)) != len(out):
22
+ raise ValueError(f"PhysicsParams xfrc_bodies {params.xfrc_bodies}: a body more than once")
23
+ return out
24
+
25
+
26
+ def gcoff(m):
27
+ from nablaengine.model import gravcomp
28
+ return gravcomp.offsets(m) is not None
29
+
30
+
31
+ def check(m, params):
32
+ """ValueError where gravity / xfrc do not apply to forest model m."""
33
+ if not active(params):
34
+ return
35
+ if "xfrc" in params.fields:
36
+ body_ids(m, params)
37
+ if "gravity" in params.fields and gcoff(m):
38
+ raise ValueError("PhysicsParams gravity: not with gravcomp applied off the COM (fused bodies of different "
39
+ "gravcomp, nablaengine.model.gravcomp)")
40
+
41
+
42
+ def defines(m, params):
43
+ lay = params.layout(m.nv)
44
+ gr = lay["gravity"][0] if "gravity" in lay else -1
45
+ xo = lay["xfrc"][0] if "xfrc" in lay else -1
46
+ ids = body_ids(m, params) if "xfrc" in lay else []
47
+ slot = "".join(f"(b) == {b} ? {k} : " for k, b in enumerate(ids)) + "-1"
48
+ return (f"#define PW_GRAV {gr} // the world's gravity in its parameters (forest_engine.world_forces)\n"
49
+ f"#define PW_XFRC {xo} // the external wrenches (forest_engine.world_forces)\n"
50
+ f"#define XFRC_SLOT(b) ({slot}) // body -> its wrench's slot, -1 none\n")
51
+
52
+
53
+ XFRC_DEVICE = r"""
54
+ // world_forces: the external wrench of body b (its xfrc slot; none: unchanged) on the body's RNE force about its origin:
55
+ // F -= f, N -= t + (R p) x f (f, t world frame, p body frame)
56
+ __device__ __forceinline__ void xfrc_apply(const float* pw, int b, const float* Q, float* F, float* N) {
57
+ const int k = XFRC_SLOT(b);
58
+ if (k < 0) return;
59
+ const float* x = pw + (PW_XFRC >= 0 ? PW_XFRC : 0) + 9 * k;
60
+ float e[3], u[3];
61
+ qrot(Q, x + 6, e);
62
+ cross(e, x, u);
63
+ for (int i = 0; i < 3; i++) { F[i] -= x[i]; N[i] -= x[3 + i] + u[i]; }
64
+ }
65
+ """
66
+ SUBSTEP_ANCHOR = "template <int PHASE = 0, class S>\n__device__ void substep_pre(S& s, const float* ctrl, int lane, float* rec) {\n"
67
+ FWD_CALL = " body_force(b, Qb, Wb, ALb, Ab, ip, Fb, Nb);\n"
68
+ FWD_XFRC = FWD_CALL + " xfrc_apply(s.pw, b, Qb, Fb, Nb); // (world_forces)\n"
69
+ FWD_GRAV = ("s.A[0][k] = -c_grav[k]; } // gravity\n", "s.A[0][k] = -s.pw[(PW_GRAV >= 0 ? PW_GRAV : 0) + k]; } // gravity "
70
+ "(world_forces: the world's)\n")
71
+ ADJ_GRAV = ("s.A[0][k] = -c_grav[k]; }\n }\n __syncwarp();\n",
72
+ "s.A[0][k] = -s.pw[(PW_GRAV >= 0 ? PW_GRAV : 0) + k]; } // (world_forces)\n }\n __syncwarp();\n")
73
+ ROOT_GRAV = ("A[k] = RSUB(qa[k], c_grav[k]); }", "A[k] = RSUB(qa[k], -Ap[k]); } /* (world_forces: Ap = -g) */")
74
+ TREE_DOWN_END = (" __syncwarp();\n for (int i = lane; i < NV; i += 32) { s.Pq[i] = 0.f; s.Pv[i] = 0.f; }\n __syncwarp();\n}\n"
75
+ "\n// A7")
76
+ ADJ_BLOCK = r""" __syncwarp();
77
+ { // world_forces: the external wrenches' VJP and the cotangents of the wrenches and of gravity (module docstring)
78
+ #if PW_GRAV >= 0
79
+ float g0 = 0.f, g1 = 0.f, g2 = 0.f;
80
+ #endif
81
+ for (int b = lane; b < NB; b += 32) if (b >= 1) {
82
+ #if PW_GRAV >= 0
83
+ const float wg = 1.f - c_gcomp[b];
84
+ g0 += wg * s.bA[b][0]; g1 += wg * s.bA[b][1]; g2 += wg * s.bA[b][2];
85
+ #endif
86
+ #if PW_XFRC >= 0
87
+ const int k = XFRC_SLOT(b);
88
+ if (k >= 0) {
89
+ const float* x = s.pw + (PW_XFRC >= 0 ? PW_XFRC : 0) + 9 * k;
90
+ float* gx = s.gpw + (PW_XFRC >= 0 ? PW_XFRC : 0) + 9 * k;
91
+ const float *Wl = s.Wl[b], *Vl = s.Vl[b];
92
+ float e[3], u[3], fw[3];
93
+ qrot(s.Q[b], x + 6, e);
94
+ cross(Wl, e, u);
95
+ for (int i = 0; i < 3; i++) { gx[i] += Vl[i] + u[i]; gx[3 + i] += Wl[i]; }
96
+ cross(x, Wl, fw); // f x Wl
97
+ qrot_inv(s.Q[b], fw, u);
98
+ for (int i = 0; i < 3; i++) gx[6 + i] += u[i];
99
+ cross(e, x, u);
100
+ for (int i = 0; i < 3; i++) { s.bVl[b][i] -= x[i]; s.bWl[b][i] -= x[3 + i] + u[i]; }
101
+ cross(e, fw, u); // e rotates with the body: e x (f x Wl)
102
+ for (int i = 0; i < 3; i++) s.tb[b][i] -= u[i];
103
+ }
104
+ #endif
105
+ }
106
+ #if PW_GRAV >= 0
107
+ g0 = warp_sum(g0); g1 = warp_sum(g1); g2 = warp_sum(g2);
108
+ if (lane == 0) {
109
+ s.gpw[(PW_GRAV >= 0 ? PW_GRAV : 0)] += g0;
110
+ s.gpw[(PW_GRAV >= 0 ? PW_GRAV : 0) + 1] += g1;
111
+ s.gpw[(PW_GRAV >= 0 ? PW_GRAV : 0) + 2] += g2;
112
+ }
113
+ #endif
114
+ }
115
+ """
116
+
117
+
118
+ def _sub(src, a, b, n=1, what=""):
119
+ if src.count(a) != n:
120
+ raise RuntimeError(f"world_forces: {what or a[:60]!r} found {src.count(a)} times, expected {n}")
121
+ return src.replace(a, b)
122
+
123
+
124
+ def _function_span(src, head):
125
+ i = src.find(head)
126
+ if i < 0 or src.find(head, i + 1) >= 0:
127
+ raise RuntimeError(f"world_forces: function {head[:60]!r} not found once")
128
+ j = src.find("\n}\n", i)
129
+ return i, j + 3
130
+
131
+
132
+ def _gravcomp_gw(src, head, call_old, call_new):
133
+ i, j = _function_span(src, head)
134
+ body = src[i:j]
135
+ k = body.find(") {\n")
136
+ body = body[:k] + ", const float* gwld" + body[k:]
137
+ body = body.replace("c_grav[", "gwld[")
138
+ src = src[:i] + body + src[j:]
139
+ return _sub(src, call_old, call_new)
140
+
141
+
142
+ def engine(src, m, params):
143
+ """The final engine text (adjoint.cuda_source) of a build with gravity / xfrc (unchanged without)."""
144
+ if not active(params):
145
+ return src
146
+ lay = params.layout(m.nv)
147
+ if "xfrc" in lay:
148
+ src = _sub(src, SUBSTEP_ANCHOR, XFRC_DEVICE + SUBSTEP_ANCHOR)
149
+ src = _sub(src, FWD_CALL, FWD_XFRC)
150
+ if "gravity" in lay:
151
+ src = _sub(src, *FWD_GRAV)
152
+ src = _sub(src, *ADJ_GRAV)
153
+ src = _sub(src, *ROOT_GRAV)
154
+ if np.any(np.asarray(m.body_gravcomp) != 0):
155
+ gw = "s.pw + (PW_GRAV >= 0 ? PW_GRAV : 0)"
156
+ src = _gravcomp_gw(src, "__device__ __forceinline__ void body_force(int b,", FWD_CALL,
157
+ FWD_CALL.replace("Fb, Nb);", f"Fb, Nb, {gw});"))
158
+ src = _gravcomp_gw(src, "__device__ void body_local_vjp(int b,", "s.bWy[b], s.bVy[b], s.tb[b]);\n",
159
+ f"s.bWy[b], s.bVy[b], s.tb[b], {gw});\n")
160
+ left = [ln for ln in src.splitlines() if "c_grav[" in ln and "c_grav[3]" not in ln
161
+ and not ("gc * c_grav[k]" in ln or "c_gcomp[b] * c_grav[k]" in ln)]
162
+ if left:
163
+ raise RuntimeError(f"world_forces: c_grav read left in the engine text: {left[:3]}")
164
+ src = _sub(src, TREE_DOWN_END, ADJ_BLOCK + TREE_DOWN_END, what="adj_tree_down's end")
165
+ return defines(m, params) + src
166
+
@@ -0,0 +1,230 @@
1
+ """Per-world physics parameters (nablaengine.params.PhysicsParams) in the forest engine's text: apply() edits the engine
2
+ (adjoint.cuda_source), the host kernels (host.KERNEL) and the kinematics (kinematics.KIN_DEVICE) of a build with
3
+ parameters; a build without them is unchanged. The device code and most anchors are the G1 engine's
4
+ (g1_engine.world_params); this module holds the forest engine's differences:"""
5
+ from nablaengine.g1_engine import world_params as G
6
+
7
+ FOREST_FIELDS = ("foot_solref", "foot_solimp", "dof_damping", "dof_armature", "dof_frictionloss", "frictionloss_solref",
8
+ "frictionloss_solimp", "torso_mass", "torso_inertia", "foot_torsional", "object_size", "gravity",
9
+ "xfrc", "body_inertial", "sole_thickness", "foot_offset")
10
+
11
+ ADJ_GCTRL = (" for (int i = lane; i < NU; i += 32) gctrl[(size_t)w * NU + i] = s.ubar[i];\n",
12
+ " for (int i = lane; i < NU; i += 32) gctrl[(size_t)w * (NU + NPARAM + 1) + i] = s.ubar[i]; // (world_params)\n"
13
+ " __syncwarp();\n"
14
+ " for (int i = lane; i <= NPARAM; i += 32) gctrl[(size_t)w * (NU + NPARAM + 1) + NU + i] = s.gpw[i];\n", 1)
15
+ ADJ_COMPOSE = (G.ADJ[1][0], G.ADJ[1][1].replace("- h * y * aadv;", "- (PW_DAMP_Q ? h * y * aadv : 0.f);"), 1)
16
+ assert ADJ_COMPOSE[1] != G.ADJ[1][1]
17
+ ARMATURE = (
18
+ G.ARMATURE[0],
19
+ (" s.M[TRI(r0 + j, r0 + i)] = dot3(kw, n) + dot3(kv, f) + (i == j ? c_armature[r0 + j] : 0.f);",
20
+ " s.M[TRI(r0 + j, r0 + i)] = dot3(kw, n) + dot3(kv, f) + (i == j ? s.pw[(PW_ARM >= 0 ? PW_ARM : 0) + r0 + j] : 0.f);"
21
+ " // (world_params)", 1),
22
+ G.ARMATURE[2],
23
+ )
24
+ PARTIALS_CALL = (
25
+ " cot[1] = cot[2] = cot[3] = 0.f;\n contact_pbar_motion(Wv, Wa, Wl, Ov, Oa, Ol, cot + 1);\n",
26
+ " if (PFOOT(pair) && zone) { // the foot pair's parameters (world_params)\n"
27
+ "#if HAS_CONDIM4\n"
28
+ " contact_param_vjp4(Vv, Va, Vl, fr, mu, dim, zone, d, D, k, b, imp, contact_invw(pair, mu), sref, simp, pp, Ov, Oa,"
29
+ " Ol, dim == 4 ? PMUS(pair) : 0.f);\n"
30
+ "#else\n"
31
+ " contact_param_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, k, b, imp, contact_invw(pair, mu), sref, simp, pp);\n"
32
+ "#endif\n"
33
+ " }\n"
34
+ " cot[1] = cot[2] = cot[3] = 0.f;\n contact_pbar_motion(Wv, Wa, Wl, Ov, Oa, Ol, cot + 1);\n", 1)
35
+ PARTIALS = (
36
+ (G.PARTIALS[0][0], G.PARTIALS[0][1].replace(
37
+ G.PARTIALS_DEVICE, "#if HAS_CONDIM4\n" + G.PARTIALS4_DEVICE + "#else\n" + G.PARTIALS_DEVICE + "#endif\n"), 1),
38
+ PARTIALS_CALL,
39
+ (G.PARTIALS[2][0], G.PARTIALS[2][1].replace("float pp[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};",
40
+ "float pp[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};"), 1),
41
+ G.PARTIALS[3],
42
+ G.PARTIALS[4],
43
+ )
44
+ _CC_HEAD = ("float* dbg CC_REC_PARAM) {", "float* dbg) {", "float* dbg, float* pp) {", "float* dbg, float* pp CC_REC_PARAM) {")
45
+ _CC_CALL = ("cw, dbg CC_REC_ARG)", "cw, dbg)", "cw, dbg, pp)", "cw, dbg, pp CC_REC_ARG)")
46
+
47
+
48
+ def _coop_safe(src, fn):
49
+ if _CC_HEAD[0] not in src:
50
+ return fn(src)
51
+ for a, b, _, _ in (_CC_HEAD, _CC_CALL):
52
+ if src.count(a) != 1 or src.count(b) != 0:
53
+ raise RuntimeError(f"world_params (forest): ccd_coop's {a!r} found {src.count(a)} times")
54
+ src = src.replace(a, b)
55
+ src = fn(src)
56
+ for _, _, c, d in (_CC_HEAD, _CC_CALL):
57
+ if src.count(c) != 1:
58
+ raise RuntimeError(f"world_params (forest): {c!r} found {src.count(c)} times after the edits")
59
+ src = src.replace(c, d)
60
+ return src
61
+
62
+
63
+ MUS_FOOT = "(PFOOT({p}) ? s.musw : PMUS({p}))"
64
+ TORS_STATE = (
65
+ (" float com[3], fric;\n", " float com[3], fric;\n float musw; // the foot pairs' spin friction (world_params)\n",
66
+ 3),
67
+ (" const float *qsm, *qacc0, *con_mu, *efc_aref; // in Hand\n",
68
+ " const float *qsm, *qacc0, *con_mu, *efc_aref; // in Hand\n float musw; // (world_params: foot_torsional)\n",
69
+ 1),
70
+ ("struct Hand {\n float M[NTRI], qsm[NV], qacc0[NV];\n",
71
+ "struct Hand {\n float M[NTRI], qsm[NV], qacc0[NV];\n float musw; // (world_params: foot_torsional)\n", 1),
72
+ )
73
+ TORS_LOAD = " if (lane == 0) s.dampw = s.pw + (PW_DAMP >= 0 ? PW_DAMP : 0);\n"
74
+ TORS_LOAD_NEW = (TORS_LOAD + " if (lane == 0) s.musw = fmaxf(com[(size_t)w * COM_STRIDE + PW_OFF + (PW_TORS >= 0 ? PW_TORS : 0)],"
75
+ " 1e-5f); // (foot_torsional)\n")
76
+ assert G.LOAD[1].count(TORS_LOAD) == 1
77
+ TORS_SPLIT = (
78
+ (G.SPLIT[0][1], G.SPLIT[0][1] + " if (lane == 0) g.musw = s.musw; // (world_params: foot_torsional)\n", 1),
79
+ ("s.qsm = g.qsm; s.dampw = g.dampw;", "s.qsm = g.qsm; s.dampw = g.dampw; s.musw = g.musw;", 1),
80
+ )
81
+ TORS_SUM = (G.PARTIALS[4][1], G.PARTIALS[4][1].replace("for (int q = 0; q < 7; q++)", "for (int q = 0; q < 8; q++)")
82
+ .replace(" else if (q == 6) s.gpw[NPARAM] += v;\n",
83
+ " else if (q == 6) s.gpw[NPARAM] += v;\n"
84
+ " else if (q == 7) s.gpw[PW_TORS >= 0 ? PW_TORS : 0] += v; // (foot_torsional)\n"), 1)
85
+ assert TORS_SUM[1] != G.PARTIALS[4][1] and "q < 8" in TORS_SUM[1]
86
+ TORSO_FORCE = (" float m = c_mass[b], gc = c_gcomp[b];",
87
+ " float m = ipos[3], gc = c_gcomp[b]; // (world_params)", 1)
88
+ TORSO_VJP_GC = (" for (int k = 0; k < 3; k++) f1[k] = A[k] + t[k] + wwc[k];\n",
89
+ " for (int k = 0; k < 3; k++) f1[k] = A[k] + t[k] + wwc[k] + c_gcomp[b] * c_grav[k]; // (gravcomp)\n")
90
+ assert G.TORSO_VJP.count(TORSO_VJP_GC[0]) == 1
91
+ TORSO_ENGINE = tuple(
92
+ TORSO_FORCE if h[0].startswith(" float m = c_mass[b];\n for (int k = 0; k < 3; k++) F[k]")
93
+ else (h[0], h[1].replace(G.TORSO_VJP, G.TORSO_VJP.replace(*TORSO_VJP_GC)), h[2]) if h[1].startswith(G.TORSO_VJP)
94
+ else h for h in G.TORSO_ENGINE)
95
+ assert TORSO_FORCE in TORSO_ENGINE and sum(TORSO_VJP_GC[1] in h[1] for h in TORSO_ENGINE) == 1
96
+ KIN_LOAD = (" if (lane < 3) s.com[lane] = com[(size_t)w * COM_STRIDE + lane]; // (fixtures: not in the kinematics "
97
+ "outputs)\n")
98
+
99
+
100
+ def check(m, params, foot_pairs, com_body):
101
+ """ValueError where params do not apply to forest model m (foot_pairs: the build's, com_body: init's)."""
102
+ import mujoco
103
+ if not params:
104
+ return
105
+ bad = [f for f in params.fields if f not in FOREST_FIELDS]
106
+ if bad:
107
+ raise ValueError(f"PhysicsParams {bad}: not on the forest engine (it has {FOREST_FIELDS})")
108
+ if int(m.opt.cone) == int(mujoco.mjtCone.mjCONE_ELLIPTIC):
109
+ raise ValueError("per-world physics parameters with the elliptic friction cone: not supported yet")
110
+ if "foot_torsional" in params.fields:
111
+ if not list(foot_pairs):
112
+ raise ValueError("PhysicsParams foot_torsional on the forest engine: init(foot_pairs=) must name the "
113
+ "condim-4 contact pairs it applies to")
114
+ if not any(int(m.pair_dim[p]) == 4 for p in foot_pairs):
115
+ raise ValueError("PhysicsParams foot_torsional: the foot pairs have no condim-4 pair")
116
+ if "object_size" in params.fields:
117
+ from nablaengine.forest_engine import object_size
118
+ object_size.check(m, params, com_body)
119
+ from nablaengine.forest_engine import world_forces, body_params, floss
120
+ world_forces.check(m, params)
121
+ floss.check(m, params)
122
+ body_params.check(m, params, foot_pairs, com_body)
123
+ if ("foot_solref" in params.fields or "foot_solimp" in params.fields) and not list(foot_pairs):
124
+ raise ValueError("PhysicsParams foot_solref / foot_solimp on the forest engine: init(foot_pairs=) must name the "
125
+ "contact pairs they apply to")
126
+ if "torso_mass" in params.fields or "torso_inertia" in params.fields:
127
+ b = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, com_body) if com_body else -1
128
+ if b < 1:
129
+ raise ValueError("PhysicsParams torso_mass / torso_inertia on the forest engine: init(com_body=) must name "
130
+ f"the (moving) body they apply to (got {com_body!r})")
131
+
132
+
133
+ def damped(m, params):
134
+ """Whether an Euler build with params solves the damped update although the model has no damping (model_hooks'
135
+ "explicit" text replaced by "euler"): dof_damping with eulerdamp enabled."""
136
+ from nablaengine.forest_engine import model_hooks
137
+ import mujoco
138
+ return (bool(params) and "dof_damping" in params.fields
139
+ and int(m.opt.integrator) == int(mujoco.mjtIntegrator.mjINT_EULER)
140
+ and not (m.opt.disableflags & mujoco.mjtDisableBit.mjDSBL_EULERDAMP)
141
+ and model_hooks.integrator(m) == "explicit")
142
+
143
+
144
+ def _kin(src):
145
+ if src.count(KIN_LOAD) != 1:
146
+ raise RuntimeError("world_params (forest): the kinematics' com load not found")
147
+ return src.replace(KIN_LOAD, G.TORSO_LOAD[1].replace(G.TORSO_LOAD[0], KIN_LOAD))
148
+
149
+
150
+ def apply(src, m, params, part, pw_off):
151
+ """apply_params(src, m, params, part, pw_off), also on a build with motor limits (g1_engine.world_params's
152
+ plain_compose: motor_hooks adds the record to adj_compose's signature, which ADJ_COMPOSE anchors on)."""
153
+ if not params:
154
+ return src
155
+ return G.plain_compose(src, lambda s: apply_params(s, m, params, part, pw_off))
156
+
157
+
158
+ def apply_params(src, m, params, part, pw_off):
159
+ """src with the edits of a forest build with parameters params (unchanged without); part: "engine"
160
+ (adjoint.cuda_source, last), "host" (host.KERNEL) or "kinematics" (model_hooks' kinematics text). pw_off: the
161
+ parameters' offset in a com row (step.com_words(m); a terrain build: forest_engine.terrain.com_words(m, terrain))."""
162
+ if not params:
163
+ return src
164
+ from nablaengine.forest_engine import model_hooks
165
+ from nablaengine.forest_engine import body_params
166
+ for a, b in G.STRIDE:
167
+ src = src.replace(a, b)
168
+ inertial = body_params.inertial_active(params)
169
+ torso = "torso_mass" in params.fields or "torso_inertia" in params.fields or inertial
170
+ if part == "kinematics":
171
+ if not torso:
172
+ return src
173
+ src = src.replace("float ip[3]", "float ip[7]")
174
+ src = G._apply(src, G.TORSO_KIN)
175
+ for a in (" Mb = c_mass[b];\n", " const float m = c_mass[b];\n"):
176
+ if src.count(a) != 1:
177
+ raise RuntimeError(f"world_params (forest): kinematics mass read {a.strip()!r} not found once")
178
+ src = src.replace(a, a.replace("c_mass[b]", "ip[3]"))
179
+ if "c_mass[" in src:
180
+ raise RuntimeError("world_params (forest): the kinematics read c_mass outside the torso edits")
181
+ return body_params.inertial(_kin(src), part) if inertial else _kin(src)
182
+ tors = "foot_torsional" in params.fields
183
+ n = 1 if part == "engine" else 3
184
+ if src.count(G.LOAD[0]) != n:
185
+ raise RuntimeError(f"world_params (forest): com loads found {src.count(G.LOAD[0])} times, expected {n}")
186
+ src = src.replace(*(G.LOAD_ADJ if part == "engine" else G.LOAD))
187
+ if tors:
188
+ src = G._apply(src, ((TORS_LOAD, TORS_LOAD_NEW, n),))
189
+ from nablaengine.forest_engine import floss
190
+ if part == "host":
191
+ src = G._apply(src, G.SPLIT + (TORS_SPLIT if tors else ()))
192
+ src = src.replace(*G.TORSO_LOAD) if torso else src
193
+ src = body_params.inertial(src, part) if inertial else src
194
+ src = floss.apply(src, m, params, part)
195
+ return body_params.iw_host(src) if body_params.iw_active(params) else src
196
+ integ = "euler" if damped(m, params) else model_hooks.integrator(m)
197
+ explicit = integ == "explicit"
198
+ lay = params.layout(m.nv)
199
+ src = (G.header(m, params, pw_off)
200
+ + f"#define PW_DAMP_Q {0 if explicit else 1} // the damping in Q (world_params)\n"
201
+ + (f"#define PW_OSIZE {lay['object_size'][0]} // the object's size (forest_engine.object_size)\n"
202
+ if "object_size" in lay else "")
203
+ + _coop_safe(src, lambda t: G._apply(t, G.STATE + (G.ADJ[0], ADJ_COMPOSE, ADJ_GCTRL) + G.FOOT + PARTIALS)))
204
+ if tors:
205
+ src = G._apply(src, TORS_STATE + (TORS_SUM,))
206
+ for a in ("s.con_pair[a]", "s.con_pair[c]"):
207
+ if f"PMUS({a})" not in src:
208
+ raise RuntimeError(f"world_params (forest): PMUS({a}) not found (foot_torsional)")
209
+ src = src.replace(f"PMUS({a})", MUS_FOOT.format(p=a))
210
+ old = "dim == 4 ? PMUS(pair) : 0.f"
211
+ if src.count(old) != 2:
212
+ raise RuntimeError(f"world_params (forest): {old!r} found {src.count(old)} times, expected 2")
213
+ src = src.replace(old, "dim == 4 ? " + MUS_FOOT.format(p="pair") + " : 0.f")
214
+ if "foot_solref" in params.fields:
215
+ src = G._apply(src, G.DIRECT_SOLREF)
216
+ if "dof_damping" in params.fields:
217
+ nd, want = src.count("c_damp[i]"), {"explicit": 2, "euler": 4, "implicitfast": 5}[integ]
218
+ if nd != want:
219
+ raise RuntimeError(f"world_params (forest): c_damp[i] found {nd} times, expected {want}")
220
+ src = src.replace("c_damp[i]", "s.dampw[i]")
221
+ if "dof_armature" in params.fields:
222
+ src = G._apply(src, ARMATURE)
223
+ src = floss.apply(src, m, params, part)
224
+ if torso:
225
+ src = src.replace("float ip[3]", "float ip[7]")
226
+ src = G._apply(src, TORSO_ENGINE)
227
+ src = src.replace(*G.TORSO_LOAD)
228
+ if inertial:
229
+ src = body_params.inertial(src, part)
230
+ return src
File without changes